@tangle-network/agent-app 0.63.28 → 0.63.30
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/{TimelineEditor-VB2UJ34D.js → TimelineEditor-MUY35ULL.js} +3 -3
- package/dist/app-auth/index.js +3 -3
- package/dist/assistant/index.js +9 -9
- package/dist/chat-react/index.js +3 -3
- package/dist/chat-routes/default-backend.d.ts +19 -2
- package/dist/chat-routes/hybrid-producer.d.ts +7 -2
- package/dist/chat-routes/index.js +4 -4
- package/dist/chat-routes/route-storage.d.ts +1 -1
- package/dist/chat-routes/router-producer.d.ts +2 -1
- package/dist/chat-routes/turn-route-contracts.d.ts +1 -1
- package/dist/chunk-53ZX7XZY.js +371 -0
- package/dist/chunk-53ZX7XZY.js.map +1 -0
- package/dist/{chunk-56JUV4DK.js → chunk-5AUZR655.js} +3335 -3020
- package/dist/chunk-5AUZR655.js.map +1 -0
- package/dist/{chunk-IVBREL7A.js → chunk-5HBIN366.js} +10 -10
- package/dist/{chunk-A7JD27SN.js → chunk-6UMIOEDR.js} +13 -13
- package/dist/{chunk-QUT3T2IN.js → chunk-L3QR274L.js} +11 -3
- package/dist/chunk-L3QR274L.js.map +1 -0
- package/dist/chunk-N425HGJW.js +261 -0
- package/dist/chunk-N425HGJW.js.map +1 -0
- package/dist/{chunk-DCJCZ7EP.js → chunk-QLZ6A73E.js} +37 -19
- package/dist/chunk-QLZ6A73E.js.map +1 -0
- package/dist/{chunk-ZZTPTCMY.js → chunk-XJXAULNI.js} +7 -7
- package/dist/conformance/cli.d.ts +2 -0
- package/dist/conformance/cli.js +67 -0
- package/dist/conformance/cli.js.map +1 -0
- package/dist/conformance/index.d.ts +3 -0
- package/dist/conformance/index.js +9 -0
- package/dist/conformance/index.js.map +1 -0
- package/dist/conformance/revision.d.ts +13 -0
- package/dist/conformance/run.d.ts +48 -0
- package/dist/conformance/session.d.ts +24 -0
- package/dist/conformance/turns.d.ts +37 -0
- package/dist/design-canvas/index.js +6 -6
- package/dist/design-canvas-react/index.js +4 -4
- package/dist/model-resolution/index.js +1 -1
- package/dist/operator/index.js +24 -252
- package/dist/operator/index.js.map +1 -1
- package/dist/platform/index.js +8 -8
- package/dist/public-consultation/index.d.ts +2 -2
- package/dist/public-consultation/index.js +4 -4
- package/dist/sandbox/computer-files.d.ts +67 -0
- package/dist/sandbox/computer-receipts.d.ts +46 -0
- package/dist/sandbox/computer-step.d.ts +78 -0
- package/dist/sandbox/index.d.ts +4 -0
- package/dist/sandbox/index.js +23 -1
- package/dist/sandbox/router-models.d.ts +26 -0
- package/dist/sandbox/sandbox-run-tool.d.ts +5 -4
- package/dist/sequences-react/index.js +3 -3
- package/dist/settings-react/index.js +1 -1
- package/dist/web-react/index.js +28 -28
- package/dist/workspace-react/index.js +5 -5
- package/package.json +8 -2
- package/dist/chunk-56JUV4DK.js.map +0 -1
- package/dist/chunk-DCJCZ7EP.js.map +0 -1
- package/dist/chunk-QUT3T2IN.js.map +0 -1
- /package/dist/{TimelineEditor-VB2UJ34D.js.map → TimelineEditor-MUY35ULL.js.map} +0 -0
- /package/dist/{chunk-IVBREL7A.js.map → chunk-5HBIN366.js.map} +0 -0
- /package/dist/{chunk-A7JD27SN.js.map → chunk-6UMIOEDR.js.map} +0 -0
- /package/dist/{chunk-ZZTPTCMY.js.map → chunk-XJXAULNI.js.map} +0 -0
|
@@ -1,12 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
LockGlyph,
|
|
3
|
-
MagnetGlyph,
|
|
4
|
-
MinusGlyph,
|
|
5
|
-
PlusGlyph,
|
|
6
|
-
RedoGlyph,
|
|
7
|
-
UndoGlyph,
|
|
8
|
-
createEditorGlyph
|
|
9
|
-
} from "./chunk-P4RRC4AO.js";
|
|
10
1
|
import {
|
|
11
2
|
MIN_SEQUENCE_CLIP_FRAMES,
|
|
12
3
|
assertClipFitsSequence,
|
|
@@ -18,6 +9,15 @@ import {
|
|
|
18
9
|
snapshotFrame,
|
|
19
10
|
trackIntervals
|
|
20
11
|
} from "./chunk-SISVELAA.js";
|
|
12
|
+
import {
|
|
13
|
+
LockGlyph,
|
|
14
|
+
MagnetGlyph,
|
|
15
|
+
MinusGlyph,
|
|
16
|
+
PlusGlyph,
|
|
17
|
+
RedoGlyph,
|
|
18
|
+
UndoGlyph,
|
|
19
|
+
createEditorGlyph
|
|
20
|
+
} from "./chunk-P4RRC4AO.js";
|
|
21
21
|
import {
|
|
22
22
|
BrandMark
|
|
23
23
|
} from "./chunk-7PULOECS.js";
|
|
@@ -2964,4 +2964,4 @@ export {
|
|
|
2964
2964
|
TimelineEditor,
|
|
2965
2965
|
TimelineEditor_default
|
|
2966
2966
|
};
|
|
2967
|
-
//# sourceMappingURL=chunk-
|
|
2967
|
+
//# sourceMappingURL=chunk-5HBIN366.js.map
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
+
import {
|
|
2
|
+
loadHistoryPage,
|
|
3
|
+
useHistoryControls,
|
|
4
|
+
useInfiniteScroll
|
|
5
|
+
} from "./chunk-UHSUY6H6.js";
|
|
1
6
|
import {
|
|
2
7
|
PATH_CONTINUATION_CHAR,
|
|
3
8
|
WORD_CHAR,
|
|
4
9
|
charAt,
|
|
5
10
|
charBefore
|
|
6
11
|
} from "./chunk-3HUFJ5LO.js";
|
|
7
|
-
import {
|
|
8
|
-
loadHistoryPage,
|
|
9
|
-
useHistoryControls,
|
|
10
|
-
useInfiniteScroll
|
|
11
|
-
} from "./chunk-UHSUY6H6.js";
|
|
12
12
|
import {
|
|
13
13
|
BrandMark
|
|
14
14
|
} from "./chunk-7PULOECS.js";
|
|
@@ -26,13 +26,6 @@ import {
|
|
|
26
26
|
ActionDialog,
|
|
27
27
|
ActionDialogButton
|
|
28
28
|
} from "./chunk-2VG6Q4TS.js";
|
|
29
|
-
import {
|
|
30
|
-
UNTITLED_SESSION_LABEL,
|
|
31
|
-
filterCommandPaletteItems,
|
|
32
|
-
groupCommandPaletteItems,
|
|
33
|
-
mergeSessionPages,
|
|
34
|
-
sessionLabel
|
|
35
|
-
} from "./chunk-SJWIZT7B.js";
|
|
36
29
|
import {
|
|
37
30
|
BrainGlyph,
|
|
38
31
|
ChevronDown,
|
|
@@ -44,6 +37,13 @@ import {
|
|
|
44
37
|
usePending,
|
|
45
38
|
usePopover
|
|
46
39
|
} from "./chunk-RO25WIVS.js";
|
|
40
|
+
import {
|
|
41
|
+
UNTITLED_SESSION_LABEL,
|
|
42
|
+
filterCommandPaletteItems,
|
|
43
|
+
groupCommandPaletteItems,
|
|
44
|
+
mergeSessionPages,
|
|
45
|
+
sessionLabel
|
|
46
|
+
} from "./chunk-SJWIZT7B.js";
|
|
47
47
|
import {
|
|
48
48
|
ReviewFeedbackForm
|
|
49
49
|
} from "./chunk-TEZETVLE.js";
|
|
@@ -8575,4 +8575,4 @@ export {
|
|
|
8575
8575
|
AgentProfileChoices,
|
|
8576
8576
|
ComposerProfilePill
|
|
8577
8577
|
};
|
|
8578
|
-
//# sourceMappingURL=chunk-
|
|
8578
|
+
//# sourceMappingURL=chunk-6UMIOEDR.js.map
|
|
@@ -6,6 +6,10 @@ import {
|
|
|
6
6
|
var UPSTREAM_UNAVAILABLE_CODES = [
|
|
7
7
|
"provider_inference_unavailable",
|
|
8
8
|
"provider_quota_exhausted",
|
|
9
|
+
// The Router has no enabled credential for this model's provider (`403 provider_disabled`, tangle-router
|
|
10
|
+
// `lib/native-credential-guard.ts`): gpt-6-luna with the OpenAI company credential off, Tax 2026-10-25 (#649).
|
|
11
|
+
// Model-scoped, so the next model in the chain may serve.
|
|
12
|
+
"provider_disabled",
|
|
9
13
|
"upstream_unavailable",
|
|
10
14
|
"insufficient_quota",
|
|
11
15
|
"model_not_available",
|
|
@@ -64,8 +68,11 @@ function readUpstreamUnavailableCode(signal) {
|
|
|
64
68
|
const code = readString(record, "errorCode") ?? readString(record, "code") ?? (nestedRecord ? readString(nestedRecord, "code") ?? readString(nestedRecord, "type") : void 0);
|
|
65
69
|
if (code && UPSTREAM_UNAVAILABLE_CODES.includes(code)) return code;
|
|
66
70
|
const message = readString(record, "message") ?? readString(record, "error") ?? (nestedRecord ? readString(nestedRecord, "message") : void 0);
|
|
67
|
-
return message
|
|
71
|
+
return message?.match(/\b(provider_quota_exhausted|provider_disabled)\b/i)?.[1]?.toLowerCase();
|
|
68
72
|
}
|
|
73
|
+
var MODEL_SCOPED_REFUSALS = [
|
|
74
|
+
"inference is unavailable for"
|
|
75
|
+
];
|
|
69
76
|
function isUpstreamUnavailable(signal) {
|
|
70
77
|
if (signal === null || typeof signal !== "object") return false;
|
|
71
78
|
const record = signal;
|
|
@@ -79,12 +86,13 @@ function isUpstreamUnavailable(signal) {
|
|
|
79
86
|
}
|
|
80
87
|
const message = readString(record, "message") ?? readString(record, "error") ?? (nestedRecord ? readString(nestedRecord, "message") : void 0);
|
|
81
88
|
if (!message) return false;
|
|
89
|
+
const lowered = message.toLowerCase();
|
|
90
|
+
if (MODEL_SCOPED_REFUSALS.some((fragment) => lowered.includes(fragment))) return true;
|
|
82
91
|
const hinted = readHttpStatusHint(message);
|
|
83
92
|
if (hinted !== void 0) {
|
|
84
93
|
if (UPSTREAM_UNAVAILABLE_STATUSES.includes(hinted)) return true;
|
|
85
94
|
if (REQUEST_ERROR_STATUSES.includes(hinted)) return false;
|
|
86
95
|
}
|
|
87
|
-
const lowered = message.toLowerCase();
|
|
88
96
|
return UPSTREAM_UNAVAILABLE_MESSAGES.some((fragment) => lowered.includes(fragment));
|
|
89
97
|
}
|
|
90
98
|
var ModelFailoverExhaustedError = class extends Error {
|
|
@@ -180,4 +188,4 @@ export {
|
|
|
180
188
|
runWithModelFailover,
|
|
181
189
|
buildModelChain
|
|
182
190
|
};
|
|
183
|
-
//# sourceMappingURL=chunk-
|
|
191
|
+
//# sourceMappingURL=chunk-L3QR274L.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/model-resolution/failover.ts"],"sourcesContent":["/**\n * Model failover — the answer to \"one upstream hit a quota wall and the customer\n * got a Bad Gateway even though the router had abundant healthy capacity\".\n *\n * This is deliberately NOT a health probe. Probing before every turn buys a\n * round-trip of latency on the happy path and still races the outage (a model\n * healthy at probe time can 502 a second later). Failover is REACTIVE: run the\n * preferred model, and on an upstream-outage signal move to the next model in\n * the chain. Zero added latency when the preferred model works.\n *\n * Two facts drive the design, both measured against a live box during the\n * 2026-07-25 Anthropic/DeepSeek outage:\n *\n * 1. An outage is NOT always a thrown error. The sandbox resolves with a\n * payload — `{ success: false, errorCode: 'provider_inference_unavailable' }`\n * — so a classifier that only inspects `catch` misses the customer-visible\n * case entirely. `isUpstreamUnavailable` inspects resolved values too.\n * 2. Catalog membership is NOT liveness. The router's `/v1/models` still listed\n * every dead model during the outage, so `validateChatModelId` admitted\n * `claude-sonnet-4-6` while every call to it returned 502. Nothing upstream\n * of the actual call can be trusted to tell you a model is serving.\n *\n * Substrate-free: the caller injects `run`, so this composes with a sandbox\n * turn, a router chat completion, or a test fake without importing any of them.\n */\n\nimport {\n checkModelPolicy,\n type ModelPolicy,\n} from '../policy-filters/index'\n\n/**\n * Error codes that mean \"this model's upstream is unavailable — a different\n * model may still work\". Deliberately excludes codes that would fail identically\n * on every model (bad request, auth, content filter): retrying those down a\n * chain burns latency and money to reach the same failure.\n */\nexport const UPSTREAM_UNAVAILABLE_CODES: readonly string[] = [\n 'provider_inference_unavailable',\n 'provider_quota_exhausted',\n // The Router has no enabled credential for this model's provider (`403 provider_disabled`, tangle-router\n // `lib/native-credential-guard.ts`): gpt-6-luna with the OpenAI company credential off, Tax 2026-10-25 (#649).\n // Model-scoped, so the next model in the chain may serve.\n 'provider_disabled',\n 'upstream_unavailable',\n 'insufficient_quota',\n 'model_not_available',\n 'server_error',\n 'bad_gateway',\n 'service_unavailable',\n]\n\n/** HTTP statuses that indicate an upstream capacity/availability problem. */\nexport const UPSTREAM_UNAVAILABLE_STATUSES: readonly number[] = [429, 500, 502, 503, 504]\n\n/**\n * Statuses that mean the REQUEST is wrong, so every model in the chain would\n * fail on it identically. Listed explicitly rather than as \"any 4xx\" because\n * 404 is NOT one of them: a model the endpoint cannot find is model-scoped, and\n * the next model in the chain may well be there. 429 is absent for the same\n * reason in reverse — it is a capacity signal and lives in the list above.\n */\nconst REQUEST_ERROR_STATUSES: readonly number[] = [400, 401, 403, 405, 413, 422]\n\n/**\n * Message fragments emitted by real upstreams during this class of outage.\n * Matched case-insensitively as a last resort, after code and status.\n */\nconst UPSTREAM_UNAVAILABLE_MESSAGES: readonly string[] = [\n 'bad gateway',\n 'service unavailable',\n 'inference temporarily unavailable',\n 'provider inference is unavailable',\n 'insufficient balance',\n 'usage limits',\n 'quota exceeded',\n 'rate limit',\n 'overloaded',\n 'temporarily unavailable',\n // Model-SCOPED unavailability. A different model in the chain can still\n // serve, so this belongs here and not with the client errors. Measured on a\n // real box 2026-07-27: the sandbox now reports an unservable model as a\n // terminal `error` whose data is `{\"message\":\"Session error:\n // {\\\"error\\\":{\\\"name\\\":\\\"UnknownError\\\",\\\"data\\\":{\\\"message\\\":\\\"Model not\n // found: openai-compat/zai/glm-4.7.\\\"}}}\"}` — no `code`, no numeric status,\n // and none of the fragments above. The shipped live product-path proof went\n // red on exactly this: `usedFallback:false`, `failed:true`, an error row to\n // the customer where a fallback was available and would have answered.\n 'model not found',\n 'is not currently available',\n]\n\n/**\n * Textual forms an HTTP status arrives in when NO numeric field carries it.\n *\n * The case that forced this is the opaque Cloudflare 502. Captured verbatim\n * from `router.tangle.tools` (cf-ray\n * `a21d793899f6cef3-DEN`): `HTTP/2 502`, `content-type: text/plain;\n * charset=UTF-8`, a 16-byte body reading `error code: 502\\n`, `server:\n * cloudflare`, and **zero `x-tangle-*` headers** where a healthy 200 from the\n * same endpoint carries nine of them.\n *\n * That capture was originally read as \"zero headers means the origin never\n * executed\". It does not, and the correction matters more than the original\n * guess did. Matching client-observed cf-rays against the origin's own access\n * log (tangle-router #307) showed all 62 of those responses WERE produced by\n * the router — `content-type: application/json`, an `X-Generation-Id`, and a\n * routing trace showing the upstream had returned 200 — and Cloudflare\n * replaced the body and every response header with its own error page, because\n * an origin 502 reads to the edge as the origin having failed.\n *\n * The classifier's BEHAVIOR here was right for the wrong reason, and stays\n * exactly as it is. What changes is why: the rescue is needed not because the\n * origin is unreachable, but because a response the origin carefully\n * structured arrives at the client as sixteen unlabelled bytes. The router now\n * emits 503 instead of 502 on those paths so the body survives, but this\n * pattern must remain — it is the client's only handle on any origin 5xx the\n * edge decides to rewrite, including from a router that has not deployed the\n * fix yet.\n *\n * Every pattern below matches a string a real producer emits:\n * - `error code: 502` — Cloudflare's edge body (the capture above).\n * - `(HTTP 502)` — `src/runtime/openai-stream.ts` wrapping a non-ok response.\n * - `returned 502` — `src/runtime/model-catalog.ts`.\n * - `failed with status 502` — `src/turn-stream/adapters.ts`.\n * - `502 Bad Gateway` — an HTTP/1.1 status line. HTTP/2 carries no reason\n * phrase at all, which is precisely why matching the phrase alone (the\n * `'bad gateway'` fragment below) read the capture as a non-outage.\n */\nconst HTTP_STATUS_HINT_PATTERNS: readonly RegExp[] = [\n /\\berror\\s+code:?\\s*([1-5]\\d{2})\\b/i,\n /\\bhttp(?:\\/[\\d.]+)?[\\s:]\\s*([1-5]\\d{2})\\b/i,\n /\\bstatus(?:\\s*code)?[\\s:=]\\s*([1-5]\\d{2})\\b/i,\n /\\b(?:returned|responded(?:\\s+with)?)\\s+([1-5]\\d{2})\\b/i,\n /\\b([1-5]\\d{2})\\s+(?:bad\\s+gateway|service\\s+unavailable|gateway\\s+time-?out|internal\\s+server\\s+error|too\\s+many\\s+requests)\\b/i,\n]\n\n/**\n * The HTTP status a message states in prose, or `undefined` when it states\n * none. Deliberately NOT \"any three digits in the string\" — an unanchored digit\n * scan would read a token count or a duration as a status.\n */\nexport function readHttpStatusHint(text: string): number | undefined {\n for (const pattern of HTTP_STATUS_HINT_PATTERNS) {\n const match = pattern.exec(text)\n if (match?.[1]) return Number(match[1])\n }\n return undefined\n}\n\nfunction readString(source: Record<string, unknown>, key: string): string | undefined {\n const value = source[key]\n return typeof value === 'string' && value.trim().length > 0 ? value : undefined\n}\n\n/** Read a recognized upstream code, including the terminal message-only shape. */\nexport function readUpstreamUnavailableCode(signal: unknown): string | undefined {\n if (signal === null || typeof signal !== 'object') return undefined\n const record = signal as Record<string, unknown>\n const nested = record.error\n const nestedRecord = nested !== null && typeof nested === 'object' ? (nested as Record<string, unknown>) : undefined\n const code =\n readString(record, 'errorCode') ??\n readString(record, 'code') ??\n (nestedRecord ? (readString(nestedRecord, 'code') ?? readString(nestedRecord, 'type')) : undefined)\n if (code && UPSTREAM_UNAVAILABLE_CODES.includes(code)) return code\n\n const message =\n readString(record, 'message') ??\n readString(record, 'error') ??\n (nestedRecord ? readString(nestedRecord, 'message') : undefined)\n return message?.match(/\\b(provider_quota_exhausted|provider_disabled)\\b/i)?.[1]?.toLowerCase()\n}\n\n/**\n * A model-scoped refusal whose text is decisive even beside a 4xx status: the Router answers a disabled provider\n * with 403, and the box agent relays it as `opencode execution failed: Tangle-funded openai inference is unavailable\n * for \"gpt-6-luna\": …` (Tax 2026-10-25). Another model may still serve, so the chain moves on.\n */\nconst MODEL_SCOPED_REFUSALS: readonly string[] = [\n 'inference is unavailable for',\n]\n\n/**\n * True when `signal` — a thrown error OR a resolved result payload — indicates\n * the model's upstream is unavailable and another model is worth trying.\n *\n * Checked in order of decreasing confidence: explicit code, HTTP status, then\n * message text. A resolved payload only counts as a failure when it carries an\n * explicit failure marker (`success: false`, or an `error`/`errorCode` field) —\n * a successful result is never misread as an outage.\n */\nexport function isUpstreamUnavailable(signal: unknown): boolean {\n if (signal === null || typeof signal !== 'object') return false\n const record = signal as Record<string, unknown>\n\n // A resolved payload that explicitly reports success is never an outage.\n if (record.success === true) return false\n\n const nested = record.error\n const nestedRecord = nested !== null && typeof nested === 'object' ? (nested as Record<string, unknown>) : undefined\n if (readUpstreamUnavailableCode(record)) return true\n\n for (const key of ['status', 'statusCode', 'httpStatus']) {\n const value = record[key]\n if (typeof value === 'number' && UPSTREAM_UNAVAILABLE_STATUSES.includes(value)) return true\n }\n\n const message =\n readString(record, 'message') ??\n readString(record, 'error') ??\n (nestedRecord ? readString(nestedRecord, 'message') : undefined)\n if (!message) return false\n\n // A status carried as PROSE, checked before the fragment list because it is\n // the stronger signal and it cuts BOTH ways. An edge 502 names no exception\n // type and sets no numeric field, so without this the shipped classifier read\n // `error code: 502` as a non-outage and handed the customer a Bad Gateway\n // instead of trying the next model — the exact failure the router cannot\n // rescue from inside its own origin.\n const lowered = message.toLowerCase()\n if (MODEL_SCOPED_REFUSALS.some((fragment) => lowered.includes(fragment))) return true\n const hinted = readHttpStatusHint(message)\n if (hinted !== undefined) {\n if (UPSTREAM_UNAVAILABLE_STATUSES.includes(hinted)) return true\n // An explicit REQUEST-error status is decisive the OTHER way. A 400\n // carrying a validation message must surface rather than walk the chain,\n // even when its body happens to contain a word from the fragment list —\n // the router's own `Function tools with reasoning_effort are not supported`\n // 400 is a request-shaping bug that fails identically on every model.\n if (REQUEST_ERROR_STATUSES.includes(hinted)) return false\n }\n\n return UPSTREAM_UNAVAILABLE_MESSAGES.some((fragment) => lowered.includes(fragment))\n}\n\n/** One model tried, and how it went. */\nexport interface ModelFailoverAttempt {\n model: string\n ok: boolean\n /** Why this model was abandoned. Absent when `ok`. */\n reason?: string\n /** Recognized upstream code carried by this failed attempt. */\n errorCode?: string\n}\n\n/** The outcome of a failover run: the value plus the full attempt trail. */\nexport interface ModelFailoverResult<T> {\n value: T\n /** The model that actually produced `value`. */\n model: string\n attempts: ModelFailoverAttempt[]\n /** True when the preferred (first) model did not serve the request. */\n usedFallback: boolean\n}\n\n/** Every model in the chain failed; carries the trail for logging. */\nexport class ModelFailoverExhaustedError extends Error {\n readonly attempts: ModelFailoverAttempt[]\n /** Last recognized upstream code across the exhausted chain, when present. */\n readonly upstreamCode?: string\n constructor(attempts: ModelFailoverAttempt[]) {\n const trail = attempts.map((a) => `${a.model}: ${a.reason ?? 'failed'}`).join(' | ')\n super(`All ${attempts.length} model(s) failed. ${trail}`)\n this.name = 'ModelFailoverExhaustedError'\n this.attempts = attempts\n this.upstreamCode = [...attempts].reverse().find((attempt) => attempt.errorCode)?.errorCode\n }\n}\n\n/** Inputs to {@link runWithModelFailover}. */\nexport interface RunWithModelFailoverInput<T> {\n /** Preferred model first, then fallbacks in descending preference. */\n models: readonly string[]\n /** Executes one turn with the given model. */\n run: (model: string) => Promise<T>\n /**\n * Product admission policy applied to EVERY chain member before it runs.\n * Without this a compliant model 502ing mid-turn would silently re-run the\n * turn's data through a non-compliant fallback: availability is not\n * eligibility. A member the policy refuses is SKIPPED (recorded in the\n * attempt trail with the refusal as its reason) and the walk continues; when\n * no member is admitted the run ends in {@link ModelFailoverExhaustedError}\n * like any other exhausted chain. Fail-closed — a member carrying no policy\n * metadata is refused.\n */\n policy?: ModelPolicy\n /**\n * Classifies a resolved result as an upstream outage. Defaults to\n * {@link isUpstreamUnavailable}, which understands the sandbox's\n * `{ success: false, errorCode }` payload.\n */\n isUnavailableResult?: (result: T) => boolean\n /** Classifies a thrown error. Defaults to {@link isUpstreamUnavailable}. */\n isUnavailableError?: (error: unknown) => boolean\n /** Observability hook fired each time a model is abandoned — including a\n * policy refusal, whose `reason` is the policy's own refusal text. */\n onFallback?: (attempt: ModelFailoverAttempt, nextModel: string) => void\n}\n\nfunction describe(signal: unknown): string {\n if (signal instanceof Error) return signal.message\n if (signal !== null && typeof signal === 'object') {\n const record = signal as Record<string, unknown>\n const message = readString(record, 'error') ?? readString(record, 'message') ?? readString(record, 'errorCode')\n if (message) return message\n }\n return String(signal)\n}\n\n/**\n * Run `run` against the first model in `models` that does not report an upstream\n * outage, falling through the chain in order.\n *\n * A non-outage failure (bad request, auth, content filter) is re-thrown\n * immediately rather than retried down the chain — those fail identically on\n * every model, so walking the chain would only multiply latency and spend.\n *\n * @throws ModelFailoverExhaustedError when every model reports an outage or is\n * refused by the configured admission policy.\n */\nexport async function runWithModelFailover<T>(\n input: RunWithModelFailoverInput<T>,\n): Promise<ModelFailoverResult<T>> {\n const models = input.models.map((m) => m.trim()).filter((m) => m.length > 0)\n if (models.length === 0) throw new Error('runWithModelFailover requires at least one model')\n\n const isUnavailableResult = input.isUnavailableResult ?? ((r: T) => isUpstreamUnavailable(r))\n const isUnavailableError = input.isUnavailableError ?? isUpstreamUnavailable\n const attempts: ModelFailoverAttempt[] = []\n\n for (let index = 0; index < models.length; index += 1) {\n const model = models[index]!\n\n // Policy BEFORE run: a chain member the deployment does not admit never\n // sees the turn's data. The refusal is one failed attempt — the walk\n // continues to the next member, and an all-refused chain exhausts exactly\n // like an all-dead one.\n if (input.policy) {\n const decision = await checkModelPolicy(model, input.policy.catalog, input.policy.filter, input.policy.context)\n if (!decision.allowed) {\n const attempt: ModelFailoverAttempt = { model, ok: false, reason: decision.reason }\n attempts.push(attempt)\n const next = models[index + 1]\n if (next) input.onFallback?.(attempt, next)\n continue\n }\n }\n\n let result: T\n try {\n result = await input.run(model)\n } catch (error) {\n if (!isUnavailableError(error)) throw error\n const errorCode = readUpstreamUnavailableCode(error)\n const attempt: ModelFailoverAttempt = {\n model,\n ok: false,\n reason: describe(error),\n ...(errorCode ? { errorCode } : {}),\n }\n attempts.push(attempt)\n const next = models[index + 1]\n if (next) input.onFallback?.(attempt, next)\n continue\n }\n\n if (isUnavailableResult(result)) {\n const errorCode = readUpstreamUnavailableCode(result)\n const attempt: ModelFailoverAttempt = {\n model,\n ok: false,\n reason: describe(result),\n ...(errorCode ? { errorCode } : {}),\n }\n attempts.push(attempt)\n const next = models[index + 1]\n if (next) input.onFallback?.(attempt, next)\n continue\n }\n\n attempts.push({ model, ok: true })\n return { value: result, model, attempts, usedFallback: index > 0 }\n }\n\n throw new ModelFailoverExhaustedError(attempts)\n}\n\n/**\n * Build a failover chain: the preferred model first, then `fallbacks`, with\n * duplicates removed so a model is never retried twice in one turn.\n */\nexport function buildModelChain(preferred: string, fallbacks: readonly string[]): string[] {\n const chain: string[] = []\n for (const model of [preferred, ...fallbacks]) {\n const cleaned = typeof model === 'string' ? model.trim() : ''\n if (cleaned.length > 0 && !chain.includes(cleaned)) chain.push(cleaned)\n }\n return chain\n}\n"],"mappings":";;;;;AAqCO,IAAM,6BAAgD;AAAA,EAC3D;AAAA,EACA;AAAA;AAAA;AAAA;AAAA,EAIA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGO,IAAM,gCAAmD,CAAC,KAAK,KAAK,KAAK,KAAK,GAAG;AASxF,IAAM,yBAA4C,CAAC,KAAK,KAAK,KAAK,KAAK,KAAK,GAAG;AAM/E,IAAM,gCAAmD;AAAA,EACvD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA;AAAA,EACA;AACF;AAuCA,IAAM,4BAA+C;AAAA,EACnD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAOO,SAAS,mBAAmB,MAAkC;AACnE,aAAW,WAAW,2BAA2B;AAC/C,UAAM,QAAQ,QAAQ,KAAK,IAAI;AAC/B,QAAI,QAAQ,CAAC,EAAG,QAAO,OAAO,MAAM,CAAC,CAAC;AAAA,EACxC;AACA,SAAO;AACT;AAEA,SAAS,WAAW,QAAiC,KAAiC;AACpF,QAAM,QAAQ,OAAO,GAAG;AACxB,SAAO,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,SAAS,IAAI,QAAQ;AACxE;AAGO,SAAS,4BAA4B,QAAqC;AAC/E,MAAI,WAAW,QAAQ,OAAO,WAAW,SAAU,QAAO;AAC1D,QAAM,SAAS;AACf,QAAM,SAAS,OAAO;AACtB,QAAM,eAAe,WAAW,QAAQ,OAAO,WAAW,WAAY,SAAqC;AAC3G,QAAM,OACJ,WAAW,QAAQ,WAAW,KAC9B,WAAW,QAAQ,MAA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AAK,IAAI;AAC3D,QAAI,QAAQ,SAAS,KAAK,CAAC,MAAM,SAAS,OAAO,EAAG,OAAM,KAAK,OAAO;AAAA,EACxE;AACA,SAAO;AACT;","names":[]}
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createApiKeyFetch
|
|
3
|
+
} from "./chunk-RN4WPTBH.js";
|
|
4
|
+
|
|
5
|
+
// src/operator/contract.ts
|
|
6
|
+
var OPERATOR_API_VERSION = "v1";
|
|
7
|
+
var OPERATOR_API_BASE_PATH = "/api/operator/v1";
|
|
8
|
+
var OPERATOR_ACCESS = [
|
|
9
|
+
{
|
|
10
|
+
scope: "operator:read",
|
|
11
|
+
label: "Read workspaces",
|
|
12
|
+
description: "Read workspaces, conversations, files, approvals, scorecards, and run status."
|
|
13
|
+
},
|
|
14
|
+
{
|
|
15
|
+
scope: "operator:write",
|
|
16
|
+
label: "Create and edit",
|
|
17
|
+
description: "Create workspaces and conversations, and write files."
|
|
18
|
+
},
|
|
19
|
+
{
|
|
20
|
+
scope: "operator:run",
|
|
21
|
+
requires: ["operator:read"],
|
|
22
|
+
label: "Run agents",
|
|
23
|
+
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."
|
|
24
|
+
}
|
|
25
|
+
];
|
|
26
|
+
var OPERATOR_API_SCOPES = OPERATOR_ACCESS.map(({ scope }) => scope);
|
|
27
|
+
var OPERATOR_SCOPE_DEPENDENCIES = Object.fromEntries(
|
|
28
|
+
OPERATOR_ACCESS.flatMap((option) => "requires" in option ? [[option.scope, option.requires]] : [])
|
|
29
|
+
);
|
|
30
|
+
var OPERATOR_WORKSPACE_SCOPE_PREFIX = "operator:workspace:";
|
|
31
|
+
var WORKSPACE_ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
32
|
+
function operatorWorkspaceScope(workspaceId) {
|
|
33
|
+
if (!WORKSPACE_ID.test(workspaceId)) throw new TypeError("Workspace ids contain only letters, digits, - and _");
|
|
34
|
+
return `${OPERATOR_WORKSPACE_SCOPE_PREFIX}${workspaceId}`;
|
|
35
|
+
}
|
|
36
|
+
function operatorKeyWorkspaces(scopes) {
|
|
37
|
+
const restricted = scopes.filter((scope) => scope.startsWith(OPERATOR_WORKSPACE_SCOPE_PREFIX));
|
|
38
|
+
if (restricted.length === 0) return null;
|
|
39
|
+
return restricted.map((scope) => scope.slice(OPERATOR_WORKSPACE_SCOPE_PREFIX.length)).filter((id) => WORKSPACE_ID.test(id));
|
|
40
|
+
}
|
|
41
|
+
var OPERATOR_SETTLED_STATES = ["succeeded", "failed"];
|
|
42
|
+
var OPERATOR_TURN_CANCELLED_CODE = "turn.cancelled";
|
|
43
|
+
var OPERATOR_ROUTES = [
|
|
44
|
+
{ id: "describe", method: "GET", path: "", scopes: ["operator:read"] },
|
|
45
|
+
{ id: "workspaces.list", method: "GET", path: "/workspaces", scopes: ["operator:read"] },
|
|
46
|
+
{ id: "workspaces.create", method: "POST", path: "/workspaces", scopes: ["operator:write"] },
|
|
47
|
+
{ id: "workspaces.get", method: "GET", path: "/workspaces/:workspaceId", scopes: ["operator:read"] },
|
|
48
|
+
{ id: "turns.start", method: "POST", path: "/workspaces/:workspaceId/turns", scopes: ["operator:read", "operator:run"] },
|
|
49
|
+
{ id: "threads.list", method: "GET", path: "/workspaces/:workspaceId/threads", scopes: ["operator:read"] },
|
|
50
|
+
{ id: "threads.get", method: "GET", path: "/workspaces/:workspaceId/threads/:threadId", scopes: ["operator:read"] },
|
|
51
|
+
{ id: "turns.get", method: "GET", path: "/workspaces/:workspaceId/threads/:threadId/turns/:turnId", scopes: ["operator:read"] },
|
|
52
|
+
{ id: "turns.cancel", method: "POST", path: "/workspaces/:workspaceId/threads/:threadId/turns/:turnId/cancel", scopes: ["operator:read", "operator:run"] },
|
|
53
|
+
{ id: "approvals.list", method: "GET", path: "/workspaces/:workspaceId/approvals", scopes: ["operator:read"] },
|
|
54
|
+
{ id: "journal.list", method: "GET", path: "/workspaces/:workspaceId/journal", scopes: ["operator:read"] },
|
|
55
|
+
{ id: "files.list", method: "GET", path: "/workspaces/:workspaceId/files", scopes: ["operator:read"] },
|
|
56
|
+
{ id: "files.read", method: "GET", path: "/workspaces/:workspaceId/file", scopes: ["operator:read"] },
|
|
57
|
+
{ id: "assets.read", method: "GET", path: "/workspaces/:workspaceId/assets/:assetId", scopes: ["operator:read"] },
|
|
58
|
+
{ id: "scorecard.get", method: "GET", path: "/workspaces/:workspaceId/scorecard", scopes: ["operator:read"] }
|
|
59
|
+
];
|
|
60
|
+
var SEGMENT = /^[A-Za-z0-9_:.%-]{1,256}$/;
|
|
61
|
+
function matchOperatorRoute(method, pathname, basePath = OPERATOR_API_BASE_PATH) {
|
|
62
|
+
if (pathname !== basePath && !pathname.startsWith(`${basePath}/`)) return null;
|
|
63
|
+
const rest = pathname.slice(basePath.length).replace(/\/$/, "");
|
|
64
|
+
const actual = rest ? rest.split("/").slice(1) : [];
|
|
65
|
+
for (const route of OPERATOR_ROUTES) {
|
|
66
|
+
if (route.method !== method) continue;
|
|
67
|
+
const pattern = route.path ? route.path.split("/").slice(1) : [];
|
|
68
|
+
if (pattern.length !== actual.length) continue;
|
|
69
|
+
const params = {};
|
|
70
|
+
let matched = true;
|
|
71
|
+
for (let index = 0; index < pattern.length; index++) {
|
|
72
|
+
const expected = pattern[index];
|
|
73
|
+
const segment2 = actual[index];
|
|
74
|
+
if (expected.startsWith(":")) {
|
|
75
|
+
if (!SEGMENT.test(segment2)) {
|
|
76
|
+
matched = false;
|
|
77
|
+
break;
|
|
78
|
+
}
|
|
79
|
+
let decoded;
|
|
80
|
+
try {
|
|
81
|
+
decoded = decodeURIComponent(segment2);
|
|
82
|
+
} catch {
|
|
83
|
+
matched = false;
|
|
84
|
+
break;
|
|
85
|
+
}
|
|
86
|
+
if (!decoded || decoded.includes("/")) {
|
|
87
|
+
matched = false;
|
|
88
|
+
break;
|
|
89
|
+
}
|
|
90
|
+
params[expected.slice(1)] = decoded;
|
|
91
|
+
} else if (expected !== segment2) {
|
|
92
|
+
matched = false;
|
|
93
|
+
break;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
if (matched) return { route, params };
|
|
97
|
+
}
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// src/operator/client.ts
|
|
102
|
+
function segment(value) {
|
|
103
|
+
return encodeURIComponent(value);
|
|
104
|
+
}
|
|
105
|
+
async function failure(response) {
|
|
106
|
+
let body = {};
|
|
107
|
+
try {
|
|
108
|
+
body = await response.json();
|
|
109
|
+
} catch {
|
|
110
|
+
}
|
|
111
|
+
return {
|
|
112
|
+
succeeded: false,
|
|
113
|
+
status: response.status,
|
|
114
|
+
code: typeof body.code === "string" ? body.code : `http_${response.status}`,
|
|
115
|
+
error: typeof body.error === "string" ? body.error : `HTTP ${response.status}`,
|
|
116
|
+
retryable: body.retryable === true || response.status === 429 || response.status >= 500
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
function transportFailure(error) {
|
|
120
|
+
const aborted = error instanceof Error && error.name === "AbortError";
|
|
121
|
+
return {
|
|
122
|
+
succeeded: false,
|
|
123
|
+
status: 0,
|
|
124
|
+
code: aborted ? "operator.aborted" : "operator.transport_failed",
|
|
125
|
+
// createApiKeyFetch never forwards transport diagnostics, which could carry the key.
|
|
126
|
+
error: error instanceof Error ? error.message : "Operator transport failed",
|
|
127
|
+
retryable: !aborted
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
var SETTLED = /* @__PURE__ */ new Set(["succeeded", "failed", "input-required"]);
|
|
131
|
+
function createOperatorClient(options) {
|
|
132
|
+
const basePath = (options.basePath ?? OPERATOR_API_BASE_PATH).replace(/\/$/, "");
|
|
133
|
+
const request = createApiKeyFetch({
|
|
134
|
+
origin: options.origin,
|
|
135
|
+
getApiKey: options.getApiKey,
|
|
136
|
+
...options.fetchImpl ? { fetchImpl: options.fetchImpl } : {},
|
|
137
|
+
...options.allowHttpLoopback ? { allowHttpLoopback: true } : {}
|
|
138
|
+
});
|
|
139
|
+
async function call(path, pick, init = {}) {
|
|
140
|
+
let response;
|
|
141
|
+
try {
|
|
142
|
+
response = await request(`${basePath}${path}`, {
|
|
143
|
+
...init,
|
|
144
|
+
headers: { accept: "application/json", ...init.body ? { "content-type": "application/json" } : {} }
|
|
145
|
+
});
|
|
146
|
+
} catch (error) {
|
|
147
|
+
return transportFailure(error);
|
|
148
|
+
}
|
|
149
|
+
if (!response.ok) return failure(response);
|
|
150
|
+
try {
|
|
151
|
+
return { succeeded: true, value: pick(await response.json()) };
|
|
152
|
+
} catch {
|
|
153
|
+
return { succeeded: false, status: response.status, code: "operator.invalid_response", error: "The response was not the expected JSON", retryable: true };
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
const query = (params) => {
|
|
157
|
+
const search = new URLSearchParams();
|
|
158
|
+
for (const [name, value] of Object.entries(params)) if (value !== void 0 && value !== "") search.set(name, String(value));
|
|
159
|
+
const text = search.toString();
|
|
160
|
+
return text ? `?${text}` : "";
|
|
161
|
+
};
|
|
162
|
+
const client = {
|
|
163
|
+
describe: () => call("", (body) => body),
|
|
164
|
+
listWorkspaces: () => call("/workspaces", (body) => body.workspaces),
|
|
165
|
+
createWorkspace: (input) => call("/workspaces", (body) => body.workspace, {
|
|
166
|
+
method: "POST",
|
|
167
|
+
body: JSON.stringify({ name: input.name })
|
|
168
|
+
}),
|
|
169
|
+
getWorkspace: (workspaceId) => call(`/workspaces/${segment(workspaceId)}`, (body) => body.workspace),
|
|
170
|
+
startTurn: (workspaceId, input) => call(`/workspaces/${segment(workspaceId)}/turns`, (body) => body.turn, {
|
|
171
|
+
method: "POST",
|
|
172
|
+
body: JSON.stringify({ ...input, turnId: input.turnId ?? crypto.randomUUID() })
|
|
173
|
+
}),
|
|
174
|
+
getTurn: (workspaceId, threadId, turnId, opts = {}) => call(
|
|
175
|
+
`/workspaces/${segment(workspaceId)}/threads/${segment(threadId)}/turns/${segment(turnId)}${query({ wait: opts.waitSeconds })}`,
|
|
176
|
+
(body) => body.turn,
|
|
177
|
+
opts.signal ? { signal: opts.signal } : {}
|
|
178
|
+
),
|
|
179
|
+
cancelTurn: (workspaceId, threadId, turnId, opts = {}) => call(
|
|
180
|
+
`/workspaces/${segment(workspaceId)}/threads/${segment(threadId)}/turns/${segment(turnId)}/cancel${query({ wait: opts.waitSeconds })}`,
|
|
181
|
+
(body) => body.turn,
|
|
182
|
+
{ method: "POST", ...opts.signal ? { signal: opts.signal } : {} }
|
|
183
|
+
),
|
|
184
|
+
async waitForTurn(workspaceId, threadId, turnId, opts) {
|
|
185
|
+
const deadline = Date.now() + opts.timeoutMs;
|
|
186
|
+
const waitSeconds = opts.waitSeconds ?? 25;
|
|
187
|
+
let last = null;
|
|
188
|
+
while (true) {
|
|
189
|
+
const remaining = Math.floor((deadline - Date.now()) / 1e3);
|
|
190
|
+
const started = Date.now();
|
|
191
|
+
last = await client.getTurn(workspaceId, threadId, turnId, {
|
|
192
|
+
waitSeconds: Math.max(0, Math.min(waitSeconds, remaining)),
|
|
193
|
+
...opts.signal ? { signal: opts.signal } : {}
|
|
194
|
+
});
|
|
195
|
+
if (!last.succeeded) {
|
|
196
|
+
if (!last.retryable || Date.now() >= deadline || opts.signal?.aborted) return last;
|
|
197
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(5e3, Math.max(0, deadline - Date.now()))));
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
if (SETTLED.has(last.value.state) || last.value.approvals.length > 0) return last;
|
|
201
|
+
if (Date.now() >= deadline || opts.signal?.aborted) return last;
|
|
202
|
+
if (Date.now() - started < 1e3) {
|
|
203
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(2e3, Math.max(0, deadline - Date.now()))));
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
},
|
|
207
|
+
listThreads: (workspaceId, q = {}) => call(
|
|
208
|
+
`/workspaces/${segment(workspaceId)}/threads${query({ cursor: q.cursor, limit: q.limit })}`,
|
|
209
|
+
(body) => ({ threads: body.threads, nextCursor: body.nextCursor ?? null })
|
|
210
|
+
),
|
|
211
|
+
getThread: (workspaceId, threadId) => call(
|
|
212
|
+
`/workspaces/${segment(workspaceId)}/threads/${segment(threadId)}`,
|
|
213
|
+
(body) => ({ thread: body.thread, latestTurn: body.latestTurn ?? null })
|
|
214
|
+
),
|
|
215
|
+
listApprovals: (workspaceId) => call(`/workspaces/${segment(workspaceId)}/approvals`, (body) => body.approvals),
|
|
216
|
+
listJournal: (workspaceId, q = {}) => call(
|
|
217
|
+
`/workspaces/${segment(workspaceId)}/journal${query({ days: q.days })}`,
|
|
218
|
+
(body) => body.entries
|
|
219
|
+
),
|
|
220
|
+
listFiles: (workspaceId, q = {}) => call(
|
|
221
|
+
`/workspaces/${segment(workspaceId)}/files${query({ prefix: q.prefix })}`,
|
|
222
|
+
(body) => body.files
|
|
223
|
+
),
|
|
224
|
+
readFile: (workspaceId, path) => call(
|
|
225
|
+
`/workspaces/${segment(workspaceId)}/file${query({ path })}`,
|
|
226
|
+
(body) => body.file
|
|
227
|
+
),
|
|
228
|
+
async readAsset(workspaceId, assetId, init = {}) {
|
|
229
|
+
let response;
|
|
230
|
+
try {
|
|
231
|
+
response = await request(`${basePath}/workspaces/${segment(workspaceId)}/assets/${segment(assetId)}`, init.signal ? { signal: init.signal } : {});
|
|
232
|
+
} catch (error) {
|
|
233
|
+
return transportFailure(error);
|
|
234
|
+
}
|
|
235
|
+
if (!response.ok) return failure(response);
|
|
236
|
+
return { succeeded: true, value: response };
|
|
237
|
+
},
|
|
238
|
+
getScorecard: (workspaceId, q = {}) => call(
|
|
239
|
+
`/workspaces/${segment(workspaceId)}/scorecard${query({ days: q.days })}`,
|
|
240
|
+
(body) => body.scorecard
|
|
241
|
+
)
|
|
242
|
+
};
|
|
243
|
+
return client;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
export {
|
|
247
|
+
OPERATOR_API_VERSION,
|
|
248
|
+
OPERATOR_API_BASE_PATH,
|
|
249
|
+
OPERATOR_ACCESS,
|
|
250
|
+
OPERATOR_API_SCOPES,
|
|
251
|
+
OPERATOR_SCOPE_DEPENDENCIES,
|
|
252
|
+
OPERATOR_WORKSPACE_SCOPE_PREFIX,
|
|
253
|
+
operatorWorkspaceScope,
|
|
254
|
+
operatorKeyWorkspaces,
|
|
255
|
+
OPERATOR_SETTLED_STATES,
|
|
256
|
+
OPERATOR_TURN_CANCELLED_CODE,
|
|
257
|
+
OPERATOR_ROUTES,
|
|
258
|
+
matchOperatorRoute,
|
|
259
|
+
createOperatorClient
|
|
260
|
+
};
|
|
261
|
+
//# sourceMappingURL=chunk-N425HGJW.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/operator/contract.ts","../src/operator/client.ts"],"sourcesContent":["/**\n * The standard operator API contract every agent app mounts at\n * `/api/operator/v1`. An outside agent (a Claude Code or Codex session, or\n * another app's agent) holds one scoped key per app and drives workspaces\n * through these routes; the app supplies only storage and execution.\n */\n\nimport type { ChatAttachmentInput } from '../chat-routes/wire.js'\n\nexport const OPERATOR_API_VERSION = 'v1'\nexport const OPERATOR_API_BASE_PATH = '/api/operator/v1'\n\n/** Key permissions, with the labels an app's API access page shows. */\nexport const OPERATOR_ACCESS = [\n {\n scope: 'operator:read',\n label: 'Read workspaces',\n description: 'Read workspaces, conversations, files, approvals, scorecards, and run status.',\n },\n {\n scope: 'operator:write',\n label: 'Create and edit',\n description: 'Create workspaces and conversations, and write files.',\n },\n {\n scope: 'operator:run',\n requires: ['operator:read'],\n label: 'Run agents',\n 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.',\n },\n] as const\n\nexport type OperatorScope = typeof OPERATOR_ACCESS[number]['scope']\n\nexport const OPERATOR_API_SCOPES: readonly OperatorScope[] = OPERATOR_ACCESS.map(({ scope }) => scope)\n\nexport const OPERATOR_SCOPE_DEPENDENCIES: Readonly<Record<string, readonly string[]>> = Object.fromEntries(\n OPERATOR_ACCESS.flatMap((option) => 'requires' in option ? [[option.scope, option.requires]] : []),\n)\n\n/**\n * A key carrying one or more of these scopes reaches only the named\n * workspaces and cannot create workspaces. Keys without one keep the owner's\n * ordinary workspace access.\n */\nexport const OPERATOR_WORKSPACE_SCOPE_PREFIX = 'operator:workspace:'\n\nconst WORKSPACE_ID = /^[A-Za-z0-9_-]{1,128}$/\n\nexport function operatorWorkspaceScope(workspaceId: string): string {\n if (!WORKSPACE_ID.test(workspaceId)) throw new TypeError('Workspace ids contain only letters, digits, - and _')\n return `${OPERATOR_WORKSPACE_SCOPE_PREFIX}${workspaceId}`\n}\n\n/** The workspaces a key is restricted to, or null when it is unrestricted. A malformed restriction restricts to nothing. */\nexport function operatorKeyWorkspaces(scopes: readonly string[]): readonly string[] | null {\n const restricted = scopes.filter((scope) => scope.startsWith(OPERATOR_WORKSPACE_SCOPE_PREFIX))\n if (restricted.length === 0) return null\n return restricted\n .map((scope) => scope.slice(OPERATOR_WORKSPACE_SCOPE_PREFIX.length))\n .filter((id) => WORKSPACE_ID.test(id))\n}\n\nexport type OperatorRole = 'owner' | 'admin' | 'editor' | 'viewer'\n\nexport interface OperatorAppInfo {\n /** Stable app identifier, such as `gtm` or `tax`. */\n app: string\n name: string\n apiVersion: typeof OPERATOR_API_VERSION\n /** Optional operations this app implements; absent ones answer 501. */\n capabilities: OperatorCapability[]\n}\n\nexport type OperatorCapability =\n | 'turns.attachments'\n | 'turns.cancel'\n | 'workspaces.create'\n | 'threads.read'\n | 'files.read'\n | 'journal.read'\n | 'assets.read'\n | 'scorecard.read'\n\nexport interface OperatorPrincipalInfo {\n keyId: string\n scopes: string[]\n /** Workspaces the key is restricted to, or null for the owner's ordinary access. */\n workspaces: string[] | null\n}\n\nexport interface OperatorWorkspace {\n id: string\n name: string\n role?: OperatorRole\n /** Browser link for a person to open the workspace. */\n url?: string\n createdAt?: string\n}\n\nexport interface OperatorThread {\n id: string\n title: string\n updatedAt?: string\n url?: string\n}\n\n/**\n * `succeeded` and `failed` are settled. `input-required` waits on a person or\n * an operator decision listed in `approvals`. `unknown` means the app cannot\n * establish the state; it is never evidence of success.\n */\nexport type OperatorTurnState = 'queued' | 'working' | 'input-required' | 'succeeded' | 'failed' | 'unknown'\n\nexport const OPERATOR_SETTLED_STATES: readonly OperatorTurnState[] = ['succeeded', 'failed']\n\n/** `failure.code` of a turn that settled because it was cancelled before it finished. */\nexport const OPERATOR_TURN_CANCELLED_CODE = 'turn.cancelled'\n\nexport interface OperatorAssetRef {\n id: string\n /** Root-relative operator route that returns the bytes. */\n path: string\n mediaType?: string\n name?: string\n}\n\nexport interface OperatorFileChange {\n path: string\n action: 'created' | 'updated' | 'deleted' | 'changed'\n}\n\nexport type OperatorApprovalKind = 'question' | 'permission' | 'plan' | 'hub' | 'asset' | 'review'\n\nexport interface OperatorApproval {\n id: string\n kind: OperatorApprovalKind\n title: string\n detail?: string\n threadId?: string\n /** Browser link where an authorized person decides it. */\n url?: string\n createdAt?: string\n expiresAt?: string\n /** Who can decide: an operator key with run access, an editor, or the workspace owner. */\n decidedBy: 'operator' | 'editor' | 'owner'\n}\n\nexport interface OperatorTurn {\n workspaceId: string\n threadId: string\n turnId: string\n state: OperatorTurnState\n url?: string\n executionId?: string\n model?: string\n costUsd?: number\n /** Producer-recorded basis for costUsd; catalog is an estimate, ledger is settlement evidence. */\n costSource?: 'ledger' | 'catalog' | 'reported' | 'unreported' | 'subscription'\n /** Producer-recorded billing path, not the identity of a payer. */\n billingOwner?: 'router' | 'sandbox-router' | 'subscription'\n /** Producer-recorded credential path; never inferred from costUsd or billingOwner. */\n credentialSource?: 'router' | 'subscription'\n /** Opaque producer settlement reference; its presence alone does not prove a charge or zero provider cost. */\n settlementRecord?: string\n /**\n * Token usage the app stored on the turn's reply; `operatorTurnUsage` maps\n * a chat-store row to it.\n * - `inputTokens`: prompt tokens NOT read from the provider's cache. Unlike\n * the turn trace's summary, it never includes cache reads; it is omitted\n * when the row's split is ambiguous, including when the row records no\n * cache count (see `operatorTurnUsage`).\n * - `cachedInputTokens`: prompt tokens read from the provider's cache (the\n * row's `cacheReadTokens`); with both present the whole prompt is\n * `inputTokens + cachedInputTokens`. When absent the cache share is unknown.\n * - `outputTokens`: completion tokens.\n * Each field is present only when known; never a guessed zero.\n */\n usage?: { inputTokens?: number; cachedInputTokens?: number; outputTokens?: number }\n completedAt?: string\n /** The settled answer; null until the turn settles. */\n reply: { content: string; mediaType: string } | null\n failure: { code?: string; message: string } | null\n assets: OperatorAssetRef[]\n files: OperatorFileChange[]\n /** Decisions open on this turn's conversation. */\n approvals: OperatorApproval[]\n}\n\nexport interface OperatorJournalEntry {\n path: string\n /** `YYYY-MM-DD` the entry belongs to. */\n date: string\n title?: string\n updatedAt?: string\n}\n\nexport interface OperatorFileEntry {\n path: string\n updatedAt?: string\n bytes?: number\n}\n\nexport interface OperatorFile {\n path: string\n content: string\n mediaType: string\n revision?: string\n}\n\nexport interface OperatorMetric {\n key: string\n label: string\n /** Null when the app has no measurement; never a guessed zero. */\n value: number | null\n unit: 'count' | 'usd' | 'ratio' | 'ms'\n note?: string\n}\n\nexport interface OperatorScorecard {\n workspaceId: string\n generatedAt: string\n window: { start: string; end: string; days: number }\n /** Work the agent did in the window. */\n metrics: OperatorMetric[]\n /** Business results recorded in the window, such as clicks, signups, or replies. */\n outcomes: OperatorMetric[]\n /** How the numbers are measured and what they exclude. */\n measurement: string\n}\n\nexport interface OperatorErrorBody {\n error: string\n code: string\n retryable?: boolean\n}\n\nexport interface StartTurnInput {\n /** Client-generated UUID. Reuse it to retry the same turn; it never starts twice. */\n turnId: string\n content: string\n /** Continue this conversation; omitted starts a new one. */\n threadId?: string\n /** Title for a new conversation. */\n title?: string\n model?: string\n /**\n * Files uploaded to this workspace ahead of the turn, as the app's\n * attachment upload route returned them in `{ files }`. They reach the\n * agent exactly as browser-composer attachments do; the app re-checks each\n * path against the workspace's own store. At most the app's\n * `maxAttachments` entries, `ATTACHMENT_MAX_COUNT` (`/chat-routes`) unless\n * the app sets one. Apps without the `turns.attachments` capability refuse\n * them.\n */\n attachments?: ChatAttachmentInput[]\n}\n\n/** Route table: method, path pattern under the base path, and required scopes. */\nexport const OPERATOR_ROUTES = [\n { id: 'describe', method: 'GET', path: '', scopes: ['operator:read'] },\n { id: 'workspaces.list', method: 'GET', path: '/workspaces', scopes: ['operator:read'] },\n { id: 'workspaces.create', method: 'POST', path: '/workspaces', scopes: ['operator:write'] },\n { id: 'workspaces.get', method: 'GET', path: '/workspaces/:workspaceId', scopes: ['operator:read'] },\n { id: 'turns.start', method: 'POST', path: '/workspaces/:workspaceId/turns', scopes: ['operator:read', 'operator:run'] },\n { id: 'threads.list', method: 'GET', path: '/workspaces/:workspaceId/threads', scopes: ['operator:read'] },\n { id: 'threads.get', method: 'GET', path: '/workspaces/:workspaceId/threads/:threadId', scopes: ['operator:read'] },\n { id: 'turns.get', method: 'GET', path: '/workspaces/:workspaceId/threads/:threadId/turns/:turnId', scopes: ['operator:read'] },\n { id: 'turns.cancel', method: 'POST', path: '/workspaces/:workspaceId/threads/:threadId/turns/:turnId/cancel', scopes: ['operator:read', 'operator:run'] },\n { id: 'approvals.list', method: 'GET', path: '/workspaces/:workspaceId/approvals', scopes: ['operator:read'] },\n { id: 'journal.list', method: 'GET', path: '/workspaces/:workspaceId/journal', scopes: ['operator:read'] },\n { id: 'files.list', method: 'GET', path: '/workspaces/:workspaceId/files', scopes: ['operator:read'] },\n { id: 'files.read', method: 'GET', path: '/workspaces/:workspaceId/file', scopes: ['operator:read'] },\n { id: 'assets.read', method: 'GET', path: '/workspaces/:workspaceId/assets/:assetId', scopes: ['operator:read'] },\n { id: 'scorecard.get', method: 'GET', path: '/workspaces/:workspaceId/scorecard', scopes: ['operator:read'] },\n] as const satisfies ReadonlyArray<{ id: string; method: 'GET' | 'POST'; path: string; scopes: readonly OperatorScope[] }>\n\nexport type OperatorRouteId = typeof OPERATOR_ROUTES[number]['id']\n\nconst SEGMENT = /^[A-Za-z0-9_:.%-]{1,256}$/\n\n/** Match a pathname under the base path to its route and decoded parameters. */\nexport function matchOperatorRoute(\n method: string,\n pathname: string,\n basePath: string = OPERATOR_API_BASE_PATH,\n): { route: typeof OPERATOR_ROUTES[number]; params: Record<string, string> } | null {\n if (pathname !== basePath && !pathname.startsWith(`${basePath}/`)) return null\n const rest = pathname.slice(basePath.length).replace(/\\/$/, '')\n const actual = rest ? rest.split('/').slice(1) : []\n for (const route of OPERATOR_ROUTES) {\n if (route.method !== method) continue\n const pattern = route.path ? route.path.split('/').slice(1) : []\n if (pattern.length !== actual.length) continue\n const params: Record<string, string> = {}\n let matched = true\n for (let index = 0; index < pattern.length; index++) {\n const expected = pattern[index]!\n const segment = actual[index]!\n if (expected.startsWith(':')) {\n if (!SEGMENT.test(segment)) { matched = false; break }\n let decoded: string\n try { decoded = decodeURIComponent(segment) } catch { matched = false; break }\n if (!decoded || decoded.includes('/')) { matched = false; break }\n params[expected.slice(1)] = decoded\n } else if (expected !== segment) {\n matched = false\n break\n }\n }\n if (matched) return { route, params }\n }\n return null\n}\n","import { createApiKeyFetch } from '../web/api-key-fetch.js'\nimport {\n OPERATOR_API_BASE_PATH,\n type OperatorApproval,\n type OperatorAppInfo,\n type OperatorErrorBody,\n type OperatorFile,\n type OperatorFileEntry,\n type OperatorJournalEntry,\n type OperatorPrincipalInfo,\n type OperatorScorecard,\n type OperatorThread,\n type OperatorTurn,\n type OperatorWorkspace,\n type StartTurnInput,\n} from './contract.js'\n\nexport type OperatorResult<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; status: number; code: string; error: string; retryable: boolean }\n\nexport interface OperatorClientOptions {\n /** The app's origin, such as `https://gtm.tangle.tools`. */\n origin: string\n /** Resolve the key from trusted secret storage on each request; never from model output. */\n getApiKey(): string | Promise<string>\n fetchImpl?: typeof fetch\n allowHttpLoopback?: boolean\n basePath?: string\n}\n\nexport interface WaitForTurnOptions {\n /** Total time to follow the turn. */\n timeoutMs: number\n /** Server hold per request, in seconds; the server caps it. */\n waitSeconds?: number\n signal?: AbortSignal\n}\n\nexport interface OperatorClient {\n describe(): Promise<OperatorResult<{ app: OperatorAppInfo; principal: OperatorPrincipalInfo }>>\n listWorkspaces(): Promise<OperatorResult<OperatorWorkspace[]>>\n createWorkspace(input: { name: string }): Promise<OperatorResult<OperatorWorkspace>>\n getWorkspace(workspaceId: string): Promise<OperatorResult<OperatorWorkspace>>\n /** Omitting turnId generates one; retry with the returned turn's id. */\n startTurn(workspaceId: string, input: Omit<StartTurnInput, 'turnId'> & { turnId?: string }): Promise<OperatorResult<OperatorTurn>>\n getTurn(workspaceId: string, threadId: string, turnId: string, options?: { waitSeconds?: number; signal?: AbortSignal }): Promise<OperatorResult<OperatorTurn>>\n /**\n * Stop a turn. A settled turn comes back as it settled; otherwise the app\n * has been asked to stop it, and the server holds up to `waitSeconds` for\n * the turn to settle `failed` with `OPERATOR_TURN_CANCELLED_CODE`. Read it\n * with `getTurn` or `waitForTurn` until it settles.\n */\n cancelTurn(workspaceId: string, threadId: string, turnId: string, options?: { waitSeconds?: number; signal?: AbortSignal }): Promise<OperatorResult<OperatorTurn>>\n /** Follow until the turn settles, waits on a decision, or the timeout passes; the last read is returned. */\n waitForTurn(workspaceId: string, threadId: string, turnId: string, options: WaitForTurnOptions): Promise<OperatorResult<OperatorTurn>>\n listThreads(workspaceId: string, query?: { cursor?: string; limit?: number }): Promise<OperatorResult<{ threads: OperatorThread[]; nextCursor: string | null }>>\n getThread(workspaceId: string, threadId: string): Promise<OperatorResult<{ thread: OperatorThread; latestTurn: OperatorTurn | null }>>\n listApprovals(workspaceId: string): Promise<OperatorResult<OperatorApproval[]>>\n listJournal(workspaceId: string, query?: { days?: number }): Promise<OperatorResult<OperatorJournalEntry[]>>\n listFiles(workspaceId: string, query?: { prefix?: string }): Promise<OperatorResult<OperatorFileEntry[]>>\n readFile(workspaceId: string, path: string): Promise<OperatorResult<OperatorFile>>\n /** The raw asset response; the caller reads and bounds its body. */\n readAsset(workspaceId: string, assetId: string, init?: { signal?: AbortSignal }): Promise<OperatorResult<Response>>\n getScorecard(workspaceId: string, query?: { days?: number }): Promise<OperatorResult<OperatorScorecard>>\n}\n\nfunction segment(value: string): string {\n return encodeURIComponent(value)\n}\n\nasync function failure(response: Response): Promise<OperatorResult<never>> {\n let body: Partial<OperatorErrorBody> = {}\n try { body = await response.json() as Partial<OperatorErrorBody> } catch { /* A non-JSON refusal keeps its status. */ }\n return {\n succeeded: false,\n status: response.status,\n code: typeof body.code === 'string' ? body.code : `http_${response.status}`,\n error: typeof body.error === 'string' ? body.error : `HTTP ${response.status}`,\n retryable: body.retryable === true || response.status === 429 || response.status >= 500,\n }\n}\n\nfunction transportFailure(error: unknown): OperatorResult<never> {\n const aborted = error instanceof Error && error.name === 'AbortError'\n return {\n succeeded: false,\n status: 0,\n code: aborted ? 'operator.aborted' : 'operator.transport_failed',\n // createApiKeyFetch never forwards transport diagnostics, which could carry the key.\n error: error instanceof Error ? error.message : 'Operator transport failed',\n retryable: !aborted,\n }\n}\n\nconst SETTLED = new Set(['succeeded', 'failed', 'input-required'])\n\n/** A typed client for one app's operator API. */\nexport function createOperatorClient(options: OperatorClientOptions): OperatorClient {\n const basePath = (options.basePath ?? OPERATOR_API_BASE_PATH).replace(/\\/$/, '')\n const request = createApiKeyFetch({\n origin: options.origin,\n getApiKey: options.getApiKey,\n ...(options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}),\n ...(options.allowHttpLoopback ? { allowHttpLoopback: true } : {}),\n })\n\n async function call<T>(\n path: string,\n pick: (body: Record<string, unknown>) => T,\n init: RequestInit = {},\n ): Promise<OperatorResult<T>> {\n let response: Response\n try {\n response = await request(`${basePath}${path}`, {\n ...init,\n headers: { accept: 'application/json', ...(init.body ? { 'content-type': 'application/json' } : {}) },\n })\n } catch (error) {\n return transportFailure(error)\n }\n if (!response.ok) return failure(response)\n try {\n return { succeeded: true, value: pick(await response.json() as Record<string, unknown>) }\n } catch {\n return { succeeded: false, status: response.status, code: 'operator.invalid_response', error: 'The response was not the expected JSON', retryable: true }\n }\n }\n\n const query = (params: Record<string, string | number | undefined>) => {\n const search = new URLSearchParams()\n for (const [name, value] of Object.entries(params)) if (value !== undefined && value !== '') search.set(name, String(value))\n const text = search.toString()\n return text ? `?${text}` : ''\n }\n\n const client: OperatorClient = {\n describe: () => call('', (body) => body as unknown as { app: OperatorAppInfo; principal: OperatorPrincipalInfo }),\n listWorkspaces: () => call('/workspaces', (body) => body.workspaces as OperatorWorkspace[]),\n createWorkspace: (input) => call('/workspaces', (body) => body.workspace as OperatorWorkspace, {\n method: 'POST', body: JSON.stringify({ name: input.name }),\n }),\n getWorkspace: (workspaceId) => call(`/workspaces/${segment(workspaceId)}`, (body) => body.workspace as OperatorWorkspace),\n startTurn: (workspaceId, input) => call(`/workspaces/${segment(workspaceId)}/turns`, (body) => body.turn as OperatorTurn, {\n method: 'POST', body: JSON.stringify({ ...input, turnId: input.turnId ?? crypto.randomUUID() }),\n }),\n getTurn: (workspaceId, threadId, turnId, opts = {}) => call(\n `/workspaces/${segment(workspaceId)}/threads/${segment(threadId)}/turns/${segment(turnId)}${query({ wait: opts.waitSeconds })}`,\n (body) => body.turn as OperatorTurn,\n opts.signal ? { signal: opts.signal } : {},\n ),\n cancelTurn: (workspaceId, threadId, turnId, opts = {}) => call(\n `/workspaces/${segment(workspaceId)}/threads/${segment(threadId)}/turns/${segment(turnId)}/cancel${query({ wait: opts.waitSeconds })}`,\n (body) => body.turn as OperatorTurn,\n { method: 'POST', ...(opts.signal ? { signal: opts.signal } : {}) },\n ),\n async waitForTurn(workspaceId, threadId, turnId, opts) {\n const deadline = Date.now() + opts.timeoutMs\n const waitSeconds = opts.waitSeconds ?? 25\n let last: OperatorResult<OperatorTurn> | null = null\n while (true) {\n const remaining = Math.floor((deadline - Date.now()) / 1000)\n const started = Date.now()\n last = await client.getTurn(workspaceId, threadId, turnId, {\n waitSeconds: Math.max(0, Math.min(waitSeconds, remaining)),\n ...(opts.signal ? { signal: opts.signal } : {}),\n })\n if (!last.succeeded) {\n if (!last.retryable || Date.now() >= deadline || opts.signal?.aborted) return last\n await new Promise((resolve) => setTimeout(resolve, Math.min(5_000, Math.max(0, deadline - Date.now()))))\n continue\n }\n if (SETTLED.has(last.value.state) || last.value.approvals.length > 0) return last\n if (Date.now() >= deadline || opts.signal?.aborted) return last\n // A server that does not hold the read still gets a bounded request rate.\n if (Date.now() - started < 1_000) {\n await new Promise((resolve) => setTimeout(resolve, Math.min(2_000, Math.max(0, deadline - Date.now()))))\n }\n }\n },\n listThreads: (workspaceId, q = {}) => call(\n `/workspaces/${segment(workspaceId)}/threads${query({ cursor: q.cursor, limit: q.limit })}`,\n (body) => ({ threads: body.threads as OperatorThread[], nextCursor: (body.nextCursor as string | null) ?? null }),\n ),\n getThread: (workspaceId, threadId) => call(\n `/workspaces/${segment(workspaceId)}/threads/${segment(threadId)}`,\n (body) => ({ thread: body.thread as OperatorThread, latestTurn: (body.latestTurn as OperatorTurn | null) ?? null }),\n ),\n listApprovals: (workspaceId) => call(`/workspaces/${segment(workspaceId)}/approvals`, (body) => body.approvals as OperatorApproval[]),\n listJournal: (workspaceId, q = {}) => call(\n `/workspaces/${segment(workspaceId)}/journal${query({ days: q.days })}`,\n (body) => body.entries as OperatorJournalEntry[],\n ),\n listFiles: (workspaceId, q = {}) => call(\n `/workspaces/${segment(workspaceId)}/files${query({ prefix: q.prefix })}`,\n (body) => body.files as OperatorFileEntry[],\n ),\n readFile: (workspaceId, path) => call(\n `/workspaces/${segment(workspaceId)}/file${query({ path })}`,\n (body) => body.file as OperatorFile,\n ),\n async readAsset(workspaceId, assetId, init = {}) {\n let response: Response\n try {\n response = await request(`${basePath}/workspaces/${segment(workspaceId)}/assets/${segment(assetId)}`, init.signal ? { signal: init.signal } : {})\n } catch (error) {\n return transportFailure(error)\n }\n if (!response.ok) return failure(response)\n return { succeeded: true, value: response }\n },\n getScorecard: (workspaceId, q = {}) => call(\n `/workspaces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