@tangle-network/agent-app 0.60.6 → 0.60.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/{DesignCanvas-OWE67ZX3.js → DesignCanvas-TW45DTK7.js} +3 -2
  2. package/dist/{DesignCanvasEditor-4FPLJ3YJ.js → DesignCanvasEditor-3DL3PF6P.js} +3 -2
  3. package/dist/app-auth/index.js +2 -1
  4. package/dist/app-auth/index.js.map +1 -1
  5. package/dist/assistant/index.js +1 -1
  6. package/dist/chat-routes/index.js +2 -1
  7. package/dist/chat-routes/index.js.map +1 -1
  8. package/dist/{chunk-DWUSVC3U.js → chunk-CN5HNTU6.js} +3 -3
  9. package/dist/chunk-MLDKEEFQ.js +48 -0
  10. package/dist/chunk-MLDKEEFQ.js.map +1 -0
  11. package/dist/chunk-RN4WPTBH.js +62 -0
  12. package/dist/chunk-RN4WPTBH.js.map +1 -0
  13. package/dist/{chunk-YNSPVKMS.js → chunk-UTAIRVOK.js} +1 -60
  14. package/dist/chunk-UTAIRVOK.js.map +1 -0
  15. package/dist/design-canvas/index.js +2 -1
  16. package/dist/design-canvas/index.js.map +1 -1
  17. package/dist/design-canvas-react/engine.js +2 -1
  18. package/dist/design-canvas-react/index.js +6 -5
  19. package/dist/design-canvas-react/index.js.map +1 -1
  20. package/dist/design-canvas-react/lazy.js +1 -1
  21. package/dist/operator/client.d.ts +76 -0
  22. package/dist/operator/contract.d.ts +255 -0
  23. package/dist/operator/index.d.ts +8 -0
  24. package/dist/operator/index.js +533 -0
  25. package/dist/operator/index.js.map +1 -0
  26. package/dist/operator/server.d.ts +101 -0
  27. package/dist/platform/index.js +5 -45
  28. package/dist/platform/index.js.map +1 -1
  29. package/dist/public-consultation/index.js +2 -1
  30. package/dist/public-consultation/index.js.map +1 -1
  31. package/dist/sequences/index.js +2 -1
  32. package/dist/sequences/index.js.map +1 -1
  33. package/dist/web/index.js +4 -2
  34. package/dist/web-react/index.js +4 -4
  35. package/package.json +6 -1
  36. package/dist/chunk-YNSPVKMS.js.map +0 -1
  37. /package/dist/{DesignCanvas-OWE67ZX3.js.map → DesignCanvas-TW45DTK7.js.map} +0 -0
  38. /package/dist/{DesignCanvasEditor-4FPLJ3YJ.js.map → DesignCanvasEditor-3DL3PF6P.js.map} +0 -0
  39. /package/dist/{chunk-DWUSVC3U.js.map → chunk-CN5HNTU6.js.map} +0 -0
@@ -0,0 +1,533 @@
1
+ import {
2
+ createApiKeyRequestAuth
3
+ } from "../chunk-MLDKEEFQ.js";
4
+ import {
5
+ createApiKeyFetch
6
+ } from "../chunk-RN4WPTBH.js";
7
+
8
+ // src/operator/contract.ts
9
+ var OPERATOR_API_VERSION = "v1";
10
+ var OPERATOR_API_BASE_PATH = "/api/operator/v1";
11
+ var OPERATOR_ACCESS = [
12
+ {
13
+ scope: "operator:read",
14
+ label: "Read workspaces",
15
+ description: "Read workspaces, conversations, files, approvals, scorecards, and run status."
16
+ },
17
+ {
18
+ scope: "operator:write",
19
+ label: "Create and edit",
20
+ description: "Create workspaces and conversations, and write files."
21
+ },
22
+ {
23
+ scope: "operator:run",
24
+ requires: ["operator:read"],
25
+ label: "Run agents",
26
+ description: "Requires read access. Start, continue, and interrupt agent turns, and answer their questions and tool-permission requests. Agents can modify workspace files. Uses your plan and budget."
27
+ }
28
+ ];
29
+ var OPERATOR_API_SCOPES = OPERATOR_ACCESS.map(({ scope }) => scope);
30
+ var OPERATOR_SCOPE_DEPENDENCIES = Object.fromEntries(
31
+ OPERATOR_ACCESS.flatMap((option) => "requires" in option ? [[option.scope, option.requires]] : [])
32
+ );
33
+ var OPERATOR_WORKSPACE_SCOPE_PREFIX = "operator:workspace:";
34
+ var WORKSPACE_ID = /^[A-Za-z0-9_-]{1,128}$/;
35
+ function operatorWorkspaceScope(workspaceId) {
36
+ if (!WORKSPACE_ID.test(workspaceId)) throw new TypeError("Workspace ids contain only letters, digits, - and _");
37
+ return `${OPERATOR_WORKSPACE_SCOPE_PREFIX}${workspaceId}`;
38
+ }
39
+ function operatorKeyWorkspaces(scopes) {
40
+ const restricted = scopes.filter((scope) => scope.startsWith(OPERATOR_WORKSPACE_SCOPE_PREFIX));
41
+ if (restricted.length === 0) return null;
42
+ return restricted.map((scope) => scope.slice(OPERATOR_WORKSPACE_SCOPE_PREFIX.length)).filter((id) => WORKSPACE_ID.test(id));
43
+ }
44
+ var OPERATOR_SETTLED_STATES = ["succeeded", "failed"];
45
+ var OPERATOR_ROUTES = [
46
+ { id: "describe", method: "GET", path: "", scopes: ["operator:read"] },
47
+ { id: "workspaces.list", method: "GET", path: "/workspaces", scopes: ["operator:read"] },
48
+ { id: "workspaces.create", method: "POST", path: "/workspaces", scopes: ["operator:write"] },
49
+ { id: "workspaces.get", method: "GET", path: "/workspaces/:workspaceId", scopes: ["operator:read"] },
50
+ { id: "turns.start", method: "POST", path: "/workspaces/:workspaceId/turns", scopes: ["operator:read", "operator:run"] },
51
+ { id: "threads.list", method: "GET", path: "/workspaces/:workspaceId/threads", scopes: ["operator:read"] },
52
+ { id: "threads.get", method: "GET", path: "/workspaces/:workspaceId/threads/:threadId", scopes: ["operator:read"] },
53
+ { id: "turns.get", method: "GET", path: "/workspaces/:workspaceId/threads/:threadId/turns/:turnId", scopes: ["operator:read"] },
54
+ { id: "approvals.list", method: "GET", path: "/workspaces/:workspaceId/approvals", scopes: ["operator:read"] },
55
+ { id: "journal.list", method: "GET", path: "/workspaces/:workspaceId/journal", scopes: ["operator:read"] },
56
+ { id: "files.list", method: "GET", path: "/workspaces/:workspaceId/files", scopes: ["operator:read"] },
57
+ { id: "files.read", method: "GET", path: "/workspaces/:workspaceId/file", scopes: ["operator:read"] },
58
+ { id: "assets.read", method: "GET", path: "/workspaces/:workspaceId/assets/:assetId", scopes: ["operator:read"] },
59
+ { id: "scorecard.get", method: "GET", path: "/workspaces/:workspaceId/scorecard", scopes: ["operator:read"] }
60
+ ];
61
+ var SEGMENT = /^[A-Za-z0-9_:.%-]{1,256}$/;
62
+ function matchOperatorRoute(method, pathname, basePath = OPERATOR_API_BASE_PATH) {
63
+ if (pathname !== basePath && !pathname.startsWith(`${basePath}/`)) return null;
64
+ const rest = pathname.slice(basePath.length).replace(/\/$/, "");
65
+ const actual = rest ? rest.split("/").slice(1) : [];
66
+ for (const route of OPERATOR_ROUTES) {
67
+ if (route.method !== method) continue;
68
+ const pattern = route.path ? route.path.split("/").slice(1) : [];
69
+ if (pattern.length !== actual.length) continue;
70
+ const params = {};
71
+ let matched = true;
72
+ for (let index = 0; index < pattern.length; index++) {
73
+ const expected = pattern[index];
74
+ const segment2 = actual[index];
75
+ if (expected.startsWith(":")) {
76
+ if (!SEGMENT.test(segment2)) {
77
+ matched = false;
78
+ break;
79
+ }
80
+ let decoded;
81
+ try {
82
+ decoded = decodeURIComponent(segment2);
83
+ } catch {
84
+ matched = false;
85
+ break;
86
+ }
87
+ if (!decoded || decoded.includes("/")) {
88
+ matched = false;
89
+ break;
90
+ }
91
+ params[expected.slice(1)] = decoded;
92
+ } else if (expected !== segment2) {
93
+ matched = false;
94
+ break;
95
+ }
96
+ }
97
+ if (matched) return { route, params };
98
+ }
99
+ return null;
100
+ }
101
+
102
+ // src/operator/server.ts
103
+ var OperatorError = class extends Error {
104
+ constructor(code, status, message, retryable = false) {
105
+ super(message ?? code);
106
+ this.code = code;
107
+ this.status = status;
108
+ this.retryable = retryable;
109
+ this.name = "OperatorError";
110
+ }
111
+ code;
112
+ status;
113
+ retryable;
114
+ };
115
+ var TURN_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
116
+ var THREAD_ID = /^[A-Za-z0-9_-]{1,256}$/;
117
+ var MAX_BODY_BYTES = 128 * 1024;
118
+ var MAX_CONTENT_BYTES = 64 * 1024;
119
+ var START_FIELDS = /* @__PURE__ */ new Set(["turnId", "content", "threadId", "title", "model"]);
120
+ var NO_STORE = { "cache-control": "private, no-store" };
121
+ function json(body, status = 200) {
122
+ return Response.json(body, { status, headers: NO_STORE });
123
+ }
124
+ function refusal(status, code, error, retryable = false) {
125
+ return json({ error, code, ...retryable ? { retryable } : {} }, status);
126
+ }
127
+ function boundedInteger(value, fallback, min, max, name) {
128
+ if (value === null || value === "") return fallback;
129
+ if (!/^\d{1,6}$/.test(value)) throw new OperatorError("operator.invalid_input", 400, `${name} must be a whole number`);
130
+ const parsed = Number(value);
131
+ if (parsed < min || parsed > max) throw new OperatorError("operator.invalid_input", 400, `${name} must be between ${min} and ${max}`);
132
+ return parsed;
133
+ }
134
+ function relativePath(value, name, { allowEmpty }) {
135
+ const path = value ?? "";
136
+ if (path === "" && allowEmpty) return "";
137
+ if (!path || path.length > 1024 || path.startsWith("/") || path.includes("\\") || /[\u0000-\u001f\u007f]/.test(path)) {
138
+ throw new OperatorError("operator.invalid_path", 400, `${name} must be a workspace-relative path`);
139
+ }
140
+ const segments = path.replace(/\/$/, "").split("/");
141
+ if (segments.some((segment2) => !segment2 || segment2 === "." || segment2 === "..")) {
142
+ throw new OperatorError("operator.invalid_path", 400, `${name} must be a workspace-relative path`);
143
+ }
144
+ return path;
145
+ }
146
+ async function readJsonBody(request) {
147
+ const declared = Number(request.headers.get("content-length") ?? "0");
148
+ if (declared > MAX_BODY_BYTES) throw new OperatorError("operator.body_too_large", 413, "Request body is too large");
149
+ const text = await request.text();
150
+ if (new TextEncoder().encode(text).byteLength > MAX_BODY_BYTES) {
151
+ throw new OperatorError("operator.body_too_large", 413, "Request body is too large");
152
+ }
153
+ let parsed;
154
+ try {
155
+ parsed = JSON.parse(text);
156
+ } catch {
157
+ throw new OperatorError("operator.invalid_json", 400, "Body must be a JSON object");
158
+ }
159
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
160
+ throw new OperatorError("operator.invalid_json", 400, "Body must be a JSON object");
161
+ }
162
+ return parsed;
163
+ }
164
+ function optionalString(body, name, max) {
165
+ const value = body[name];
166
+ if (value === void 0 || value === null) return void 0;
167
+ if (typeof value !== "string" || !value.trim() || value.length > max) {
168
+ throw new OperatorError("operator.invalid_input", 400, `${name} must be a nonempty string of at most ${max} characters`);
169
+ }
170
+ return value.trim();
171
+ }
172
+ function parseStartTurn(body) {
173
+ const unknown = Object.keys(body).filter((field) => !START_FIELDS.has(field));
174
+ if (unknown.length) throw new OperatorError("operator.invalid_input", 400, `Unknown fields: ${unknown.join(", ")}`);
175
+ if (typeof body.turnId !== "string" || !TURN_ID.test(body.turnId)) {
176
+ throw new OperatorError("operator.invalid_input", 400, "turnId must be a client-generated UUID");
177
+ }
178
+ if (typeof body.content !== "string" || !body.content.trim()) {
179
+ throw new OperatorError("operator.invalid_input", 400, "content must be a nonempty string");
180
+ }
181
+ if (new TextEncoder().encode(body.content).byteLength > MAX_CONTENT_BYTES) {
182
+ throw new OperatorError("operator.invalid_input", 400, `content must be at most ${MAX_CONTENT_BYTES} bytes`);
183
+ }
184
+ const threadId = optionalString(body, "threadId", 256);
185
+ if (threadId !== void 0 && !THREAD_ID.test(threadId)) {
186
+ throw new OperatorError("operator.invalid_input", 400, "threadId contains only letters, digits, - and _");
187
+ }
188
+ const title = optionalString(body, "title", 200);
189
+ const model = optionalString(body, "model", 200);
190
+ return {
191
+ turnId: body.turnId.toLowerCase(),
192
+ content: body.content,
193
+ ...threadId === void 0 ? {} : { threadId },
194
+ ...title === void 0 ? {} : { title },
195
+ ...model === void 0 ? {} : { model }
196
+ };
197
+ }
198
+ function capabilities(adapter) {
199
+ const present = [
200
+ ["workspaces.create", adapter.createWorkspace],
201
+ ["threads.read", adapter.getThread ?? adapter.listThreads],
202
+ ["files.read", adapter.readFile ?? adapter.listFiles],
203
+ ["journal.read", adapter.listJournal],
204
+ ["assets.read", adapter.readAsset],
205
+ ["scorecard.read", adapter.getScorecard]
206
+ ];
207
+ return present.filter(([, implemented]) => typeof implemented === "function").map(([name]) => name);
208
+ }
209
+ function unsupported() {
210
+ throw new OperatorError("operator.unsupported", 501, "This app does not implement this operation");
211
+ }
212
+ function needsAttention(turn) {
213
+ return turn.state === "succeeded" || turn.state === "failed" || turn.state === "input-required" || turn.approvals.length > 0;
214
+ }
215
+ var sleep = (ms, signal) => new Promise((resolve) => {
216
+ if (signal.aborted) return resolve();
217
+ const timer = setTimeout(resolve, ms);
218
+ signal.addEventListener("abort", () => {
219
+ clearTimeout(timer);
220
+ resolve();
221
+ }, { once: true });
222
+ });
223
+ function createOperatorApi(options) {
224
+ const basePath = (options.basePath ?? OPERATOR_API_BASE_PATH).replace(/\/$/, "");
225
+ const maxWaitSeconds = Math.max(0, Math.min(options.maxWaitSeconds ?? 25, 55));
226
+ const pollIntervalMs = Math.max(250, options.pollIntervalMs ?? 2e3);
227
+ const { adapter } = options;
228
+ function matches(request) {
229
+ const { pathname } = new URL(request.url);
230
+ return pathname === basePath || pathname.startsWith(`${basePath}/`);
231
+ }
232
+ async function handle(request) {
233
+ const url = new URL(request.url);
234
+ const match = matchOperatorRoute(request.method, url.pathname, basePath);
235
+ if (!match) return refusal(404, "operator.route_not_found", "No operator route matches this method and path");
236
+ const { route, params } = match;
237
+ if (request.headers.get("Authorization") === null) {
238
+ return refusal(401, "operator.unauthenticated", "An operator API key is required");
239
+ }
240
+ let verified;
241
+ try {
242
+ const authenticate = createApiKeyRequestAuth({
243
+ verify: (authorization) => options.keys.verify(authorization),
244
+ requiredScope: () => route.scopes,
245
+ resolveIdentity: async (key) => {
246
+ const identity = await options.keys.resolveIdentity(key);
247
+ return identity === null || identity === void 0 ? null : { identity, key };
248
+ },
249
+ claimRequest: (key, requestId) => options.keys.claimRequest(key, requestId)
250
+ });
251
+ const result = await authenticate(request);
252
+ if (!result) return refusal(401, "operator.unauthenticated", "An operator API key is required");
253
+ verified = result;
254
+ } catch (error) {
255
+ if (error instanceof Response) return error;
256
+ options.onError?.(error, route.id);
257
+ return refusal(503, "operator.auth_unavailable", "Key verification is unavailable", true);
258
+ }
259
+ const ctx = {
260
+ identity: verified.identity,
261
+ key: { keyId: verified.key.keyId, scopes: [...verified.key.scopes] },
262
+ request
263
+ };
264
+ const restriction = operatorKeyWorkspaces(verified.key.scopes);
265
+ try {
266
+ if (route.id === "describe") {
267
+ return json({
268
+ app: {
269
+ app: options.app.id,
270
+ name: options.app.name,
271
+ apiVersion: OPERATOR_API_VERSION,
272
+ capabilities: capabilities(adapter)
273
+ },
274
+ principal: { keyId: ctx.key.keyId, scopes: [...ctx.key.scopes], workspaces: restriction ? [...restriction] : null }
275
+ });
276
+ }
277
+ if (route.id === "workspaces.list") {
278
+ const listed = await adapter.listWorkspaces(ctx);
279
+ return json({ workspaces: restriction ? listed.filter((workspace2) => restriction.includes(workspace2.id)) : listed });
280
+ }
281
+ if (route.id === "workspaces.create") {
282
+ if (restriction) {
283
+ throw new OperatorError("operator.workspace_restricted", 403, "A workspace-restricted key cannot create workspaces");
284
+ }
285
+ if (!adapter.createWorkspace) unsupported();
286
+ const body = await readJsonBody(request);
287
+ const unknown = Object.keys(body).filter((field) => field !== "name");
288
+ if (unknown.length) throw new OperatorError("operator.invalid_input", 400, `Unknown fields: ${unknown.join(", ")}`);
289
+ const name = optionalString(body, "name", 120);
290
+ if (!name) throw new OperatorError("operator.invalid_input", 400, "name is required");
291
+ return json({ workspace: await adapter.createWorkspace(ctx, { name }) }, 201);
292
+ }
293
+ const workspaceId = params.workspaceId;
294
+ if (restriction && !restriction.includes(workspaceId)) {
295
+ throw new OperatorError("operator.workspace_not_found", 404, "Workspace not found");
296
+ }
297
+ const workspace = await adapter.authorizeWorkspace(ctx, workspaceId, route.id === "turns.start" ? "run" : "read");
298
+ if (!workspace) throw new OperatorError("operator.workspace_not_found", 404, "Workspace not found");
299
+ switch (route.id) {
300
+ case "workspaces.get":
301
+ return json({ workspace });
302
+ case "turns.start": {
303
+ const input = parseStartTurn(await readJsonBody(request));
304
+ return json({ turn: await adapter.startTurn(ctx, workspace, input) }, 202);
305
+ }
306
+ case "threads.list": {
307
+ if (!adapter.listThreads) unsupported();
308
+ const limit = boundedInteger(url.searchParams.get("limit"), 25, 1, 100, "limit");
309
+ const cursor = url.searchParams.get("cursor") ?? void 0;
310
+ if (cursor !== void 0 && (cursor.length > 512 || !cursor)) {
311
+ throw new OperatorError("operator.invalid_input", 400, "cursor is invalid");
312
+ }
313
+ return json(await adapter.listThreads(ctx, workspace, { limit, ...cursor ? { cursor } : {} }));
314
+ }
315
+ case "threads.get": {
316
+ if (!adapter.getThread) unsupported();
317
+ const found = await adapter.getThread(ctx, workspace, params.threadId);
318
+ if (!found) throw new OperatorError("operator.thread_not_found", 404, "Thread not found");
319
+ return json(found);
320
+ }
321
+ case "turns.get": {
322
+ const target = { threadId: params.threadId, turnId: params.turnId };
323
+ const wait = boundedInteger(url.searchParams.get("wait"), 0, 0, maxWaitSeconds, "wait");
324
+ const deadline = Date.now() + wait * 1e3;
325
+ let turn = await adapter.getTurn(ctx, workspace, target);
326
+ while (turn && !needsAttention(turn) && Date.now() + pollIntervalMs <= deadline && !request.signal.aborted) {
327
+ await sleep(pollIntervalMs, request.signal);
328
+ turn = await adapter.getTurn(ctx, workspace, target);
329
+ }
330
+ if (!turn) throw new OperatorError("operator.turn_not_found", 404, "Turn not found");
331
+ return json({ turn });
332
+ }
333
+ case "approvals.list":
334
+ return json({ approvals: await adapter.listApprovals(ctx, workspace) });
335
+ case "journal.list": {
336
+ if (!adapter.listJournal) unsupported();
337
+ const days = boundedInteger(url.searchParams.get("days"), 7, 1, 90, "days");
338
+ return json({ entries: await adapter.listJournal(ctx, workspace, { days }) });
339
+ }
340
+ case "files.list": {
341
+ if (!adapter.listFiles) unsupported();
342
+ const prefix = relativePath(url.searchParams.get("prefix"), "prefix", { allowEmpty: true });
343
+ return json({ files: await adapter.listFiles(ctx, workspace, { prefix }) });
344
+ }
345
+ case "files.read": {
346
+ if (!adapter.readFile) unsupported();
347
+ const path = relativePath(url.searchParams.get("path"), "path", { allowEmpty: false });
348
+ const file = await adapter.readFile(ctx, workspace, path);
349
+ if (!file) throw new OperatorError("operator.file_not_found", 404, "File not found");
350
+ return json({ file });
351
+ }
352
+ case "assets.read": {
353
+ if (!adapter.readAsset) unsupported();
354
+ const response = await adapter.readAsset(ctx, workspace, params.assetId);
355
+ if (!response) throw new OperatorError("operator.asset_not_found", 404, "Asset not found");
356
+ const headers = new Headers(response.headers);
357
+ headers.set("cache-control", "private, no-store");
358
+ headers.delete("set-cookie");
359
+ return new Response(response.body, { status: response.status, headers });
360
+ }
361
+ case "scorecard.get": {
362
+ if (!adapter.getScorecard) unsupported();
363
+ const days = boundedInteger(url.searchParams.get("days"), 7, 1, 90, "days");
364
+ return json({ scorecard: await adapter.getScorecard(ctx, workspace, { days }) });
365
+ }
366
+ }
367
+ return refusal(404, "operator.route_not_found", "No operator route matches this method and path");
368
+ } catch (error) {
369
+ if (error instanceof OperatorError) return refusal(error.status, error.code, error.message, error.retryable);
370
+ if (error instanceof Response) return error;
371
+ options.onError?.(error, route.id);
372
+ return refusal(500, "operator.internal", "The operation failed", true);
373
+ }
374
+ }
375
+ return { matches, handle };
376
+ }
377
+
378
+ // src/operator/client.ts
379
+ function segment(value) {
380
+ return encodeURIComponent(value);
381
+ }
382
+ async function failure(response) {
383
+ let body = {};
384
+ try {
385
+ body = await response.json();
386
+ } catch {
387
+ }
388
+ return {
389
+ succeeded: false,
390
+ status: response.status,
391
+ code: typeof body.code === "string" ? body.code : `http_${response.status}`,
392
+ error: typeof body.error === "string" ? body.error : `HTTP ${response.status}`,
393
+ retryable: body.retryable === true || response.status === 429 || response.status >= 500
394
+ };
395
+ }
396
+ function transportFailure(error) {
397
+ const aborted = error instanceof Error && error.name === "AbortError";
398
+ return {
399
+ succeeded: false,
400
+ status: 0,
401
+ code: aborted ? "operator.aborted" : "operator.transport_failed",
402
+ // createApiKeyFetch never forwards transport diagnostics, which could carry the key.
403
+ error: error instanceof Error ? error.message : "Operator transport failed",
404
+ retryable: !aborted
405
+ };
406
+ }
407
+ var SETTLED = /* @__PURE__ */ new Set(["succeeded", "failed", "input-required"]);
408
+ function createOperatorClient(options) {
409
+ const basePath = (options.basePath ?? OPERATOR_API_BASE_PATH).replace(/\/$/, "");
410
+ const request = createApiKeyFetch({
411
+ origin: options.origin,
412
+ getApiKey: options.getApiKey,
413
+ ...options.fetchImpl ? { fetchImpl: options.fetchImpl } : {},
414
+ ...options.allowHttpLoopback ? { allowHttpLoopback: true } : {}
415
+ });
416
+ async function call(path, pick, init = {}) {
417
+ let response;
418
+ try {
419
+ response = await request(`${basePath}${path}`, {
420
+ ...init,
421
+ headers: { accept: "application/json", ...init.body ? { "content-type": "application/json" } : {} }
422
+ });
423
+ } catch (error) {
424
+ return transportFailure(error);
425
+ }
426
+ if (!response.ok) return failure(response);
427
+ try {
428
+ return { succeeded: true, value: pick(await response.json()) };
429
+ } catch {
430
+ return { succeeded: false, status: response.status, code: "operator.invalid_response", error: "The response was not the expected JSON", retryable: true };
431
+ }
432
+ }
433
+ const query = (params) => {
434
+ const search = new URLSearchParams();
435
+ for (const [name, value] of Object.entries(params)) if (value !== void 0 && value !== "") search.set(name, String(value));
436
+ const text = search.toString();
437
+ return text ? `?${text}` : "";
438
+ };
439
+ const client = {
440
+ describe: () => call("", (body) => body),
441
+ listWorkspaces: () => call("/workspaces", (body) => body.workspaces),
442
+ createWorkspace: (input) => call("/workspaces", (body) => body.workspace, {
443
+ method: "POST",
444
+ body: JSON.stringify({ name: input.name })
445
+ }),
446
+ getWorkspace: (workspaceId) => call(`/workspaces/${segment(workspaceId)}`, (body) => body.workspace),
447
+ startTurn: (workspaceId, input) => call(`/workspaces/${segment(workspaceId)}/turns`, (body) => body.turn, {
448
+ method: "POST",
449
+ body: JSON.stringify({ ...input, turnId: input.turnId ?? crypto.randomUUID() })
450
+ }),
451
+ getTurn: (workspaceId, threadId, turnId, opts = {}) => call(
452
+ `/workspaces/${segment(workspaceId)}/threads/${segment(threadId)}/turns/${segment(turnId)}${query({ wait: opts.waitSeconds })}`,
453
+ (body) => body.turn,
454
+ opts.signal ? { signal: opts.signal } : {}
455
+ ),
456
+ async waitForTurn(workspaceId, threadId, turnId, opts) {
457
+ const deadline = Date.now() + opts.timeoutMs;
458
+ const waitSeconds = opts.waitSeconds ?? 25;
459
+ let last = null;
460
+ while (true) {
461
+ const remaining = Math.floor((deadline - Date.now()) / 1e3);
462
+ const started = Date.now();
463
+ last = await client.getTurn(workspaceId, threadId, turnId, {
464
+ waitSeconds: Math.max(0, Math.min(waitSeconds, remaining)),
465
+ ...opts.signal ? { signal: opts.signal } : {}
466
+ });
467
+ if (!last.succeeded) {
468
+ if (!last.retryable || Date.now() >= deadline || opts.signal?.aborted) return last;
469
+ await new Promise((resolve) => setTimeout(resolve, Math.min(5e3, Math.max(0, deadline - Date.now()))));
470
+ continue;
471
+ }
472
+ if (SETTLED.has(last.value.state) || last.value.approvals.length > 0) return last;
473
+ if (Date.now() >= deadline || opts.signal?.aborted) return last;
474
+ if (Date.now() - started < 1e3) {
475
+ await new Promise((resolve) => setTimeout(resolve, Math.min(2e3, Math.max(0, deadline - Date.now()))));
476
+ }
477
+ }
478
+ },
479
+ listThreads: (workspaceId, q = {}) => call(
480
+ `/workspaces/${segment(workspaceId)}/threads${query({ cursor: q.cursor, limit: q.limit })}`,
481
+ (body) => ({ threads: body.threads, nextCursor: body.nextCursor ?? null })
482
+ ),
483
+ getThread: (workspaceId, threadId) => call(
484
+ `/workspaces/${segment(workspaceId)}/threads/${segment(threadId)}`,
485
+ (body) => ({ thread: body.thread, latestTurn: body.latestTurn ?? null })
486
+ ),
487
+ listApprovals: (workspaceId) => call(`/workspaces/${segment(workspaceId)}/approvals`, (body) => body.approvals),
488
+ listJournal: (workspaceId, q = {}) => call(
489
+ `/workspaces/${segment(workspaceId)}/journal${query({ days: q.days })}`,
490
+ (body) => body.entries
491
+ ),
492
+ listFiles: (workspaceId, q = {}) => call(
493
+ `/workspaces/${segment(workspaceId)}/files${query({ prefix: q.prefix })}`,
494
+ (body) => body.files
495
+ ),
496
+ readFile: (workspaceId, path) => call(
497
+ `/workspaces/${segment(workspaceId)}/file${query({ path })}`,
498
+ (body) => body.file
499
+ ),
500
+ async readAsset(workspaceId, assetId, init = {}) {
501
+ let response;
502
+ try {
503
+ response = await request(`${basePath}/workspaces/${segment(workspaceId)}/assets/${segment(assetId)}`, init.signal ? { signal: init.signal } : {});
504
+ } catch (error) {
505
+ return transportFailure(error);
506
+ }
507
+ if (!response.ok) return failure(response);
508
+ return { succeeded: true, value: response };
509
+ },
510
+ getScorecard: (workspaceId, q = {}) => call(
511
+ `/workspaces/${segment(workspaceId)}/scorecard${query({ days: q.days })}`,
512
+ (body) => body.scorecard
513
+ )
514
+ };
515
+ return client;
516
+ }
517
+ export {
518
+ OPERATOR_ACCESS,
519
+ OPERATOR_API_BASE_PATH,
520
+ OPERATOR_API_SCOPES,
521
+ OPERATOR_API_VERSION,
522
+ OPERATOR_ROUTES,
523
+ OPERATOR_SCOPE_DEPENDENCIES,
524
+ OPERATOR_SETTLED_STATES,
525
+ OPERATOR_WORKSPACE_SCOPE_PREFIX,
526
+ OperatorError,
527
+ createOperatorApi,
528
+ createOperatorClient,
529
+ matchOperatorRoute,
530
+ operatorKeyWorkspaces,
531
+ operatorWorkspaceScope
532
+ };
533
+ //# sourceMappingURL=index.js.map