@zenadmin-ai/sdk 0.2.0 → 0.3.1
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/dist/auth.d.ts +5 -0
- package/dist/client.d.ts +15 -2
- package/dist/errors.d.ts +1 -1
- package/dist/index.js +51 -9
- package/dist/types.d.ts +18 -3
- package/package.json +1 -1
package/dist/auth.d.ts
CHANGED
|
@@ -8,6 +8,11 @@ export interface ResolvedCredentials {
|
|
|
8
8
|
source: "option" | "environment" | "file" | null;
|
|
9
9
|
/** The credentials file is readable by other users. */
|
|
10
10
|
insecureFile: boolean;
|
|
11
|
+
/**
|
|
12
|
+
* Set when a saved token was not used because it was saved for another API URL (this one): the
|
|
13
|
+
* token is never sent anywhere else.
|
|
14
|
+
*/
|
|
15
|
+
savedTokenUrl?: string;
|
|
11
16
|
}
|
|
12
17
|
/** Only http(s) origins; the agent API path is added by the client. */
|
|
13
18
|
export declare function normaliseApiUrl(value: string): string;
|
package/dist/client.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type Operation, type ReadResult, type Tool, type WhoAmI } from "./types.js";
|
|
2
|
-
export declare const SDK_VERSION = "0.
|
|
2
|
+
export declare const SDK_VERSION = "0.3.1";
|
|
3
3
|
export interface ZenAdminOptions {
|
|
4
4
|
token: string;
|
|
5
5
|
apiUrl?: string;
|
|
@@ -12,6 +12,13 @@ export interface ZenAdminOptions {
|
|
|
12
12
|
fetch?: typeof fetch;
|
|
13
13
|
/** Debug lines (method, path, status, request ID). Never the token or bodies. */
|
|
14
14
|
log?: (line: string) => void;
|
|
15
|
+
/**
|
|
16
|
+
* Correlation: every request's X-Request-Id becomes `<prefix>.<n>`, so a caller's own log line
|
|
17
|
+
* (the hosted MCP server's, for example) finds the backend's lines. 8–48 of A-Z a-z 0-9 _ -.
|
|
18
|
+
*/
|
|
19
|
+
requestIdPrefix?: string;
|
|
20
|
+
/** The longest Retry-After a 429 is retried after; a longer one is reported at once. Default 60 s. */
|
|
21
|
+
maxRetryWaitMs?: number;
|
|
15
22
|
/** For tests: how long to wait before a retry. */
|
|
16
23
|
sleep?: (ms: number) => Promise<void>;
|
|
17
24
|
}
|
|
@@ -25,6 +32,9 @@ export declare class ZenAdmin {
|
|
|
25
32
|
private readonly fetchImpl;
|
|
26
33
|
private readonly log?;
|
|
27
34
|
private readonly sleep;
|
|
35
|
+
private readonly requestIdPrefix?;
|
|
36
|
+
private readonly maxRetryWaitMs;
|
|
37
|
+
private requestCount;
|
|
28
38
|
constructor(options: ZenAdminOptions);
|
|
29
39
|
/** Token and URL from options, then ZENADMIN_TOKEN / ZENADMIN_API_URL, then `zen login`. */
|
|
30
40
|
static fromEnvironment(options?: Partial<ZenAdminOptions>, env?: NodeJS.ProcessEnv): Promise<ZenAdmin>;
|
|
@@ -32,7 +42,10 @@ export declare class ZenAdmin {
|
|
|
32
42
|
whoami(): Promise<WhoAmI>;
|
|
33
43
|
/** Every tool this token can use right now, with its input JSON Schema, kind and impact. */
|
|
34
44
|
tools(): Promise<Tool[]>;
|
|
35
|
-
/**
|
|
45
|
+
/**
|
|
46
|
+
* Runs a read tool: inventory.search, inventory.details, employees.search, catalog.search,
|
|
47
|
+
* orders.search or quotes.search (see tools() for what this token can use).
|
|
48
|
+
*/
|
|
36
49
|
read(toolId: string, input: Record<string, unknown>): Promise<ReadResult>;
|
|
37
50
|
/**
|
|
38
51
|
* Prepares a change. Nothing happens until the admin approves it in ZenAdmin. Sending the same
|
package/dist/errors.d.ts
CHANGED
|
@@ -48,6 +48,6 @@ export declare class NetworkError extends ZenAdminError {
|
|
|
48
48
|
}
|
|
49
49
|
/** No token was configured. */
|
|
50
50
|
export declare class NotSignedInError extends ZenAdminError {
|
|
51
|
-
constructor();
|
|
51
|
+
constructor(message?: string);
|
|
52
52
|
}
|
|
53
53
|
export declare function errorFromResponse(status: number, body: unknown, requestId: string | null, retryAfter: string | null): ZenAdminError;
|
package/dist/index.js
CHANGED
|
@@ -45,6 +45,15 @@ async function resolveCredentials(options = {}, env = process.env) {
|
|
|
45
45
|
return { token: env.ZENADMIN_TOKEN, apiUrl, source: "environment", insecureFile: false };
|
|
46
46
|
}
|
|
47
47
|
if (stored.creds) {
|
|
48
|
+
let savedFor;
|
|
49
|
+
try {
|
|
50
|
+
savedFor = normaliseApiUrl(stored.creds.api_url || DEFAULT_API_URL);
|
|
51
|
+
} catch {
|
|
52
|
+
savedFor = String(stored.creds.api_url);
|
|
53
|
+
}
|
|
54
|
+
if (savedFor !== apiUrl) {
|
|
55
|
+
return { token: null, apiUrl, source: null, insecureFile: stored.insecure, savedTokenUrl: savedFor };
|
|
56
|
+
}
|
|
48
57
|
return { token: stored.creds.token, apiUrl, source: "file", insecureFile: stored.insecure };
|
|
49
58
|
}
|
|
50
59
|
return { token: null, apiUrl, source: null, insecureFile: false };
|
|
@@ -160,10 +169,10 @@ class NetworkError extends ZenAdminError {
|
|
|
160
169
|
}
|
|
161
170
|
|
|
162
171
|
class NotSignedInError extends ZenAdminError {
|
|
163
|
-
constructor() {
|
|
172
|
+
constructor(message) {
|
|
164
173
|
super({
|
|
165
174
|
code: "NOT_SIGNED_IN",
|
|
166
|
-
message: "No ZenAdmin token. Create one in ZenAdmin (
|
|
175
|
+
message: message ?? "No ZenAdmin token. Create one in ZenAdmin (Zen AI > Access tokens), then run `zen login` or set ZENADMIN_TOKEN.",
|
|
167
176
|
status: 0
|
|
168
177
|
});
|
|
169
178
|
this.name = "NotSignedInError";
|
|
@@ -196,6 +205,7 @@ import { z } from "zod";
|
|
|
196
205
|
var ChannelSchema = z.enum(["console", "mcp", "cli"]);
|
|
197
206
|
var WhoAmISchema = z.object({
|
|
198
207
|
company_id: z.string(),
|
|
208
|
+
company_name: z.string().nullish(),
|
|
199
209
|
user_id: z.string(),
|
|
200
210
|
channel: ChannelSchema,
|
|
201
211
|
token: z.object({
|
|
@@ -240,7 +250,11 @@ var OperationSchema = z.object({
|
|
|
240
250
|
links: z.array(LinkSchema),
|
|
241
251
|
impact: z.enum(["low", "medium", "high"]),
|
|
242
252
|
expires_at: z.string(),
|
|
243
|
-
result: z.object({
|
|
253
|
+
result: z.object({
|
|
254
|
+
message: z.string(),
|
|
255
|
+
links: z.array(LinkSchema),
|
|
256
|
+
partial: z.object({ done: z.number(), total: z.number() }).optional()
|
|
257
|
+
}).nullable(),
|
|
244
258
|
error: z.object({ code: z.string(), message: z.string() }).nullable(),
|
|
245
259
|
channel: ChannelSchema.optional(),
|
|
246
260
|
approval_url: z.string().nullable().optional()
|
|
@@ -252,7 +266,7 @@ function outcomeOf(operation) {
|
|
|
252
266
|
case "running":
|
|
253
267
|
return "in_progress";
|
|
254
268
|
case "succeeded":
|
|
255
|
-
return "completed";
|
|
269
|
+
return operation.result?.partial ? "partial" : "completed";
|
|
256
270
|
case "failed":
|
|
257
271
|
return "failed";
|
|
258
272
|
case "cancelled":
|
|
@@ -264,10 +278,11 @@ function outcomeOf(operation) {
|
|
|
264
278
|
}
|
|
265
279
|
}
|
|
266
280
|
var isSettled = (operation) => !["pending_approval", "running"].includes(operation.status);
|
|
281
|
+
var isReusable = (operation) => !isSettled(operation) || operation.status === "unknown";
|
|
267
282
|
var ReadResultSchema = z.record(z.string(), z.unknown());
|
|
268
283
|
|
|
269
284
|
// packages/sdk/src/client.ts
|
|
270
|
-
var SDK_VERSION = "0.
|
|
285
|
+
var SDK_VERSION = "0.3.1";
|
|
271
286
|
var REQUEST_ID = /^[A-Za-z0-9_-]{8,64}$/;
|
|
272
287
|
var RETRY_STATUSES = new Set([429, 502, 503, 504]);
|
|
273
288
|
var defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
@@ -298,6 +313,9 @@ class ZenAdmin {
|
|
|
298
313
|
fetchImpl;
|
|
299
314
|
log;
|
|
300
315
|
sleep;
|
|
316
|
+
requestIdPrefix;
|
|
317
|
+
maxRetryWaitMs;
|
|
318
|
+
requestCount = 0;
|
|
301
319
|
constructor(options) {
|
|
302
320
|
if (!options.token)
|
|
303
321
|
throw new NotSignedInError;
|
|
@@ -310,9 +328,19 @@ class ZenAdmin {
|
|
|
310
328
|
this.fetchImpl = options.fetch ?? fetch;
|
|
311
329
|
this.log = options.log;
|
|
312
330
|
this.sleep = options.sleep ?? defaultSleep;
|
|
331
|
+
this.maxRetryWaitMs = options.maxRetryWaitMs ?? 60000;
|
|
332
|
+
if (options.requestIdPrefix !== undefined) {
|
|
333
|
+
if (!/^[A-Za-z0-9_-]{8,48}$/.test(options.requestIdPrefix)) {
|
|
334
|
+
throw new Error("requestIdPrefix is 8–48 letters, digits, _ or -.");
|
|
335
|
+
}
|
|
336
|
+
this.requestIdPrefix = options.requestIdPrefix;
|
|
337
|
+
}
|
|
313
338
|
}
|
|
314
339
|
static async fromEnvironment(options = {}, env = process.env) {
|
|
315
340
|
const creds = await resolveCredentials({ token: options.token, apiUrl: options.apiUrl }, env);
|
|
341
|
+
if (!creds.token && creds.savedTokenUrl) {
|
|
342
|
+
throw new NotSignedInError(`The token saved by \`zen login\` is for ${creds.savedTokenUrl}, so it is not sent to ${creds.apiUrl}. ` + `Run \`zen login --api-url ${creds.apiUrl}\` to sign in there, or set ZENADMIN_TOKEN.`);
|
|
343
|
+
}
|
|
316
344
|
if (!creds.token)
|
|
317
345
|
throw new NotSignedInError;
|
|
318
346
|
return new ZenAdmin({ ...options, token: creds.token, apiUrl: creds.apiUrl });
|
|
@@ -362,7 +390,19 @@ class ZenAdmin {
|
|
|
362
390
|
const signal = options.signal;
|
|
363
391
|
for (;; ) {
|
|
364
392
|
signal?.throwIfAborted();
|
|
365
|
-
|
|
393
|
+
let operation;
|
|
394
|
+
try {
|
|
395
|
+
operation = await this.operation(id, { signal });
|
|
396
|
+
} catch (error) {
|
|
397
|
+
const wait = error instanceof RateLimitError ? error.retryAfterSeconds * 1000 : null;
|
|
398
|
+
if (wait === null || Date.now() + wait > deadline) {
|
|
399
|
+
if (last && wait !== null)
|
|
400
|
+
return { operation: last, timedOut: true };
|
|
401
|
+
throw error;
|
|
402
|
+
}
|
|
403
|
+
await abortable(this.sleep(wait), signal);
|
|
404
|
+
continue;
|
|
405
|
+
}
|
|
366
406
|
signal?.throwIfAborted();
|
|
367
407
|
if (!last || last.status !== operation.status)
|
|
368
408
|
options.onUpdate?.(operation);
|
|
@@ -379,7 +419,7 @@ class ZenAdmin {
|
|
|
379
419
|
let attempt = 0;
|
|
380
420
|
for (;; ) {
|
|
381
421
|
signal?.throwIfAborted();
|
|
382
|
-
const requestId = randomUUID();
|
|
422
|
+
const requestId = this.requestIdPrefix ? `${this.requestIdPrefix}.${++this.requestCount}` : randomUUID();
|
|
383
423
|
const requestSignal = signal ? AbortSignal.any([signal, AbortSignal.timeout(this.timeoutMs)]) : AbortSignal.timeout(this.timeoutMs);
|
|
384
424
|
let response;
|
|
385
425
|
try {
|
|
@@ -416,9 +456,10 @@ class ZenAdmin {
|
|
|
416
456
|
}
|
|
417
457
|
if (!response.ok) {
|
|
418
458
|
const error = errorFromResponse(response.status, json, answeredId, response.headers.get("retry-after"));
|
|
419
|
-
|
|
459
|
+
const tooLong = error instanceof RateLimitError && error.retryAfterSeconds * 1000 > this.maxRetryWaitMs;
|
|
460
|
+
if (RETRY_STATUSES.has(response.status) && attempt < this.maxRetries && !tooLong) {
|
|
420
461
|
attempt++;
|
|
421
|
-
const wait = error instanceof RateLimitError ?
|
|
462
|
+
const wait = error instanceof RateLimitError ? error.retryAfterSeconds * 1000 : 250 * 2 ** attempt;
|
|
422
463
|
await abortable(this.sleep(wait), signal);
|
|
423
464
|
continue;
|
|
424
465
|
}
|
|
@@ -461,6 +502,7 @@ export {
|
|
|
461
502
|
clearCredentials,
|
|
462
503
|
credentialsPath,
|
|
463
504
|
errorFromResponse,
|
|
505
|
+
isReusable,
|
|
464
506
|
isSettled,
|
|
465
507
|
looksLikeToken,
|
|
466
508
|
normaliseApiUrl,
|
package/dist/types.d.ts
CHANGED
|
@@ -10,6 +10,7 @@ export declare const ChannelSchema: z.ZodEnum<{
|
|
|
10
10
|
}>;
|
|
11
11
|
export declare const WhoAmISchema: z.ZodObject<{
|
|
12
12
|
company_id: z.ZodString;
|
|
13
|
+
company_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
13
14
|
user_id: z.ZodString;
|
|
14
15
|
channel: z.ZodEnum<{
|
|
15
16
|
console: "console";
|
|
@@ -132,6 +133,10 @@ export declare const OperationSchema: z.ZodObject<{
|
|
|
132
133
|
label: z.ZodString;
|
|
133
134
|
href: z.ZodString;
|
|
134
135
|
}, z.core.$strip>>;
|
|
136
|
+
partial: z.ZodOptional<z.ZodObject<{
|
|
137
|
+
done: z.ZodNumber;
|
|
138
|
+
total: z.ZodNumber;
|
|
139
|
+
}, z.core.$strip>>;
|
|
135
140
|
}, z.core.$strip>>;
|
|
136
141
|
error: z.ZodNullable<z.ZodObject<{
|
|
137
142
|
code: z.ZodString;
|
|
@@ -147,12 +152,22 @@ export declare const OperationSchema: z.ZodObject<{
|
|
|
147
152
|
export type Operation = z.infer<typeof OperationSchema>;
|
|
148
153
|
/**
|
|
149
154
|
* What an operation's status means for the caller. A token can never approve, so a new proposal
|
|
150
|
-
* is always `approval_required` until the admin acts in ZenAdmin.
|
|
155
|
+
* is always `approval_required` until the admin acts in ZenAdmin. `in_progress` is approved and
|
|
156
|
+
* submitted; `partial` is a bulk change where some targets were not done.
|
|
151
157
|
*/
|
|
152
|
-
export type Outcome = "approval_required" | "in_progress" | "completed" | "failed" | "cancelled" | "expired" | "check_result";
|
|
153
|
-
export declare function outcomeOf(operation: Pick<Operation, "status">
|
|
158
|
+
export type Outcome = "approval_required" | "in_progress" | "completed" | "partial" | "failed" | "cancelled" | "expired" | "check_result";
|
|
159
|
+
export declare function outcomeOf(operation: Pick<Operation, "status"> & {
|
|
160
|
+
result?: Operation["result"];
|
|
161
|
+
}): Outcome;
|
|
154
162
|
/** Final statuses: nothing more will happen to the operation. */
|
|
155
163
|
export declare const isSettled: (operation: Pick<Operation, "status">) => boolean;
|
|
164
|
+
/**
|
|
165
|
+
* Whether asking for the same change again should get this operation back rather than a new one:
|
|
166
|
+
* while it still waits for approval or runs, and when its run did not report back (`unknown`: it
|
|
167
|
+
* may still be running, so a second proposal could repeat it). Done, failed, cancelled and expired
|
|
168
|
+
* changes are proposed afresh, for the admin to approve again.
|
|
169
|
+
*/
|
|
170
|
+
export declare const isReusable: (operation: Pick<Operation, "status">) => boolean;
|
|
156
171
|
/** Read tool results are passed through as the server returns them (bounded lists with links). */
|
|
157
172
|
export declare const ReadResultSchema: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
158
173
|
export type ReadResult = z.infer<typeof ReadResultSchema>;
|