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