@witqq/agent-sdk 0.6.1 → 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 (145) hide show
  1. package/README.md +539 -6
  2. package/dist/{types-BvwNzZCj.d.cts → agent-CW9XbmG_.d.ts} +148 -95
  3. package/dist/{types-BvwNzZCj.d.ts → agent-DxY68NZL.d.cts} +148 -95
  4. package/dist/auth/index.cjs +260 -2
  5. package/dist/auth/index.cjs.map +1 -1
  6. package/dist/auth/index.d.cts +21 -138
  7. package/dist/auth/index.d.ts +21 -138
  8. package/dist/auth/index.js +260 -3
  9. package/dist/auth/index.js.map +1 -1
  10. package/dist/backends/claude.cjs +653 -140
  11. package/dist/backends/claude.cjs.map +1 -1
  12. package/dist/backends/claude.d.cts +4 -1
  13. package/dist/backends/claude.d.ts +4 -1
  14. package/dist/backends/claude.js +653 -140
  15. package/dist/backends/claude.js.map +1 -1
  16. package/dist/backends/copilot.cjs +428 -88
  17. package/dist/backends/copilot.cjs.map +1 -1
  18. package/dist/backends/copilot.d.cts +13 -4
  19. package/dist/backends/copilot.d.ts +13 -4
  20. package/dist/backends/copilot.js +428 -88
  21. package/dist/backends/copilot.js.map +1 -1
  22. package/dist/backends/vercel-ai.cjs +349 -77
  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 +349 -77
  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 +147 -0
  31. package/dist/chat/accumulator.cjs.map +1 -0
  32. package/dist/chat/accumulator.d.cts +64 -0
  33. package/dist/chat/accumulator.d.ts +64 -0
  34. package/dist/chat/accumulator.js +145 -0
  35. package/dist/chat/accumulator.js.map +1 -0
  36. package/dist/chat/backends.cjs +3524 -0
  37. package/dist/chat/backends.cjs.map +1 -0
  38. package/dist/chat/backends.d.cts +66 -0
  39. package/dist/chat/backends.d.ts +66 -0
  40. package/dist/chat/backends.js +3512 -0
  41. package/dist/chat/backends.js.map +1 -0
  42. package/dist/chat/context.cjs +280 -0
  43. package/dist/chat/context.cjs.map +1 -0
  44. package/dist/chat/context.d.cts +191 -0
  45. package/dist/chat/context.d.ts +191 -0
  46. package/dist/chat/context.js +277 -0
  47. package/dist/chat/context.js.map +1 -0
  48. package/dist/chat/core.cjs +305 -0
  49. package/dist/chat/core.cjs.map +1 -0
  50. package/dist/chat/core.d.cts +84 -0
  51. package/dist/chat/core.d.ts +84 -0
  52. package/dist/chat/core.js +282 -0
  53. package/dist/chat/core.js.map +1 -0
  54. package/dist/chat/errors.cjs +273 -0
  55. package/dist/chat/errors.cjs.map +1 -0
  56. package/dist/chat/errors.d.cts +97 -0
  57. package/dist/chat/errors.d.ts +97 -0
  58. package/dist/chat/errors.js +266 -0
  59. package/dist/chat/errors.js.map +1 -0
  60. package/dist/chat/events.cjs +203 -0
  61. package/dist/chat/events.cjs.map +1 -0
  62. package/dist/chat/events.d.cts +245 -0
  63. package/dist/chat/events.d.ts +245 -0
  64. package/dist/chat/events.js +196 -0
  65. package/dist/chat/events.js.map +1 -0
  66. package/dist/chat/index.cjs +5550 -0
  67. package/dist/chat/index.cjs.map +1 -0
  68. package/dist/chat/index.d.cts +77 -0
  69. package/dist/chat/index.d.ts +77 -0
  70. package/dist/chat/index.js +5505 -0
  71. package/dist/chat/index.js.map +1 -0
  72. package/dist/chat/react/theme.css +2517 -0
  73. package/dist/chat/react.cjs +3589 -0
  74. package/dist/chat/react.cjs.map +1 -0
  75. package/dist/chat/react.d.cts +1088 -0
  76. package/dist/chat/react.d.ts +1088 -0
  77. package/dist/chat/react.js +3547 -0
  78. package/dist/chat/react.js.map +1 -0
  79. package/dist/chat/runtime.cjs +1245 -0
  80. package/dist/chat/runtime.cjs.map +1 -0
  81. package/dist/chat/runtime.d.cts +182 -0
  82. package/dist/chat/runtime.d.ts +182 -0
  83. package/dist/chat/runtime.js +1243 -0
  84. package/dist/chat/runtime.js.map +1 -0
  85. package/dist/chat/server.cjs +2668 -0
  86. package/dist/chat/server.cjs.map +1 -0
  87. package/dist/chat/server.d.cts +648 -0
  88. package/dist/chat/server.d.ts +648 -0
  89. package/dist/chat/server.js +2628 -0
  90. package/dist/chat/server.js.map +1 -0
  91. package/dist/chat/sessions.cjs +380 -0
  92. package/dist/chat/sessions.cjs.map +1 -0
  93. package/dist/chat/sessions.d.cts +158 -0
  94. package/dist/chat/sessions.d.ts +158 -0
  95. package/dist/chat/sessions.js +376 -0
  96. package/dist/chat/sessions.js.map +1 -0
  97. package/dist/chat/sqlite.cjs +441 -0
  98. package/dist/chat/sqlite.cjs.map +1 -0
  99. package/dist/chat/sqlite.d.cts +128 -0
  100. package/dist/chat/sqlite.d.ts +128 -0
  101. package/dist/chat/sqlite.js +435 -0
  102. package/dist/chat/sqlite.js.map +1 -0
  103. package/dist/chat/state.cjs +190 -0
  104. package/dist/chat/state.cjs.map +1 -0
  105. package/dist/chat/state.d.cts +95 -0
  106. package/dist/chat/state.d.ts +95 -0
  107. package/dist/chat/state.js +180 -0
  108. package/dist/chat/state.js.map +1 -0
  109. package/dist/chat/storage.cjs +249 -0
  110. package/dist/chat/storage.cjs.map +1 -0
  111. package/dist/chat/storage.d.cts +197 -0
  112. package/dist/chat/storage.d.ts +197 -0
  113. package/dist/chat/storage.js +245 -0
  114. package/dist/chat/storage.js.map +1 -0
  115. package/dist/errors-C-so0M4t.d.cts +33 -0
  116. package/dist/errors-C-so0M4t.d.ts +33 -0
  117. package/dist/errors-CmVvczxZ.d.cts +28 -0
  118. package/dist/errors-CmVvczxZ.d.ts +28 -0
  119. package/dist/in-process-transport-C1JnJGVR.d.ts +228 -0
  120. package/dist/in-process-transport-C7DSqPyX.d.cts +228 -0
  121. package/dist/index.cjs +365 -59
  122. package/dist/index.cjs.map +1 -1
  123. package/dist/index.d.cts +322 -125
  124. package/dist/index.d.ts +322 -125
  125. package/dist/index.js +359 -60
  126. package/dist/index.js.map +1 -1
  127. package/dist/provider-types-PTSlRPNB.d.cts +39 -0
  128. package/dist/provider-types-PTSlRPNB.d.ts +39 -0
  129. package/dist/refresh-manager-B81PpYBr.d.cts +153 -0
  130. package/dist/refresh-manager-Dlv_iNZi.d.ts +153 -0
  131. package/dist/testing.cjs +383 -0
  132. package/dist/testing.cjs.map +1 -0
  133. package/dist/testing.d.cts +132 -0
  134. package/dist/testing.d.ts +132 -0
  135. package/dist/testing.js +377 -0
  136. package/dist/testing.js.map +1 -0
  137. package/dist/token-store-CSUBgYwn.d.ts +48 -0
  138. package/dist/token-store-CuC4hB9Z.d.cts +48 -0
  139. package/dist/transport-Cdh3M0tS.d.cts +68 -0
  140. package/dist/transport-Ciap4PWK.d.ts +68 -0
  141. package/dist/types-4vbcmPTp.d.cts +143 -0
  142. package/dist/types-BxggH0Yh.d.ts +143 -0
  143. package/dist/types-DRgd_9R7.d.cts +363 -0
  144. package/dist/types-ajANVzf7.d.ts +363 -0
  145. package/package.json +178 -6
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;
@@ -83,9 +18,19 @@ interface ToolDeclaration<TParams = unknown> {
83
18
  };
84
19
  }
85
20
  /** Full tool with execute function. Required for API-based backends.
86
- * CLI backends extract declaration; execute map held internally. */
21
+ * CLI backends extract declaration; execute map held internally.
22
+ * The optional second parameter receives request-scoped context
23
+ * when invoked through ChatRuntime (session ID, user data, custom metadata). */
87
24
  interface ToolDefinition<TParams = unknown> extends ToolDeclaration<TParams> {
88
- execute: (params: TParams) => Promise<JSONValue> | JSONValue;
25
+ execute: (params: TParams, context?: ToolContext) => Promise<unknown> | unknown;
26
+ }
27
+ /** Request-scoped context passed to tool execute functions via ChatRuntime.
28
+ * Contains session identity and user-defined metadata from the current session. */
29
+ interface ToolContext {
30
+ /** Active chat session ID */
31
+ sessionId: string;
32
+ /** Custom metadata from the session (e.g. user ID, tenant, permissions) */
33
+ custom?: Record<string, unknown>;
89
34
  }
90
35
  /** A tool call made by the LLM during execution */
91
36
  interface ToolCall {
@@ -100,6 +45,18 @@ interface ToolResult {
100
45
  result: JSONValue;
101
46
  isError?: boolean;
102
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
+ };
103
60
  /** Conversation message — discriminated union on `role` */
104
61
  type Message = {
105
62
  role: "user";
@@ -116,12 +73,15 @@ type Message = {
116
73
  role: "system";
117
74
  content: string;
118
75
  };
76
+
119
77
  /** Scope for "remember this decision" */
120
78
  type PermissionScope = "once" | "session" | "project" | "always";
121
79
  /** What the permission callback receives */
122
80
  interface PermissionRequest {
123
81
  toolName: string;
124
82
  toolArgs: Record<string, unknown>;
83
+ /** Unique identifier for this specific tool call */
84
+ toolCallId?: string;
125
85
  /** SDK-suggested scope (from Claude CLI's suggestions) */
126
86
  suggestedScope?: PermissionScope;
127
87
  /** Original SDK permission request (for pass-through) */
@@ -159,12 +119,68 @@ interface SupervisorHooks {
159
119
  onPermission?: PermissionCallback;
160
120
  onAskUser?: (request: UserInputRequest, signal: AbortSignal) => Promise<UserInputResponse>;
161
121
  }
162
- /** Configuration for typed structured output from LLM */
163
- interface StructuredOutputConfig<T = unknown> {
164
- schema: z.ZodType<T>;
122
+
123
+ /** Model metadata returned by listModels() */
124
+ interface ModelInfo {
125
+ id: string;
165
126
  name?: string;
166
- 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[];
167
141
  }
142
+ /** Result of backend validation check */
143
+ interface ValidationResult {
144
+ valid: boolean;
145
+ errors: string[];
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
+
168
184
  /** Usage data from LLM execution — tokens consumed plus optional metadata */
169
185
  interface UsageData {
170
186
  promptTokens: number;
@@ -223,24 +239,130 @@ type AgentEvent = {
223
239
  type: "error";
224
240
  error: string;
225
241
  recoverable: boolean;
242
+ code?: ErrorCode;
226
243
  } | {
227
244
  type: "done";
228
245
  finalOutput: string | null;
229
246
  structuredOutput?: unknown;
247
+ streamed?: boolean;
230
248
  };
231
- /** Options passed to agent.run() / agent.stream() */
232
- interface RunOptions {
233
- /** 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 */
234
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;
235
360
  /** Arbitrary context passed to the agent run */
236
361
  context?: Record<string, unknown>;
237
- }
238
- /** LLM model parameters */
239
- interface ModelParams {
240
- temperature?: number;
241
- maxTokens?: number;
242
- topP?: number;
243
- 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;
244
366
  }
245
367
  /** Timeout configuration for agent operations */
246
368
  interface TimeoutConfig {
@@ -265,12 +387,10 @@ interface ErrorHandlingConfig {
265
387
  phase: "tool" | "llm" | "permission" | "ask-user";
266
388
  }) => void;
267
389
  }
268
- /** 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. */
269
392
  interface AgentConfig {
270
- model?: string;
271
- modelParams?: ModelParams;
272
393
  systemPrompt: string;
273
- tools: ToolDefinition[];
274
394
  supervisor?: SupervisorHooks;
275
395
  maxTurns?: number;
276
396
  timeout?: TimeoutConfig;
@@ -280,8 +400,14 @@ interface AgentConfig {
280
400
  /** How to apply systemPrompt: "append" adds to backend default, "replace" overrides it.
281
401
  * Default: "append". Currently used by the Copilot backend. */
282
402
  systemMessageMode?: "append" | "replace";
283
- /** Filter for backend built-in tools (e.g. ["web_search", "web_fetch"] for Copilot).
284
- * 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
+ */
285
411
  availableTools?: string[];
286
412
  /** Callback invoked with usage data after run completion or during streaming.
287
413
  * Fire-and-forget: errors are logged but not propagated. */
@@ -295,11 +421,24 @@ interface AgentConfig {
295
421
  * "persistent": reuses the same CLI session across calls, preserving conversation
296
422
  * history natively in the CLI backend. Session is destroyed on agent dispose(). */
297
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[];
298
434
  /** Provider-specific options passed through to the underlying SDK.
299
435
  * For Vercel AI: passed as providerOptions to generateText/streamText.
300
436
  * Example: { google: { thinkingConfig: { thinkingBudget: 1024 } } } */
301
437
  providerOptions?: Record<string, Record<string, unknown>>;
302
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;
303
442
  /** Result of an agent run, generic over structured output type T */
304
443
  interface AgentResult<T = void> {
305
444
  output: string | null;
@@ -321,15 +460,15 @@ interface IAgent {
321
460
  * or before the first call. Can be stored externally for session resume. */
322
461
  readonly sessionId: string | undefined;
323
462
  /** Run a single prompt and return the result. Wraps prompt in a user message. */
324
- run(prompt: MessageContent, options?: RunOptions): Promise<AgentResult>;
463
+ run(prompt: MessageContent, options: RunOptions): Promise<AgentResult>;
325
464
  /** Run with full conversation history. Messages are passed directly to the backend. */
326
- runWithContext(messages: Message[], options?: RunOptions): Promise<AgentResult>;
465
+ runWithContext(messages: Message[], options: RunOptions): Promise<AgentResult>;
327
466
  /** Run with structured output validated against a Zod schema. */
328
- 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>>;
329
468
  /** Stream events for a single prompt. Wraps prompt in a user message. */
330
- stream(prompt: MessageContent, options?: RunOptions): AsyncIterable<AgentEvent>;
469
+ stream(prompt: MessageContent, options: RunOptions): AsyncIterable<AgentEvent>;
331
470
  /** Stream events with full conversation history. Messages are passed directly to the backend. */
332
- streamWithContext(messages: Message[], options?: RunOptions): AsyncIterable<AgentEvent>;
471
+ streamWithContext(messages: Message[], options: RunOptions): AsyncIterable<AgentEvent>;
333
472
  /** Abort the current operation. No-op if not running. */
334
473
  abort(): void;
335
474
  /** Gracefully interrupt the current operation. Resolves when the backend acknowledges. */
@@ -337,29 +476,19 @@ interface IAgent {
337
476
  /** Get current agent lifecycle state. */
338
477
  getState(): AgentState;
339
478
  /** Get frozen agent configuration. */
340
- getConfig(): Readonly<AgentConfig>;
479
+ getConfig(): Readonly<FullAgentConfig>;
341
480
  /** Release resources. After dispose(), agent must not be used. */
342
481
  dispose(): void;
343
482
  }
344
- /** Model metadata returned by listModels() */
345
- interface ModelInfo {
346
- id: string;
347
- name?: string;
348
- provider?: string;
349
- }
350
- /** Result of backend validation check */
351
- interface ValidationResult {
352
- valid: boolean;
353
- errors: string[];
354
- }
355
483
  /** Backend service interface — creates agents, lists models, validates config */
356
484
  interface IAgentService {
357
485
  readonly name: string;
358
- createAgent(config: AgentConfig): IAgent;
486
+ createAgent(config: FullAgentConfig): IAgent;
359
487
  listModels(): Promise<ModelInfo[]>;
360
488
  validate(): Promise<ValidationResult>;
361
489
  dispose(): Promise<void>;
362
490
  }
491
+
363
492
  /** Options for Copilot CLI backend */
364
493
  interface CopilotBackendOptions {
365
494
  cliPath?: string;
@@ -370,8 +499,13 @@ interface CopilotBackendOptions {
370
499
  cliArgs?: string[];
371
500
  /** Timeout in milliseconds for sendAndWait() calls. When undefined, uses copilot-sdk default (60s). */
372
501
  timeout?: number;
502
+ /** Timeout in milliseconds for CLI startup and auth check (default: 30000). */
503
+ startupTimeoutMs?: number;
373
504
  /** Custom environment variables merged into the subprocess env */
374
505
  env?: Record<string, string | undefined>;
506
+ /** Session ID to resume after server restart. On startup, the backend attempts
507
+ * to resume this session before creating a new one. */
508
+ resumeSessionId?: string;
375
509
  }
376
510
  /** Options for Claude CLI backend */
377
511
  interface ClaudeBackendOptions {
@@ -382,6 +516,9 @@ interface ClaudeBackendOptions {
382
516
  oauthToken?: string;
383
517
  /** Custom environment variables merged into the subprocess env */
384
518
  env?: Record<string, string | undefined>;
519
+ /** Session ID to resume after server restart. On startup, the backend attempts
520
+ * to resume this session before creating a new one. */
521
+ resumeSessionId?: string;
385
522
  }
386
523
  /** Options for Vercel AI SDK backend */
387
524
  interface VercelAIBackendOptions {
@@ -389,6 +526,7 @@ interface VercelAIBackendOptions {
389
526
  provider?: string;
390
527
  baseUrl?: string;
391
528
  }
529
+
392
530
  /** Type guard: checks if a ToolDeclaration has an execute function (i.e., is a ToolDefinition) */
393
531
  declare function isToolDefinition(tool: ToolDeclaration): tool is ToolDefinition;
394
532
  /** Type guard: checks if MessageContent is plain string */
@@ -398,9 +536,31 @@ declare function isMultiPartContent(content: MessageContent): content is Content
398
536
  /** Extract text from MessageContent regardless of format */
399
537
  declare function getTextContent(content: MessageContent): string;
400
538
 
401
- /** Base error class for agent-sdk */
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
+ }
548
+ /** Base error class for agent-sdk.
549
+ *
550
+ * Use `AgentSDKError.is(err)` for reliable cross-module `instanceof` checks
551
+ * (works across separately bundled entry points where `instanceof` may fail). */
402
552
  declare class AgentSDKError extends Error {
403
- constructor(message: string, options?: ErrorOptions);
553
+ /** @internal Marker for cross-bundle identity checks */
554
+ readonly _agentSDKError: true;
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);
562
+ /** Check if an error is an AgentSDKError (works across bundled copies) */
563
+ static is(error: unknown): error is AgentSDKError;
404
564
  }
405
565
  /** Thrown when agent.run() is called while already running (M8 re-entrancy guard) */
406
566
  declare class ReentrancyError extends AgentSDKError {
@@ -436,6 +596,10 @@ declare class ToolExecutionError extends AgentSDKError {
436
596
  readonly toolName: string;
437
597
  constructor(toolName: string, message: string, options?: ErrorOptions);
438
598
  }
599
+ /** Thrown when a stream has no activity within the configured timeout */
600
+ declare class ActivityTimeoutError extends AgentSDKError {
601
+ constructor(timeoutMs: number);
602
+ }
439
603
  /** Thrown when structured output parsing fails */
440
604
  declare class StructuredOutputError extends AgentSDKError {
441
605
  constructor(message: string, options?: ErrorOptions);
@@ -455,45 +619,73 @@ type BuiltinBackendName = keyof BackendOptionsMap;
455
619
  declare function registerBackend<TOptions = unknown>(name: string, factory: BackendFactory<TOptions>): void;
456
620
  /** Unregister a backend (primarily for testing) */
457
621
  declare function unregisterBackend(name: string): boolean;
458
- /** Check if a backend is registered */
622
+ /** Check if a backend is registered (eagerly or lazily) */
459
623
  declare function hasBackend(name: string): boolean;
460
- /** List all registered backend names */
624
+ /** List all registered backend names (eager + lazy) */
461
625
  declare function listBackends(): string[];
462
626
  /** Reset registry to initial state (for testing) */
463
627
  declare function resetRegistry(): void;
464
- /** Create a backend service with type-safe options */
465
- declare function createAgentService<K extends BuiltinBackendName>(name: K, options: BackendOptionsMap[K]): Promise<IAgentService>;
466
- 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>;
467
645
 
468
646
  /** Abstract base agent with shared lifecycle logic.
469
647
  * Concrete backends extend this and implement the protected _run/_stream methods. */
470
648
  declare abstract class BaseAgent implements IAgent {
471
649
  protected state: AgentState;
472
650
  protected abortController: AbortController | null;
473
- protected readonly config: AgentConfig;
651
+ protected readonly config: FullAgentConfig;
652
+ private _cleanupExternalSignal;
653
+ private _streamMiddleware;
474
654
  /** Backend identifier (e.g. "copilot", "claude", "vercel-ai") */
475
655
  protected abstract readonly backendName: string;
476
656
  /** CLI session ID for persistent mode. Override in backends that support it. */
477
657
  get sessionId(): string | undefined;
478
- constructor(config: AgentConfig);
479
- run(prompt: MessageContent, options?: RunOptions): Promise<AgentResult>;
480
- runWithContext(messages: Message[], options?: RunOptions): Promise<AgentResult>;
481
- runStructured<T>(prompt: MessageContent, schema: StructuredOutputConfig<T>, options?: RunOptions): Promise<AgentResult<T>>;
482
- stream(prompt: MessageContent, options?: RunOptions): AsyncIterable<AgentEvent>;
483
- 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;
484
668
  abort(): void;
485
669
  /** Default interrupt — falls back to abort(). Backends may override with graceful shutdown. */
486
670
  interrupt(): Promise<void>;
487
671
  getState(): AgentState;
488
- getConfig(): Readonly<AgentConfig>;
672
+ getConfig(): Readonly<FullAgentConfig>;
489
673
  /** Mark agent as disposed. Override to add cleanup. */
490
674
  dispose(): void;
491
675
  /** Execute a blocking run. Backend implements the actual LLM call. */
492
- protected abstract executeRun(messages: Message[], options: RunOptions | undefined, signal: AbortSignal): Promise<AgentResult>;
676
+ protected abstract executeRun(messages: Message[], options: RunOptions, signal: AbortSignal): Promise<AgentResult>;
493
677
  /** Execute a structured output run. Backend implements parsing. */
494
- 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>>;
495
679
  /** Execute a streaming run. Backend yields events. */
496
- 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[];
497
689
  /** Enrich result usage with model/backend and fire onUsage callback */
498
690
  private enrichAndNotifyUsage;
499
691
  /** Wrap a stream to enrich usage_update events and fire onUsage callback */
@@ -503,10 +695,15 @@ declare abstract class BaseAgent implements IAgent {
503
695
  /** Wrap a stream to emit heartbeat events at configured intervals.
504
696
  * When heartbeatInterval is not set, passes through directly. */
505
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;
506
701
  protected guardReentrancy(): void;
507
702
  protected guardDisposed(): void;
508
703
  /** Throw AbortError if signal is already aborted */
509
704
  protected checkAbort(signal: AbortSignal): void;
705
+ /** Clean up after a run completes (success, error, or abort). */
706
+ private cleanupRun;
510
707
  private createAbortController;
511
708
  }
512
709
 
@@ -521,4 +718,4 @@ declare function contentToText(content: MessageContent): string;
521
718
  /** Build a system prompt with optional structured output instruction */
522
719
  declare function buildSystemPrompt(base: string, schemaInstruction?: string): string;
523
720
 
524
- 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 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 };