@agent-api/sdk 1.1.0 → 1.1.2

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/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # Changelog — @agent-api/sdk
2
2
 
3
+ ## 1.1.2
4
+
5
+ ### Added
6
+
7
+ - Added a model-facing `local_workspace` driver/tool primitive for local workspace operations.
8
+ - Added approval-aware dispatch for mutating local workspace actions.
9
+
10
+ ### Changed
11
+
12
+ - Replaced fragmented local workspace tool presentation with an action-based adapter over the low-level local APIs.
13
+
14
+ ## 1.1.1
15
+
16
+ ### Added
17
+
18
+ - Browser/device login helpers for CLI and desktop integrations: `client.auth.startDeviceAuth()`, `client.auth.pollDeviceAuth()`, and `client.auth.waitForDeviceAuth()`.
19
+ - Convenience methods on `AgentAPI`: `startDeviceAuth()`, `pollDeviceAuth()`, and `waitForDeviceAuth()`.
20
+ - `DeviceAuthFlowError` for expired, consumed, or timed-out device login flows.
21
+
3
22
  ## 1.1.0
4
23
 
5
24
  ### Added
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Production JavaScript/TypeScript SDK for the Managed Agent API.
4
4
 
5
- **Published on npm:** [`@agent-api/sdk`](https://www.npmjs.com/package/@agent-api/sdk) (v1.0.8)
5
+ **Published on npm:** [`@agent-api/sdk`](https://www.npmjs.com/package/@agent-api/sdk) (v1.1.2)
6
6
 
7
7
  ## Install
8
8
 
@@ -46,7 +46,7 @@ src/
46
46
  errors.ts # Typed error hierarchy + retry helpers
47
47
  pagination.ts # Cursor pagination utilities
48
48
  streaming.ts # SSE parser
49
- resources/ # responses, models, presets, tools, volumes, skills
49
+ resources/ # auth, responses, models, presets, tools, volumes, skills
50
50
  types/ # Request/response TypeScript types
51
51
  internal/http.ts # Retries, timeouts, User-Agent
52
52
  ```
@@ -61,6 +61,25 @@ src/
61
61
  | `client.tools` | `list` |
62
62
  | `client.volumes` | `list`, `create`, `retrieve`, `update`, `delete`, `listEntries`, `searchEntries`, `readFile`, `writeFile`, `deletePath`, `reconcileUsage`, `createDirectory`, `downloadArchive`, `summarize`, `readLines`, `patchLines`, `grep` |
63
63
  | `client.skills` | `list`, `create`, `discover`, `focus`, `createDev`, `updateFile`, `retrieve`, `update`, `archive`, `delete`, `diff`, `acceptDev`, `discardDev`, `exportArchive`, `importArchive`, `pushDirectory`, `pullDirectory`, `listFiles`, `readFile`, `writeFile`, `deleteFile` |
64
+ | `client.auth` | `startDeviceAuth`, `pollDeviceAuth`, `waitForDeviceAuth` |
65
+
66
+ ## Browser Device Login
67
+
68
+ CLI and desktop apps can use browser login without handling user passwords or static API keys.
69
+
70
+ ```typescript
71
+ const challenge = await client.auth.startDeviceAuth({ client_name: "Agent CLI" });
72
+ console.log(`Open ${challenge.verification_uri_complete}`);
73
+
74
+ const session = await client.auth.waitForDeviceAuth({
75
+ device_code: challenge.device_code,
76
+ interval_seconds: challenge.interval_seconds,
77
+ });
78
+
79
+ console.log(session.access_token);
80
+ ```
81
+
82
+ The SDK returns URLs and polling helpers only. Opening the browser belongs to the CLI, Electron, Tauri, or native host app.
64
83
 
65
84
  ## Durable Volumes
66
85
 
package/dist/client.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { AuthResource } from "./resources/auth.js";
1
2
  import { ModelsResource } from "./resources/models.js";
2
3
  import { PresetsResource } from "./resources/presets.js";
3
4
  import { ResponsesResource } from "./resources/responses.js";
@@ -23,7 +24,11 @@ export declare class AgentAPI {
23
24
  readonly tools: ToolsResource;
24
25
  readonly volumes: VolumesResource;
25
26
  readonly skills: SkillsResource;
27
+ readonly auth: AuthResource;
26
28
  private readonly http;
27
29
  constructor(options?: ClientOptions);
30
+ startDeviceAuth: (...args: Parameters<AuthResource["startDeviceAuth"]>) => Promise<import("./index.js").DeviceAuthStart>;
31
+ pollDeviceAuth: (...args: Parameters<AuthResource["pollDeviceAuth"]>) => Promise<import("./index.js").DeviceAuthPollResult>;
32
+ waitForDeviceAuth: (...args: Parameters<AuthResource["waitForDeviceAuth"]>) => Promise<import("./index.js").ApprovedDeviceAuth>;
28
33
  }
29
34
  export { VERSION };
package/dist/client.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { APIConnectionError } from "./errors.js";
2
2
  import { readEnv } from "./internal/env.js";
3
3
  import { HTTPClient } from "./internal/http.js";
4
+ import { AuthResource } from "./resources/auth.js";
4
5
  import { ModelsResource } from "./resources/models.js";
5
6
  import { PresetsResource } from "./resources/presets.js";
6
7
  import { ResponsesResource } from "./resources/responses.js";
@@ -25,6 +26,7 @@ export class AgentAPI {
25
26
  tools;
26
27
  volumes;
27
28
  skills;
29
+ auth;
28
30
  http;
29
31
  constructor(options = {}) {
30
32
  this.apiKey = options.apiKey ?? readEnv("AGENT_API_KEY");
@@ -53,6 +55,10 @@ export class AgentAPI {
53
55
  this.tools = new ToolsResource(this.http);
54
56
  this.volumes = new VolumesResource(this.http);
55
57
  this.skills = new SkillsResource(this.http);
58
+ this.auth = new AuthResource(this.http);
56
59
  }
60
+ startDeviceAuth = (...args) => this.auth.startDeviceAuth(...args);
61
+ pollDeviceAuth = (...args) => this.auth.pollDeviceAuth(...args);
62
+ waitForDeviceAuth = (...args) => this.auth.waitForDeviceAuth(...args);
57
63
  }
58
64
  export { VERSION };
package/dist/index.d.ts CHANGED
@@ -5,5 +5,8 @@ export { APIError, APIConnectionError, APIStatusError, AuthenticationError, BadR
5
5
  export * from "./types/index.js";
6
6
  export { functionCallOutputInput, pendingFunctionCalls, runLocalFunctionHandlers, } from "./local-functions.js";
7
7
  export type { LocalFunctionHandler, LocalFunctionHandlers } from "./local-functions.js";
8
+ export { LocalWorkspaceDriver, createLocalWorkspaceToolRegistry, localWorkspaceToolDefinition, localWorkspaceToolInstructions, } from "./local/tools.js";
9
+ export type { LocalWorkspaceAction, LocalWorkspaceAccessMode, LocalWorkspaceToolRegistry, LocalWorkspaceToolRegistryOptions, } from "./local/tools.js";
8
10
  export { localSkillFromDirectory, pendingLocalSkillCalls, runLocalSkillHandlers } from "./local-skills.js";
9
11
  export type { LocalSkillDirectoryOptions } from "./local-skills.js";
12
+ export { AuthResource, DeviceAuthFlowError } from "./resources/auth.js";
package/dist/index.js CHANGED
@@ -3,4 +3,6 @@ export { Page, collectPage } from "./pagination.js";
3
3
  export { APIError, APIConnectionError, APIStatusError, AuthenticationError, BadRequestError, InternalServerError, NotFoundError, PermissionDeniedError, RateLimitError, isRetryableStatus, parseResponseError, } from "./errors.js";
4
4
  export * from "./types/index.js";
5
5
  export { functionCallOutputInput, pendingFunctionCalls, runLocalFunctionHandlers, } from "./local-functions.js";
6
+ export { LocalWorkspaceDriver, createLocalWorkspaceToolRegistry, localWorkspaceToolDefinition, localWorkspaceToolInstructions, } from "./local/tools.js";
6
7
  export { localSkillFromDirectory, pendingLocalSkillCalls, runLocalSkillHandlers } from "./local-skills.js";
8
+ export { AuthResource, DeviceAuthFlowError } from "./resources/auth.js";
@@ -1,2 +1,3 @@
1
1
  export * from "./core.js";
2
2
  export * from "./context.js";
3
+ export * from "./tools.js";
@@ -1,2 +1,3 @@
1
1
  export * from "./core.js";
2
2
  export * from "./context.js";
3
+ export * from "./tools.js";
@@ -0,0 +1,34 @@
1
+ import type { FunctionTool } from "../types/tools.js";
2
+ import type { LocalWorkspace } from "./core.js";
3
+ export type LocalWorkspaceAccessMode = "approval" | "full";
4
+ export type LocalWorkspaceAction = "summarize" | "list" | "search" | "grep" | "read" | "read_lines" | "context" | "snapshot" | "classify_path" | "preview_edits" | "apply_edits" | "write" | "mkdir" | "delete";
5
+ export interface LocalWorkspaceToolRegistryOptions {
6
+ accessMode?: LocalWorkspaceAccessMode;
7
+ toolName?: string;
8
+ }
9
+ export interface LocalWorkspaceToolRegistry {
10
+ readonly workspace: LocalWorkspace;
11
+ readonly accessMode: LocalWorkspaceAccessMode;
12
+ readonly toolName: string;
13
+ definitions(): FunctionTool[];
14
+ handlers(): Record<string, (args: Record<string, unknown>) => Promise<Record<string, unknown>>>;
15
+ execute(name: string, args: Record<string, unknown>): Promise<Record<string, unknown>>;
16
+ requiresApproval(name: string, args?: Record<string, unknown>): boolean;
17
+ }
18
+ export interface LocalWorkspaceDriverOptions {
19
+ accessMode?: LocalWorkspaceAccessMode;
20
+ }
21
+ export declare class LocalWorkspaceDriver {
22
+ readonly workspace: LocalWorkspace;
23
+ readonly accessMode: LocalWorkspaceAccessMode;
24
+ constructor(workspace: LocalWorkspace, options?: LocalWorkspaceDriverOptions);
25
+ dispatch(args: Record<string, unknown>): Promise<Record<string, unknown>>;
26
+ requiresApproval(args: Record<string, unknown>): boolean;
27
+ private dispatchApplyEdits;
28
+ private dispatchWrite;
29
+ private dispatchMkdir;
30
+ private dispatchDelete;
31
+ }
32
+ export declare function createLocalWorkspaceToolRegistry(workspace: LocalWorkspace, options?: LocalWorkspaceToolRegistryOptions): LocalWorkspaceToolRegistry;
33
+ export declare function localWorkspaceToolDefinition(name?: string): FunctionTool;
34
+ export declare function localWorkspaceToolInstructions(): string;
@@ -0,0 +1,373 @@
1
+ import { createLocalContextPackage } from "./context.js";
2
+ export class LocalWorkspaceDriver {
3
+ workspace;
4
+ accessMode;
5
+ constructor(workspace, options = {}) {
6
+ this.workspace = workspace;
7
+ this.accessMode = options.accessMode ?? "approval";
8
+ }
9
+ async dispatch(args) {
10
+ const action = workspaceAction(args);
11
+ switch (action) {
12
+ case "summarize":
13
+ return localToolResult(action, localSummaryResult(await this.workspace.summarize(summaryArgs(args))));
14
+ case "list":
15
+ return localToolResult(action, await this.workspace.listEntries(optionalStringArg(args, "path") ?? ".", listArgs(args)));
16
+ case "search":
17
+ return localToolResult(action, await this.workspace.searchEntries(searchEntriesArgs(args)));
18
+ case "grep":
19
+ return localToolResult(action, await this.workspace.grep(grepArgs(args)));
20
+ case "read":
21
+ return localToolResult(action, await this.workspace.readFile(stringArg(args, "path"), readFileArgs(args)));
22
+ case "read_lines":
23
+ return localToolResult(action, await this.workspace.readLines(stringArg(args, "path"), readLinesArgs(args)));
24
+ case "context":
25
+ return localToolResult(action, await createLocalContextPackage(this.workspace, contextPackageArgs(args)));
26
+ case "snapshot":
27
+ return localToolResult(action, await this.workspace.snapshot(snapshotArgs(args)));
28
+ case "classify_path":
29
+ return localToolResult(action, this.workspace.classifyPath(stringArg(args, "path")));
30
+ case "preview_edits":
31
+ return localToolResult(action, await this.workspace.previewEdits(editsArg(args)));
32
+ case "apply_edits":
33
+ return await this.dispatchApplyEdits(args);
34
+ case "write":
35
+ return await this.dispatchWrite(args);
36
+ case "mkdir":
37
+ return await this.dispatchMkdir(args);
38
+ case "delete":
39
+ return await this.dispatchDelete(args);
40
+ default:
41
+ throw new Error(`unsupported local_workspace action: ${action}`);
42
+ }
43
+ }
44
+ requiresApproval(args) {
45
+ if (this.accessMode === "full") {
46
+ return false;
47
+ }
48
+ return mutatingLocalWorkspaceActions.has(workspaceAction(args));
49
+ }
50
+ async dispatchApplyEdits(args) {
51
+ const edits = editsArg(args);
52
+ if (this.accessMode !== "full") {
53
+ return approvalRequired("apply_edits", args, await this.workspace.previewEdits(edits));
54
+ }
55
+ return localToolResult("apply_edits", await this.workspace.applyEdits(edits));
56
+ }
57
+ async dispatchWrite(args) {
58
+ if (this.accessMode !== "full") {
59
+ return approvalRequired("write", args);
60
+ }
61
+ return localToolResult("write", await this.workspace.writeText(stringArg(args, "path"), stringArg(args, "content")));
62
+ }
63
+ async dispatchMkdir(args) {
64
+ if (this.accessMode !== "full") {
65
+ return approvalRequired("mkdir", args);
66
+ }
67
+ return localToolResult("mkdir", await this.workspace.createDirectory(stringArg(args, "path")));
68
+ }
69
+ async dispatchDelete(args) {
70
+ if (this.accessMode !== "full") {
71
+ return approvalRequired("delete", args);
72
+ }
73
+ return localToolResult("delete", await this.workspace.deletePath(stringArg(args, "path")));
74
+ }
75
+ }
76
+ export function createLocalWorkspaceToolRegistry(workspace, options = {}) {
77
+ const toolName = options.toolName ?? "local_workspace";
78
+ const driver = new LocalWorkspaceDriver(workspace, { accessMode: options.accessMode });
79
+ const definition = localWorkspaceToolDefinition(toolName);
80
+ return {
81
+ workspace,
82
+ accessMode: driver.accessMode,
83
+ toolName,
84
+ definitions: () => [{ ...definition }],
85
+ handlers: () => ({ [toolName]: (args) => driver.dispatch(args) }),
86
+ execute: async (name, args) => {
87
+ if (name !== toolName) {
88
+ throw new Error(`unknown local workspace tool: ${name}`);
89
+ }
90
+ return await driver.dispatch(args);
91
+ },
92
+ requiresApproval: (name, args = {}) => name === toolName && driver.requiresApproval(args),
93
+ };
94
+ }
95
+ export function localWorkspaceToolDefinition(name = "local_workspace") {
96
+ return {
97
+ type: "function",
98
+ name,
99
+ description: localWorkspaceToolDescription,
100
+ parameters: localWorkspaceToolParameters(),
101
+ strict: false,
102
+ };
103
+ }
104
+ export function localWorkspaceToolInstructions() {
105
+ return localWorkspaceToolDescription;
106
+ }
107
+ const localWorkspaceActions = [
108
+ "summarize",
109
+ "list",
110
+ "search",
111
+ "grep",
112
+ "read",
113
+ "read_lines",
114
+ "context",
115
+ "snapshot",
116
+ "classify_path",
117
+ "preview_edits",
118
+ "apply_edits",
119
+ "write",
120
+ "mkdir",
121
+ "delete",
122
+ ];
123
+ const mutatingLocalWorkspaceActions = new Set([
124
+ "apply_edits",
125
+ "write",
126
+ "mkdir",
127
+ "delete",
128
+ ]);
129
+ const localWorkspaceToolDescription = [
130
+ "Inspect and modify the selected local workspace through one model-facing primitive.",
131
+ "Use action=list/search/grep/summarize/context to discover files, read/read_lines for file content, preview_edits before edits, and apply_edits/write/mkdir/delete only when mutation is intended.",
132
+ "In approval mode, mutating actions return requires_approval with a safe preview instead of changing files. In full mode, mutating actions execute immediately.",
133
+ "Paths are relative to the selected local workspace; never use absolute paths.",
134
+ ].join(" ");
135
+ function localWorkspaceToolParameters() {
136
+ return objectSchema({
137
+ action: {
138
+ type: "string",
139
+ enum: localWorkspaceActions,
140
+ description: "Workspace operation. Prefer summarize/list/search/grep before reading or editing. Prefer read_lines and apply_edits for source changes.",
141
+ },
142
+ path: stringSchema("Relative path. File path for read/write/delete/edit actions; directory base for list/search/grep/summarize/context/snapshot."),
143
+ query: stringSchema("Path/name query for search, or optional context query."),
144
+ pattern: stringSchema("Literal text pattern for grep."),
145
+ content: stringSchema("Text content for write."),
146
+ start_line: integerSchema("1-based start line for read_lines and edit entries."),
147
+ end_line: integerSchema("1-based inclusive end line; omit or 0 for EOF when supported."),
148
+ replacement: stringSchema("Replacement text for simple single edit flows."),
149
+ edits: {
150
+ type: "array",
151
+ minItems: 1,
152
+ description: "Line edits for preview_edits/apply_edits.",
153
+ items: objectSchema({
154
+ path: requiredStringSchema("Relative file path."),
155
+ start_line: requiredIntegerSchema("1-based start line."),
156
+ end_line: integerSchema("1-based inclusive end line."),
157
+ replacement: stringSchema("Replacement text. Empty string deletes the line range."),
158
+ expected_sha256: stringSchema("Optional expected SHA-256 for conflict detection."),
159
+ }, ["path", "start_line"]),
160
+ },
161
+ options: objectSchema({
162
+ recursive: booleanSchema("List recursively."),
163
+ include_directories: booleanSchema("Include directories in list results."),
164
+ max_depth: integerSchema("Maximum recursive list depth."),
165
+ limit: integerSchema("Maximum entries or matches."),
166
+ max_files: integerSchema("Maximum files to scan or package."),
167
+ max_bytes: integerSchema("Maximum total bytes to read/package."),
168
+ max_bytes_per_file: integerSchema("Maximum bytes per file."),
169
+ max_previews: integerSchema("Maximum summary previews."),
170
+ include_content: booleanSchema("Include file contents in context packages."),
171
+ include_summary: booleanSchema("Include workspace summary in context packages."),
172
+ include_search: booleanSchema("Include grep results in context packages when query is set."),
173
+ include_secrets: booleanSchema("Include likely secret file contents in context packages."),
174
+ hash: booleanSchema("Include SHA-256 hashes in snapshots."),
175
+ }),
176
+ }, ["action"]);
177
+ }
178
+ function workspaceAction(args) {
179
+ const value = stringArg(args, "action").trim().toLowerCase();
180
+ if (!localWorkspaceActions.includes(value)) {
181
+ throw new Error(`unsupported local_workspace action: ${value}`);
182
+ }
183
+ return value;
184
+ }
185
+ function summaryArgs(args) {
186
+ return {
187
+ path: optionalStringArg(args, "path"),
188
+ maxFiles: optionalNumberArg(args, "maxFiles", "max_files"),
189
+ maxPreviews: optionalNumberArg(args, "maxPreviews", "max_previews"),
190
+ };
191
+ }
192
+ function grepArgs(args) {
193
+ return {
194
+ pattern: stringArg(args, "pattern"),
195
+ path: optionalStringArg(args, "path"),
196
+ limit: optionalNumberArg(args, "limit"),
197
+ maxFiles: optionalNumberArg(args, "maxFiles", "max_files"),
198
+ };
199
+ }
200
+ function listArgs(args) {
201
+ return {
202
+ recursive: optionalBooleanArg(args, "recursive"),
203
+ includeDirectories: optionalBooleanArg(args, "includeDirectories", "include_directories"),
204
+ maxDepth: optionalNumberArg(args, "maxDepth", "max_depth"),
205
+ };
206
+ }
207
+ function searchEntriesArgs(args) {
208
+ return {
209
+ query: stringArg(args, "query"),
210
+ path: optionalStringArg(args, "path"),
211
+ limit: optionalNumberArg(args, "limit"),
212
+ };
213
+ }
214
+ function readFileArgs(args) {
215
+ return {
216
+ maxBytes: optionalNumberArg(args, "maxBytes", "max_bytes"),
217
+ };
218
+ }
219
+ function readLinesArgs(args) {
220
+ return {
221
+ startLine: numberArg(args, "startLine", "start_line"),
222
+ endLine: optionalNumberArg(args, "endLine", "end_line"),
223
+ maxBytes: optionalNumberArg(args, "maxBytes", "max_bytes"),
224
+ };
225
+ }
226
+ function snapshotArgs(args) {
227
+ return {
228
+ path: optionalStringArg(args, "path"),
229
+ hash: optionalBooleanArg(args, "hash"),
230
+ maxBytesPerFile: optionalNumberArg(args, "maxBytesPerFile", "max_bytes_per_file"),
231
+ };
232
+ }
233
+ function contextPackageArgs(args) {
234
+ return {
235
+ path: optionalStringArg(args, "path"),
236
+ query: optionalStringArg(args, "query"),
237
+ maxFiles: optionalNumberArg(args, "maxFiles", "max_files"),
238
+ maxBytes: optionalNumberArg(args, "maxBytes", "max_bytes"),
239
+ maxBytesPerFile: optionalNumberArg(args, "maxBytesPerFile", "max_bytes_per_file"),
240
+ includeContent: optionalBooleanArg(args, "includeContent", "include_content"),
241
+ includeSummary: optionalBooleanArg(args, "includeSummary", "include_summary"),
242
+ includeSearch: optionalBooleanArg(args, "includeSearch", "include_search"),
243
+ includeSecrets: optionalBooleanArg(args, "includeSecrets", "include_secrets"),
244
+ };
245
+ }
246
+ function editsArg(args) {
247
+ const edits = args.edits;
248
+ if (Array.isArray(edits) && edits.length > 0) {
249
+ return edits.map((edit) => {
250
+ if (!edit || typeof edit !== "object") {
251
+ throw new Error("each edit must be an object");
252
+ }
253
+ return editArg(edit);
254
+ });
255
+ }
256
+ if (typeof args.path === "string" && typeof (args.startLine ?? args.start_line) === "number") {
257
+ return [editArg(args)];
258
+ }
259
+ throw new Error("edits must be a non-empty array");
260
+ }
261
+ function editArg(record) {
262
+ return {
263
+ path: stringArg(record, "path"),
264
+ startLine: numberArg(record, "startLine", "start_line"),
265
+ endLine: optionalNumberArg(record, "endLine", "end_line"),
266
+ replacement: typeof record.replacement === "string" ? record.replacement : "",
267
+ expectedSha256: optionalStringArg(record, "expectedSha256", "expected_sha256"),
268
+ };
269
+ }
270
+ function localSummaryResult(summary) {
271
+ return summary;
272
+ }
273
+ function localToolResult(action, value) {
274
+ const result = value;
275
+ if (result && typeof result === "object" && !Array.isArray(result)) {
276
+ return { ok: true, action, ...result };
277
+ }
278
+ return { ok: true, action, result };
279
+ }
280
+ function stringArg(args, key, alternateKey) {
281
+ const direct = args[key] ?? (alternateKey ? args[alternateKey] : undefined);
282
+ const fromOptions = args.options && typeof args.options === "object"
283
+ ? args.options[key] ?? (alternateKey ? args.options[alternateKey] : undefined)
284
+ : undefined;
285
+ const value = direct ?? fromOptions;
286
+ if (typeof value !== "string" || !value.trim()) {
287
+ throw new Error(`${key} must be a non-empty string`);
288
+ }
289
+ return value;
290
+ }
291
+ function optionalStringArg(args, key, alternateKey) {
292
+ const direct = args[key] ?? (alternateKey ? args[alternateKey] : undefined);
293
+ const fromOptions = args.options && typeof args.options === "object"
294
+ ? args.options[key] ?? (alternateKey ? args.options[alternateKey] : undefined)
295
+ : undefined;
296
+ const value = direct ?? fromOptions;
297
+ if (value == null || value === "")
298
+ return undefined;
299
+ if (typeof value !== "string") {
300
+ throw new Error(`${key} must be a string`);
301
+ }
302
+ return value;
303
+ }
304
+ function numberArg(args, key, alternateKey) {
305
+ const direct = args[key] ?? (alternateKey ? args[alternateKey] : undefined);
306
+ const fromOptions = args.options && typeof args.options === "object"
307
+ ? args.options[key] ?? (alternateKey ? args.options[alternateKey] : undefined)
308
+ : undefined;
309
+ const value = direct ?? fromOptions;
310
+ if (typeof value !== "number" || !Number.isFinite(value)) {
311
+ throw new Error(`${key} must be a number`);
312
+ }
313
+ return Math.trunc(value);
314
+ }
315
+ function optionalNumberArg(args, key, alternateKey) {
316
+ const direct = args[key] ?? (alternateKey ? args[alternateKey] : undefined);
317
+ const fromOptions = args.options && typeof args.options === "object"
318
+ ? args.options[key] ?? (alternateKey ? args.options[alternateKey] : undefined)
319
+ : undefined;
320
+ const value = direct ?? fromOptions;
321
+ if (value == null)
322
+ return undefined;
323
+ if (typeof value !== "number" || !Number.isFinite(value)) {
324
+ throw new Error(`${key} must be a number`);
325
+ }
326
+ return Math.trunc(value);
327
+ }
328
+ function optionalBooleanArg(args, key, alternateKey) {
329
+ const direct = args[key] ?? (alternateKey ? args[alternateKey] : undefined);
330
+ const fromOptions = args.options && typeof args.options === "object"
331
+ ? args.options[key] ?? (alternateKey ? args.options[alternateKey] : undefined)
332
+ : undefined;
333
+ const value = direct ?? fromOptions;
334
+ if (value == null)
335
+ return undefined;
336
+ if (typeof value !== "boolean") {
337
+ throw new Error(`${key} must be a boolean`);
338
+ }
339
+ return value;
340
+ }
341
+ function approvalRequired(action, args, preview) {
342
+ return {
343
+ ok: false,
344
+ action,
345
+ requires_approval: true,
346
+ arguments: args,
347
+ preview,
348
+ message: `local_workspace action ${action} requires approval`,
349
+ };
350
+ }
351
+ function objectSchema(properties, required = []) {
352
+ return {
353
+ type: "object",
354
+ properties,
355
+ required,
356
+ additionalProperties: false,
357
+ };
358
+ }
359
+ function stringSchema(description) {
360
+ return { type: "string", description };
361
+ }
362
+ function requiredStringSchema(description) {
363
+ return stringSchema(description);
364
+ }
365
+ function integerSchema(description) {
366
+ return { type: "integer", description };
367
+ }
368
+ function booleanSchema(description) {
369
+ return { type: "boolean", description };
370
+ }
371
+ function requiredIntegerSchema(description) {
372
+ return integerSchema(description);
373
+ }
@@ -0,0 +1,14 @@
1
+ import type { HTTPClient } from "../internal/http.js";
2
+ import type { ApprovedDeviceAuth, DeviceAuthPollResult, DeviceAuthStart, PollDeviceAuthParams, StartDeviceAuthParams, WaitForDeviceAuthParams } from "../types/auth.js";
3
+ import type { RequestOptions } from "../types/common.js";
4
+ export declare class AuthResource {
5
+ private readonly http;
6
+ constructor(http: HTTPClient);
7
+ startDeviceAuth(params?: StartDeviceAuthParams, options?: RequestOptions): Promise<DeviceAuthStart>;
8
+ pollDeviceAuth(params: PollDeviceAuthParams, options?: RequestOptions): Promise<DeviceAuthPollResult>;
9
+ waitForDeviceAuth(params: WaitForDeviceAuthParams, options?: RequestOptions): Promise<ApprovedDeviceAuth>;
10
+ }
11
+ export declare class DeviceAuthFlowError extends Error {
12
+ readonly result?: DeviceAuthPollResult;
13
+ constructor(message: string, result?: DeviceAuthPollResult);
14
+ }
@@ -0,0 +1,87 @@
1
+ const defaultDevicePollIntervalSeconds = 5;
2
+ export class AuthResource {
3
+ http;
4
+ constructor(http) {
5
+ this.http = http;
6
+ }
7
+ startDeviceAuth(params = {}, options = {}) {
8
+ return this.http.request("POST", "/v1/auth/device/start", params, options);
9
+ }
10
+ pollDeviceAuth(params, options = {}) {
11
+ requireDeviceCode(params.device_code);
12
+ return this.http.request("POST", "/v1/auth/device/poll", params, options);
13
+ }
14
+ async waitForDeviceAuth(params, options = {}) {
15
+ requireDeviceCode(params.device_code);
16
+ const startedAt = Date.now();
17
+ for (;;) {
18
+ throwIfAborted(params.signal);
19
+ const result = await this.pollDeviceAuth({ device_code: params.device_code }, options);
20
+ params.on_poll?.(result);
21
+ if (result.status === "approved" && result.access_token && result.refresh_token) {
22
+ return result;
23
+ }
24
+ if (result.status === "expired" || result.status === "consumed") {
25
+ throw new DeviceAuthFlowError(result.message || `Device auth ${result.status}`, result);
26
+ }
27
+ const timeoutMs = effectiveTimeoutMs(params, result);
28
+ if (timeoutMs !== undefined && Date.now() - startedAt >= timeoutMs) {
29
+ throw new DeviceAuthFlowError("Device auth timed out", result);
30
+ }
31
+ await sleep(pollDelayMs(params, result), params.signal);
32
+ }
33
+ }
34
+ }
35
+ export class DeviceAuthFlowError extends Error {
36
+ result;
37
+ constructor(message, result) {
38
+ super(message);
39
+ this.name = "DeviceAuthFlowError";
40
+ this.result = result;
41
+ Object.setPrototypeOf(this, DeviceAuthFlowError.prototype);
42
+ }
43
+ }
44
+ function requireDeviceCode(deviceCode) {
45
+ if (!deviceCode || !deviceCode.trim()) {
46
+ throw new TypeError("device_code is required");
47
+ }
48
+ }
49
+ function pollDelayMs(params, result) {
50
+ const seconds = params.interval_seconds ?? result.interval_seconds ?? defaultDevicePollIntervalSeconds;
51
+ return Math.max(1, seconds) * 1000;
52
+ }
53
+ function effectiveTimeoutMs(params, result) {
54
+ if (params.timeout_ms !== undefined) {
55
+ return Math.max(0, params.timeout_ms);
56
+ }
57
+ const expiresAt = result.expires_at;
58
+ if (!expiresAt)
59
+ return undefined;
60
+ return Math.max(0, expiresAt * 1000 - Date.now());
61
+ }
62
+ function sleep(ms, signal) {
63
+ if (!signal) {
64
+ return new Promise((resolve) => setTimeout(resolve, ms));
65
+ }
66
+ throwIfAborted(signal);
67
+ return new Promise((resolve, reject) => {
68
+ const timeout = setTimeout(cleanupResolve, ms);
69
+ signal.addEventListener("abort", cleanupReject, { once: true });
70
+ function cleanupResolve() {
71
+ signal?.removeEventListener("abort", cleanupReject);
72
+ resolve();
73
+ }
74
+ function cleanupReject() {
75
+ clearTimeout(timeout);
76
+ reject(abortError());
77
+ }
78
+ });
79
+ }
80
+ function throwIfAborted(signal) {
81
+ if (signal?.aborted) {
82
+ throw abortError();
83
+ }
84
+ }
85
+ function abortError() {
86
+ return new DOMException("Device auth wait aborted", "AbortError");
87
+ }
@@ -0,0 +1,63 @@
1
+ export type DeviceAuthStatus = "pending" | "approved" | "expired" | "consumed" | string;
2
+ export interface DeviceAuthStart {
3
+ device_code: string;
4
+ user_code: string;
5
+ verification_uri: string;
6
+ verification_uri_complete: string;
7
+ expires_at: number;
8
+ interval_seconds: number;
9
+ }
10
+ export interface AuthSession {
11
+ access_token: string;
12
+ refresh_token: string;
13
+ token_type?: string;
14
+ access_token_expires_at: number;
15
+ refresh_token_expires_at?: number;
16
+ user_id: string;
17
+ workspace_id: string;
18
+ workspace_name?: string;
19
+ workspace_role: string;
20
+ scopes: string[];
21
+ }
22
+ export interface DeviceAuthPollResult {
23
+ status: DeviceAuthStatus;
24
+ message?: string;
25
+ interval_seconds?: number;
26
+ expires_at?: number;
27
+ access_token?: string;
28
+ refresh_token?: string;
29
+ token_type?: string;
30
+ access_token_expires_at?: number;
31
+ refresh_token_expires_at?: number;
32
+ user_id?: string;
33
+ workspace_id?: string;
34
+ workspace_name?: string;
35
+ workspace_role?: string;
36
+ scopes?: string[];
37
+ }
38
+ export type ApprovedDeviceAuth = DeviceAuthPollResult & {
39
+ status: "approved";
40
+ access_token: string;
41
+ refresh_token: string;
42
+ access_token_expires_at: number;
43
+ user_id: string;
44
+ workspace_id: string;
45
+ workspace_role: string;
46
+ scopes: string[];
47
+ };
48
+ export interface StartDeviceAuthParams {
49
+ client_name?: string;
50
+ }
51
+ export interface PollDeviceAuthParams {
52
+ device_code: string;
53
+ }
54
+ export interface WaitForDeviceAuthParams extends PollDeviceAuthParams {
55
+ /** Polling interval in seconds. Defaults to the server interval or 5 seconds. */
56
+ interval_seconds?: number;
57
+ /** Overall wait timeout in milliseconds. Defaults to the challenge expiry when present. */
58
+ timeout_ms?: number;
59
+ /** Optional cancellation signal for CLI/Desktop integrations. */
60
+ signal?: AbortSignal;
61
+ /** Called after every poll response, including pending responses. */
62
+ on_poll?: (result: DeviceAuthPollResult) => void;
63
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -6,3 +6,4 @@ export * from "./streaming.js";
6
6
  export * from "./catalog.js";
7
7
  export * from "./volumes.js";
8
8
  export * from "./skills.js";
9
+ export * from "./auth.js";
@@ -6,3 +6,4 @@ export * from "./streaming.js";
6
6
  export * from "./catalog.js";
7
7
  export * from "./volumes.js";
8
8
  export * from "./skills.js";
9
+ export * from "./auth.js";
@@ -2,10 +2,17 @@ import type { AgentCapabilityPreference, ErrorInfo, ModelRoutingMode, ModelRouti
2
2
  import type { ContentPart, Input, MemoryOptions, ReasoningConfig, ResponseFormat } from "./input.js";
3
3
  import type { LocalSkillDescriptor, SkillReference } from "./skills.js";
4
4
  import type { Tool } from "./tools.js";
5
+ export interface CallerContext {
6
+ timezone?: string;
7
+ locale?: string;
8
+ locality?: string;
9
+ extra?: unknown;
10
+ }
5
11
  export interface ResponseCreateParamsBase {
6
12
  input: Input;
7
13
  instructions?: string;
8
14
  language_preference?: string;
15
+ caller_context?: CallerContext;
9
16
  model?: string;
10
17
  models?: string[];
11
18
  model_routing?: ModelRoutingMode;
package/dist/version.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export declare const VERSION = "1.1.0";
2
- export declare const USER_AGENT = "@agent-api/sdk/1.1.0";
1
+ export declare const VERSION = "1.1.2";
2
+ export declare const USER_AGENT = "@agent-api/sdk/1.1.2";
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
- export const VERSION = "1.1.0";
1
+ export const VERSION = "1.1.2";
2
2
  export const USER_AGENT = `@agent-api/sdk/${VERSION}`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-api/sdk",
3
- "version": "1.1.0",
3
+ "version": "1.1.2",
4
4
  "description": "Production JavaScript SDK for the Managed Agent API",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -46,7 +46,7 @@
46
46
  "build": "tsc -p tsconfig.json",
47
47
  "sync-version": "node scripts/sync-version.mjs",
48
48
  "prepack": "npm run sync-version && npm run build",
49
- "test": "npm run sync-version && npm run build && node --test test/index.test.mjs test/local-function-integration.test.mjs test/local-runtime.test.mjs",
49
+ "test": "npm run sync-version && npm run build && node --test test/index.test.mjs test/local-function-integration.test.mjs test/local-runtime.test.mjs test/local-tools.test.mjs",
50
50
  "test:integration": "npm run sync-version && npm run build && node --test test/integration.test.mjs",
51
51
  "test:integration:local-functions": "npm run sync-version && npm run build && node --test test/local-function-integration.test.mjs",
52
52
  "check:routes": "node scripts/check-routes.mjs"