@0perator/operator 0.2.0 → 0.2.2-next.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.
Files changed (117) hide show
  1. package/README.md +5 -4
  2. package/dist/auth/byo.js +1 -1
  3. package/dist/auth/commands.js +15 -5
  4. package/dist/auth/identity.js +1 -0
  5. package/dist/auth/staff.js +55 -0
  6. package/dist/autonomy/agent-cli.js +1 -1
  7. package/dist/autonomy/delegate-mode.js +2 -2
  8. package/dist/autonomy/delegate.js +41 -14
  9. package/dist/autonomy/headless.js +37 -10
  10. package/dist/autonomy/index.js +2 -4
  11. package/dist/autonomy/pr-isolation.js +92 -0
  12. package/dist/autonomy/pr-preflight.js +474 -0
  13. package/dist/autonomy/session-factory.js +13 -12
  14. package/dist/autonomy/subagent-model.js +17 -7
  15. package/dist/background/capacity.js +136 -0
  16. package/dist/background/evidence.js +42 -0
  17. package/dist/background/index.js +311 -44
  18. package/dist/background/lane-phase.js +60 -0
  19. package/dist/background/lane-summary.js +151 -0
  20. package/dist/background/notices.js +12 -3
  21. package/dist/background/synthesis.js +25 -0
  22. package/dist/browser/capture.js +505 -0
  23. package/dist/browser/engine.js +4 -3
  24. package/dist/browser/page-capture.js +167 -0
  25. package/dist/browser/png.js +116 -0
  26. package/dist/browser/visual-compare.js +229 -0
  27. package/dist/bus/beam-drop.js +55 -0
  28. package/dist/bus/inbox.js +157 -7
  29. package/dist/cli.js +316 -120
  30. package/dist/config/features.js +3 -3
  31. package/dist/config/managed.js +40 -1
  32. package/dist/config/persona.js +80 -29
  33. package/dist/config/product-hosts.js +2 -0
  34. package/dist/config/settings.js +289 -31
  35. package/dist/config/skills-index.js +37 -14
  36. package/dist/config/staff-prompt.js +12 -0
  37. package/dist/engine/agent.js +52 -41
  38. package/dist/engine/aurora.js +54 -13
  39. package/dist/engine/batch-scheduler.js +4 -13
  40. package/dist/engine/compaction.js +1 -1
  41. package/dist/engine/continuation.js +66 -32
  42. package/dist/engine/decision-points.js +2 -3
  43. package/dist/engine/fanout.js +16 -0
  44. package/dist/engine/identity.js +42 -0
  45. package/dist/engine/loop-guard.js +26 -83
  46. package/dist/engine/messages.js +2 -2
  47. package/dist/engine/moa.js +23 -1
  48. package/dist/engine/native-vision-node.js +72 -0
  49. package/dist/engine/native-vision.js +103 -0
  50. package/dist/engine/net-error.js +15 -0
  51. package/dist/engine/rolling-summary.js +142 -93
  52. package/dist/engine/verify-gate.js +37 -7
  53. package/dist/engine/waterfall.js +33 -0
  54. package/dist/gateway-cli.js +24 -4
  55. package/dist/memory/live-progress.js +4 -5
  56. package/dist/memory/session-index.js +3 -3
  57. package/dist/moa/codeact-lane.js +98 -0
  58. package/dist/moa/codeact-sandbox.js +409 -0
  59. package/dist/moa/codeact.js +140 -0
  60. package/dist/permissions/artifact-visibility.js +10 -0
  61. package/dist/permissions/index.js +2 -1
  62. package/dist/permissions/policy.js +9 -2
  63. package/dist/permissions/tier.js +13 -3
  64. package/dist/products/craft.js +92 -3
  65. package/dist/products/temple.js +20 -1
  66. package/dist/products/voice.js +112 -0
  67. package/dist/remote/grants.js +119 -0
  68. package/dist/remote/host.js +33 -5
  69. package/dist/router/free-models.js +5 -9
  70. package/dist/router/models.js +80 -26
  71. package/dist/router/provider-models.js +78 -0
  72. package/dist/router/router.js +15 -3
  73. package/dist/selfimprove/index.js +8 -6
  74. package/dist/selfimprove/lessons.js +23 -0
  75. package/dist/services/preflight.js +35 -91
  76. package/dist/session.js +316 -125
  77. package/dist/skills/catalogue.js +5 -2
  78. package/dist/skills/finder.js +4 -4
  79. package/dist/skills/install-guard.js +68 -0
  80. package/dist/skills/install.js +67 -0
  81. package/dist/toolchain/manifest.json +13 -13
  82. package/dist/tools/background-result.js +1 -1
  83. package/dist/tools/beam.js +246 -0
  84. package/dist/tools/classes.js +103 -0
  85. package/dist/tools/contract.js +1 -1
  86. package/dist/tools/craft.js +36 -2
  87. package/dist/tools/deferred.js +7 -3
  88. package/dist/tools/doc-text.js +1 -1
  89. package/dist/tools/executor.js +25 -15
  90. package/dist/tools/generation-gateway.js +94 -0
  91. package/dist/tools/registry.js +135 -158
  92. package/dist/tools/sandbox.js +6 -6
  93. package/dist/ui/App.js +17 -6
  94. package/dist/ui/ApprovalPrompt.js +1 -1
  95. package/dist/ui/BgPanel.js +15 -10
  96. package/dist/ui/Composer.js +44 -2
  97. package/dist/ui/Header.js +1 -6
  98. package/dist/ui/StatusRule.js +20 -8
  99. package/dist/ui/ToolStep.js +3 -3
  100. package/dist/ui/Transcript.js +41 -14
  101. package/dist/ui/batchLine.js +4 -4
  102. package/dist/ui/editdiff.js +2 -4
  103. package/dist/ui/format.js +4 -20
  104. package/dist/ui/liveTools.js +3 -3
  105. package/dist/ui/modelPicker.js +10 -6
  106. package/dist/ui/opsMode.js +20 -0
  107. package/dist/ui/phase.js +4 -2
  108. package/dist/ui/slashCommands.js +1 -0
  109. package/dist/ui/types.js +0 -2
  110. package/dist/ui/voice.js +185 -0
  111. package/dist/update-check.js +17 -6
  112. package/dist/update.js +1 -2
  113. package/dist/util/audio-io.js +82 -0
  114. package/dist/util/slash.js +2 -2
  115. package/dist/vision/pairs.js +239 -0
  116. package/package.json +1 -1
  117. package/dist/tools/mutating.js +0 -15
@@ -3,7 +3,7 @@
3
3
  // (the tools array is the cached prompt prefix), and `safe` stays authoritative. scripts/tool-catalog.mts
4
4
  // publishes every contract to toolchain/tools/catalog.json; test/tool-contract.test.mts and
5
5
  // test/tool-bins.test.mts hold the gaps to toolchain/tools/baseline.json, whose lists may only shrink.
6
- // A DEPENDENCY-FREE leaf like mutating.ts: registry.ts reaches it from the neutral bundle.
6
+ // A DEPENDENCY-FREE leaf like classes.ts: registry.ts reaches it from the neutral bundle.
7
7
  export const EFFECTS = ["read", "fetch", "state", "write", "egress", "exec", "destructive", "device"];
8
8
  /** What `safe` should mean once contracts drive it: every declared effect is a read. */
9
9
  export const isReadOnly = (c) => c.effects.every((e) => e === "read" || e === "fetch");
@@ -18,18 +18,27 @@ export const CRAFT_TOOLS = [
18
18
  },
19
19
  {
20
20
  name: "craft_update",
21
+ contract: { v: 1, effects: ["egress"], audit: ["id", "visibility"] },
21
22
  description: "Update a craft you own by id — new content, title, or visibility (private | link | public). Optimistic concurrency: pass expected_version (from craft_get) to avoid clobbering a change made since you read it.",
22
23
  parameters: { type: "object", additionalProperties: false, required: ["id"], properties: {
23
- id: { type: "string", description: "the craft id (from craft_create / craft_list)" },
24
+ id: { type: "string", description: "the artifact id (from artifact_create / craft_list)" },
24
25
  content: { type: "string", description: "replacement body" },
25
26
  title: { type: "string", description: "new title" },
26
27
  visibility: { type: "string", description: "private | link | public" },
27
28
  expected_version: { type: "string", description: "the version you last read (optimistic concurrency)" },
28
29
  } },
29
- async run(args) { return (await craft()).craftUpdate(args); },
30
+ async run(args) {
31
+ const { artifactVisibility } = await nodeImport("../permissions/artifact-visibility.js");
32
+ const { loadSettings } = await nodeImport("../config/settings.js");
33
+ const vis = artifactVisibility(loadSettings().permissions?.tier, args.visibility, false);
34
+ if ("error" in vis)
35
+ return `error: ${vis.error}`;
36
+ return (await craft()).craftUpdate(args);
37
+ },
30
38
  },
31
39
  {
32
40
  name: "craft_list", safe: true,
41
+ contract: { v: 1, effects: ["fetch"] },
33
42
  description: "List the crafts your account owns (id · type · title · visibility · URL). Read-only.",
34
43
  parameters: { type: "object", additionalProperties: false, properties: {
35
44
  limit: { type: "number", description: "max rows (default 20, max 100)" },
@@ -38,6 +47,7 @@ export const CRAFT_TOOLS = [
38
47
  },
39
48
  {
40
49
  name: "craft_get", safe: true,
50
+ contract: { v: 1, effects: ["fetch"], audit: ["id"] },
41
51
  description: "Fetch one craft by id — its metadata (owner, version, visibility), URL, and current content. Read-only.",
42
52
  parameters: { type: "object", additionalProperties: false, required: ["id"], properties: {
43
53
  id: { type: "string", description: "the craft id" },
@@ -46,10 +56,34 @@ export const CRAFT_TOOLS = [
46
56
  },
47
57
  {
48
58
  name: "craft_delete",
59
+ contract: { v: 1, effects: ["destructive", "fetch"], audit: ["id"] },
49
60
  description: "Delete a craft you own by id. Its share link stops working.",
50
61
  parameters: { type: "object", additionalProperties: false, required: ["id"], properties: {
51
62
  id: { type: "string", description: "the craft id" },
52
63
  } },
53
64
  async run(args) { return (await craft()).craftDelete(args); },
54
65
  },
66
+ {
67
+ name: "craft_room",
68
+ description: "Work on one craft together with other agents and its owner, in the craft's room. join (once) → read tasks and messages; claim a task to hold its file (15-min lease, renewed by each edit); edit writes ONE file onto the live version (others' changes to other files are kept; if your file changed since base_version you get the live file to merge, nothing is overwritten); post to talk (@handle mentions); task_state review/done; wait long-polls for news; link = the page the owner watches. Use a stable handle per agent (operator, operator/<role>-<n>).",
69
+ parameters: { type: "object", additionalProperties: false, required: ["action", "id"], properties: {
70
+ action: { type: "string", description: "join | get | post | task_add | claim | release | task_state | edit | wait | link" },
71
+ id: { type: "string", description: "the craft id" },
72
+ handle: { type: "string", description: "your name in the room (default operator); sub-agents use their own" },
73
+ body: { type: "string", description: "post: the message" },
74
+ title: { type: "string", description: "task_add: what needs doing" },
75
+ detail: { type: "string", description: "task_add: more detail" },
76
+ target: { type: "string", description: "task_add: the file it covers, e.g. tui.html" },
77
+ task_id: { type: "string", description: "claim / release / task_state: the task" },
78
+ state: { type: "string", description: "task_state: review | done | blocked | open" },
79
+ rev: { type: "number", description: "task_state: the task's rev you read" },
80
+ note: { type: "string", description: "task_state: a short note" },
81
+ path: { type: "string", description: "edit: the file you hold" },
82
+ content: { type: "string", description: "edit: the file's full new content" },
83
+ base_version: { type: "number", description: "edit: the craft version you read the file at" },
84
+ after: { type: "number", description: "wait: the cursor (last seq) you have seen" },
85
+ timeout_secs: { type: "number", description: "wait: up to 25" },
86
+ } },
87
+ async run(args) { return (await craft()).craftRoom(args); },
88
+ },
55
89
  ];
@@ -131,17 +131,21 @@ export function deferredEnabled(mcpToolCount, env) {
131
131
  /** Attached to every request. Chosen from the audit trail (45,208 tool calls, 493 sessions, 09/25–11/24): the 14 most
132
132
  * called tools once `shell_exec` and `grep_search` are counted as what they are (aliases of `bash` and `search`),
133
133
  * plus `task_add`, without which `task_update` has nothing to update. 86.5% of all calls land on these directly,
134
- * 93.8% with the two aliases. Ranking: _ai-docs/decisions/2026-11-24-small-core-tool-loading.md. */
134
+ * 93.8% with the two aliases. Ranking: _ai-docs/decisions/2026-11-24-small-core-tool-loading.md. Since 12/01
135
+ * `image_analyze` and `image_generate` are deferred (2,377 chars of every request): tool_search / tool_call reach
136
+ * them, and a direct call by name still runs. */
135
137
  export const NATIVE_CORE_TOOLS = [
136
138
  "bash", "file_read", "read_files", "file_write", "file_edit", "search", "list_directory",
137
- "git_status", "git_command", "task_add", "task_update", "web_search", "web_fetch", "image_analyze", "image_generate",
139
+ "git_status", "git_command", "task_add", "task_update", "web_search", "web_fetch",
138
140
  ];
139
141
  /** Attached whenever the session has them, whatever their call count — the harness leans on them by name: the engine
140
142
  * turns the decision-point gate and the delegation-by-prose guard on by finding `ask_user` / `spawn_agent` in the
141
143
  * request (engine/agent.ts), and the MoA planner brief hands every step to `delegate_task` (engine/moa.ts). The bash
142
144
  * timeout and auto-background results send the model to `shell_background` / `bash_output`, and the verify gate
143
145
  * counts a finished background check by seeing a call named `bash_output` (engine/verify-gate.ts). */
144
- export const NATIVE_HARNESS_TOOLS = ["ask_user", "spawn_agent", "delegate_task", "shell_background", "bash_output"];
146
+ export const NATIVE_HARNESS_TOOLS = ["ask_user", "spawn_agent", "delegate_task", "shell_background", "bash_output",
147
+ // A model that can start a sub-agent must see how to stop it: deferred, it reached for a shell kill.
148
+ "stop_agent"];
145
149
  export const NATIVE_META_NAMES = ["tool_search", "tool_call"];
146
150
  const byName = (schemas) => {
147
151
  const m = new Map();
@@ -1,5 +1,5 @@
1
1
  // Document → TEXT, so file_read and image_analyze read a PDF/DOCX/XLSX/PPTX by its words instead of a
2
- // picture of page 1 (the Hermes read_extract model). Dependency-free: macOS PDFKit through the JXA ObjC
2
+ // picture of page 1. Dependency-free: macOS PDFKit through the JXA ObjC
3
3
  // bridge for PDF, `textutil` for the word-processor formats, and `unzip` + the OOXML parts for sheets and
4
4
  // decks. Every extractor is time-bounded; a failure or an empty result returns null so the caller can
5
5
  // fall back (image_analyze then renders the page for vision — the scanned-PDF case).
@@ -8,7 +8,7 @@
8
8
  // new user turn (not required by SPEC §3's
9
9
  // round loop itself, but needed so the guard
10
10
  // doesn't bleed across turns)
11
- import { IDEMPOTENT_TOOLS } from "../engine/loop-guard.js";
11
+ import { CWD_DEFAULTED, DIR_DEFAULTED, IDEMPOTENT, POLLERS, SHELL_FOREGROUND, WORKSPACE_DEFAULTED, mutationLanded } from "./classes.js";
12
12
  import { isAbsolute, join, resolve } from "node:path";
13
13
  import { registry } from "./registry.js";
14
14
  import { expandPath } from "./paths.js";
@@ -18,15 +18,11 @@ import { shellKeyStore, shellExecMode, shellSignalStore } from "./shell-context.
18
18
  import { capToolResult } from "./result-cap.js";
19
19
  import { spillToolOutput } from "./tool-output-spill.js"; // GW-10: lossless eviction — spill big outputs, hand back a re-readable pointer
20
20
  import { semanticCompress } from "./semantic-compress.js";
21
+ import { allowSandboxWriteRoot } from "./sandbox.js";
21
22
  export { TOOL_RESULT_MAX_CHARS, capToolResult } from "./result-cap.js";
22
23
  import { runBatch, defaultClassify, defaultKeys } from "../engine/batch-scheduler.js";
23
- // Command tools whose working directory should default to the executor root (they take an optional `cwd`).
24
- const CWD_TOOLS = new Set(["bash", "shell_exec", "shell_background", "git", "git_command", "git_status"]);
25
24
  // Args that name a filesystem path the file tools read/write; a RELATIVE one is resolved under the root.
26
25
  const PATH_ARGS = ["path", "file", "filename", "workspace"];
27
- // Tools that take an optional `workspace` and otherwise fall back to process.cwd() — a rooted session must
28
- // default it to its own root or the call lands in whatever directory the host process happens to run in.
29
- const WORKSPACE_TOOLS = new Set(["checkpoint"]);
30
26
  // BTX conflict keys must be the ABSOLUTE path a call will really touch, or "d.txt", "./d.txt", "/cwd/d.txt" and
31
27
  // "~/d.txt" each look like a different resource and a batched write+read of one file races. Only path-named args
32
28
  // are resolved (array elements and nested objects included, by the arg name they sit under); a url, or an id
@@ -46,15 +42,15 @@ export function rootArgs(name, args, root) {
46
42
  }
47
43
  if (typeof a.cwd === "string" && a.cwd && !isAbsolute(a.cwd) && !a.cwd.startsWith("~"))
48
44
  a.cwd = join(root, a.cwd);
49
- else if (a.cwd == null && CWD_TOOLS.has(name))
45
+ else if (a.cwd == null && CWD_DEFAULTED.has(name))
50
46
  a.cwd = root;
51
- if (a.workspace == null && WORKSPACE_TOOLS.has(name))
47
+ if (a.workspace == null && WORKSPACE_DEFAULTED.has(name))
52
48
  a.workspace = root;
49
+ if (a.path == null && DIR_DEFAULTED.has(name))
50
+ a.path = root;
53
51
  return a;
54
52
  }
55
53
  const LOOP_GUARD_THRESHOLD = 5; // must match agent.ts LOOP_GUARD_LIMIT so this secondary guard never fires first
56
- import { mutationLanded } from "./mutating.js"; // single source of truth (see tools/mutating.ts) — a LANDED workspace edit ⇒ prior identical-call counts are stale
57
- const LOOP_GUARD_EXEMPT = new Set(["agent_status", "bash_output"]); // poll/status tools — repeated calls are legit, never guarded
58
54
  // Unique fallback id per Executor instance, so two sessions with no sessionId and no root (the
59
55
  // foreground and a read-only sub-agent lane) still get DISTINCT shell keys. One Executor lives for
60
56
  // its session's whole lifetime (the Session is constructed once and reused across turns), so this id
@@ -76,12 +72,27 @@ export class Executor {
76
72
  this.shellKey = shellKey || `exec-${++_execSeq}`;
77
73
  }
78
74
  seen = new Map();
75
+ /** A one-turn root (a mentor-wake whose brief names a worktree): wins over `root` until cleared. */
76
+ turnRoot;
77
+ /** Root THIS turn's tool calls under `dir` (undefined clears it). Session sets it at a wake turn's start and clears it in finally. */
78
+ setTurnRoot(dir) {
79
+ this.releaseTurnRoot?.();
80
+ this.releaseTurnRoot = undefined;
81
+ this.turnRoot = dir || undefined;
82
+ if (this.turnRoot)
83
+ this.releaseTurnRoot = allowSandboxWriteRoot(this.turnRoot); // strict mode writes there too
84
+ }
85
+ releaseTurnRoot;
86
+ get effectiveRoot() {
87
+ return this.turnRoot ?? this.root;
88
+ }
79
89
  resetTurn() {
80
90
  this.seen.clear();
81
91
  }
82
92
  async execute(name, rawArgs, report) {
83
- const args = this.root ? rootArgs(name, rawArgs, this.root) : rawArgs;
84
- if (!LOOP_GUARD_EXEMPT.has(name) && !IDEMPOTENT_TOOLS.has(name)) { // poll/status tools are never loop-guarded (repeated calls are legit)
93
+ const root = this.effectiveRoot;
94
+ const args = root ? rootArgs(name, rawArgs, root) : rawArgs;
95
+ if (!POLLERS.has(name) && !IDEMPOTENT.has(name)) { // poll/status tools are never loop-guarded (repeated calls are legit)
85
96
  const key = `${name} ${JSON.stringify(args)}`;
86
97
  const count = (this.seen.get(key) ?? 0) + 1;
87
98
  this.seen.set(key, count);
@@ -120,7 +131,7 @@ export class Executor {
120
131
  };
121
132
  /** Same resolution the tools apply (root join, ~ expansion), done lexically so a not-yet-written file still keys. */
122
133
  resolveKey(p, argName) {
123
- return KEY_PATH_ARG.test(argName) && !URL_LIKE.test(p) ? resolve(this.root ?? process.cwd(), expandPath(p)) : p;
134
+ return KEY_PATH_ARG.test(argName) && !URL_LIKE.test(p) ? resolve(this.effectiveRoot ?? process.cwd(), expandPath(p)) : p;
124
135
  }
125
136
  async executeParallel(calls, onSettle, signal, onStart) {
126
137
  // BTX: one shared DAG scheduler (engine/batch-scheduler.ts) — per-resource write chains,
@@ -130,8 +141,7 @@ export class Executor {
130
141
  // Matching Cursor for shells: when this round has ≥2 bash/shell_exec calls, run them as ephemeral
131
142
  // one-shots so the persistent ShellSession FIFO cannot serialize wall-clock. A lone bash still
132
143
  // uses the persistent session (cwd/env + ctrl+b detach stick). See shellExecMode.
133
- const SHELL_TOOLS = new Set(["bash", "shell_exec"]);
134
- const shellCount = calls.reduce((n, c) => n + (SHELL_TOOLS.has(c.name) ? 1 : 0), 0);
144
+ const shellCount = calls.reduce((n, c) => n + (SHELL_FOREGROUND.has(c.name) ? 1 : 0), 0);
135
145
  const mode = shellCount >= 2 ? "ephemeral" : "persistent";
136
146
  return shellExecMode.run(mode, () => runBatch(calls, {
137
147
  classify: this.sched.classify,
@@ -0,0 +1,94 @@
1
+ // One door for generation: image_generate posts to OUR gateway's `image` route, and
2
+ // the router owns which render servers back it (legs, maxInflight, canary-gated health). A render takes minutes and the
3
+ // public edge cuts a response at ~100 s, so each request is a router job (Prefer: respond-async): submitted once, then
4
+ // polled until the route's answer is ready. Gateways in order: the local router on loopback (no token), then the public
5
+ // gateway with the signed-in Operator token. A router without jobs answers the POST itself, which is taken as is.
6
+ import { getOperatorToken, operatorTrustedUrl } from "../engine/aurora.js";
7
+ import { GATEWAY_BASE, LOCAL_GATEWAY_BASE } from "../router/models.js";
8
+ export const GENERATION_ROUTES = { image: "image" };
9
+ const PATHS = { image: "/images/generations" };
10
+ const SUBMIT_TIMEOUT_MS = 30_000;
11
+ const POLL_MS = 5_000;
12
+ const isLoopback = (u) => /^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:|\/|$)/.test(u);
13
+ /** The gateways to ask, in order. A signed-out public gateway stays listed with `skip`, so the "down" line says why. */
14
+ export function generationGateways(o = {}) {
15
+ const local = (o.localBase ?? LOCAL_GATEWAY_BASE).replace(/\/$/, "");
16
+ const pub = (o.publicBase ?? GATEWAY_BASE).replace(/\/$/, "");
17
+ const token = !isLoopback(pub) && operatorTrustedUrl(pub) ? getOperatorToken() || process.env.KODE_OPERATOR_TOKEN : undefined;
18
+ return [
19
+ { base: local, auth: {}, label: "local gateway" },
20
+ { base: pub, auth: token ? { Authorization: `Bearer ${token}` } : {}, label: "0perator gateway", ...(token ? {} : { skip: "not signed in" }) },
21
+ ];
22
+ }
23
+ /** Why a router said no, in plain words: busy (every leg at capacity, or the queue full or timed out) or not available. Never a host, port or leg name. */
24
+ async function refusal(res) {
25
+ const j = (await res.json().catch(() => null));
26
+ if (j?.error?.tried?.some((t) => /maxInflight|busy|queue/i.test(t.reason ?? "")))
27
+ return "busy";
28
+ return "unavailable";
29
+ }
30
+ async function viaGateway(gw, kind, body, timeoutMs, deadline, pollMs) {
31
+ const headers = { "Content-Type": "application/json", "User-Agent": "operator/kode-tsi", ...gw.auth };
32
+ let res;
33
+ try {
34
+ res = await fetch(`${gw.base}${PATHS[kind]}`, {
35
+ method: "POST", headers: { ...headers, Prefer: "respond-async" }, signal: AbortSignal.timeout(Math.max(1, Math.min(SUBMIT_TIMEOUT_MS, deadline - Date.now()))),
36
+ body: JSON.stringify({ ...body, model: GENERATION_ROUTES[kind] }),
37
+ });
38
+ }
39
+ catch {
40
+ return { down: "unreachable" };
41
+ }
42
+ if (res.status === 202) {
43
+ const id = (await res.json().catch(() => null))?.id;
44
+ if (typeof id !== "string")
45
+ return { down: "accepted the job without an id", started: true };
46
+ // From here a render is running: a slow or lost answer is reported, never retried on another gateway (a second render).
47
+ for (;;) {
48
+ if (Date.now() + pollMs > deadline)
49
+ return { down: `no answer in ${Math.round(timeoutMs / 1000)}s (job ${id} still running)`, started: true };
50
+ await new Promise((r) => setTimeout(r, pollMs));
51
+ try {
52
+ res = await fetch(`${gw.base}/jobs/${id}`, { headers, signal: AbortSignal.timeout(SUBMIT_TIMEOUT_MS) });
53
+ }
54
+ catch {
55
+ continue; // one failed poll is not a failed render
56
+ }
57
+ if (res.status === 202) {
58
+ await res.body?.cancel();
59
+ continue;
60
+ }
61
+ if (res.status === 404)
62
+ return { down: `lost job ${id} (the router restarted or it expired)`, started: true };
63
+ break;
64
+ }
65
+ }
66
+ if (!res.ok)
67
+ return { down: await refusal(res) };
68
+ const json = (await res.json().catch(() => null));
69
+ if (!json)
70
+ return { down: "returned no JSON", started: true };
71
+ const backend = res.headers.get("x-0perator-backend") ?? undefined;
72
+ return { json, ...(backend ? { backend } : {}) };
73
+ }
74
+ /** One generation through the first gateway that serves it. Throws one plain line when none does. */
75
+ export async function generate(gateways, kind, body, timeoutMs, pollMs = POLL_MS) {
76
+ const deadline = Date.now() + timeoutMs;
77
+ const down = [];
78
+ let started = false;
79
+ for (const gw of gateways) {
80
+ const r = gw.skip ? { down: gw.skip } : await viaGateway(gw, kind, body, timeoutMs, deadline, pollMs);
81
+ if ("json" in r)
82
+ return r;
83
+ down.push(r.down);
84
+ if (r.started) {
85
+ started = true;
86
+ break;
87
+ }
88
+ }
89
+ if (started)
90
+ throw new Error(`Image generation didn't finish in time (${down[down.length - 1]}). Check again shortly rather than resubmitting.`);
91
+ if (down.includes("busy"))
92
+ throw new Error("Image generation is busy — queued requests are waiting on a render. Try again in a few minutes.");
93
+ throw new Error("Image generation isn't available right now. Not worth retrying this turn.");
94
+ }