@yushaw/sanqian-sdk 0.2.9 → 0.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,430 @@
1
+ /**
2
+ * Sanqian SDK Type Definitions
3
+ */
4
+ interface SDKConfig {
5
+ /** Unique app identifier (e.g., "sanqian-todolist") */
6
+ appName: string;
7
+ /** App version string */
8
+ appVersion: string;
9
+ /** Display name shown in Sanqian UI */
10
+ displayName?: string;
11
+ /** Command to launch this app (for auto-start) */
12
+ launchCommand?: string;
13
+ /** Tools provided by this app */
14
+ tools: ToolDefinition[];
15
+ /** Reconnect interval in ms (default: 5000) */
16
+ reconnectInterval?: number;
17
+ /** Heartbeat interval in ms (default: 30000) */
18
+ heartbeatInterval?: number;
19
+ /** Tool execution timeout in ms (default: 30000) */
20
+ toolExecutionTimeout?: number;
21
+ /**
22
+ * Auto-launch Sanqian if not running (default: false)
23
+ * When enabled, SDK will try to start Sanqian in hidden/tray mode
24
+ */
25
+ autoLaunchSanqian?: boolean;
26
+ /**
27
+ * Custom path to Sanqian executable (optional)
28
+ * If not provided, SDK will search in standard installation locations
29
+ */
30
+ sanqianPath?: string;
31
+ /**
32
+ * Enable debug logging (default: false)
33
+ * When enabled, SDK will output detailed logs to console
34
+ */
35
+ debug?: boolean;
36
+ /**
37
+ * Pre-configured connection info (for browser environments)
38
+ * When provided, SDK skips file-based discovery and connects directly.
39
+ * This is useful for browser extensions that discover Sanqian via other means
40
+ * (e.g., native messaging or HTTP API).
41
+ */
42
+ connectionInfo?: ConnectionInfo;
43
+ }
44
+ interface ToolDefinition {
45
+ /** Tool name (without app prefix) */
46
+ name: string;
47
+ /** Tool description for LLM */
48
+ description: string;
49
+ /** JSON Schema for parameters */
50
+ parameters: JSONSchema;
51
+ /** Handler function */
52
+ handler: (args: any) => Promise<any>;
53
+ /**
54
+ * Whether this tool can be discovered via search_capability (default: true)
55
+ * Set to false for internal tools that should be available but not searchable
56
+ */
57
+ searchable?: boolean;
58
+ }
59
+ interface JSONSchema {
60
+ type: "object" | "array" | "string" | "number" | "boolean";
61
+ properties?: Record<string, JSONSchemaProperty>;
62
+ required?: string[];
63
+ items?: JSONSchemaProperty;
64
+ description?: string;
65
+ }
66
+ interface JSONSchemaProperty {
67
+ type: "string" | "number" | "boolean" | "array" | "object";
68
+ description?: string;
69
+ enum?: (string | number)[];
70
+ default?: unknown;
71
+ items?: JSONSchemaProperty;
72
+ properties?: Record<string, JSONSchemaProperty>;
73
+ required?: string[];
74
+ format?: string;
75
+ }
76
+ interface ConnectionInfo {
77
+ version: number;
78
+ port: number;
79
+ ws_path: string;
80
+ token: string;
81
+ pid: number;
82
+ started_at: string;
83
+ /** Path to Sanqian executable (for SDK auto-launch) */
84
+ executable?: string;
85
+ }
86
+ interface ConnectionState {
87
+ connected: boolean;
88
+ registering: boolean;
89
+ registered: boolean;
90
+ lastError?: Error;
91
+ reconnectAttempts: number;
92
+ }
93
+ /** Remote tool definition for dynamic tool injection */
94
+ interface RemoteToolDefinition {
95
+ /** Tool name */
96
+ name: string;
97
+ /** Tool description for LLM */
98
+ description: string;
99
+ /** JSON Schema for parameters */
100
+ parameters: JSONSchema;
101
+ }
102
+ interface ChatRequest {
103
+ /** Agent ID (can be short name, SDK auto-adds app prefix) */
104
+ agentId: string;
105
+ /** Messages to send */
106
+ messages: ChatMessage[];
107
+ /** Conversation ID for stateful mode (server stores messages) */
108
+ conversationId?: string;
109
+ /** Enable streaming (default: true) */
110
+ stream?: boolean;
111
+ /** Dynamic tools to inject at call time */
112
+ remoteTools?: RemoteToolDefinition[];
113
+ }
114
+ interface ChatMessage {
115
+ role: "user" | "assistant" | "system" | "tool";
116
+ content: string;
117
+ tool_calls?: ToolCall[];
118
+ tool_call_id?: string;
119
+ }
120
+ interface ToolCall {
121
+ id: string;
122
+ type: "function";
123
+ function: {
124
+ name: string;
125
+ arguments: string;
126
+ };
127
+ }
128
+ interface ChatResponse {
129
+ message: ChatMessage;
130
+ conversationId: string;
131
+ /** Conversation title (truncated from first user message, or LLM-generated after 3rd round) */
132
+ title?: string;
133
+ usage?: {
134
+ prompt_tokens: number;
135
+ completion_tokens: number;
136
+ total_tokens: number;
137
+ };
138
+ }
139
+ interface ChatStreamEvent {
140
+ type: "text" | "tool_call" | "done" | "error";
141
+ content?: string;
142
+ tool_call?: ToolCall;
143
+ conversationId?: string;
144
+ /** Conversation title (sent with "done" event) */
145
+ title?: string;
146
+ error?: string;
147
+ }
148
+ /** Agent configuration for create/update */
149
+ interface AgentConfig {
150
+ /** Unique agent ID within this app (e.g., "assistant") */
151
+ agent_id: string;
152
+ /** Display name */
153
+ name: string;
154
+ /** Description */
155
+ description?: string;
156
+ /** System prompt */
157
+ system_prompt?: string;
158
+ /** Tool names from this app to enable (without prefix) */
159
+ tools?: string[];
160
+ /**
161
+ * Sub-agents this agent can call via task tool.
162
+ * - undefined/null: Cannot use task tool (default)
163
+ * - []: Cannot use task tool (explicit)
164
+ * - ["*"]: Can call all available agents
165
+ * - ["agent1", "agent2"]: Can only call specified agents
166
+ */
167
+ subagents?: string[];
168
+ /**
169
+ * Whether this agent can be discovered via search_capability (default: true)
170
+ * Set to false if you want the agent to be usable but not discoverable by other agents
171
+ */
172
+ searchable?: boolean;
173
+ }
174
+ /** Agent info returned from list */
175
+ interface AgentInfo {
176
+ /** Full agent ID (app_name:agent_id) */
177
+ agent_id: string;
178
+ name: string;
179
+ description?: string;
180
+ /** Tool names with sdk_ prefix */
181
+ tools: string[];
182
+ /** Sub-agents this agent can call via task tool */
183
+ subagents?: string[] | null;
184
+ /** Whether this agent can be discovered via search_capability */
185
+ searchable?: boolean;
186
+ created_at?: string;
187
+ }
188
+ /** Conversation info */
189
+ interface ConversationInfo {
190
+ conversation_id: string;
191
+ agent_id: string;
192
+ title?: string;
193
+ message_count: number;
194
+ created_at?: string;
195
+ updated_at?: string;
196
+ }
197
+ /** Message in a conversation */
198
+ interface ConversationMessage {
199
+ id: string;
200
+ role: "user" | "assistant" | "system" | "tool";
201
+ content: string;
202
+ tool_calls?: ToolCall[] | null;
203
+ tool_call_id?: string | null;
204
+ created_at?: string;
205
+ }
206
+ /** Full conversation with messages */
207
+ interface ConversationDetail extends ConversationInfo {
208
+ messages?: ConversationMessage[];
209
+ }
210
+ /** Agent update configuration (all fields optional except agent_id) */
211
+ interface AgentUpdateConfig {
212
+ /** Agent ID to update */
213
+ agent_id: string;
214
+ /** New display name */
215
+ name?: string;
216
+ /** New description */
217
+ description?: string;
218
+ /** New system prompt */
219
+ system_prompt?: string;
220
+ /** New tool names from this app to enable (without prefix) */
221
+ tools?: string[];
222
+ /**
223
+ * Sub-agents this agent can call via task tool.
224
+ * - undefined: Keep existing value
225
+ * - null/[]: Cannot use task tool
226
+ * - ["*"]: Can call all available agents
227
+ * - ["agent1", "agent2"]: Can only call specified agents
228
+ */
229
+ subagents?: string[] | null;
230
+ /**
231
+ * Whether this agent can be discovered via search_capability
232
+ * - undefined: Keep existing value
233
+ * - true/false: Set explicitly
234
+ */
235
+ searchable?: boolean;
236
+ }
237
+ interface SDKEvents {
238
+ connected: () => void;
239
+ disconnected: (reason: string) => void;
240
+ registered: () => void;
241
+ error: (error: Error) => void;
242
+ tool_call: (call: {
243
+ name: string;
244
+ arguments: Record<string, unknown>;
245
+ }) => void;
246
+ }
247
+ type SDKEventName = keyof SDKEvents;
248
+
249
+ /**
250
+ * Sanqian SDK Client - Browser Build
251
+ *
252
+ * This is a browser-optimized version of the SDK client that does NOT include
253
+ * DiscoveryManager or any Node.js APIs (fs, path, child_process, os).
254
+ *
255
+ * IMPORTANT: When using this build, you MUST provide connectionInfo in config.
256
+ * Auto-discovery and auto-launch features are not available in browser environments.
257
+ */
258
+
259
+ declare class SanqianSDK {
260
+ private config;
261
+ private ws;
262
+ private connectionInfo;
263
+ private state;
264
+ private toolHandlers;
265
+ private pendingRequests;
266
+ private heartbeatTimer;
267
+ private reconnectTimer;
268
+ private heartbeatAckPending;
269
+ private missedHeartbeats;
270
+ private static readonly MAX_MISSED_HEARTBEATS;
271
+ private connectingPromise;
272
+ private reconnectRefCount;
273
+ private eventListeners;
274
+ private log;
275
+ private warn;
276
+ constructor(config: SDKConfig);
277
+ /**
278
+ * Build WebSocket URL from connection info
279
+ */
280
+ private buildWebSocketUrl;
281
+ connect(): Promise<void>;
282
+ private connectWithInfo;
283
+ disconnect(): Promise<void>;
284
+ private register;
285
+ private handleMessage;
286
+ private handleChatStream;
287
+ private handleToolCall;
288
+ private sendToolResult;
289
+ private handleDisconnect;
290
+ private shouldAutoReconnect;
291
+ acquireReconnect(): void;
292
+ releaseReconnect(): void;
293
+ private scheduleReconnect;
294
+ private stopReconnect;
295
+ private startHeartbeat;
296
+ private stopHeartbeat;
297
+ private send;
298
+ private sendAndWait;
299
+ getState(): ConnectionState;
300
+ isConnected(): boolean;
301
+ ensureReady(): Promise<void>;
302
+ private doFullConnect;
303
+ updateTools(tools: ToolDefinition[]): Promise<void>;
304
+ createAgent(config: AgentConfig): Promise<AgentInfo>;
305
+ listAgents(): Promise<AgentInfo[]>;
306
+ deleteAgent(agentId: string): Promise<void>;
307
+ updateAgent(agentId: string, updates: Omit<AgentUpdateConfig, "agent_id">): Promise<AgentInfo>;
308
+ listConversations(options?: {
309
+ agentId?: string;
310
+ limit?: number;
311
+ offset?: number;
312
+ }): Promise<{
313
+ conversations: ConversationInfo[];
314
+ total: number;
315
+ }>;
316
+ getConversation(conversationId: string, options?: {
317
+ includeMessages?: boolean;
318
+ messageLimit?: number;
319
+ messageOffset?: number;
320
+ }): Promise<ConversationDetail>;
321
+ deleteConversation(conversationId: string): Promise<void>;
322
+ private streamHandlers;
323
+ chat(agentId: string, messages: ChatMessage[], options?: {
324
+ conversationId?: string;
325
+ remoteTools?: RemoteToolDefinition[];
326
+ }): Promise<ChatResponse>;
327
+ chatStream(agentId: string, messages: ChatMessage[], options?: {
328
+ conversationId?: string;
329
+ remoteTools?: RemoteToolDefinition[];
330
+ }): AsyncGenerator<ChatStreamEvent>;
331
+ startConversation(agentId: string): Conversation;
332
+ on<T extends SDKEventName>(event: T, listener: SDKEvents[T]): this;
333
+ off<T extends SDKEventName>(event: T, listener: SDKEvents[T]): this;
334
+ once<T extends SDKEventName>(event: T, listener: SDKEvents[T]): this;
335
+ /**
336
+ * Remove all event listeners
337
+ *
338
+ * Call this to prevent memory leaks when disposing the SDK instance.
339
+ * If event is specified, only removes listeners for that event.
340
+ */
341
+ removeAllListeners(event?: SDKEventName): this;
342
+ private emit;
343
+ private generateId;
344
+ private createTimeout;
345
+ }
346
+ /**
347
+ * Conversation helper for multi-turn chat
348
+ */
349
+ declare class Conversation {
350
+ private sdk;
351
+ private agentId;
352
+ private _conversationId;
353
+ constructor(sdk: SanqianSDK, agentId: string, conversationId?: string);
354
+ get id(): string | null;
355
+ send(content: string, options?: {
356
+ remoteTools?: RemoteToolDefinition[];
357
+ }): Promise<ChatResponse>;
358
+ sendStream(content: string, options?: {
359
+ remoteTools?: RemoteToolDefinition[];
360
+ }): AsyncGenerator<ChatStreamEvent>;
361
+ delete(): Promise<void>;
362
+ getDetails(options?: {
363
+ messageLimit?: number;
364
+ }): Promise<ConversationDetail>;
365
+ }
366
+
367
+ /**
368
+ * SDK Error Messages
369
+ *
370
+ * User-friendly error messages in English and Chinese.
371
+ * All errors guide users to sanqian.io for installation.
372
+ */
373
+ declare const SANQIAN_WEBSITE = "https://sanqian.io";
374
+ /**
375
+ * Error codes for SDK errors
376
+ */
377
+ declare enum SDKErrorCode {
378
+ NOT_INSTALLED = "NOT_INSTALLED",
379
+ NOT_RUNNING = "NOT_RUNNING",
380
+ CONNECTION_TIMEOUT = "CONNECTION_TIMEOUT",
381
+ STARTUP_TIMEOUT = "STARTUP_TIMEOUT",
382
+ REGISTRATION_FAILED = "REGISTRATION_FAILED",
383
+ REQUEST_TIMEOUT = "REQUEST_TIMEOUT",
384
+ REQUEST_FAILED = "REQUEST_FAILED",
385
+ DISCONNECTED = "DISCONNECTED",
386
+ WEBSOCKET_ERROR = "WEBSOCKET_ERROR",
387
+ AGENT_NOT_FOUND = "AGENT_NOT_FOUND",
388
+ CONVERSATION_NOT_FOUND = "CONVERSATION_NOT_FOUND",
389
+ TOOL_NOT_FOUND = "TOOL_NOT_FOUND",
390
+ TOOL_EXECUTION_TIMEOUT = "TOOL_EXECUTION_TIMEOUT"
391
+ }
392
+ /**
393
+ * Bilingual error messages
394
+ */
395
+ declare const ErrorMessages: Record<SDKErrorCode, {
396
+ en: string;
397
+ zh: string;
398
+ hint?: {
399
+ en: string;
400
+ zh: string;
401
+ };
402
+ }>;
403
+ /**
404
+ * Custom SDK Error with code and bilingual message
405
+ */
406
+ declare class SanqianSDKError extends Error {
407
+ code: SDKErrorCode;
408
+ messageZh: string;
409
+ hint?: string;
410
+ hintZh?: string;
411
+ constructor(code: SDKErrorCode, details?: string);
412
+ /**
413
+ * Get full error message with hint (English)
414
+ */
415
+ getFullMessage(): string;
416
+ /**
417
+ * Get full error message with hint (Chinese)
418
+ */
419
+ getFullMessageZh(): string;
420
+ /**
421
+ * Get bilingual error message
422
+ */
423
+ getBilingualMessage(): string;
424
+ }
425
+ /**
426
+ * Create a user-friendly SDK error
427
+ */
428
+ declare function createSDKError(code: SDKErrorCode, details?: string): SanqianSDKError;
429
+
430
+ export { type AgentConfig, type AgentInfo, type AgentUpdateConfig, type ChatMessage, type ChatRequest, type ChatResponse, type ChatStreamEvent, type ConnectionInfo, type ConnectionState, Conversation, type ConversationDetail, type ConversationInfo, type ConversationMessage, ErrorMessages, type JSONSchema, type JSONSchemaProperty, type RemoteToolDefinition, SANQIAN_WEBSITE, type SDKConfig, SDKErrorCode, type SDKEventName, type SDKEvents, SanqianSDK, SanqianSDKError, type ToolCall, type ToolDefinition, createSDKError };