@zenadmin-ai/sdk 0.0.0-stage → 0.2.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 CHANGED
@@ -1,3 +1,15 @@
1
- # Temporary Holding Version
1
+ # @zenadmin-ai/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ TypeScript client for the ZenAdmin agent API, used by `@zenadmin-ai/cli` and `@zenadmin-ai/mcp-server`.
4
+ Runs on Node 22+ and Bun.
5
+
6
+ ```ts
7
+ import { ZenAdmin } from "@zenadmin-ai/sdk";
8
+
9
+ const zen = await ZenAdmin.fromEnvironment({ client: "cli" }); // ZENADMIN_TOKEN or `zen login`
10
+ const found = await zen.read("employees.search", { query: "ada" });
11
+ const change = await zen.propose("webstore.request_quote", input, { requestId: "nightly-job-42" });
12
+ // change.approval_url: an admin approves it in ZenAdmin; follow it with zen.waitForOperation(change.id)
13
+ ```
14
+
15
+ A token can read and prepare changes, never approve them. Guide: https://github.com/Usehybrid/mewtwo#typescript-sdk
package/dist/auth.d.ts ADDED
@@ -0,0 +1,33 @@
1
+ export declare const DEFAULT_API_URL = "https://prod-api.zenadmin.ai";
2
+ export declare const looksLikeToken: (value: string) => boolean;
3
+ export declare function credentialsPath(env?: NodeJS.ProcessEnv): string;
4
+ export interface ResolvedCredentials {
5
+ token: string | null;
6
+ apiUrl: string;
7
+ /** Where the token came from, so `zen whoami` can say. */
8
+ source: "option" | "environment" | "file" | null;
9
+ /** The credentials file is readable by other users. */
10
+ insecureFile: boolean;
11
+ }
12
+ /** Only http(s) origins; the agent API path is added by the client. */
13
+ export declare function normaliseApiUrl(value: string): string;
14
+ export declare function resolveCredentials(options?: {
15
+ token?: string;
16
+ apiUrl?: string;
17
+ }, env?: NodeJS.ProcessEnv): Promise<ResolvedCredentials>;
18
+ /** Saves the token for this user only (directory 0700, file 0600). */
19
+ export declare function storeCredentials(token: string, apiUrl?: string, env?: NodeJS.ProcessEnv): Promise<string>;
20
+ /** Forgets the stored token. The token itself keeps working until it is revoked in ZenAdmin. */
21
+ export declare function clearCredentials(env?: NodeJS.ProcessEnv): Promise<boolean>;
22
+ /**
23
+ * Bun loads .env files from the working directory into process.env (expanding `$OTHER` references);
24
+ * Node does not. A .env in a project the admin happens to be in must not choose where the token goes
25
+ * (ZENADMIN_API_URL), which token or credentials file is used, or anything else, so every ZENADMIN_*
26
+ * key named in one of those files is dropped, whatever its value. A value set in the shell for the
27
+ * same key is dropped too, since the two cannot be told apart; `zen login`, `--api-url` and the
28
+ * MCP client's config still work.
29
+ */
30
+ export declare function withoutDotenvSettings(env?: NodeJS.ProcessEnv, cwd?: string): Promise<{
31
+ env: NodeJS.ProcessEnv;
32
+ ignored: string[];
33
+ }>;
@@ -0,0 +1,72 @@
1
+ import { type Operation, type ReadResult, type Tool, type WhoAmI } from "./types.js";
2
+ export declare const SDK_VERSION = "0.2.0";
3
+ export interface ZenAdminOptions {
4
+ token: string;
5
+ apiUrl?: string;
6
+ /** Recorded on every operation, so the admin sees where a change came from. */
7
+ client?: "mcp" | "cli";
8
+ userAgent?: string;
9
+ timeoutMs?: number;
10
+ maxRetries?: number;
11
+ /** For tests. */
12
+ fetch?: typeof fetch;
13
+ /** Debug lines (method, path, status, request ID). Never the token or bodies. */
14
+ log?: (line: string) => void;
15
+ /** For tests: how long to wait before a retry. */
16
+ sleep?: (ms: number) => Promise<void>;
17
+ }
18
+ export declare class ZenAdmin {
19
+ readonly apiUrl: string;
20
+ readonly client: "mcp" | "cli";
21
+ private readonly token;
22
+ private readonly userAgent;
23
+ private readonly timeoutMs;
24
+ private readonly maxRetries;
25
+ private readonly fetchImpl;
26
+ private readonly log?;
27
+ private readonly sleep;
28
+ constructor(options: ZenAdminOptions);
29
+ /** Token and URL from options, then ZENADMIN_TOKEN / ZENADMIN_API_URL, then `zen login`. */
30
+ static fromEnvironment(options?: Partial<ZenAdminOptions>, env?: NodeJS.ProcessEnv): Promise<ZenAdmin>;
31
+ /** Who the token acts as, and what it may do. Clients call this first and stop if it fails. */
32
+ whoami(): Promise<WhoAmI>;
33
+ /** Every tool this token can use right now, with its input JSON Schema, kind and impact. */
34
+ tools(): Promise<Tool[]>;
35
+ /** Runs a read tool (inventory.search, employees.search, catalog.search). */
36
+ read(toolId: string, input: Record<string, unknown>): Promise<ReadResult>;
37
+ /**
38
+ * Prepares a change. Nothing happens until the admin approves it in ZenAdmin. Sending the same
39
+ * requestId again (after a timeout, or from another process) returns the same proposal.
40
+ */
41
+ propose(actionId: string, input: Record<string, unknown>, options?: {
42
+ requestId?: string;
43
+ }): Promise<Operation & {
44
+ request_id: string;
45
+ }>;
46
+ operation(id: string, options?: {
47
+ signal?: AbortSignal;
48
+ }): Promise<Operation>;
49
+ /**
50
+ * The caller's proposal made with this request ID, or null if there is none. Lets a client that
51
+ * lost a response check before proposing again.
52
+ */
53
+ operationByRequest(requestId: string): Promise<Operation | null>;
54
+ /** Cancels a change that is still waiting for approval. Returns its state either way. */
55
+ cancel(id: string): Promise<Operation>;
56
+ /**
57
+ * Polls until the operation is settled (done, failed, cancelled, expired or check_result) or the
58
+ * time runs out, and returns the latest state. A timeout is not a failure: the change may still
59
+ * be approved later. Aborting `signal` stops at once, also mid-request or mid-wait, and rejects
60
+ * with the signal's reason.
61
+ */
62
+ waitForOperation(id: string, options?: {
63
+ timeoutMs?: number;
64
+ intervalMs?: number;
65
+ signal?: AbortSignal;
66
+ onUpdate?: (op: Operation) => void;
67
+ }): Promise<{
68
+ operation: Operation;
69
+ timedOut: boolean;
70
+ }>;
71
+ private request;
72
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Errors from the ZenAdmin agent API. `code` is the server's stable code (INVALID_TOKEN,
3
+ * INSUFFICIENT_SCOPE, APPROVAL_REQUIRED, IDEMPOTENCY_CONFLICT, ...); `requestId` is the X-Request-Id
4
+ * to quote to support. Messages never contain the token.
5
+ */
6
+ export declare class ZenAdminError extends Error {
7
+ readonly code: string;
8
+ readonly status: number;
9
+ readonly requestId: string | null;
10
+ constructor(opts: {
11
+ code: string;
12
+ message: string;
13
+ status: number;
14
+ requestId?: string | null;
15
+ });
16
+ toJSON(): {
17
+ error: {
18
+ code: string;
19
+ message: string;
20
+ status: number;
21
+ request_id: string | null;
22
+ };
23
+ };
24
+ }
25
+ /** Missing, malformed, expired or revoked token (401). */
26
+ export declare class AuthenticationError extends ZenAdminError {
27
+ constructor(message: string, requestId?: string | null, code?: string);
28
+ }
29
+ /** The token or the admin may not do this (403): scope, permission, or a console-only step. */
30
+ export declare class ForbiddenError extends ZenAdminError {
31
+ constructor(code: string, message: string, requestId?: string | null);
32
+ }
33
+ /** Unknown record, operation or action (404). ACTION_NOT_FOUND means the action is not supported. */
34
+ export declare class NotFoundError extends ZenAdminError {
35
+ constructor(code: string, message: string, requestId?: string | null);
36
+ }
37
+ /** The request conflicts with an earlier one, e.g. a request ID reused for another change (409). */
38
+ export declare class ConflictError extends ZenAdminError {
39
+ constructor(code: string, message: string, requestId?: string | null);
40
+ }
41
+ export declare class RateLimitError extends ZenAdminError {
42
+ readonly retryAfterSeconds: number;
43
+ constructor(message: string, retryAfterSeconds: number, requestId?: string | null);
44
+ }
45
+ /** The API could not be reached, or did not answer in time. */
46
+ export declare class NetworkError extends ZenAdminError {
47
+ constructor(message: string);
48
+ }
49
+ /** No token was configured. */
50
+ export declare class NotSignedInError extends ZenAdminError {
51
+ constructor();
52
+ }
53
+ export declare function errorFromResponse(status: number, body: unknown, requestId: string | null, retryAfter: string | null): ZenAdminError;
@@ -0,0 +1,4 @@
1
+ export { ZenAdmin, SDK_VERSION, type ZenAdminOptions } from "./client.js";
2
+ export * from "./auth.js";
3
+ export * from "./errors.js";
4
+ export * from "./types.js";
package/dist/index.js ADDED
@@ -0,0 +1,471 @@
1
+ // packages/sdk/src/client.ts
2
+ import { randomUUID } from "node:crypto";
3
+
4
+ // packages/sdk/src/auth.ts
5
+ import { chmod, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
6
+ import { homedir } from "node:os";
7
+ import { dirname, join } from "node:path";
8
+ var DEFAULT_API_URL = "https://prod-api.zenadmin.ai";
9
+ var TOKEN = /^zat_[A-Za-z0-9_-]{43}$/;
10
+ var looksLikeToken = (value) => TOKEN.test(value);
11
+ function credentialsPath(env = process.env) {
12
+ return env.ZENADMIN_CREDENTIALS_FILE || join(homedir(), ".zenadmin", "credentials.json");
13
+ }
14
+ function normaliseApiUrl(value) {
15
+ const url = new URL(value);
16
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
17
+ throw new Error("The API URL must start with https://");
18
+ }
19
+ if (url.protocol === "http:" && !["localhost", "127.0.0.1"].includes(url.hostname)) {
20
+ throw new Error("Use https:// for the API URL (http:// is only for localhost)");
21
+ }
22
+ return url.origin + url.pathname.replace(/\/+$/, "");
23
+ }
24
+ async function readStored(path) {
25
+ try {
26
+ const [raw, info] = await Promise.all([readFile(path, "utf8"), stat(path)]);
27
+ const parsed = JSON.parse(raw);
28
+ const insecure = process.platform !== "win32" && (info.mode & 63) !== 0;
29
+ if (typeof parsed.token !== "string")
30
+ return { creds: null, insecure };
31
+ return {
32
+ creds: { token: parsed.token, api_url: typeof parsed.api_url === "string" ? parsed.api_url : undefined },
33
+ insecure
34
+ };
35
+ } catch {
36
+ return { creds: null, insecure: false };
37
+ }
38
+ }
39
+ async function resolveCredentials(options = {}, env = process.env) {
40
+ const stored = await readStored(credentialsPath(env));
41
+ const apiUrl = normaliseApiUrl(options.apiUrl || env.ZENADMIN_API_URL || stored.creds?.api_url || DEFAULT_API_URL);
42
+ if (options.token)
43
+ return { token: options.token, apiUrl, source: "option", insecureFile: false };
44
+ if (env.ZENADMIN_TOKEN) {
45
+ return { token: env.ZENADMIN_TOKEN, apiUrl, source: "environment", insecureFile: false };
46
+ }
47
+ if (stored.creds) {
48
+ return { token: stored.creds.token, apiUrl, source: "file", insecureFile: stored.insecure };
49
+ }
50
+ return { token: null, apiUrl, source: null, insecureFile: false };
51
+ }
52
+ async function storeCredentials(token, apiUrl, env = process.env) {
53
+ if (!looksLikeToken(token))
54
+ throw new Error("That does not look like a ZenAdmin access token.");
55
+ const path = credentialsPath(env);
56
+ await mkdir(dirname(path), { recursive: true, mode: 448 });
57
+ const body = { token, ...apiUrl ? { api_url: normaliseApiUrl(apiUrl) } : {} };
58
+ await writeFile(path, `${JSON.stringify(body, null, 2)}
59
+ `, { mode: 384 });
60
+ await chmod(path, 384);
61
+ return path;
62
+ }
63
+ async function clearCredentials(env = process.env) {
64
+ try {
65
+ await rm(credentialsPath(env));
66
+ return true;
67
+ } catch {
68
+ return false;
69
+ }
70
+ }
71
+ var DOTENV_FILES = [".env", ".env.local", ".env.development", ".env.production", ".env.test"];
72
+ async function withoutDotenvSettings(env = process.env, cwd = process.cwd()) {
73
+ if (typeof globalThis.Bun === "undefined")
74
+ return { env, ignored: [] };
75
+ const named = new Set;
76
+ for (const file of DOTENV_FILES) {
77
+ let text;
78
+ try {
79
+ text = await readFile(join(cwd, file), "utf8");
80
+ } catch {
81
+ continue;
82
+ }
83
+ for (const match of text.matchAll(/^[ \t]*(?:export[ \t]+)?(ZENADMIN_[A-Za-z0-9_]*)[ \t]*[=:]/gm)) {
84
+ named.add(match[1]);
85
+ }
86
+ }
87
+ const cleaned = { ...env };
88
+ const ignored = [...named].filter((key) => cleaned[key] !== undefined).sort();
89
+ for (const key of ignored)
90
+ delete cleaned[key];
91
+ return { env: cleaned, ignored };
92
+ }
93
+
94
+ // packages/sdk/src/errors.ts
95
+ class ZenAdminError extends Error {
96
+ code;
97
+ status;
98
+ requestId;
99
+ constructor(opts) {
100
+ super(opts.message);
101
+ this.name = "ZenAdminError";
102
+ this.code = opts.code;
103
+ this.status = opts.status;
104
+ this.requestId = opts.requestId ?? null;
105
+ }
106
+ toJSON() {
107
+ return {
108
+ error: {
109
+ code: this.code,
110
+ message: this.message,
111
+ status: this.status,
112
+ request_id: this.requestId
113
+ }
114
+ };
115
+ }
116
+ }
117
+
118
+ class AuthenticationError extends ZenAdminError {
119
+ constructor(message, requestId, code = "INVALID_TOKEN") {
120
+ super({ code, message, status: 401, requestId });
121
+ this.name = "AuthenticationError";
122
+ }
123
+ }
124
+
125
+ class ForbiddenError extends ZenAdminError {
126
+ constructor(code, message, requestId) {
127
+ super({ code, message, status: 403, requestId });
128
+ this.name = "ForbiddenError";
129
+ }
130
+ }
131
+
132
+ class NotFoundError extends ZenAdminError {
133
+ constructor(code, message, requestId) {
134
+ super({ code, message, status: 404, requestId });
135
+ this.name = "NotFoundError";
136
+ }
137
+ }
138
+
139
+ class ConflictError extends ZenAdminError {
140
+ constructor(code, message, requestId) {
141
+ super({ code, message, status: 409, requestId });
142
+ this.name = "ConflictError";
143
+ }
144
+ }
145
+
146
+ class RateLimitError extends ZenAdminError {
147
+ retryAfterSeconds;
148
+ constructor(message, retryAfterSeconds, requestId) {
149
+ super({ code: "RATE_LIMITED", message, status: 429, requestId });
150
+ this.name = "RateLimitError";
151
+ this.retryAfterSeconds = retryAfterSeconds;
152
+ }
153
+ }
154
+
155
+ class NetworkError extends ZenAdminError {
156
+ constructor(message) {
157
+ super({ code: "NETWORK_ERROR", message, status: 0 });
158
+ this.name = "NetworkError";
159
+ }
160
+ }
161
+
162
+ class NotSignedInError extends ZenAdminError {
163
+ constructor() {
164
+ super({
165
+ code: "NOT_SIGNED_IN",
166
+ message: "No ZenAdmin token. Create one in ZenAdmin (Ask AI > Access tokens), then run `zen login` or set ZENADMIN_TOKEN.",
167
+ status: 0
168
+ });
169
+ this.name = "NotSignedInError";
170
+ }
171
+ }
172
+ function errorFromResponse(status, body, requestId, retryAfter) {
173
+ const data = body && typeof body === "object" ? body : {};
174
+ const code = typeof data.code === "string" ? data.code : `HTTP_${status}`;
175
+ const message = typeof data.message === "string" && data.message ? data.message : `ZenAdmin answered with status ${status}.`;
176
+ switch (status) {
177
+ case 401:
178
+ return new AuthenticationError(message, requestId, code);
179
+ case 403:
180
+ return new ForbiddenError(code, message, requestId);
181
+ case 404:
182
+ return new NotFoundError(code, message, requestId);
183
+ case 409:
184
+ return new ConflictError(code, message, requestId);
185
+ case 429: {
186
+ const seconds = Number(retryAfter);
187
+ return new RateLimitError(message, Number.isFinite(seconds) && seconds > 0 ? seconds : 60, requestId);
188
+ }
189
+ default:
190
+ return new ZenAdminError({ code, message, status, requestId });
191
+ }
192
+ }
193
+
194
+ // packages/sdk/src/types.ts
195
+ import { z } from "zod";
196
+ var ChannelSchema = z.enum(["console", "mcp", "cli"]);
197
+ var WhoAmISchema = z.object({
198
+ company_id: z.string(),
199
+ user_id: z.string(),
200
+ channel: ChannelSchema,
201
+ token: z.object({
202
+ id: z.string(),
203
+ kind: z.enum(["personal", "automation", "connection"]),
204
+ scopes: z.array(z.enum(["read", "propose"])),
205
+ expires_at: z.string()
206
+ }).nullable(),
207
+ can_propose: z.boolean()
208
+ });
209
+ var ImpactSchema = z.enum(["none", "low", "medium", "high"]);
210
+ var ToolSchema = z.object({
211
+ id: z.string().regex(/^[a-z_]+\.[a-z_]+$/),
212
+ label: z.string(),
213
+ description: z.string(),
214
+ kind: z.enum(["read", "write"]),
215
+ module: z.string(),
216
+ requires_approval: z.boolean(),
217
+ impact: ImpactSchema,
218
+ scope: z.enum(["read", "propose"]),
219
+ input_schema: z.record(z.string(), z.unknown())
220
+ });
221
+ var ToolListSchema = z.object({ tools: z.array(ToolSchema) });
222
+ var LinkSchema = z.object({ label: z.string(), href: z.string() });
223
+ var OperationStatusSchema = z.enum([
224
+ "pending_approval",
225
+ "running",
226
+ "succeeded",
227
+ "failed",
228
+ "cancelled",
229
+ "expired",
230
+ "unknown"
231
+ ]);
232
+ var OperationSchema = z.object({
233
+ id: z.string(),
234
+ action: z.string(),
235
+ status: OperationStatusSchema,
236
+ payload_hash: z.string(),
237
+ title: z.string(),
238
+ fields: z.array(z.object({ label: z.string(), value: z.string(), from: z.string().nullish() })),
239
+ effects: z.array(z.string()),
240
+ links: z.array(LinkSchema),
241
+ impact: z.enum(["low", "medium", "high"]),
242
+ expires_at: z.string(),
243
+ result: z.object({ message: z.string(), links: z.array(LinkSchema) }).nullable(),
244
+ error: z.object({ code: z.string(), message: z.string() }).nullable(),
245
+ channel: ChannelSchema.optional(),
246
+ approval_url: z.string().nullable().optional()
247
+ });
248
+ function outcomeOf(operation) {
249
+ switch (operation.status) {
250
+ case "pending_approval":
251
+ return "approval_required";
252
+ case "running":
253
+ return "in_progress";
254
+ case "succeeded":
255
+ return "completed";
256
+ case "failed":
257
+ return "failed";
258
+ case "cancelled":
259
+ return "cancelled";
260
+ case "expired":
261
+ return "expired";
262
+ default:
263
+ return "check_result";
264
+ }
265
+ }
266
+ var isSettled = (operation) => !["pending_approval", "running"].includes(operation.status);
267
+ var ReadResultSchema = z.record(z.string(), z.unknown());
268
+
269
+ // packages/sdk/src/client.ts
270
+ var SDK_VERSION = "0.2.0";
271
+ var REQUEST_ID = /^[A-Za-z0-9_-]{8,64}$/;
272
+ var RETRY_STATUSES = new Set([429, 502, 503, 504]);
273
+ var defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
274
+ function abortable(wait, signal) {
275
+ if (!signal)
276
+ return wait;
277
+ signal.throwIfAborted();
278
+ return new Promise((resolve, reject) => {
279
+ const onAbort = () => reject(signal.reason);
280
+ signal.addEventListener("abort", onAbort, { once: true });
281
+ wait.then(() => {
282
+ signal.removeEventListener("abort", onAbort);
283
+ resolve();
284
+ }, (error) => {
285
+ signal.removeEventListener("abort", onAbort);
286
+ reject(error);
287
+ });
288
+ });
289
+ }
290
+
291
+ class ZenAdmin {
292
+ apiUrl;
293
+ client;
294
+ token;
295
+ userAgent;
296
+ timeoutMs;
297
+ maxRetries;
298
+ fetchImpl;
299
+ log;
300
+ sleep;
301
+ constructor(options) {
302
+ if (!options.token)
303
+ throw new NotSignedInError;
304
+ this.token = options.token;
305
+ this.apiUrl = normaliseApiUrl(options.apiUrl ?? DEFAULT_API_URL);
306
+ this.client = options.client ?? "cli";
307
+ this.userAgent = options.userAgent ?? `zenadmin-sdk/${SDK_VERSION} (node ${process.version})`;
308
+ this.timeoutMs = options.timeoutMs ?? 30000;
309
+ this.maxRetries = options.maxRetries ?? 3;
310
+ this.fetchImpl = options.fetch ?? fetch;
311
+ this.log = options.log;
312
+ this.sleep = options.sleep ?? defaultSleep;
313
+ }
314
+ static async fromEnvironment(options = {}, env = process.env) {
315
+ const creds = await resolveCredentials({ token: options.token, apiUrl: options.apiUrl }, env);
316
+ if (!creds.token)
317
+ throw new NotSignedInError;
318
+ return new ZenAdmin({ ...options, token: creds.token, apiUrl: creds.apiUrl });
319
+ }
320
+ whoami() {
321
+ return this.request("GET", "/whoami", WhoAmISchema);
322
+ }
323
+ async tools() {
324
+ return (await this.request("GET", "/tools", ToolListSchema)).tools;
325
+ }
326
+ read(toolId, input) {
327
+ return this.request("POST", `/actions/${encodeURIComponent(toolId)}`, ReadResultSchema, { input });
328
+ }
329
+ async propose(actionId, input, options = {}) {
330
+ const requestId = options.requestId ?? randomUUID();
331
+ if (!REQUEST_ID.test(requestId)) {
332
+ throw new ZenAdminError({
333
+ code: "INVALID_INPUT",
334
+ message: "A request ID is 8–64 letters, digits, - or _.",
335
+ status: 0
336
+ });
337
+ }
338
+ const operation = await this.request("POST", `/actions/${encodeURIComponent(actionId)}/propose`, OperationSchema, { input, client_request_id: requestId });
339
+ return { ...operation, request_id: requestId };
340
+ }
341
+ operation(id, options = {}) {
342
+ return this.request("GET", `/operations/${encodeURIComponent(id)}`, OperationSchema, undefined, options.signal);
343
+ }
344
+ async operationByRequest(requestId) {
345
+ if (!REQUEST_ID.test(requestId))
346
+ return null;
347
+ try {
348
+ return await this.request("GET", `/operations/by-request/${encodeURIComponent(requestId)}`, OperationSchema);
349
+ } catch (error) {
350
+ if (error instanceof NotFoundError)
351
+ return null;
352
+ throw error;
353
+ }
354
+ }
355
+ cancel(id) {
356
+ return this.request("POST", `/operations/${encodeURIComponent(id)}/cancel`, OperationSchema, {});
357
+ }
358
+ async waitForOperation(id, options = {}) {
359
+ const deadline = Date.now() + (options.timeoutMs ?? 10 * 60000);
360
+ const interval = Math.max(1000, options.intervalMs ?? 3000);
361
+ let last = null;
362
+ const signal = options.signal;
363
+ for (;; ) {
364
+ signal?.throwIfAborted();
365
+ const operation = await this.operation(id, { signal });
366
+ signal?.throwIfAborted();
367
+ if (!last || last.status !== operation.status)
368
+ options.onUpdate?.(operation);
369
+ last = operation;
370
+ if (isSettled(operation))
371
+ return { operation, timedOut: false };
372
+ if (Date.now() + interval > deadline)
373
+ return { operation, timedOut: true };
374
+ await abortable(this.sleep(interval), signal);
375
+ }
376
+ }
377
+ async request(method, path, schema, body, signal) {
378
+ const url = `${this.apiUrl}/api/agent/v1${path}`;
379
+ let attempt = 0;
380
+ for (;; ) {
381
+ signal?.throwIfAborted();
382
+ const requestId = randomUUID();
383
+ const requestSignal = signal ? AbortSignal.any([signal, AbortSignal.timeout(this.timeoutMs)]) : AbortSignal.timeout(this.timeoutMs);
384
+ let response;
385
+ try {
386
+ response = await this.fetchImpl(url, {
387
+ method,
388
+ headers: {
389
+ Authorization: `Bearer ${this.token}`,
390
+ Accept: "application/json",
391
+ "User-Agent": this.userAgent,
392
+ "X-ZenAdmin-Client": this.client,
393
+ "X-Request-Id": requestId,
394
+ ...body === undefined ? {} : { "Content-Type": "application/json" }
395
+ },
396
+ body: body === undefined ? undefined : JSON.stringify(body),
397
+ signal: requestSignal
398
+ });
399
+ } catch (error) {
400
+ signal?.throwIfAborted();
401
+ const failure = new NetworkError(`Could not reach ZenAdmin at ${this.apiUrl}: ${error instanceof Error ? error.message : String(error)}`);
402
+ if (attempt < this.maxRetries) {
403
+ attempt++;
404
+ await abortable(this.sleep(250 * 2 ** attempt), signal);
405
+ continue;
406
+ }
407
+ throw failure;
408
+ }
409
+ const answeredId = response.headers.get("x-request-id") ?? requestId;
410
+ this.log?.(`${method} ${path} → ${response.status} (request ${answeredId})`);
411
+ let json = null;
412
+ try {
413
+ json = await response.json();
414
+ } catch {
415
+ json = null;
416
+ }
417
+ if (!response.ok) {
418
+ const error = errorFromResponse(response.status, json, answeredId, response.headers.get("retry-after"));
419
+ if (RETRY_STATUSES.has(response.status) && attempt < this.maxRetries) {
420
+ attempt++;
421
+ const wait = error instanceof RateLimitError ? Math.min(error.retryAfterSeconds * 1000, 60000) : 250 * 2 ** attempt;
422
+ await abortable(this.sleep(wait), signal);
423
+ continue;
424
+ }
425
+ throw error;
426
+ }
427
+ const envelope = json;
428
+ const parsed = envelope && envelope.error === false ? schema.safeParse(envelope.data) : null;
429
+ if (!parsed?.success) {
430
+ throw new ZenAdminError({
431
+ code: "INVALID_RESPONSE",
432
+ message: `ZenAdmin sent an unexpected response to ${method} ${path}. Update @zenadmin packages, or contact support with this request ID.`,
433
+ status: response.status,
434
+ requestId: answeredId
435
+ });
436
+ }
437
+ return parsed.data;
438
+ }
439
+ }
440
+ }
441
+ export {
442
+ AuthenticationError,
443
+ ChannelSchema,
444
+ ConflictError,
445
+ DEFAULT_API_URL,
446
+ ForbiddenError,
447
+ ImpactSchema,
448
+ NetworkError,
449
+ NotFoundError,
450
+ NotSignedInError,
451
+ OperationSchema,
452
+ OperationStatusSchema,
453
+ RateLimitError,
454
+ ReadResultSchema,
455
+ SDK_VERSION,
456
+ ToolListSchema,
457
+ ToolSchema,
458
+ WhoAmISchema,
459
+ ZenAdmin,
460
+ ZenAdminError,
461
+ clearCredentials,
462
+ credentialsPath,
463
+ errorFromResponse,
464
+ isSettled,
465
+ looksLikeToken,
466
+ normaliseApiUrl,
467
+ outcomeOf,
468
+ resolveCredentials,
469
+ storeCredentials,
470
+ withoutDotenvSettings
471
+ };
@@ -0,0 +1,158 @@
1
+ /**
2
+ * The agent API contract (hybr1d-backend docs/agent-layer.md, "MCP and CLI clients"). Responses are
3
+ * validated here so a server change surfaces as a clear error instead of a wrong answer.
4
+ */
5
+ import { z } from "zod";
6
+ export declare const ChannelSchema: z.ZodEnum<{
7
+ console: "console";
8
+ mcp: "mcp";
9
+ cli: "cli";
10
+ }>;
11
+ export declare const WhoAmISchema: z.ZodObject<{
12
+ company_id: z.ZodString;
13
+ user_id: z.ZodString;
14
+ channel: z.ZodEnum<{
15
+ console: "console";
16
+ mcp: "mcp";
17
+ cli: "cli";
18
+ }>;
19
+ token: z.ZodNullable<z.ZodObject<{
20
+ id: z.ZodString;
21
+ kind: z.ZodEnum<{
22
+ personal: "personal";
23
+ automation: "automation";
24
+ connection: "connection";
25
+ }>;
26
+ scopes: z.ZodArray<z.ZodEnum<{
27
+ read: "read";
28
+ propose: "propose";
29
+ }>>;
30
+ expires_at: z.ZodString;
31
+ }, z.core.$strip>>;
32
+ can_propose: z.ZodBoolean;
33
+ }, z.core.$strip>;
34
+ export type WhoAmI = z.infer<typeof WhoAmISchema>;
35
+ export declare const ImpactSchema: z.ZodEnum<{
36
+ none: "none";
37
+ low: "low";
38
+ medium: "medium";
39
+ high: "high";
40
+ }>;
41
+ /** One tool the caller can use now. Every tool is classified: read or write, impact, scope. */
42
+ export declare const ToolSchema: z.ZodObject<{
43
+ id: z.ZodString;
44
+ label: z.ZodString;
45
+ description: z.ZodString;
46
+ kind: z.ZodEnum<{
47
+ read: "read";
48
+ write: "write";
49
+ }>;
50
+ module: z.ZodString;
51
+ requires_approval: z.ZodBoolean;
52
+ impact: z.ZodEnum<{
53
+ none: "none";
54
+ low: "low";
55
+ medium: "medium";
56
+ high: "high";
57
+ }>;
58
+ scope: z.ZodEnum<{
59
+ read: "read";
60
+ propose: "propose";
61
+ }>;
62
+ input_schema: z.ZodRecord<z.ZodString, z.ZodUnknown>;
63
+ }, z.core.$strip>;
64
+ export type Tool = z.infer<typeof ToolSchema>;
65
+ export declare const ToolListSchema: z.ZodObject<{
66
+ tools: z.ZodArray<z.ZodObject<{
67
+ id: z.ZodString;
68
+ label: z.ZodString;
69
+ description: z.ZodString;
70
+ kind: z.ZodEnum<{
71
+ read: "read";
72
+ write: "write";
73
+ }>;
74
+ module: z.ZodString;
75
+ requires_approval: z.ZodBoolean;
76
+ impact: z.ZodEnum<{
77
+ none: "none";
78
+ low: "low";
79
+ medium: "medium";
80
+ high: "high";
81
+ }>;
82
+ scope: z.ZodEnum<{
83
+ read: "read";
84
+ propose: "propose";
85
+ }>;
86
+ input_schema: z.ZodRecord<z.ZodString, z.ZodUnknown>;
87
+ }, z.core.$strip>>;
88
+ }, z.core.$strip>;
89
+ export declare const OperationStatusSchema: z.ZodEnum<{
90
+ unknown: "unknown";
91
+ pending_approval: "pending_approval";
92
+ running: "running";
93
+ succeeded: "succeeded";
94
+ failed: "failed";
95
+ cancelled: "cancelled";
96
+ expired: "expired";
97
+ }>;
98
+ export type OperationStatus = z.infer<typeof OperationStatusSchema>;
99
+ export declare const OperationSchema: z.ZodObject<{
100
+ id: z.ZodString;
101
+ action: z.ZodString;
102
+ status: z.ZodEnum<{
103
+ unknown: "unknown";
104
+ pending_approval: "pending_approval";
105
+ running: "running";
106
+ succeeded: "succeeded";
107
+ failed: "failed";
108
+ cancelled: "cancelled";
109
+ expired: "expired";
110
+ }>;
111
+ payload_hash: z.ZodString;
112
+ title: z.ZodString;
113
+ fields: z.ZodArray<z.ZodObject<{
114
+ label: z.ZodString;
115
+ value: z.ZodString;
116
+ from: z.ZodOptional<z.ZodNullable<z.ZodString>>;
117
+ }, z.core.$strip>>;
118
+ effects: z.ZodArray<z.ZodString>;
119
+ links: z.ZodArray<z.ZodObject<{
120
+ label: z.ZodString;
121
+ href: z.ZodString;
122
+ }, z.core.$strip>>;
123
+ impact: z.ZodEnum<{
124
+ low: "low";
125
+ medium: "medium";
126
+ high: "high";
127
+ }>;
128
+ expires_at: z.ZodString;
129
+ result: z.ZodNullable<z.ZodObject<{
130
+ message: z.ZodString;
131
+ links: z.ZodArray<z.ZodObject<{
132
+ label: z.ZodString;
133
+ href: z.ZodString;
134
+ }, z.core.$strip>>;
135
+ }, z.core.$strip>>;
136
+ error: z.ZodNullable<z.ZodObject<{
137
+ code: z.ZodString;
138
+ message: z.ZodString;
139
+ }, z.core.$strip>>;
140
+ channel: z.ZodOptional<z.ZodEnum<{
141
+ console: "console";
142
+ mcp: "mcp";
143
+ cli: "cli";
144
+ }>>;
145
+ approval_url: z.ZodOptional<z.ZodNullable<z.ZodString>>;
146
+ }, z.core.$strip>;
147
+ export type Operation = z.infer<typeof OperationSchema>;
148
+ /**
149
+ * 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.
151
+ */
152
+ export type Outcome = "approval_required" | "in_progress" | "completed" | "failed" | "cancelled" | "expired" | "check_result";
153
+ export declare function outcomeOf(operation: Pick<Operation, "status">): Outcome;
154
+ /** Final statuses: nothing more will happen to the operation. */
155
+ export declare const isSettled: (operation: Pick<Operation, "status">) => boolean;
156
+ /** Read tool results are passed through as the server returns them (bounded lists with links). */
157
+ export declare const ReadResultSchema: z.ZodRecord<z.ZodString, z.ZodUnknown>;
158
+ export type ReadResult = z.infer<typeof ReadResultSchema>;
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@zenadmin-ai/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "TypeScript client for the ZenAdmin agent API: read tools and approval-bound changes.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist"
16
+ ],
17
+ "sideEffects": false,
18
+ "license": "UNLICENSED",
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/Usehybrid/mewtwo.git"
22
+ },
23
+ "homepage": "https://github.com/Usehybrid/mewtwo#readme",
24
+ "engines": {
25
+ "node": ">=22",
26
+ "bun": ">=1.4"
27
+ },
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
31
+ "scripts": {
32
+ "typecheck": "tsc --noEmit",
33
+ "test": "bun test"
34
+ },
35
+ "dependencies": {
36
+ "zod": "^4.6.6"
37
+ },
38
+ "devDependencies": {
39
+ "@types/node": "^25.4.0",
40
+ "bun-types": "^1.3.10",
41
+ "typescript": "^5.9.3"
42
+ }
43
+ }