@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.
- package/README.md +539 -6
- package/dist/{types-BvwNzZCj.d.cts → agent-CW9XbmG_.d.ts} +148 -95
- package/dist/{types-BvwNzZCj.d.ts → agent-DxY68NZL.d.cts} +148 -95
- package/dist/auth/index.cjs +260 -2
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.d.cts +21 -138
- package/dist/auth/index.d.ts +21 -138
- package/dist/auth/index.js +260 -3
- package/dist/auth/index.js.map +1 -1
- package/dist/backends/claude.cjs +653 -140
- package/dist/backends/claude.cjs.map +1 -1
- package/dist/backends/claude.d.cts +4 -1
- package/dist/backends/claude.d.ts +4 -1
- package/dist/backends/claude.js +653 -140
- package/dist/backends/claude.js.map +1 -1
- package/dist/backends/copilot.cjs +428 -88
- package/dist/backends/copilot.cjs.map +1 -1
- package/dist/backends/copilot.d.cts +13 -4
- package/dist/backends/copilot.d.ts +13 -4
- package/dist/backends/copilot.js +428 -88
- package/dist/backends/copilot.js.map +1 -1
- package/dist/backends/vercel-ai.cjs +349 -77
- package/dist/backends/vercel-ai.cjs.map +1 -1
- package/dist/backends/vercel-ai.d.cts +3 -1
- package/dist/backends/vercel-ai.d.ts +3 -1
- package/dist/backends/vercel-ai.js +349 -77
- package/dist/backends/vercel-ai.js.map +1 -1
- package/dist/backends-BSrsBYFn.d.cts +39 -0
- package/dist/backends-BSrsBYFn.d.ts +39 -0
- package/dist/chat/accumulator.cjs +147 -0
- package/dist/chat/accumulator.cjs.map +1 -0
- package/dist/chat/accumulator.d.cts +64 -0
- package/dist/chat/accumulator.d.ts +64 -0
- package/dist/chat/accumulator.js +145 -0
- package/dist/chat/accumulator.js.map +1 -0
- package/dist/chat/backends.cjs +3524 -0
- package/dist/chat/backends.cjs.map +1 -0
- package/dist/chat/backends.d.cts +66 -0
- package/dist/chat/backends.d.ts +66 -0
- package/dist/chat/backends.js +3512 -0
- package/dist/chat/backends.js.map +1 -0
- package/dist/chat/context.cjs +280 -0
- package/dist/chat/context.cjs.map +1 -0
- package/dist/chat/context.d.cts +191 -0
- package/dist/chat/context.d.ts +191 -0
- package/dist/chat/context.js +277 -0
- package/dist/chat/context.js.map +1 -0
- package/dist/chat/core.cjs +305 -0
- package/dist/chat/core.cjs.map +1 -0
- package/dist/chat/core.d.cts +84 -0
- package/dist/chat/core.d.ts +84 -0
- package/dist/chat/core.js +282 -0
- package/dist/chat/core.js.map +1 -0
- package/dist/chat/errors.cjs +273 -0
- package/dist/chat/errors.cjs.map +1 -0
- package/dist/chat/errors.d.cts +97 -0
- package/dist/chat/errors.d.ts +97 -0
- package/dist/chat/errors.js +266 -0
- package/dist/chat/errors.js.map +1 -0
- package/dist/chat/events.cjs +203 -0
- package/dist/chat/events.cjs.map +1 -0
- package/dist/chat/events.d.cts +245 -0
- package/dist/chat/events.d.ts +245 -0
- package/dist/chat/events.js +196 -0
- package/dist/chat/events.js.map +1 -0
- package/dist/chat/index.cjs +5550 -0
- package/dist/chat/index.cjs.map +1 -0
- package/dist/chat/index.d.cts +77 -0
- package/dist/chat/index.d.ts +77 -0
- package/dist/chat/index.js +5505 -0
- package/dist/chat/index.js.map +1 -0
- package/dist/chat/react/theme.css +2517 -0
- package/dist/chat/react.cjs +3589 -0
- package/dist/chat/react.cjs.map +1 -0
- package/dist/chat/react.d.cts +1088 -0
- package/dist/chat/react.d.ts +1088 -0
- package/dist/chat/react.js +3547 -0
- package/dist/chat/react.js.map +1 -0
- package/dist/chat/runtime.cjs +1245 -0
- package/dist/chat/runtime.cjs.map +1 -0
- package/dist/chat/runtime.d.cts +182 -0
- package/dist/chat/runtime.d.ts +182 -0
- package/dist/chat/runtime.js +1243 -0
- package/dist/chat/runtime.js.map +1 -0
- package/dist/chat/server.cjs +2668 -0
- package/dist/chat/server.cjs.map +1 -0
- package/dist/chat/server.d.cts +648 -0
- package/dist/chat/server.d.ts +648 -0
- package/dist/chat/server.js +2628 -0
- package/dist/chat/server.js.map +1 -0
- package/dist/chat/sessions.cjs +380 -0
- package/dist/chat/sessions.cjs.map +1 -0
- package/dist/chat/sessions.d.cts +158 -0
- package/dist/chat/sessions.d.ts +158 -0
- package/dist/chat/sessions.js +376 -0
- package/dist/chat/sessions.js.map +1 -0
- package/dist/chat/sqlite.cjs +441 -0
- package/dist/chat/sqlite.cjs.map +1 -0
- package/dist/chat/sqlite.d.cts +128 -0
- package/dist/chat/sqlite.d.ts +128 -0
- package/dist/chat/sqlite.js +435 -0
- package/dist/chat/sqlite.js.map +1 -0
- package/dist/chat/state.cjs +190 -0
- package/dist/chat/state.cjs.map +1 -0
- package/dist/chat/state.d.cts +95 -0
- package/dist/chat/state.d.ts +95 -0
- package/dist/chat/state.js +180 -0
- package/dist/chat/state.js.map +1 -0
- package/dist/chat/storage.cjs +249 -0
- package/dist/chat/storage.cjs.map +1 -0
- package/dist/chat/storage.d.cts +197 -0
- package/dist/chat/storage.d.ts +197 -0
- package/dist/chat/storage.js +245 -0
- package/dist/chat/storage.js.map +1 -0
- package/dist/errors-C-so0M4t.d.cts +33 -0
- package/dist/errors-C-so0M4t.d.ts +33 -0
- package/dist/errors-CmVvczxZ.d.cts +28 -0
- package/dist/errors-CmVvczxZ.d.ts +28 -0
- package/dist/in-process-transport-C1JnJGVR.d.ts +228 -0
- package/dist/in-process-transport-C7DSqPyX.d.cts +228 -0
- package/dist/index.cjs +365 -59
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +322 -125
- package/dist/index.d.ts +322 -125
- package/dist/index.js +359 -60
- package/dist/index.js.map +1 -1
- package/dist/provider-types-PTSlRPNB.d.cts +39 -0
- package/dist/provider-types-PTSlRPNB.d.ts +39 -0
- package/dist/refresh-manager-B81PpYBr.d.cts +153 -0
- package/dist/refresh-manager-Dlv_iNZi.d.ts +153 -0
- package/dist/testing.cjs +383 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +132 -0
- package/dist/testing.d.ts +132 -0
- package/dist/testing.js +377 -0
- package/dist/testing.js.map +1 -0
- package/dist/token-store-CSUBgYwn.d.ts +48 -0
- package/dist/token-store-CuC4hB9Z.d.cts +48 -0
- package/dist/transport-Cdh3M0tS.d.cts +68 -0
- package/dist/transport-Ciap4PWK.d.ts +68 -0
- package/dist/types-4vbcmPTp.d.cts +143 -0
- package/dist/types-BxggH0Yh.d.ts +143 -0
- package/dist/types-DRgd_9R7.d.cts +363 -0
- package/dist/types-ajANVzf7.d.ts +363 -0
- package/package.json +178 -6
|
@@ -1,34 +1,11 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
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
|
-
}
|
|
2
|
+
import { E as ErrorCode } from './errors-C-so0M4t.cjs';
|
|
16
3
|
|
|
17
4
|
/** JSON-serializable value used for tool arguments and results */
|
|
18
5
|
type JSONValue = string | number | boolean | null | JSONValue[] | {
|
|
19
6
|
[key: string]: JSONValue;
|
|
20
7
|
};
|
|
21
|
-
|
|
22
|
-
type MessageContent = string | Array<ContentPart>;
|
|
23
|
-
/** Individual content part within a multi-part message */
|
|
24
|
-
type ContentPart = {
|
|
25
|
-
type: "text";
|
|
26
|
-
text: string;
|
|
27
|
-
} | {
|
|
28
|
-
type: "image";
|
|
29
|
-
data: string;
|
|
30
|
-
mimeType: string;
|
|
31
|
-
};
|
|
8
|
+
|
|
32
9
|
/** What the LLM sees — name, description, schema. Passed to all backends. */
|
|
33
10
|
interface ToolDeclaration<TParams = unknown> {
|
|
34
11
|
name: string;
|
|
@@ -42,9 +19,19 @@ interface ToolDeclaration<TParams = unknown> {
|
|
|
42
19
|
};
|
|
43
20
|
}
|
|
44
21
|
/** Full tool with execute function. Required for API-based backends.
|
|
45
|
-
* CLI backends extract declaration; execute map held internally.
|
|
22
|
+
* CLI backends extract declaration; execute map held internally.
|
|
23
|
+
* The optional second parameter receives request-scoped context
|
|
24
|
+
* when invoked through ChatRuntime (session ID, user data, custom metadata). */
|
|
46
25
|
interface ToolDefinition<TParams = unknown> extends ToolDeclaration<TParams> {
|
|
47
|
-
execute: (params: TParams) => Promise<
|
|
26
|
+
execute: (params: TParams, context?: ToolContext) => Promise<unknown> | unknown;
|
|
27
|
+
}
|
|
28
|
+
/** Request-scoped context passed to tool execute functions via ChatRuntime.
|
|
29
|
+
* Contains session identity and user-defined metadata from the current session. */
|
|
30
|
+
interface ToolContext {
|
|
31
|
+
/** Active chat session ID */
|
|
32
|
+
sessionId: string;
|
|
33
|
+
/** Custom metadata from the session (e.g. user ID, tenant, permissions) */
|
|
34
|
+
custom?: Record<string, unknown>;
|
|
48
35
|
}
|
|
49
36
|
/** A tool call made by the LLM during execution */
|
|
50
37
|
interface ToolCall {
|
|
@@ -59,6 +46,18 @@ interface ToolResult {
|
|
|
59
46
|
result: JSONValue;
|
|
60
47
|
isError?: boolean;
|
|
61
48
|
}
|
|
49
|
+
|
|
50
|
+
/** Message content — plain string or array of text/image parts */
|
|
51
|
+
type MessageContent = string | Array<ContentPart>;
|
|
52
|
+
/** Individual content part within a multi-part message */
|
|
53
|
+
type ContentPart = {
|
|
54
|
+
type: "text";
|
|
55
|
+
text: string;
|
|
56
|
+
} | {
|
|
57
|
+
type: "image";
|
|
58
|
+
data: string;
|
|
59
|
+
mimeType: string;
|
|
60
|
+
};
|
|
62
61
|
/** Conversation message — discriminated union on `role` */
|
|
63
62
|
type Message = {
|
|
64
63
|
role: "user";
|
|
@@ -75,12 +74,15 @@ type Message = {
|
|
|
75
74
|
role: "system";
|
|
76
75
|
content: string;
|
|
77
76
|
};
|
|
77
|
+
|
|
78
78
|
/** Scope for "remember this decision" */
|
|
79
79
|
type PermissionScope = "once" | "session" | "project" | "always";
|
|
80
80
|
/** What the permission callback receives */
|
|
81
81
|
interface PermissionRequest {
|
|
82
82
|
toolName: string;
|
|
83
83
|
toolArgs: Record<string, unknown>;
|
|
84
|
+
/** Unique identifier for this specific tool call */
|
|
85
|
+
toolCallId?: string;
|
|
84
86
|
/** SDK-suggested scope (from Claude CLI's suggestions) */
|
|
85
87
|
suggestedScope?: PermissionScope;
|
|
86
88
|
/** Original SDK permission request (for pass-through) */
|
|
@@ -118,12 +120,32 @@ interface SupervisorHooks {
|
|
|
118
120
|
onPermission?: PermissionCallback;
|
|
119
121
|
onAskUser?: (request: UserInputRequest, signal: AbortSignal) => Promise<UserInputResponse>;
|
|
120
122
|
}
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
123
|
+
|
|
124
|
+
/** Model metadata returned by listModels() */
|
|
125
|
+
interface ModelInfo {
|
|
126
|
+
id: string;
|
|
124
127
|
name?: string;
|
|
125
|
-
|
|
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[];
|
|
126
147
|
}
|
|
148
|
+
|
|
127
149
|
/** Usage data from LLM execution — tokens consumed plus optional metadata */
|
|
128
150
|
interface UsageData {
|
|
129
151
|
promptTokens: number;
|
|
@@ -182,24 +204,78 @@ type AgentEvent = {
|
|
|
182
204
|
type: "error";
|
|
183
205
|
error: string;
|
|
184
206
|
recoverable: boolean;
|
|
207
|
+
code?: ErrorCode;
|
|
185
208
|
} | {
|
|
186
209
|
type: "done";
|
|
187
210
|
finalOutput: string | null;
|
|
188
211
|
structuredOutput?: unknown;
|
|
212
|
+
streamed?: boolean;
|
|
189
213
|
};
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
214
|
+
|
|
215
|
+
/** Pluggable store for persisting permission (scope) decisions across runs. */
|
|
216
|
+
interface IPermissionStore {
|
|
217
|
+
/** Check if tool is already approved */
|
|
218
|
+
isApproved(toolName: string): Promise<boolean>;
|
|
219
|
+
/** Store an approval decision */
|
|
220
|
+
approve(toolName: string, scope: PermissionScope): Promise<void>;
|
|
221
|
+
/** Revoke approval for a tool */
|
|
222
|
+
revoke(toolName: string): Promise<void>;
|
|
223
|
+
/** Clear all approvals */
|
|
224
|
+
clear(): Promise<void>;
|
|
225
|
+
/** Dispose resources */
|
|
226
|
+
dispose(): Promise<void>;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Per-call overrides passed to run(), stream(), runStructured().
|
|
230
|
+
* Allows overriding the model, tools, signal, and other parameters
|
|
231
|
+
* on a per-request basis without modifying the agent configuration. */
|
|
232
|
+
interface CallOptions {
|
|
233
|
+
/** Override the default model for this call */
|
|
234
|
+
model?: string;
|
|
235
|
+
/** Override/extend tools for this call */
|
|
236
|
+
tools?: ToolDefinition[];
|
|
237
|
+
/** Per-call abort signal */
|
|
193
238
|
signal?: AbortSignal;
|
|
239
|
+
/** Override system message for this call */
|
|
240
|
+
systemMessage?: string;
|
|
241
|
+
/** Provider-specific options passed through to the underlying SDK */
|
|
242
|
+
providerOptions?: Record<string, unknown>;
|
|
243
|
+
/** Per-call timeout in milliseconds */
|
|
244
|
+
timeout?: number;
|
|
245
|
+
/** Per-call token limit */
|
|
246
|
+
maxTokens?: number;
|
|
247
|
+
/** Retry configuration for this call */
|
|
248
|
+
retry?: RetryConfig;
|
|
249
|
+
}
|
|
250
|
+
/** Configuration for automatic retries on transient errors */
|
|
251
|
+
interface RetryConfig {
|
|
252
|
+
/** Maximum number of retries (default: 0 — no retry) */
|
|
253
|
+
maxRetries?: number;
|
|
254
|
+
/** Initial delay in ms before first retry (default: 1000) */
|
|
255
|
+
initialDelayMs?: number;
|
|
256
|
+
/** Backoff multiplier (default: 2) */
|
|
257
|
+
backoffMultiplier?: number;
|
|
258
|
+
/** Which error codes to retry (default: all recoverable codes) */
|
|
259
|
+
retryableErrors?: ErrorCode[];
|
|
260
|
+
}
|
|
261
|
+
/** Configuration for typed structured output from LLM */
|
|
262
|
+
interface StructuredOutputConfig<T = unknown> {
|
|
263
|
+
schema: z.ZodType<T>;
|
|
264
|
+
name?: string;
|
|
265
|
+
description?: string;
|
|
266
|
+
}
|
|
267
|
+
/** Options passed to agent.run() / agent.stream().
|
|
268
|
+
* Extends CallOptions with run-specific fields (context, activityTimeoutMs).
|
|
269
|
+
* model is REQUIRED — every agent call must specify the model explicitly. */
|
|
270
|
+
interface RunOptions extends CallOptions {
|
|
271
|
+
/** Model to use for this call (required — no implicit defaults) */
|
|
272
|
+
model: string;
|
|
194
273
|
/** Arbitrary context passed to the agent run */
|
|
195
274
|
context?: Record<string, unknown>;
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
maxTokens?: number;
|
|
201
|
-
topP?: number;
|
|
202
|
-
stopSequences?: string[];
|
|
275
|
+
/** Inactivity timeout for streaming (ms). When set, the stream aborts if no
|
|
276
|
+
* event (including heartbeats/progress) arrives within this period. Resets on
|
|
277
|
+
* every received event. Default: no timeout. Only affects stream()/streamWithContext(). */
|
|
278
|
+
activityTimeoutMs?: number;
|
|
203
279
|
}
|
|
204
280
|
/** Timeout configuration for agent operations */
|
|
205
281
|
interface TimeoutConfig {
|
|
@@ -224,12 +300,10 @@ interface ErrorHandlingConfig {
|
|
|
224
300
|
phase: "tool" | "llm" | "permission" | "ask-user";
|
|
225
301
|
}) => void;
|
|
226
302
|
}
|
|
227
|
-
/**
|
|
303
|
+
/** Identity-only agent configuration — defines the agent's behavior, NOT per-call defaults.
|
|
304
|
+
* For creating an agent with model/tools defaults, use FullAgentConfig. */
|
|
228
305
|
interface AgentConfig {
|
|
229
|
-
model?: string;
|
|
230
|
-
modelParams?: ModelParams;
|
|
231
306
|
systemPrompt: string;
|
|
232
|
-
tools: ToolDefinition[];
|
|
233
307
|
supervisor?: SupervisorHooks;
|
|
234
308
|
maxTurns?: number;
|
|
235
309
|
timeout?: TimeoutConfig;
|
|
@@ -239,8 +313,14 @@ interface AgentConfig {
|
|
|
239
313
|
/** How to apply systemPrompt: "append" adds to backend default, "replace" overrides it.
|
|
240
314
|
* Default: "append". Currently used by the Copilot backend. */
|
|
241
315
|
systemMessageMode?: "append" | "replace";
|
|
242
|
-
/**
|
|
243
|
-
*
|
|
316
|
+
/**
|
|
317
|
+
* Filter for backend built-in tools (e.g. `["web_search", "web_fetch"]` for Copilot).
|
|
318
|
+
* When set, only listed built-in tools are available. Backend-specific.
|
|
319
|
+
*
|
|
320
|
+
* **Security note**: This is a trust boundary — it controls which backend-native tools
|
|
321
|
+
* the AI agent can invoke. By default, backends expose ALL their built-in tools.
|
|
322
|
+
* Set this to restrict access (e.g. prevent file system access in a web-facing agent).
|
|
323
|
+
*/
|
|
244
324
|
availableTools?: string[];
|
|
245
325
|
/** Callback invoked with usage data after run completion or during streaming.
|
|
246
326
|
* Fire-and-forget: errors are logged but not propagated. */
|
|
@@ -254,11 +334,24 @@ interface AgentConfig {
|
|
|
254
334
|
* "persistent": reuses the same CLI session across calls, preserving conversation
|
|
255
335
|
* history natively in the CLI backend. Session is destroyed on agent dispose(). */
|
|
256
336
|
sessionMode?: "per-call" | "persistent";
|
|
337
|
+
}
|
|
338
|
+
/** Per-call defaults that can be provided at agent creation time.
|
|
339
|
+
* Each field can also be overridden on individual calls via RunOptions. */
|
|
340
|
+
interface CallDefaults {
|
|
341
|
+
/** Default model (overridable per-call via RunOptions.model) */
|
|
342
|
+
model?: string;
|
|
343
|
+
/** Default model parameters */
|
|
344
|
+
modelParams?: ModelParams;
|
|
345
|
+
/** Default tools (overridable per-call via RunOptions.tools) */
|
|
346
|
+
tools?: ToolDefinition[];
|
|
257
347
|
/** Provider-specific options passed through to the underlying SDK.
|
|
258
348
|
* For Vercel AI: passed as providerOptions to generateText/streamText.
|
|
259
349
|
* Example: { google: { thinkingConfig: { thinkingBudget: 1024 } } } */
|
|
260
350
|
providerOptions?: Record<string, Record<string, unknown>>;
|
|
261
351
|
}
|
|
352
|
+
/** Full agent configuration: identity + per-call defaults.
|
|
353
|
+
* This is what createAgent() accepts. Backward-compatible with the old AgentConfig shape. */
|
|
354
|
+
type FullAgentConfig = AgentConfig & CallDefaults;
|
|
262
355
|
/** Result of an agent run, generic over structured output type T */
|
|
263
356
|
interface AgentResult<T = void> {
|
|
264
357
|
output: string | null;
|
|
@@ -280,15 +373,15 @@ interface IAgent {
|
|
|
280
373
|
* or before the first call. Can be stored externally for session resume. */
|
|
281
374
|
readonly sessionId: string | undefined;
|
|
282
375
|
/** Run a single prompt and return the result. Wraps prompt in a user message. */
|
|
283
|
-
run(prompt: MessageContent, options
|
|
376
|
+
run(prompt: MessageContent, options: RunOptions): Promise<AgentResult>;
|
|
284
377
|
/** Run with full conversation history. Messages are passed directly to the backend. */
|
|
285
|
-
runWithContext(messages: Message[], options
|
|
378
|
+
runWithContext(messages: Message[], options: RunOptions): Promise<AgentResult>;
|
|
286
379
|
/** Run with structured output validated against a Zod schema. */
|
|
287
|
-
runStructured<T>(prompt: MessageContent, schema: StructuredOutputConfig<T>, options
|
|
380
|
+
runStructured<T>(prompt: MessageContent, schema: StructuredOutputConfig<T>, options: RunOptions): Promise<AgentResult<T>>;
|
|
288
381
|
/** Stream events for a single prompt. Wraps prompt in a user message. */
|
|
289
|
-
stream(prompt: MessageContent, options
|
|
382
|
+
stream(prompt: MessageContent, options: RunOptions): AsyncIterable<AgentEvent>;
|
|
290
383
|
/** Stream events with full conversation history. Messages are passed directly to the backend. */
|
|
291
|
-
streamWithContext(messages: Message[], options
|
|
384
|
+
streamWithContext(messages: Message[], options: RunOptions): AsyncIterable<AgentEvent>;
|
|
292
385
|
/** Abort the current operation. No-op if not running. */
|
|
293
386
|
abort(): void;
|
|
294
387
|
/** Gracefully interrupt the current operation. Resolves when the backend acknowledges. */
|
|
@@ -296,57 +389,17 @@ interface IAgent {
|
|
|
296
389
|
/** Get current agent lifecycle state. */
|
|
297
390
|
getState(): AgentState;
|
|
298
391
|
/** Get frozen agent configuration. */
|
|
299
|
-
getConfig(): Readonly<
|
|
392
|
+
getConfig(): Readonly<FullAgentConfig>;
|
|
300
393
|
/** Release resources. After dispose(), agent must not be used. */
|
|
301
394
|
dispose(): void;
|
|
302
395
|
}
|
|
303
|
-
/** Model metadata returned by listModels() */
|
|
304
|
-
interface ModelInfo {
|
|
305
|
-
id: string;
|
|
306
|
-
name?: string;
|
|
307
|
-
provider?: string;
|
|
308
|
-
}
|
|
309
|
-
/** Result of backend validation check */
|
|
310
|
-
interface ValidationResult {
|
|
311
|
-
valid: boolean;
|
|
312
|
-
errors: string[];
|
|
313
|
-
}
|
|
314
396
|
/** Backend service interface — creates agents, lists models, validates config */
|
|
315
397
|
interface IAgentService {
|
|
316
398
|
readonly name: string;
|
|
317
|
-
createAgent(config:
|
|
399
|
+
createAgent(config: FullAgentConfig): IAgent;
|
|
318
400
|
listModels(): Promise<ModelInfo[]>;
|
|
319
401
|
validate(): Promise<ValidationResult>;
|
|
320
402
|
dispose(): Promise<void>;
|
|
321
403
|
}
|
|
322
|
-
/** Options for Copilot CLI backend */
|
|
323
|
-
interface CopilotBackendOptions {
|
|
324
|
-
cliPath?: string;
|
|
325
|
-
workingDirectory?: string;
|
|
326
|
-
githubToken?: string;
|
|
327
|
-
useLoggedInUser?: boolean;
|
|
328
|
-
/** Extra CLI arguments passed to the Copilot subprocess (e.g. ["--allow-all"]) */
|
|
329
|
-
cliArgs?: string[];
|
|
330
|
-
/** Timeout in milliseconds for sendAndWait() calls. When undefined, uses copilot-sdk default (60s). */
|
|
331
|
-
timeout?: number;
|
|
332
|
-
/** Custom environment variables merged into the subprocess env */
|
|
333
|
-
env?: Record<string, string | undefined>;
|
|
334
|
-
}
|
|
335
|
-
/** Options for Claude CLI backend */
|
|
336
|
-
interface ClaudeBackendOptions {
|
|
337
|
-
cliPath?: string;
|
|
338
|
-
workingDirectory?: string;
|
|
339
|
-
maxTurns?: number;
|
|
340
|
-
/** OAuth token for Claude authentication (set as CLAUDE_CODE_OAUTH_TOKEN env var) */
|
|
341
|
-
oauthToken?: string;
|
|
342
|
-
/** Custom environment variables merged into the subprocess env */
|
|
343
|
-
env?: Record<string, string | undefined>;
|
|
344
|
-
}
|
|
345
|
-
/** Options for Vercel AI SDK backend */
|
|
346
|
-
interface VercelAIBackendOptions {
|
|
347
|
-
apiKey: string;
|
|
348
|
-
provider?: string;
|
|
349
|
-
baseUrl?: string;
|
|
350
|
-
}
|
|
351
404
|
|
|
352
|
-
export type {
|
|
405
|
+
export type { AgentEvent as A, FullAgentConfig as F, IAgentService as I, ModelInfo as M, RunOptions as R, ToolDefinition as T, UsageData as U, ValidationResult as V, MessageContent as a, AgentResult as b, IAgent as c, Message as d, ToolResult as e };
|
package/dist/auth/index.cjs
CHANGED
|
@@ -2,10 +2,33 @@
|
|
|
2
2
|
|
|
3
3
|
var crypto = require('crypto');
|
|
4
4
|
|
|
5
|
-
// src/
|
|
6
|
-
var
|
|
5
|
+
// src/errors.ts
|
|
6
|
+
var AgentSDKError = class extends Error {
|
|
7
|
+
/** @internal Marker for cross-bundle identity checks */
|
|
8
|
+
_agentSDKError = true;
|
|
9
|
+
/** Machine-readable error code. Prefer values from the ErrorCode enum. */
|
|
10
|
+
code;
|
|
11
|
+
/** Whether this error is safe to retry */
|
|
12
|
+
retryable;
|
|
13
|
+
/** HTTP status code hint for error classification */
|
|
14
|
+
httpStatus;
|
|
7
15
|
constructor(message, options) {
|
|
8
16
|
super(message, options);
|
|
17
|
+
this.name = "AgentSDKError";
|
|
18
|
+
this.code = options?.code;
|
|
19
|
+
this.retryable = options?.retryable ?? false;
|
|
20
|
+
this.httpStatus = options?.httpStatus;
|
|
21
|
+
}
|
|
22
|
+
/** Check if an error is an AgentSDKError (works across bundled copies) */
|
|
23
|
+
static is(error) {
|
|
24
|
+
return error instanceof Error && "_agentSDKError" in error && error._agentSDKError === true;
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
// src/auth/types.ts
|
|
29
|
+
var AuthError = class extends AgentSDKError {
|
|
30
|
+
constructor(message, options) {
|
|
31
|
+
super(message, { ...options, code: "AUTH_EXPIRED" /* AUTH_EXPIRED */ });
|
|
9
32
|
this.name = "AuthError";
|
|
10
33
|
}
|
|
11
34
|
};
|
|
@@ -118,6 +141,12 @@ var CopilotAuth = class {
|
|
|
118
141
|
tokenType: data.token_type ?? "bearer",
|
|
119
142
|
obtainedAt: Date.now()
|
|
120
143
|
};
|
|
144
|
+
if (data.refresh_token) {
|
|
145
|
+
token.refreshToken = data.refresh_token;
|
|
146
|
+
}
|
|
147
|
+
if (data.expires_in) {
|
|
148
|
+
token.expiresIn = data.expires_in;
|
|
149
|
+
}
|
|
121
150
|
try {
|
|
122
151
|
const login = await this.fetchUserLogin(data.access_token, signal);
|
|
123
152
|
if (login) token.login = login;
|
|
@@ -155,6 +184,62 @@ var CopilotAuth = class {
|
|
|
155
184
|
const user = await response.json();
|
|
156
185
|
return user.login;
|
|
157
186
|
}
|
|
187
|
+
/**
|
|
188
|
+
* Refresh an expired Copilot token using a refresh token.
|
|
189
|
+
* Only works for GitHub App tokens that include a refresh_token.
|
|
190
|
+
*
|
|
191
|
+
* @param refreshToken - The refresh token from the original auth flow
|
|
192
|
+
* @param signal - Optional abort signal
|
|
193
|
+
* @returns Fresh CopilotAuthToken with new access and refresh tokens
|
|
194
|
+
* @throws {TokenExchangeError} If the refresh request fails
|
|
195
|
+
*
|
|
196
|
+
* @example
|
|
197
|
+
* ```ts
|
|
198
|
+
* const auth = new CopilotAuth();
|
|
199
|
+
* const newToken = await auth.refreshToken(oldToken.refreshToken!);
|
|
200
|
+
* ```
|
|
201
|
+
*/
|
|
202
|
+
async refreshToken(refreshToken, signal) {
|
|
203
|
+
const response = await this.fetchFn(ACCESS_TOKEN_URL, {
|
|
204
|
+
method: "POST",
|
|
205
|
+
headers: {
|
|
206
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
207
|
+
Accept: "application/json"
|
|
208
|
+
},
|
|
209
|
+
body: new URLSearchParams({
|
|
210
|
+
client_id: CLIENT_ID,
|
|
211
|
+
grant_type: "refresh_token",
|
|
212
|
+
refresh_token: refreshToken
|
|
213
|
+
}),
|
|
214
|
+
signal
|
|
215
|
+
});
|
|
216
|
+
if (!response.ok) {
|
|
217
|
+
throw new TokenExchangeError(
|
|
218
|
+
`Token refresh failed: ${response.status} ${response.statusText}`
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
const data = await response.json();
|
|
222
|
+
if (data.error) {
|
|
223
|
+
throw new TokenExchangeError(
|
|
224
|
+
data.error_description ?? `Token refresh error: ${data.error}`
|
|
225
|
+
);
|
|
226
|
+
}
|
|
227
|
+
if (!data.access_token) {
|
|
228
|
+
throw new TokenExchangeError("Token refresh response missing access_token");
|
|
229
|
+
}
|
|
230
|
+
const token = {
|
|
231
|
+
accessToken: data.access_token,
|
|
232
|
+
tokenType: data.token_type ?? "bearer",
|
|
233
|
+
obtainedAt: Date.now()
|
|
234
|
+
};
|
|
235
|
+
if (data.refresh_token) {
|
|
236
|
+
token.refreshToken = data.refresh_token;
|
|
237
|
+
}
|
|
238
|
+
if (data.expires_in) {
|
|
239
|
+
token.expiresIn = data.expires_in;
|
|
240
|
+
}
|
|
241
|
+
return token;
|
|
242
|
+
}
|
|
158
243
|
delay(ms, signal) {
|
|
159
244
|
return new Promise((resolve, reject) => {
|
|
160
245
|
const timer = setTimeout(resolve, ms);
|
|
@@ -349,11 +434,184 @@ function hexEncode(bytes) {
|
|
|
349
434
|
return Buffer.from(bytes).toString("hex");
|
|
350
435
|
}
|
|
351
436
|
|
|
437
|
+
// src/auth/refresh-manager.ts
|
|
438
|
+
var TokenRefreshManager = class {
|
|
439
|
+
currentToken;
|
|
440
|
+
refreshFn;
|
|
441
|
+
threshold;
|
|
442
|
+
maxRetries;
|
|
443
|
+
retryDelayMs;
|
|
444
|
+
minDelayMs;
|
|
445
|
+
timerId = null;
|
|
446
|
+
running = false;
|
|
447
|
+
disposed = false;
|
|
448
|
+
listeners = {
|
|
449
|
+
refreshed: /* @__PURE__ */ new Set(),
|
|
450
|
+
error: /* @__PURE__ */ new Set(),
|
|
451
|
+
expired: /* @__PURE__ */ new Set(),
|
|
452
|
+
disposed: /* @__PURE__ */ new Set()
|
|
453
|
+
};
|
|
454
|
+
constructor(options) {
|
|
455
|
+
this.currentToken = { ...options.token };
|
|
456
|
+
this.refreshFn = options.refresh;
|
|
457
|
+
this.threshold = options.refreshThreshold ?? 0.8;
|
|
458
|
+
this.maxRetries = options.maxRetries ?? 3;
|
|
459
|
+
this.retryDelayMs = options.retryDelayMs ?? 1e3;
|
|
460
|
+
this.minDelayMs = options.minDelayMs ?? 1e3;
|
|
461
|
+
}
|
|
462
|
+
/** Register an event listener */
|
|
463
|
+
on(event, listener) {
|
|
464
|
+
this.listeners[event].add(listener);
|
|
465
|
+
return this;
|
|
466
|
+
}
|
|
467
|
+
/** Remove an event listener */
|
|
468
|
+
off(event, listener) {
|
|
469
|
+
this.listeners[event].delete(listener);
|
|
470
|
+
return this;
|
|
471
|
+
}
|
|
472
|
+
/** Current token managed by this instance */
|
|
473
|
+
get token() {
|
|
474
|
+
return { ...this.currentToken };
|
|
475
|
+
}
|
|
476
|
+
/** Whether the manager is currently running */
|
|
477
|
+
get isRunning() {
|
|
478
|
+
return this.running;
|
|
479
|
+
}
|
|
480
|
+
/** Whether the manager has been disposed */
|
|
481
|
+
get isDisposed() {
|
|
482
|
+
return this.disposed;
|
|
483
|
+
}
|
|
484
|
+
/**
|
|
485
|
+
* Start automatic refresh scheduling.
|
|
486
|
+
* If the token is already expired, emits "expired" immediately.
|
|
487
|
+
* If the token has no expiresIn, does nothing (long-lived token).
|
|
488
|
+
*/
|
|
489
|
+
start() {
|
|
490
|
+
if (this.disposed) return;
|
|
491
|
+
if (this.running) return;
|
|
492
|
+
this.running = true;
|
|
493
|
+
this.schedule();
|
|
494
|
+
}
|
|
495
|
+
/** Stop automatic refresh (can be restarted with start()) */
|
|
496
|
+
stop() {
|
|
497
|
+
this.running = false;
|
|
498
|
+
this.clearTimer();
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* Update the managed token (e.g. after manual refresh).
|
|
502
|
+
* Reschedules automatic refresh if running.
|
|
503
|
+
*/
|
|
504
|
+
updateToken(token) {
|
|
505
|
+
if (this.disposed) return;
|
|
506
|
+
this.currentToken = { ...token };
|
|
507
|
+
if (this.running) {
|
|
508
|
+
this.clearTimer();
|
|
509
|
+
this.schedule();
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
/** Stop and clean up all resources */
|
|
513
|
+
dispose() {
|
|
514
|
+
if (this.disposed) return;
|
|
515
|
+
this.stop();
|
|
516
|
+
this.disposed = true;
|
|
517
|
+
this.emit("disposed");
|
|
518
|
+
for (const set of Object.values(this.listeners)) {
|
|
519
|
+
set.clear();
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
// ─── Private ──────────────────────────────────────────────────
|
|
523
|
+
schedule() {
|
|
524
|
+
if (!this.running || this.disposed) return;
|
|
525
|
+
const delayMs = this.computeRefreshDelay();
|
|
526
|
+
if (delayMs === null) {
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
529
|
+
if (delayMs <= 0) {
|
|
530
|
+
this.timerId = setTimeout(() => {
|
|
531
|
+
this.timerId = null;
|
|
532
|
+
if (!this.running || this.disposed) return;
|
|
533
|
+
void this.performRefresh();
|
|
534
|
+
}, 0);
|
|
535
|
+
return;
|
|
536
|
+
}
|
|
537
|
+
this.timerId = setTimeout(() => {
|
|
538
|
+
this.timerId = null;
|
|
539
|
+
if (!this.running || this.disposed) return;
|
|
540
|
+
void this.performRefresh();
|
|
541
|
+
}, Math.max(delayMs, this.minDelayMs));
|
|
542
|
+
}
|
|
543
|
+
async performRefresh(attempt = 1) {
|
|
544
|
+
if (!this.running || this.disposed) return;
|
|
545
|
+
try {
|
|
546
|
+
const newToken = await this.refreshFn(this.currentToken);
|
|
547
|
+
if (!this.running || this.disposed) return;
|
|
548
|
+
this.currentToken = { ...newToken };
|
|
549
|
+
this.emit("refreshed", newToken);
|
|
550
|
+
this.schedule();
|
|
551
|
+
} catch (err) {
|
|
552
|
+
if (!this.running || this.disposed) return;
|
|
553
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
554
|
+
this.emit("error", error, attempt);
|
|
555
|
+
if (attempt < this.maxRetries) {
|
|
556
|
+
const delay = this.retryDelayMs * Math.pow(2, attempt - 1);
|
|
557
|
+
this.timerId = setTimeout(() => {
|
|
558
|
+
this.timerId = null;
|
|
559
|
+
if (!this.running || this.disposed) return;
|
|
560
|
+
void this.performRefresh(attempt + 1);
|
|
561
|
+
}, delay);
|
|
562
|
+
} else {
|
|
563
|
+
if (this.isTokenExpired()) {
|
|
564
|
+
this.running = false;
|
|
565
|
+
this.emit("expired");
|
|
566
|
+
} else {
|
|
567
|
+
const expiresIn = this.currentToken.expiresIn;
|
|
568
|
+
if (expiresIn == null) return;
|
|
569
|
+
const expiresAt = this.currentToken.obtainedAt + expiresIn * 1e3;
|
|
570
|
+
const waitMs = Math.max(expiresAt - Date.now(), this.minDelayMs);
|
|
571
|
+
this.timerId = setTimeout(() => {
|
|
572
|
+
this.timerId = null;
|
|
573
|
+
if (!this.running || this.disposed) return;
|
|
574
|
+
void this.performRefresh();
|
|
575
|
+
}, waitMs);
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
computeRefreshDelay() {
|
|
581
|
+
if (this.currentToken.expiresIn == null) return null;
|
|
582
|
+
const lifetimeMs = this.currentToken.expiresIn * 1e3;
|
|
583
|
+
const refreshAtMs = this.currentToken.obtainedAt + lifetimeMs * this.threshold;
|
|
584
|
+
const now = Date.now();
|
|
585
|
+
const delay = refreshAtMs - now;
|
|
586
|
+
return delay;
|
|
587
|
+
}
|
|
588
|
+
isTokenExpired() {
|
|
589
|
+
if (this.currentToken.expiresIn == null) return false;
|
|
590
|
+
const expiresAt = this.currentToken.obtainedAt + this.currentToken.expiresIn * 1e3;
|
|
591
|
+
return Date.now() >= expiresAt;
|
|
592
|
+
}
|
|
593
|
+
clearTimer() {
|
|
594
|
+
if (this.timerId !== null) {
|
|
595
|
+
clearTimeout(this.timerId);
|
|
596
|
+
this.timerId = null;
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
emit(event, ...args) {
|
|
600
|
+
for (const listener of this.listeners[event]) {
|
|
601
|
+
try {
|
|
602
|
+
listener(...args);
|
|
603
|
+
} catch {
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
};
|
|
608
|
+
|
|
352
609
|
exports.AccessDeniedError = AccessDeniedError;
|
|
353
610
|
exports.AuthError = AuthError;
|
|
354
611
|
exports.ClaudeAuth = ClaudeAuth;
|
|
355
612
|
exports.CopilotAuth = CopilotAuth;
|
|
356
613
|
exports.DeviceCodeExpiredError = DeviceCodeExpiredError;
|
|
357
614
|
exports.TokenExchangeError = TokenExchangeError;
|
|
615
|
+
exports.TokenRefreshManager = TokenRefreshManager;
|
|
358
616
|
//# sourceMappingURL=index.cjs.map
|
|
359
617
|
//# sourceMappingURL=index.cjs.map
|