yii-public

yii-agent-sdk (0.1.1)

Published 2026-04-12 03:54:52 +00:00 by luthics in yii-public/yii-agent

Installation

registry=
npm install yii-agent-sdk@0.1.1
"yii-agent-sdk": "0.1.1"

About this package

yii-agent-sdk

Minimal TypeScript SDK for communicating with a yii-agent backend. Handles authentication, streaming responses (SSE), and tool execution.

Install

bun add yii-agent-sdk
# or point to local path
bun add yii-agent-sdk@../yii-agent-sdk

Quick Start

import { configure, chat } from 'yii-agent-sdk'

configure({
  serverUrl: 'https://your-agent-server.com',
  username: 'alice',
  password: 'secret',
})

const { text, sessionId } = await chat('yii-agent', 'Hello!')
console.log(text)

API

configure(config)

Must be called once before any other API. Sets the server address and credentials.

configure({
  serverUrl: 'https://your-agent-server.com',
  username: 'alice',
  password: 'secret',
})

chat(agentName, prompt, options?)Promise<ChatResponse>

High-level convenience function. Sends a message and waits for the full reply.

const { text, reasoning, sessionId } = await chat('yii-agent', 'What is 2+2?')

Options:

Option Type Description
sessionId string Resume an existing conversation
userId string User identifier (default: 'sdk-user')
tools ToolDefinition[] Tools the agent can call
executeTool (name, args) => Promise<string> Required if tools is provided
onTextDelta (delta, fullText) => void Called on each streamed text chunk
onTextDone (text) => void Called when a response turn completes
onReasoningDelta (content) => void Called on reasoning/thinking chunks

Multi-turn conversation:

const r1 = await chat('yii-agent', 'My name is Alice.')
const r2 = await chat('yii-agent', 'What is my name?', { sessionId: r1.sessionId })

Streaming output:

const { text } = await chat('yii-agent', 'Tell me a story', {
  onTextDelta: (delta) => process.stdout.write(delta),
})

Custom tools:

const { text } = await chat('yii-agent', "What's the weather in Beijing?", {
  tools: [
    {
      name: 'get_weather',
      description: 'Get current weather for a city',
      parameters: {
        type: 'object',
        properties: { city: { type: 'string' } },
        required: ['city'],
      },
    },
  ],
  executeTool: async (name, args) => {
    if (name === 'get_weather') return JSON.stringify({ temp: 22, condition: 'sunny' })
    throw new Error(`Unknown tool: ${name}`)
  },
})

Low-level API

Use these when you need more control than chat() provides.

chatWithAgent(params)Promise<ChatResult>

Creates or resumes a conversation. Returns a streamId to subscribe to.

const { streamId, sessionId } = await chatWithAgent({
  agentName: 'yii-agent',
  prompt: 'Hello',
  userId: 'user-123',
  sessionId: previousSessionId,  // optional
  tools: [],                      // optional
})

subscribeStream(streamId, callbacks)

Subscribes to a streaming response. Handles text_delta, tool_request, agent_done, and error events.

await subscribeStream(streamId, {
  onTextDelta: (delta, fullText) => process.stdout.write(delta),
  onTextDone: async (text) => console.log('turn done:', text),
  onDone: async ({ text, reasoning }) => console.log('finished:', text),
  onError: async (message) => console.error('error:', message),
  executeTool: async (name, args) => {
    // execute the tool and return a JSON string result
    return JSON.stringify({ result: 'ok' })
  },
})

submitToolResult(params)

Manually submit a tool result (used internally by subscribeStream).

await submitToolResult({ callId: 'abc123', result: JSON.stringify({ ok: true }) })
// or on failure:
await submitToolResult({ callId: 'abc123', error: 'timeout' })

abortChat(streamId, sessionId?)

Abort an in-progress conversation.

await abortChat(streamId)

login() / clearAuth()

Authentication is handled automatically (auto-login, auto-refresh). Call these only if you need manual control.

await login()   // force a fresh login
clearAuth()     // clear cached tokens (e.g. on logout)

authGet(url, headers?) / authPost(url, body, headers?)

Authenticated HTTP primitives for calling other endpoints on the server. All POST bodies are automatically encrypted.

const resp = await authGet('https://your-server.com/api/v1/agents')
const data = await resp.json()

Types

interface SdkConfig {
  serverUrl: string
  username: string
  password: string
}

interface ToolDefinition {
  name: string
  description: string
  parameters: Record<string, any>  // JSON Schema
}

interface ChatOptions {
  sessionId?: string
  userId?: string
  tools?: ToolDefinition[]
  executeTool?: (name: string, args: Record<string, any>) => Promise<string>
  onTextDelta?: (delta: string, fullText: string) => void
  onTextDone?: (text: string) => void
  onReasoningDelta?: (content: string) => void
}

interface ChatResponse {
  text: string
  reasoning: string
  sessionId: string
}

Security

All POST request bodies are encrypted before transmission. Access tokens are refreshed automatically 30 seconds before expiry.

Dependencies

Development Dependencies

ID Version
@types/bun ^1.3.9
jsonrepair ^3.12.0
typescript ^5
Details
npm
2026-04-12 03:54:52 +00:00
16
7.7 KiB
Assets (1)
Versions (2) View all
0.2.0 2026-04-15
0.1.1 2026-04-12