@witqq/agent-sdk 0.7.0 → 0.9.0

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.
Files changed (154) hide show
  1. package/dist/{types-CqvUAYxt.d.ts → agent-C6H2CgJA.d.cts} +139 -102
  2. package/dist/{types-CqvUAYxt.d.cts → agent-F7oB6eKp.d.ts} +139 -102
  3. package/dist/auth/index.cjs +72 -1
  4. package/dist/auth/index.cjs.map +1 -1
  5. package/dist/auth/index.d.cts +21 -154
  6. package/dist/auth/index.d.ts +21 -154
  7. package/dist/auth/index.js +72 -1
  8. package/dist/auth/index.js.map +1 -1
  9. package/dist/backends/claude.cjs +480 -261
  10. package/dist/backends/claude.cjs.map +1 -1
  11. package/dist/backends/claude.d.cts +3 -1
  12. package/dist/backends/claude.d.ts +3 -1
  13. package/dist/backends/claude.js +480 -261
  14. package/dist/backends/claude.js.map +1 -1
  15. package/dist/backends/copilot.cjs +337 -112
  16. package/dist/backends/copilot.cjs.map +1 -1
  17. package/dist/backends/copilot.d.cts +12 -4
  18. package/dist/backends/copilot.d.ts +12 -4
  19. package/dist/backends/copilot.js +337 -112
  20. package/dist/backends/copilot.js.map +1 -1
  21. package/dist/backends/mock-llm.cjs +719 -0
  22. package/dist/backends/mock-llm.cjs.map +1 -0
  23. package/dist/backends/mock-llm.d.cts +37 -0
  24. package/dist/backends/mock-llm.d.ts +37 -0
  25. package/dist/backends/mock-llm.js +717 -0
  26. package/dist/backends/mock-llm.js.map +1 -0
  27. package/dist/backends/vercel-ai.cjs +301 -61
  28. package/dist/backends/vercel-ai.cjs.map +1 -1
  29. package/dist/backends/vercel-ai.d.cts +3 -1
  30. package/dist/backends/vercel-ai.d.ts +3 -1
  31. package/dist/backends/vercel-ai.js +301 -61
  32. package/dist/backends/vercel-ai.js.map +1 -1
  33. package/dist/backends-Cno0gZjy.d.cts +114 -0
  34. package/dist/backends-Cno0gZjy.d.ts +114 -0
  35. package/dist/chat/accumulator.cjs +1 -1
  36. package/dist/chat/accumulator.cjs.map +1 -1
  37. package/dist/chat/accumulator.d.cts +5 -2
  38. package/dist/chat/accumulator.d.ts +5 -2
  39. package/dist/chat/accumulator.js +1 -1
  40. package/dist/chat/accumulator.js.map +1 -1
  41. package/dist/chat/backends.cjs +1084 -821
  42. package/dist/chat/backends.cjs.map +1 -1
  43. package/dist/chat/backends.d.cts +10 -6
  44. package/dist/chat/backends.d.ts +10 -6
  45. package/dist/chat/backends.js +1082 -800
  46. package/dist/chat/backends.js.map +1 -1
  47. package/dist/chat/context.cjs +50 -0
  48. package/dist/chat/context.cjs.map +1 -1
  49. package/dist/chat/context.d.cts +27 -3
  50. package/dist/chat/context.d.ts +27 -3
  51. package/dist/chat/context.js +50 -0
  52. package/dist/chat/context.js.map +1 -1
  53. package/dist/chat/core.cjs +60 -27
  54. package/dist/chat/core.cjs.map +1 -1
  55. package/dist/chat/core.d.cts +41 -382
  56. package/dist/chat/core.d.ts +41 -382
  57. package/dist/chat/core.js +58 -28
  58. package/dist/chat/core.js.map +1 -1
  59. package/dist/chat/errors.cjs +48 -26
  60. package/dist/chat/errors.cjs.map +1 -1
  61. package/dist/chat/errors.d.cts +6 -31
  62. package/dist/chat/errors.d.ts +6 -31
  63. package/dist/chat/errors.js +48 -25
  64. package/dist/chat/errors.js.map +1 -1
  65. package/dist/chat/events.cjs.map +1 -1
  66. package/dist/chat/events.d.cts +6 -2
  67. package/dist/chat/events.d.ts +6 -2
  68. package/dist/chat/events.js.map +1 -1
  69. package/dist/chat/index.cjs +1612 -1125
  70. package/dist/chat/index.cjs.map +1 -1
  71. package/dist/chat/index.d.cts +35 -10
  72. package/dist/chat/index.d.ts +35 -10
  73. package/dist/chat/index.js +1600 -1097
  74. package/dist/chat/index.js.map +1 -1
  75. package/dist/chat/react/theme.css +2517 -0
  76. package/dist/chat/react.cjs +2212 -1158
  77. package/dist/chat/react.cjs.map +1 -1
  78. package/dist/chat/react.d.cts +665 -122
  79. package/dist/chat/react.d.ts +665 -122
  80. package/dist/chat/react.js +2191 -1156
  81. package/dist/chat/react.js.map +1 -1
  82. package/dist/chat/runtime.cjs +405 -186
  83. package/dist/chat/runtime.cjs.map +1 -1
  84. package/dist/chat/runtime.d.cts +92 -28
  85. package/dist/chat/runtime.d.ts +92 -28
  86. package/dist/chat/runtime.js +405 -186
  87. package/dist/chat/runtime.js.map +1 -1
  88. package/dist/chat/server.cjs +2247 -212
  89. package/dist/chat/server.cjs.map +1 -1
  90. package/dist/chat/server.d.cts +451 -90
  91. package/dist/chat/server.d.ts +451 -90
  92. package/dist/chat/server.js +2234 -213
  93. package/dist/chat/server.js.map +1 -1
  94. package/dist/chat/sessions.cjs +64 -66
  95. package/dist/chat/sessions.cjs.map +1 -1
  96. package/dist/chat/sessions.d.cts +37 -118
  97. package/dist/chat/sessions.d.ts +37 -118
  98. package/dist/chat/sessions.js +65 -67
  99. package/dist/chat/sessions.js.map +1 -1
  100. package/dist/chat/sqlite.cjs +536 -0
  101. package/dist/chat/sqlite.cjs.map +1 -0
  102. package/dist/chat/sqlite.d.cts +164 -0
  103. package/dist/chat/sqlite.d.ts +164 -0
  104. package/dist/chat/sqlite.js +527 -0
  105. package/dist/chat/sqlite.js.map +1 -0
  106. package/dist/chat/state.cjs +14 -1
  107. package/dist/chat/state.cjs.map +1 -1
  108. package/dist/chat/state.d.cts +5 -2
  109. package/dist/chat/state.d.ts +5 -2
  110. package/dist/chat/state.js +14 -1
  111. package/dist/chat/state.js.map +1 -1
  112. package/dist/chat/storage.cjs +58 -33
  113. package/dist/chat/storage.cjs.map +1 -1
  114. package/dist/chat/storage.d.cts +18 -8
  115. package/dist/chat/storage.d.ts +18 -8
  116. package/dist/chat/storage.js +59 -34
  117. package/dist/chat/storage.js.map +1 -1
  118. package/dist/errors-C-so0M4t.d.cts +33 -0
  119. package/dist/errors-C-so0M4t.d.ts +33 -0
  120. package/dist/errors-CmVvczxZ.d.cts +28 -0
  121. package/dist/errors-CmVvczxZ.d.ts +28 -0
  122. package/dist/{in-process-transport-C2oPTYs6.d.ts → in-process-transport-7EIit9Xk.d.ts} +72 -33
  123. package/dist/{in-process-transport-DG-w5G6k.d.cts → in-process-transport-Ct9YcX8I.d.cts} +72 -33
  124. package/dist/index.cjs +354 -60
  125. package/dist/index.cjs.map +1 -1
  126. package/dist/index.d.cts +294 -123
  127. package/dist/index.d.ts +294 -123
  128. package/dist/index.js +347 -60
  129. package/dist/index.js.map +1 -1
  130. package/dist/provider-types-PTSlRPNB.d.cts +39 -0
  131. package/dist/provider-types-PTSlRPNB.d.ts +39 -0
  132. package/dist/refresh-manager-B81PpYBr.d.cts +153 -0
  133. package/dist/refresh-manager-Dlv_iNZi.d.ts +153 -0
  134. package/dist/testing.cjs +1107 -0
  135. package/dist/testing.cjs.map +1 -0
  136. package/dist/testing.d.cts +144 -0
  137. package/dist/testing.d.ts +144 -0
  138. package/dist/testing.js +1101 -0
  139. package/dist/testing.js.map +1 -0
  140. package/dist/token-store-CSUBgYwn.d.ts +48 -0
  141. package/dist/token-store-CuC4hB9Z.d.cts +48 -0
  142. package/dist/{transport-DX1Nhm4N.d.cts → transport-DLWCN18G.d.cts} +5 -4
  143. package/dist/{transport-D1OaUgRk.d.ts → transport-DsuS-GeM.d.ts} +5 -4
  144. package/dist/{types-CGF7AEX1.d.cts → types-4vbcmPTp.d.cts} +4 -2
  145. package/dist/{types-Bh5AhqD-.d.ts → types-BxggH0Yh.d.ts} +4 -2
  146. package/dist/types-DgtI1hzh.d.ts +364 -0
  147. package/dist/types-DkSXALKg.d.cts +364 -0
  148. package/package.json +41 -5
  149. package/LICENSE +0 -21
  150. package/README.md +0 -948
  151. package/dist/errors-BDLbNu9w.d.cts +0 -13
  152. package/dist/errors-BDLbNu9w.d.ts +0 -13
  153. package/dist/types-DLZzlJxt.d.ts +0 -39
  154. package/dist/types-tE0CXwBl.d.cts +0 -39
package/dist/index.d.cts CHANGED
@@ -1,75 +1,10 @@
1
1
  import { z } from 'zod';
2
2
 
3
- /** Pluggable store for persisting permission (scope) decisions across runs. */
4
- interface IPermissionStore {
5
- /** Check if tool is already approved */
6
- isApproved(toolName: string): Promise<boolean>;
7
- /** Store an approval decision */
8
- approve(toolName: string, scope: PermissionScope): Promise<void>;
9
- /** Revoke approval for a tool */
10
- revoke(toolName: string): Promise<void>;
11
- /** Clear all approvals */
12
- clear(): Promise<void>;
13
- /** Dispose resources */
14
- dispose(): Promise<void>;
15
- }
16
- /** In-memory store — approvals live until process exits (or dispose). */
17
- declare class InMemoryPermissionStore implements IPermissionStore {
18
- private approvals;
19
- isApproved(toolName: string): Promise<boolean>;
20
- approve(toolName: string, scope: PermissionScope): Promise<void>;
21
- revoke(toolName: string): Promise<void>;
22
- clear(): Promise<void>;
23
- dispose(): Promise<void>;
24
- }
25
- /** File-backed store — reads/writes a JSON file for persistent approvals. */
26
- declare class FilePermissionStore implements IPermissionStore {
27
- private readonly filePath;
28
- constructor(filePath: string);
29
- isApproved(toolName: string): Promise<boolean>;
30
- approve(toolName: string, scope: PermissionScope): Promise<void>;
31
- revoke(toolName: string): Promise<void>;
32
- clear(): Promise<void>;
33
- dispose(): Promise<void>;
34
- private readFile;
35
- private writeFileAtomic;
36
- }
37
- /**
38
- * Composes multiple stores — checks in order, routes writes by scope.
39
- *
40
- * - "session" → sessionStore (in-memory)
41
- * - "project" → projectStore (file-based in project directory)
42
- * - "always" → userStore (file-based in user home)
43
- */
44
- declare class CompositePermissionStore implements IPermissionStore {
45
- private readonly sessionStore;
46
- private readonly projectStore;
47
- private readonly userStore;
48
- constructor(sessionStore: IPermissionStore, projectStore: IPermissionStore, userStore?: IPermissionStore);
49
- isApproved(toolName: string): Promise<boolean>;
50
- approve(toolName: string, scope: PermissionScope): Promise<void>;
51
- revoke(toolName: string): Promise<void>;
52
- clear(): Promise<void>;
53
- dispose(): Promise<void>;
54
- }
55
- /** Create a default composite store with separate project and user-level persistence. */
56
- declare function createDefaultPermissionStore(projectDir?: string): CompositePermissionStore;
57
-
58
3
  /** JSON-serializable value used for tool arguments and results */
59
4
  type JSONValue = string | number | boolean | null | JSONValue[] | {
60
5
  [key: string]: JSONValue;
61
6
  };
62
- /** Message content — plain string or array of text/image parts */
63
- type MessageContent = string | Array<ContentPart>;
64
- /** Individual content part within a multi-part message */
65
- type ContentPart = {
66
- type: "text";
67
- text: string;
68
- } | {
69
- type: "image";
70
- data: string;
71
- mimeType: string;
72
- };
7
+
73
8
  /** What the LLM sees — name, description, schema. Passed to all backends. */
74
9
  interface ToolDeclaration<TParams = unknown> {
75
10
  name: string;
@@ -87,7 +22,7 @@ interface ToolDeclaration<TParams = unknown> {
87
22
  * The optional second parameter receives request-scoped context
88
23
  * when invoked through ChatRuntime (session ID, user data, custom metadata). */
89
24
  interface ToolDefinition<TParams = unknown> extends ToolDeclaration<TParams> {
90
- execute: (params: TParams, context?: ToolContext) => Promise<JSONValue> | JSONValue;
25
+ execute: (params: TParams, context?: ToolContext) => Promise<unknown> | unknown;
91
26
  }
92
27
  /** Request-scoped context passed to tool execute functions via ChatRuntime.
93
28
  * Contains session identity and user-defined metadata from the current session. */
@@ -110,6 +45,18 @@ interface ToolResult {
110
45
  result: JSONValue;
111
46
  isError?: boolean;
112
47
  }
48
+
49
+ /** Message content — plain string or array of text/image parts */
50
+ type MessageContent = string | Array<ContentPart>;
51
+ /** Individual content part within a multi-part message */
52
+ type ContentPart = {
53
+ type: "text";
54
+ text: string;
55
+ } | {
56
+ type: "image";
57
+ data: string;
58
+ mimeType: string;
59
+ };
113
60
  /** Conversation message — discriminated union on `role` */
114
61
  type Message = {
115
62
  role: "user";
@@ -118,6 +65,7 @@ type Message = {
118
65
  role: "assistant";
119
66
  content: MessageContent;
120
67
  toolCalls?: ToolCall[];
68
+ thinking?: string;
121
69
  } | {
122
70
  role: "tool";
123
71
  content?: string;
@@ -126,12 +74,15 @@ type Message = {
126
74
  role: "system";
127
75
  content: string;
128
76
  };
77
+
129
78
  /** Scope for "remember this decision" */
130
79
  type PermissionScope = "once" | "session" | "project" | "always";
131
80
  /** What the permission callback receives */
132
81
  interface PermissionRequest {
133
82
  toolName: string;
134
83
  toolArgs: Record<string, unknown>;
84
+ /** Unique identifier for this specific tool call */
85
+ toolCallId?: string;
135
86
  /** SDK-suggested scope (from Claude CLI's suggestions) */
136
87
  suggestedScope?: PermissionScope;
137
88
  /** Original SDK permission request (for pass-through) */
@@ -169,12 +120,68 @@ interface SupervisorHooks {
169
120
  onPermission?: PermissionCallback;
170
121
  onAskUser?: (request: UserInputRequest, signal: AbortSignal) => Promise<UserInputResponse>;
171
122
  }
172
- /** Configuration for typed structured output from LLM */
173
- interface StructuredOutputConfig<T = unknown> {
174
- schema: z.ZodType<T>;
123
+
124
+ /** Model metadata returned by listModels() */
125
+ interface ModelInfo {
126
+ id: string;
175
127
  name?: string;
176
- description?: string;
128
+ provider?: string;
129
+ /** Model tier for UI categorization and cost hints */
130
+ tier?: "fast" | "standard" | "premium";
131
+ /** Context window size in tokens */
132
+ contextWindow?: number;
133
+ /** Model capabilities (e.g. "vision", "tools", "structured") */
134
+ capabilities?: string[];
135
+ }
136
+ /** LLM model parameters */
137
+ interface ModelParams {
138
+ temperature?: number;
139
+ maxTokens?: number;
140
+ topP?: number;
141
+ stopSequences?: string[];
142
+ }
143
+ /** Result of backend validation check */
144
+ interface ValidationResult {
145
+ valid: boolean;
146
+ errors: string[];
177
147
  }
148
+
149
+ /** Unified error codes for all SDK errors — single source of truth. */
150
+ declare enum ErrorCode {
151
+ AUTH_EXPIRED = "AUTH_EXPIRED",
152
+ AUTH_INVALID = "AUTH_INVALID",
153
+ RATE_LIMIT = "RATE_LIMIT",
154
+ NETWORK = "NETWORK",
155
+ TIMEOUT = "TIMEOUT",
156
+ PROVIDER_ERROR = "PROVIDER_ERROR",
157
+ MODEL_NOT_FOUND = "MODEL_NOT_FOUND",
158
+ MODEL_OVERLOADED = "MODEL_OVERLOADED",
159
+ CONTEXT_OVERFLOW = "CONTEXT_OVERFLOW",
160
+ INVALID_INPUT = "INVALID_INPUT",
161
+ INVALID_RESPONSE = "INVALID_RESPONSE",
162
+ REENTRANCY = "REENTRANCY",
163
+ DISPOSED = "DISPOSED",
164
+ ABORTED = "ABORTED",
165
+ INVALID_TRANSITION = "INVALID_TRANSITION",
166
+ DEPENDENCY_MISSING = "DEPENDENCY_MISSING",
167
+ BACKEND_NOT_INSTALLED = "BACKEND_NOT_INSTALLED",
168
+ TOOL_EXECUTION = "TOOL_EXECUTION",
169
+ PERMISSION_DENIED = "PERMISSION_DENIED",
170
+ SESSION_NOT_FOUND = "SESSION_NOT_FOUND",
171
+ SESSION_EXPIRED = "SESSION_EXPIRED",
172
+ PROVIDER_NOT_FOUND = "PROVIDER_NOT_FOUND",
173
+ AUTH_REQUIRED = "AUTH_REQUIRED",
174
+ STORAGE_ERROR = "STORAGE_ERROR",
175
+ STORAGE_NOT_FOUND = "STORAGE_NOT_FOUND",
176
+ STORAGE_DUPLICATE_KEY = "STORAGE_DUPLICATE_KEY",
177
+ STORAGE_IO_ERROR = "STORAGE_IO_ERROR",
178
+ STORAGE_SERIALIZATION_ERROR = "STORAGE_SERIALIZATION_ERROR"
179
+ }
180
+ /** Check if an error code is recoverable */
181
+ declare function isRecoverableErrorCode(code: ErrorCode): boolean;
182
+ /** Classify an error message string into an ErrorCode */
183
+ declare function classifyAgentError(error: string | Error): ErrorCode;
184
+
178
185
  /** Usage data from LLM execution — tokens consumed plus optional metadata */
179
186
  interface UsageData {
180
187
  promptTokens: number;
@@ -233,24 +240,131 @@ type AgentEvent = {
233
240
  type: "error";
234
241
  error: string;
235
242
  recoverable: boolean;
243
+ code?: ErrorCode;
236
244
  } | {
237
245
  type: "done";
238
246
  finalOutput: string | null;
239
247
  structuredOutput?: unknown;
248
+ streamed?: boolean;
249
+ finishReason?: string;
240
250
  };
241
- /** Options passed to agent.run() / agent.stream() */
242
- interface RunOptions {
243
- /** AbortSignal for cancellation */
251
+ /** Context passed to stream middleware — immutable per stream invocation */
252
+ interface StreamContext {
253
+ model: string;
254
+ backend: string;
255
+ abortController: AbortController;
256
+ /** Agent config snapshot. Loosely typed to avoid leaking internal FullAgentConfig to external middleware consumers. */
257
+ config: Readonly<Record<string, unknown>>;
258
+ }
259
+ /** A composable transform over the agent event stream.
260
+ * Receives the upstream source and context, returns a transformed stream. */
261
+ type StreamMiddleware = (source: AsyncIterable<AgentEvent>, context: StreamContext) => AsyncIterable<AgentEvent>;
262
+
263
+ /** Pluggable store for persisting permission (scope) decisions across runs. */
264
+ interface IPermissionStore {
265
+ /** Check if tool is already approved */
266
+ isApproved(toolName: string): Promise<boolean>;
267
+ /** Store an approval decision */
268
+ approve(toolName: string, scope: PermissionScope): Promise<void>;
269
+ /** Revoke approval for a tool */
270
+ revoke(toolName: string): Promise<void>;
271
+ /** Clear all approvals */
272
+ clear(): Promise<void>;
273
+ /** Dispose resources */
274
+ dispose(): Promise<void>;
275
+ }
276
+ /** In-memory store — approvals live until process exits (or dispose). */
277
+ declare class InMemoryPermissionStore implements IPermissionStore {
278
+ private approvals;
279
+ isApproved(toolName: string): Promise<boolean>;
280
+ approve(toolName: string, scope: PermissionScope): Promise<void>;
281
+ revoke(toolName: string): Promise<void>;
282
+ clear(): Promise<void>;
283
+ dispose(): Promise<void>;
284
+ }
285
+ /** File-backed store — reads/writes a JSON file for persistent approvals. */
286
+ declare class FilePermissionStore implements IPermissionStore {
287
+ private readonly filePath;
288
+ constructor(filePath: string);
289
+ isApproved(toolName: string): Promise<boolean>;
290
+ approve(toolName: string, scope: PermissionScope): Promise<void>;
291
+ revoke(toolName: string): Promise<void>;
292
+ clear(): Promise<void>;
293
+ dispose(): Promise<void>;
294
+ private readStore;
295
+ private writeStoreAtomic;
296
+ }
297
+ /**
298
+ * Composes multiple stores — checks in order, routes writes by scope.
299
+ *
300
+ * - "session" → sessionStore (in-memory)
301
+ * - "project" → projectStore (file-based in project directory)
302
+ * - "always" → userStore (file-based in user home)
303
+ */
304
+ declare class CompositePermissionStore implements IPermissionStore {
305
+ private readonly sessionStore;
306
+ private readonly projectStore;
307
+ private readonly userStore;
308
+ constructor(sessionStore: IPermissionStore, projectStore: IPermissionStore, userStore?: IPermissionStore);
309
+ isApproved(toolName: string): Promise<boolean>;
310
+ approve(toolName: string, scope: PermissionScope): Promise<void>;
311
+ revoke(toolName: string): Promise<void>;
312
+ clear(): Promise<void>;
313
+ dispose(): Promise<void>;
314
+ }
315
+ /** Create a default composite store with separate project and user-level persistence. */
316
+ declare function createDefaultPermissionStore(projectDir?: string): CompositePermissionStore;
317
+
318
+ /** Per-call overrides passed to run(), stream(), runStructured().
319
+ * Allows overriding the model, tools, signal, and other parameters
320
+ * on a per-request basis without modifying the agent configuration. */
321
+ interface CallOptions {
322
+ /** Override the default model for this call */
323
+ model?: string;
324
+ /** Override/extend tools for this call */
325
+ tools?: ToolDefinition[];
326
+ /** Per-call abort signal */
244
327
  signal?: AbortSignal;
328
+ /** Override system message for this call */
329
+ systemMessage?: string;
330
+ /** Provider-specific options passed through to the underlying SDK */
331
+ providerOptions?: Record<string, unknown>;
332
+ /** Per-call timeout in milliseconds */
333
+ timeout?: number;
334
+ /** Per-call token limit */
335
+ maxTokens?: number;
336
+ /** Retry configuration for this call */
337
+ retry?: RetryConfig;
338
+ }
339
+ /** Configuration for automatic retries on transient errors */
340
+ interface RetryConfig {
341
+ /** Maximum number of retries (default: 0 — no retry) */
342
+ maxRetries?: number;
343
+ /** Initial delay in ms before first retry (default: 1000) */
344
+ initialDelayMs?: number;
345
+ /** Backoff multiplier (default: 2) */
346
+ backoffMultiplier?: number;
347
+ /** Which error codes to retry (default: all recoverable codes) */
348
+ retryableErrors?: ErrorCode[];
349
+ }
350
+ /** Configuration for typed structured output from LLM */
351
+ interface StructuredOutputConfig<T = unknown> {
352
+ schema: z.ZodType<T>;
353
+ name?: string;
354
+ description?: string;
355
+ }
356
+ /** Options passed to agent.run() / agent.stream().
357
+ * Extends CallOptions with run-specific fields (context, activityTimeoutMs).
358
+ * model is REQUIRED — every agent call must specify the model explicitly. */
359
+ interface RunOptions extends CallOptions {
360
+ /** Model to use for this call (required — no implicit defaults) */
361
+ model: string;
245
362
  /** Arbitrary context passed to the agent run */
246
363
  context?: Record<string, unknown>;
247
- }
248
- /** LLM model parameters */
249
- interface ModelParams {
250
- temperature?: number;
251
- maxTokens?: number;
252
- topP?: number;
253
- stopSequences?: string[];
364
+ /** Inactivity timeout for streaming (ms). When set, the stream aborts if no
365
+ * event (including heartbeats/progress) arrives within this period. Resets on
366
+ * every received event. Default: no timeout. Only affects stream()/streamWithContext(). */
367
+ activityTimeoutMs?: number;
254
368
  }
255
369
  /** Timeout configuration for agent operations */
256
370
  interface TimeoutConfig {
@@ -275,12 +389,10 @@ interface ErrorHandlingConfig {
275
389
  phase: "tool" | "llm" | "permission" | "ask-user";
276
390
  }) => void;
277
391
  }
278
- /** Configuration for creating an agent */
392
+ /** Identity-only agent configuration defines the agent's behavior, NOT per-call defaults.
393
+ * For creating an agent with model/tools defaults, use FullAgentConfig. */
279
394
  interface AgentConfig {
280
- model?: string;
281
- modelParams?: ModelParams;
282
395
  systemPrompt: string;
283
- tools: ToolDefinition[];
284
396
  supervisor?: SupervisorHooks;
285
397
  maxTurns?: number;
286
398
  timeout?: TimeoutConfig;
@@ -290,8 +402,14 @@ interface AgentConfig {
290
402
  /** How to apply systemPrompt: "append" adds to backend default, "replace" overrides it.
291
403
  * Default: "append". Currently used by the Copilot backend. */
292
404
  systemMessageMode?: "append" | "replace";
293
- /** Filter for backend built-in tools (e.g. ["web_search", "web_fetch"] for Copilot).
294
- * When set, only listed built-in tools are available. Backend-specific. */
405
+ /**
406
+ * Filter for backend built-in tools (e.g. `["web_search", "web_fetch"]` for Copilot).
407
+ * When set, only listed built-in tools are available. Backend-specific.
408
+ *
409
+ * **Security note**: This is a trust boundary — it controls which backend-native tools
410
+ * the AI agent can invoke. By default, backends expose ALL their built-in tools.
411
+ * Set this to restrict access (e.g. prevent file system access in a web-facing agent).
412
+ */
295
413
  availableTools?: string[];
296
414
  /** Callback invoked with usage data after run completion or during streaming.
297
415
  * Fire-and-forget: errors are logged but not propagated. */
@@ -305,11 +423,24 @@ interface AgentConfig {
305
423
  * "persistent": reuses the same CLI session across calls, preserving conversation
306
424
  * history natively in the CLI backend. Session is destroyed on agent dispose(). */
307
425
  sessionMode?: "per-call" | "persistent";
426
+ }
427
+ /** Per-call defaults that can be provided at agent creation time.
428
+ * Each field can also be overridden on individual calls via RunOptions. */
429
+ interface CallDefaults {
430
+ /** Default model (overridable per-call via RunOptions.model) */
431
+ model?: string;
432
+ /** Default model parameters */
433
+ modelParams?: ModelParams;
434
+ /** Default tools (overridable per-call via RunOptions.tools) */
435
+ tools?: ToolDefinition[];
308
436
  /** Provider-specific options passed through to the underlying SDK.
309
437
  * For Vercel AI: passed as providerOptions to generateText/streamText.
310
438
  * Example: { google: { thinkingConfig: { thinkingBudget: 1024 } } } */
311
439
  providerOptions?: Record<string, Record<string, unknown>>;
312
440
  }
441
+ /** Full agent configuration: identity + per-call defaults.
442
+ * This is what createAgent() accepts. Backward-compatible with the old AgentConfig shape. */
443
+ type FullAgentConfig = AgentConfig & CallDefaults;
313
444
  /** Result of an agent run, generic over structured output type T */
314
445
  interface AgentResult<T = void> {
315
446
  output: string | null;
@@ -331,15 +462,15 @@ interface IAgent {
331
462
  * or before the first call. Can be stored externally for session resume. */
332
463
  readonly sessionId: string | undefined;
333
464
  /** Run a single prompt and return the result. Wraps prompt in a user message. */
334
- run(prompt: MessageContent, options?: RunOptions): Promise<AgentResult>;
465
+ run(prompt: MessageContent, options: RunOptions): Promise<AgentResult>;
335
466
  /** Run with full conversation history. Messages are passed directly to the backend. */
336
- runWithContext(messages: Message[], options?: RunOptions): Promise<AgentResult>;
467
+ runWithContext(messages: Message[], options: RunOptions): Promise<AgentResult>;
337
468
  /** Run with structured output validated against a Zod schema. */
338
- runStructured<T>(prompt: MessageContent, schema: StructuredOutputConfig<T>, options?: RunOptions): Promise<AgentResult<T>>;
469
+ runStructured<T>(prompt: MessageContent, schema: StructuredOutputConfig<T>, options: RunOptions): Promise<AgentResult<T>>;
339
470
  /** Stream events for a single prompt. Wraps prompt in a user message. */
340
- stream(prompt: MessageContent, options?: RunOptions): AsyncIterable<AgentEvent>;
471
+ stream(prompt: MessageContent, options: RunOptions): AsyncIterable<AgentEvent>;
341
472
  /** Stream events with full conversation history. Messages are passed directly to the backend. */
342
- streamWithContext(messages: Message[], options?: RunOptions): AsyncIterable<AgentEvent>;
473
+ streamWithContext(messages: Message[], options: RunOptions): AsyncIterable<AgentEvent>;
343
474
  /** Abort the current operation. No-op if not running. */
344
475
  abort(): void;
345
476
  /** Gracefully interrupt the current operation. Resolves when the backend acknowledges. */
@@ -347,29 +478,19 @@ interface IAgent {
347
478
  /** Get current agent lifecycle state. */
348
479
  getState(): AgentState;
349
480
  /** Get frozen agent configuration. */
350
- getConfig(): Readonly<AgentConfig>;
481
+ getConfig(): Readonly<FullAgentConfig>;
351
482
  /** Release resources. After dispose(), agent must not be used. */
352
483
  dispose(): void;
353
484
  }
354
- /** Model metadata returned by listModels() */
355
- interface ModelInfo {
356
- id: string;
357
- name?: string;
358
- provider?: string;
359
- }
360
- /** Result of backend validation check */
361
- interface ValidationResult {
362
- valid: boolean;
363
- errors: string[];
364
- }
365
485
  /** Backend service interface — creates agents, lists models, validates config */
366
486
  interface IAgentService {
367
487
  readonly name: string;
368
- createAgent(config: AgentConfig): IAgent;
488
+ createAgent(config: FullAgentConfig): IAgent;
369
489
  listModels(): Promise<ModelInfo[]>;
370
490
  validate(): Promise<ValidationResult>;
371
491
  dispose(): Promise<void>;
372
492
  }
493
+
373
494
  /** Options for Copilot CLI backend */
374
495
  interface CopilotBackendOptions {
375
496
  cliPath?: string;
@@ -407,6 +528,7 @@ interface VercelAIBackendOptions {
407
528
  provider?: string;
408
529
  baseUrl?: string;
409
530
  }
531
+
410
532
  /** Type guard: checks if a ToolDeclaration has an execute function (i.e., is a ToolDefinition) */
411
533
  declare function isToolDefinition(tool: ToolDeclaration): tool is ToolDefinition;
412
534
  /** Type guard: checks if MessageContent is plain string */
@@ -416,6 +538,15 @@ declare function isMultiPartContent(content: MessageContent): content is Content
416
538
  /** Extract text from MessageContent regardless of format */
417
539
  declare function getTextContent(content: MessageContent): string;
418
540
 
541
+ /** Options for constructing an AgentSDKError */
542
+ interface AgentSDKErrorOptions extends ErrorOptions {
543
+ /** Machine-readable error code */
544
+ code?: string;
545
+ /** Whether this error is retryable (default: false) */
546
+ retryable?: boolean;
547
+ /** HTTP status code hint (e.g. 401, 429, 500) */
548
+ httpStatus?: number;
549
+ }
419
550
  /** Base error class for agent-sdk.
420
551
  *
421
552
  * Use `AgentSDKError.is(err)` for reliable cross-module `instanceof` checks
@@ -423,7 +554,13 @@ declare function getTextContent(content: MessageContent): string;
423
554
  declare class AgentSDKError extends Error {
424
555
  /** @internal Marker for cross-bundle identity checks */
425
556
  readonly _agentSDKError: true;
426
- constructor(message: string, options?: ErrorOptions);
557
+ /** Machine-readable error code. Prefer values from the ErrorCode enum. */
558
+ readonly code?: string;
559
+ /** Whether this error is safe to retry */
560
+ readonly retryable: boolean;
561
+ /** HTTP status code hint for error classification */
562
+ readonly httpStatus?: number;
563
+ constructor(message: string, options?: AgentSDKErrorOptions);
427
564
  /** Check if an error is an AgentSDKError (works across bundled copies) */
428
565
  static is(error: unknown): error is AgentSDKError;
429
566
  }
@@ -461,6 +598,10 @@ declare class ToolExecutionError extends AgentSDKError {
461
598
  readonly toolName: string;
462
599
  constructor(toolName: string, message: string, options?: ErrorOptions);
463
600
  }
601
+ /** Thrown when a stream has no activity within the configured timeout */
602
+ declare class ActivityTimeoutError extends AgentSDKError {
603
+ constructor(timeoutMs: number);
604
+ }
464
605
  /** Thrown when structured output parsing fails */
465
606
  declare class StructuredOutputError extends AgentSDKError {
466
607
  constructor(message: string, options?: ErrorOptions);
@@ -480,46 +621,73 @@ type BuiltinBackendName = keyof BackendOptionsMap;
480
621
  declare function registerBackend<TOptions = unknown>(name: string, factory: BackendFactory<TOptions>): void;
481
622
  /** Unregister a backend (primarily for testing) */
482
623
  declare function unregisterBackend(name: string): boolean;
483
- /** Check if a backend is registered */
624
+ /** Check if a backend is registered (eagerly or lazily) */
484
625
  declare function hasBackend(name: string): boolean;
485
- /** List all registered backend names */
626
+ /** List all registered backend names (eager + lazy) */
486
627
  declare function listBackends(): string[];
487
628
  /** Reset registry to initial state (for testing) */
488
629
  declare function resetRegistry(): void;
489
- /** Create a backend service with type-safe options */
490
- declare function createAgentService<K extends BuiltinBackendName>(name: K, options: BackendOptionsMap[K]): Promise<IAgentService>;
491
- declare function createAgentService(name: string, options: unknown): Promise<IAgentService>;
630
+ /** Dispose all cached service instances for a backend, or a single named config.
631
+ * Returns the number of instances disposed. */
632
+ declare function disposeBackend(name: string, configId?: string): Promise<number>;
633
+ /** List all active config IDs for a backend */
634
+ declare function listConfigs(name: string): string[];
635
+ /**
636
+ * Register a lazy-loaded backend. The loader is called once on first use,
637
+ * then the resulting factory is cached in the main registry.
638
+ * Use this for backends that have heavy dependencies (peer deps, native modules).
639
+ */
640
+ declare function registerLazyBackend(name: string, loader: () => Promise<BackendFactory>): void;
641
+ /** Create a backend service with type-safe options.
642
+ * When `configId` is provided, the service instance is cached and reused
643
+ * on subsequent calls with the same name+configId pair. Without configId,
644
+ * a new instance is created every call. */
645
+ declare function createAgentService<K extends BuiltinBackendName>(name: K, options: BackendOptionsMap[K], configId?: string): Promise<IAgentService>;
646
+ declare function createAgentService(name: string, options: unknown, configId?: string): Promise<IAgentService>;
492
647
 
493
648
  /** Abstract base agent with shared lifecycle logic.
494
649
  * Concrete backends extend this and implement the protected _run/_stream methods. */
495
650
  declare abstract class BaseAgent implements IAgent {
496
651
  protected state: AgentState;
497
652
  protected abortController: AbortController | null;
498
- protected readonly config: AgentConfig;
653
+ protected readonly config: FullAgentConfig;
499
654
  private _cleanupExternalSignal;
655
+ private _streamMiddleware;
500
656
  /** Backend identifier (e.g. "copilot", "claude", "vercel-ai") */
501
657
  protected abstract readonly backendName: string;
502
658
  /** CLI session ID for persistent mode. Override in backends that support it. */
503
659
  get sessionId(): string | undefined;
504
- constructor(config: AgentConfig);
505
- run(prompt: MessageContent, options?: RunOptions): Promise<AgentResult>;
506
- runWithContext(messages: Message[], options?: RunOptions): Promise<AgentResult>;
507
- runStructured<T>(prompt: MessageContent, schema: StructuredOutputConfig<T>, options?: RunOptions): Promise<AgentResult<T>>;
508
- stream(prompt: MessageContent, options?: RunOptions): AsyncIterable<AgentEvent>;
509
- streamWithContext(messages: Message[], options?: RunOptions): AsyncIterable<AgentEvent>;
660
+ constructor(config: FullAgentConfig);
661
+ run(prompt: MessageContent, options: RunOptions): Promise<AgentResult>;
662
+ runWithContext(messages: Message[], options: RunOptions): Promise<AgentResult>;
663
+ runStructured<T>(prompt: MessageContent, schema: StructuredOutputConfig<T>, options: RunOptions): Promise<AgentResult<T>>;
664
+ stream(prompt: MessageContent, options: RunOptions): AsyncIterable<AgentEvent>;
665
+ streamWithContext(messages: Message[], options: RunOptions): AsyncIterable<AgentEvent>;
666
+ /** Register a stream middleware. Applied in registration order after built-in transforms. */
667
+ addStreamMiddleware(middleware: StreamMiddleware): void;
668
+ /** Apply built-in transforms (enrich→timeout→heartbeat) then custom middleware */
669
+ private applyStreamPipeline;
510
670
  abort(): void;
511
671
  /** Default interrupt — falls back to abort(). Backends may override with graceful shutdown. */
512
672
  interrupt(): Promise<void>;
513
673
  getState(): AgentState;
514
- getConfig(): Readonly<AgentConfig>;
674
+ getConfig(): Readonly<FullAgentConfig>;
515
675
  /** Mark agent as disposed. Override to add cleanup. */
516
676
  dispose(): void;
517
677
  /** Execute a blocking run. Backend implements the actual LLM call. */
518
- protected abstract executeRun(messages: Message[], options: RunOptions | undefined, signal: AbortSignal): Promise<AgentResult>;
678
+ protected abstract executeRun(messages: Message[], options: RunOptions, signal: AbortSignal): Promise<AgentResult>;
519
679
  /** Execute a structured output run. Backend implements parsing. */
520
- protected abstract executeRunStructured<T>(messages: Message[], schema: StructuredOutputConfig<T>, options: RunOptions | undefined, signal: AbortSignal): Promise<AgentResult<T>>;
680
+ protected abstract executeRunStructured<T>(messages: Message[], schema: StructuredOutputConfig<T>, options: RunOptions, signal: AbortSignal): Promise<AgentResult<T>>;
521
681
  /** Execute a streaming run. Backend yields events. */
522
- protected abstract executeStream(messages: Message[], options: RunOptions | undefined, signal: AbortSignal): AsyncIterable<AgentEvent>;
682
+ protected abstract executeStream(messages: Message[], options: RunOptions, signal: AbortSignal): AsyncIterable<AgentEvent>;
683
+ /** Check if an error should be retried given the retry configuration. */
684
+ private isRetryableError;
685
+ /** Execute a function with retry logic per RetryConfig. */
686
+ private withRetry;
687
+ /** Execute a stream factory with pre-stream retry: retries until first event, then committed. */
688
+ private streamWithRetry;
689
+ /** Resolve tools to use for this call (per-call override > config default) */
690
+ protected resolveTools(options?: RunOptions): ToolDefinition[];
523
691
  /** Enrich result usage with model/backend and fire onUsage callback */
524
692
  private enrichAndNotifyUsage;
525
693
  /** Wrap a stream to enrich usage_update events and fire onUsage callback */
@@ -529,6 +697,9 @@ declare abstract class BaseAgent implements IAgent {
529
697
  /** Wrap a stream to emit heartbeat events at configured intervals.
530
698
  * When heartbeatInterval is not set, passes through directly. */
531
699
  private heartbeatStream;
700
+ /** Wrap a stream to abort on inactivity. Resets timer on every event.
701
+ * When timeoutMs is not set, passes through directly. */
702
+ private activityTimeoutStream;
532
703
  protected guardReentrancy(): void;
533
704
  protected guardDisposed(): void;
534
705
  /** Throw AbortError if signal is already aborted */
@@ -549,4 +720,4 @@ declare function contentToText(content: MessageContent): string;
549
720
  /** Build a system prompt with optional structured output instruction */
550
721
  declare function buildSystemPrompt(base: string, schemaInstruction?: string): string;
551
722
 
552
- export { AbortError, type AgentConfig, type AgentEvent, type AgentResult, AgentSDKError, type AgentState, BackendAlreadyRegisteredError, type BackendFactory, BackendNotFoundError, type BackendOptionsMap, BaseAgent, type BuiltinBackendName, type ClaudeBackendOptions, CompositePermissionStore, type ContentPart, type CopilotBackendOptions, DependencyError, DisposedError, type ErrorHandlingConfig, FilePermissionStore, type IAgent, type IAgentService, type IPermissionStore, InMemoryPermissionStore, type JSONValue, type Message, type MessageContent, type ModelInfo, type ModelParams, type PermissionCallback, type PermissionDecision, type PermissionRequest, type PermissionScope, ReentrancyError, type RunOptions, type StructuredOutputConfig, StructuredOutputError, SubprocessError, type SupervisorHooks, type TimeoutConfig, type ToolCall, type ToolContext, type ToolDeclaration, type ToolDefinition, ToolExecutionError, type ToolResult, type UsageData, type UserInputRequest, type UserInputResponse, type ValidationResult, type VercelAIBackendOptions, buildSystemPrompt, contentToText, createAgentService, createDefaultPermissionStore, getTextContent, hasBackend, isMultiPartContent, isTextContent, isToolDefinition, listBackends, messagesToPrompt, registerBackend, resetRegistry, unregisterBackend, zodToJsonSchema };
723
+ export { AbortError, ActivityTimeoutError, type AgentConfig, type AgentEvent, type AgentResult, AgentSDKError, type AgentSDKErrorOptions, type AgentState, BackendAlreadyRegisteredError, type BackendFactory, BackendNotFoundError, type BackendOptionsMap, BaseAgent, type BuiltinBackendName, type CallDefaults, type CallOptions, type ClaudeBackendOptions, CompositePermissionStore, type ContentPart, type CopilotBackendOptions, DependencyError, DisposedError, ErrorCode, type ErrorHandlingConfig, FilePermissionStore, type FullAgentConfig, type IAgent, type IAgentService, type IPermissionStore, InMemoryPermissionStore, type JSONValue, type Message, type MessageContent, type ModelInfo, type ModelParams, type PermissionCallback, type PermissionDecision, type PermissionRequest, type PermissionScope, ReentrancyError, type RetryConfig, type RunOptions, type StreamContext, type StreamMiddleware, type StructuredOutputConfig, StructuredOutputError, SubprocessError, type SupervisorHooks, type TimeoutConfig, type ToolCall, type ToolContext, type ToolDeclaration, type ToolDefinition, ToolExecutionError, type ToolResult, type UsageData, type UserInputRequest, type UserInputResponse, type ValidationResult, type VercelAIBackendOptions, buildSystemPrompt, classifyAgentError, contentToText, createAgentService, createDefaultPermissionStore, disposeBackend, getTextContent, hasBackend, isMultiPartContent, isRecoverableErrorCode, isTextContent, isToolDefinition, listBackends, listConfigs, messagesToPrompt, registerBackend, registerLazyBackend, resetRegistry, unregisterBackend, zodToJsonSchema };