@0perator/operator 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -3
- package/dist/auth/commands.js +7 -3
- package/dist/auth/identity.js +1 -0
- package/dist/auth/staff.js +55 -0
- package/dist/autonomy/delegate-mode.js +2 -2
- package/dist/autonomy/delegate.js +41 -14
- package/dist/autonomy/headless.js +7 -4
- package/dist/autonomy/index.js +2 -4
- package/dist/autonomy/session-factory.js +11 -12
- package/dist/autonomy/subagent-model.js +17 -7
- package/dist/background/capacity.js +136 -0
- package/dist/background/evidence.js +42 -0
- package/dist/background/index.js +311 -44
- package/dist/background/lane-phase.js +60 -0
- package/dist/background/lane-summary.js +151 -0
- package/dist/background/notices.js +12 -3
- package/dist/background/synthesis.js +25 -0
- package/dist/bus/inbox.js +150 -6
- package/dist/cli.js +191 -96
- package/dist/config/features.js +3 -3
- package/dist/config/persona.js +29 -3
- package/dist/config/settings.js +261 -20
- package/dist/config/staff-prompt.js +12 -0
- package/dist/engine/agent.js +51 -40
- package/dist/engine/aurora.js +36 -4
- package/dist/engine/batch-scheduler.js +4 -13
- package/dist/engine/compaction.js +1 -1
- package/dist/engine/continuation.js +30 -32
- package/dist/engine/decision-points.js +2 -3
- package/dist/engine/fanout.js +16 -0
- package/dist/engine/loop-guard.js +26 -83
- package/dist/engine/messages.js +2 -2
- package/dist/engine/moa.js +16 -1
- package/dist/engine/native-vision-node.js +72 -0
- package/dist/engine/native-vision.js +103 -0
- package/dist/engine/verify-gate.js +37 -7
- package/dist/gateway-cli.js +14 -3
- package/dist/memory/live-progress.js +4 -5
- package/dist/moa/codeact-lane.js +98 -0
- package/dist/moa/codeact-sandbox.js +409 -0
- package/dist/moa/codeact.js +140 -0
- package/dist/permissions/artifact-visibility.js +10 -0
- package/dist/permissions/tier.js +4 -2
- package/dist/products/craft.js +2 -2
- package/dist/remote/grants.js +119 -0
- package/dist/remote/host.js +33 -5
- package/dist/router/models.js +24 -14
- package/dist/selfimprove/index.js +8 -6
- package/dist/services/preflight.js +35 -91
- package/dist/session.js +127 -41
- package/dist/skills/install-guard.js +68 -0
- package/dist/skills/install.js +67 -0
- package/dist/toolchain/manifest.json +13 -13
- package/dist/tools/background-result.js +1 -1
- package/dist/tools/classes.js +103 -0
- package/dist/tools/contract.js +1 -1
- package/dist/tools/craft.js +13 -2
- package/dist/tools/executor.js +25 -15
- package/dist/tools/generation-gateway.js +94 -0
- package/dist/tools/registry.js +83 -152
- package/dist/ui/App.js +15 -4
- package/dist/ui/BgPanel.js +15 -10
- package/dist/ui/Header.js +1 -6
- package/dist/ui/StatusRule.js +18 -7
- package/dist/ui/ToolStep.js +3 -3
- package/dist/ui/Transcript.js +36 -14
- package/dist/ui/batchLine.js +4 -4
- package/dist/ui/editdiff.js +2 -4
- package/dist/ui/format.js +4 -20
- package/dist/ui/liveTools.js +3 -3
- package/dist/ui/opsMode.js +20 -0
- package/dist/ui/types.js +0 -2
- package/dist/update-check.js +17 -6
- package/package.json +1 -1
- package/dist/tools/mutating.js +0 -15
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// The guarded way a skill, plugin or connector from the AXE skills hub (Barracks) reaches a user's own Operator home.
|
|
2
|
+
// Fetch -> quarantine -> scan -> policy -> install or block, with an audit line either way. Provider- and model-agnostic:
|
|
3
|
+
// a skill is plain instructions, so nothing here knows or cares which model will read it. Pure decisions live here;
|
|
4
|
+
// the fetch and the CLI/TUI wiring are elsewhere. There is deliberately NO setting that turns the scanner off or lets a
|
|
5
|
+
// "dangerous" verdict through: the Hermes scanner can be disabled by a config switch (user reports), ours cannot.
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
const RULES = [
|
|
8
|
+
{ id: "pipe-to-shell", severity: "dangerous", re: /\b(?:curl|wget|fetch)\b[^\n|]*\|\s*(?:sudo\s+)?(?:ba|z|da)?sh\b/i },
|
|
9
|
+
{ id: "decode-and-run", severity: "dangerous", re: /\bbase64\s+(?:-d|--decode)\b[^\n]*\|\s*(?:ba|z)?sh\b|\beval\s*\(\s*(?:atob|base64|Buffer\.from)/i },
|
|
10
|
+
{ id: "credential-store-read", severity: "dangerous", re: /(?:~|\$HOME|\/Users\/[^/\s]+)?\/?\.(?:ssh|aws|gnupg|docker\/config\.json|kube\/config)\b|\bsecurity\s+find-(?:generic|internet)-password\b|\b(?:Login Data|Cookies\.sqlite|Local State)\b|\bid_(?:rsa|ed25519)\b/i },
|
|
11
|
+
{ id: "exfiltration", severity: "dangerous", re: /\b(?:webhook\.site|requestbin|pipedream\.net|ngrok\.(?:io|app)|pastebin\.com|transfer\.sh|discord(?:app)?\.com\/api\/webhooks)\b/i },
|
|
12
|
+
{ id: "destructive", severity: "dangerous", re: /\brm\s+-[a-z]*r[a-z]*\s+(?:\/|~\/?|\$HOME\/?)(?:\s|$|\*)|\bmkfs\b|\bdd\s+if=[^\n]*\bof=\/dev\/|:\(\)\s*\{\s*:\|:&\s*\};:/i },
|
|
13
|
+
{ id: "persistence", severity: "dangerous", re: /\bcrontab\s+-|\/Library\/Launch(?:Agents|Daemons)\/|\bsystemctl\s+(?:--user\s+)?enable\b|\.(?:bashrc|zshrc|profile)\b[^\n]*(?:>>|tee\s+-a)/i },
|
|
14
|
+
{ id: "prompt-override", severity: "dangerous", re: /\b(?:ignore|disregard|forget)\s+(?:all\s+|any\s+|your\s+|the\s+)?(?:previous|prior|above|system)\s+(?:instructions|prompt|rules)\b|\bdo\s+not\s+(?:tell|inform|mention\s+to)\s+the\s+user\b|\bwithout\s+(?:telling|informing)\s+the\s+user\b/i },
|
|
15
|
+
{ id: "wallet-signing", severity: "dangerous", re: /\b(?:seed\s+phrase|mnemonic|private\s+key)\b[^\n]*\b(?:send|post|upload|sign|paste)\b|\b(?:send|post|upload|sign)\b[^\n]*\b(?:seed\s+phrase|mnemonic|private\s+key)\b/i },
|
|
16
|
+
{ id: "hijack-any-request", severity: "caution", re: /\b(?:use|apply|invoke)\s+this\s+(?:skill\s+)?(?:for|on)\s+(?:any|every|all)\s+(?:request|task|query|prompt)s?\b|\balways\s+use\s+this\s+skill\b/i },
|
|
17
|
+
{ id: "needs-credentials", severity: "caution", re: /\b(?:API_KEY|SECRET_KEY|ACCESS_TOKEN|PASSWORD|BEARER)\b|\bapi[-_ ]?key\b[^\n]*\b(?:paste|provide|enter|set)\b/i },
|
|
18
|
+
{ id: "installs-software", severity: "caution", re: /\b(?:pip3?\s+install|npm\s+(?:i|install)\s+-g|brew\s+install|apt(?:-get)?\s+install|curl\s+[^\n|]*-o\b|wget\s+[^\n|]*-O\b)/i },
|
|
19
|
+
{ id: "writes-outside-workspace", severity: "caution", re: /(?:>|tee)\s*(?:\/etc\/|\/usr\/|~\/\.|\$HOME\/\.)/i },
|
|
20
|
+
{ id: "evades-bot-detection", severity: "caution", re: /\b(?:bypass|evade|defeat|solve)\b[^\n]*\b(?:captcha|bot[- ]detection|cloudflare|anti-?bot)\b|\bstealth\s+(?:mode|plugin)\b/i },
|
|
21
|
+
{ id: "moves-money", severity: "caution", re: /\b(?:place|execute|submit)\s+(?:a\s+)?(?:trade|order)s?\b|\b(?:transfer|send|withdraw)\s+(?:funds|crypto|usdc|eth|btc)\b|\bcard\s+number\b/i },
|
|
22
|
+
{ id: "obfuscation", severity: "caution", re: /[A-Za-z0-9+/]{200,}={0,2}|(?:\\x[0-9a-f]{2}){12,}/i },
|
|
23
|
+
];
|
|
24
|
+
const excerpt = (s) => s.trim().replace(/\s+/g, " ").slice(0, 120);
|
|
25
|
+
/** Static analysis of a skill's text. Regex only: it finds the patterns that matter, it does not prove safety. */
|
|
26
|
+
export function scanContent(text) {
|
|
27
|
+
const findings = [];
|
|
28
|
+
const lines = text.split("\n");
|
|
29
|
+
for (let i = 0; i < lines.length && findings.length < 50; i++) {
|
|
30
|
+
for (const r of RULES)
|
|
31
|
+
if (r.re.test(lines[i]))
|
|
32
|
+
findings.push({ rule: r.id, severity: r.severity, line: i + 1, excerpt: excerpt(lines[i]) });
|
|
33
|
+
}
|
|
34
|
+
const verdict = findings.some((f) => f.severity === "dangerous") ? "dangerous" : findings.length ? "caution" : "safe";
|
|
35
|
+
return { verdict, findings };
|
|
36
|
+
}
|
|
37
|
+
export const sha256Hex = (text) => createHash("sha256").update(text, "utf8").digest("hex");
|
|
38
|
+
/** The pinned reference a client records and re-checks: name@version#sha256:<12 hex>. */
|
|
39
|
+
export const pinnedRef = (r, computed) => `${r.name}@${r.version ?? "0"}#sha256:${(r.checksum ?? computed).slice(0, 12)}`;
|
|
40
|
+
/** first-party and verified come from the hub's own record; anything else is community, quarantined until reviewed. */
|
|
41
|
+
export function trustOf(r) {
|
|
42
|
+
if (r.card?.verified === true && /^axe[:/]|first-party/i.test(r.card.source ?? ""))
|
|
43
|
+
return "first-party";
|
|
44
|
+
if (r.card?.verified === true && r.tenant_id !== "community-quarantine")
|
|
45
|
+
return "verified";
|
|
46
|
+
return "community";
|
|
47
|
+
}
|
|
48
|
+
/** The install policy. Order matters: the refusals that nothing can override come first. */
|
|
49
|
+
export function decideInstall(p) {
|
|
50
|
+
if (p.yanked)
|
|
51
|
+
return { action: "block", reasons: ["withdrawn upstream"] };
|
|
52
|
+
if (!p.checksumOk)
|
|
53
|
+
return { action: "block", reasons: ["content does not match the hub's checksum"] };
|
|
54
|
+
if (p.verdict === "dangerous")
|
|
55
|
+
return { action: "block", reasons: ["the scan found dangerous patterns"] };
|
|
56
|
+
if (p.trust === "community" && p.managed)
|
|
57
|
+
return { action: "block", reasons: ["your organisation's policy allows only reviewed items"] };
|
|
58
|
+
const reasons = [];
|
|
59
|
+
if (p.trust === "community")
|
|
60
|
+
reasons.push("not reviewed: it comes from a community source");
|
|
61
|
+
if (p.verdict === "caution")
|
|
62
|
+
reasons.push("the scan raised cautions");
|
|
63
|
+
if (p.unpinned)
|
|
64
|
+
reasons.push("the hub gave no checksum to verify against");
|
|
65
|
+
if (p.kind !== "skill")
|
|
66
|
+
reasons.push(`a ${p.kind} is installed switched off and needs your approval to turn on`);
|
|
67
|
+
return reasons.length ? { action: "confirm", reasons } : { action: "allow", reasons: ["reviewed, scanned clean and checksum verified"] };
|
|
68
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// Install one hub record into the user's own Operator home, guarded and audited (policy in install-guard.ts).
|
|
2
|
+
// skills -> <home>/skills/<name>/SKILL.md
|
|
3
|
+
// plugins -> <home>/plugins/<name>/manifest.json (installed OFF)
|
|
4
|
+
// connectors -> <home>/connectors/<name>/manifest.json (installed OFF; turning one on is a separate, explicit step)
|
|
5
|
+
// Every attempt, allowed or blocked, appends one line to <home>/skills/.audit.jsonl (no content, no secrets).
|
|
6
|
+
import { appendFileSync, chmodSync, existsSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { decideInstall, pinnedRef, scanContent, sha256Hex, trustOf } from "./install-guard.js";
|
|
9
|
+
const SAFE_NAME = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
|
10
|
+
const dirFor = { skill: "skills", plugin: "plugins", connector: "connectors" };
|
|
11
|
+
export async function installFromHub(rec, o) {
|
|
12
|
+
const kind = o.kind ?? (rec.card?.kind === "plugin" || rec.card?.kind === "connector" ? rec.card.kind : "skill");
|
|
13
|
+
const now = (o.now?.() ?? new Date()).toISOString();
|
|
14
|
+
const computed = sha256Hex(rec.content ?? "");
|
|
15
|
+
const ref = pinnedRef(rec, computed);
|
|
16
|
+
const trust = trustOf(rec);
|
|
17
|
+
const { verdict, findings } = scanContent(rec.content ?? "");
|
|
18
|
+
const audit = (decision, reasons, confirmed) => {
|
|
19
|
+
try {
|
|
20
|
+
const dir = join(o.home, "skills");
|
|
21
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
22
|
+
appendFileSync(join(dir, ".audit.jsonl"), `${JSON.stringify({ ts: now, name: rec.name, kind, ref, sha256: computed, trust, verdict, rules: [...new Set(findings.map((f) => f.rule))], decision, reasons, ...(confirmed !== undefined ? { confirmed } : {}), userType: o.userType ?? "external", ...(o.source ? { source: o.source } : {}) })}\n`, { mode: 0o600 });
|
|
23
|
+
}
|
|
24
|
+
catch { /* an audit that cannot be written must not hide the install decision */ }
|
|
25
|
+
};
|
|
26
|
+
const refuse = (status, reasons) => { audit(status, reasons); return { status, ref, reasons, trust, verdict, findings }; };
|
|
27
|
+
if (!SAFE_NAME.test(rec.name) || rec.name.includes(".."))
|
|
28
|
+
return refuse("blocked", ["the name is not a plain identifier"]);
|
|
29
|
+
const decision = decideInstall({
|
|
30
|
+
verdict, trust, kind,
|
|
31
|
+
checksumOk: !rec.checksum || rec.checksum.toLowerCase() === computed,
|
|
32
|
+
unpinned: !rec.checksum,
|
|
33
|
+
yanked: !!rec.yanked_at,
|
|
34
|
+
managed: !!o.managed,
|
|
35
|
+
});
|
|
36
|
+
if (decision.action === "block")
|
|
37
|
+
return refuse("blocked", decision.reasons);
|
|
38
|
+
let confirmed;
|
|
39
|
+
if (decision.action === "confirm") {
|
|
40
|
+
confirmed = o.confirm ? await o.confirm({ name: rec.name, ref, trust, verdict, findings, reasons: decision.reasons }).catch(() => false) : false;
|
|
41
|
+
if (!confirmed)
|
|
42
|
+
return refuse("declined", decision.reasons);
|
|
43
|
+
}
|
|
44
|
+
// Stage in quarantine, then move into place: a half-written install never shows up as a usable skill.
|
|
45
|
+
const base = join(o.home, dirFor[kind]);
|
|
46
|
+
const stage = join(o.home, "skills", ".quarantine", `${rec.name}@${computed.slice(0, 12)}`);
|
|
47
|
+
const dest = join(base, rec.name);
|
|
48
|
+
rmSync(stage, { recursive: true, force: true });
|
|
49
|
+
mkdirSync(stage, { recursive: true, mode: 0o700 });
|
|
50
|
+
const enabled = kind === "skill";
|
|
51
|
+
if (kind === "skill")
|
|
52
|
+
writeFileSync(join(stage, "SKILL.md"), rec.content, { mode: 0o600 });
|
|
53
|
+
else
|
|
54
|
+
writeFileSync(join(stage, "manifest.json"), `${JSON.stringify({ name: rec.name, kind, version: rec.version ?? null, ref, sha256: computed, trust, enabled: false, installedAt: now, content: rec.content }, null, 2)}\n`, { mode: 0o600 });
|
|
55
|
+
writeFileSync(join(stage, ".install.json"), `${JSON.stringify({ ref, sha256: computed, trust, verdict, installedAt: now, source: o.source ?? null })}\n`, { mode: 0o600 });
|
|
56
|
+
mkdirSync(base, { recursive: true, mode: 0o700 });
|
|
57
|
+
rmSync(dest, { recursive: true, force: true });
|
|
58
|
+
renameSync(stage, dest);
|
|
59
|
+
if (existsSync(dest)) {
|
|
60
|
+
try {
|
|
61
|
+
chmodSync(dest, 0o700);
|
|
62
|
+
}
|
|
63
|
+
catch { /* best effort */ }
|
|
64
|
+
}
|
|
65
|
+
audit("installed", decision.reasons, confirmed);
|
|
66
|
+
return { status: "installed", path: dest, ref, trust, verdict, enabled };
|
|
67
|
+
}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schema": "operator.toolchain/1",
|
|
3
|
-
"serial":
|
|
3
|
+
"serial": 2,
|
|
4
4
|
"expires": "2026-12-18",
|
|
5
5
|
"targets": ["darwin-arm64"],
|
|
6
6
|
"hosts": ["github.com", "release-assets.githubusercontent.com", "objects.githubusercontent.com", "nodejs.org", "registry.npmjs.org",
|
|
7
7
|
"ffmpeg.martin-riedl.de", "cdn.playwright.dev", "storage.googleapis.com", "huggingface.co", "*.hf.co"],
|
|
8
|
-
"rollout": {"llamacpp-metal": {"target": "
|
|
8
|
+
"rollout": {"llamacpp-metal": {"target": "12242", "until": "2026-12-08"}},
|
|
9
9
|
"exceptions": [
|
|
10
10
|
{"box": "jl1", "match": "--port 8668", "owner": "Ghost", "until": "2026-11-10",
|
|
11
11
|
"reason": "ghost1-v2-final: unmanaged Homebrew b11429 on 0.0.0.0, not in the portal registry"}
|
|
@@ -16,27 +16,27 @@
|
|
|
16
16
|
},
|
|
17
17
|
"packages": {
|
|
18
18
|
"llamacpp-metal": {
|
|
19
|
-
"version": "
|
|
20
|
-
"artifacts": {"darwin-arm64": [{"url": "https://github.com/ggml-org/llama.cpp/releases/download/
|
|
21
|
-
"sha256": "
|
|
22
|
-
"entry": "llamacpp-metal-
|
|
23
|
-
"layout": {"format": "tar.gz", "strip": 1, "root": "llama-
|
|
24
|
-
"tree": "sha256:
|
|
19
|
+
"version": "12242",
|
|
20
|
+
"artifacts": {"darwin-arm64": [{"url": "https://github.com/ggml-org/llama.cpp/releases/download/b12242/llama-b12242-bin-macos-arm64.tar.gz",
|
|
21
|
+
"sha256": "d58f23da84befb84b7d07590e7fd18ea68a3f1df59f9808b52370255aa60f20b", "size": 16743054, "role": "payload"}]},
|
|
22
|
+
"entry": "llamacpp-metal-12242-darwin-arm64",
|
|
23
|
+
"layout": {"format": "tar.gz", "strip": 1, "root": "llama-b12242"},
|
|
24
|
+
"tree": "sha256:afd1c636d915b79410306ce45936f26b6dd5167ac1ccd55a8c6794498859a79f",
|
|
25
25
|
"provides": {"llama-server": "llama-server", "llama-cli": "llama-cli", "llama-bench": "llama-bench"},
|
|
26
26
|
"env": {},
|
|
27
|
-
"probe": {"bin": "llama-server", "args": ["--version"], "expect": "(build
|
|
27
|
+
"probe": {"bin": "llama-server", "args": ["--version"], "expect": "(build 12242, commit 3b4d6ab3f)"},
|
|
28
28
|
"codesign": {"expect": "adhoc"},
|
|
29
29
|
"relocatable": true,
|
|
30
|
-
"provenance": {"hash_source": "github-asset-digest", "verified": "2026-11-
|
|
31
|
-
"commit": "
|
|
30
|
+
"provenance": {"hash_source": "github-asset-digest", "verified": "2026-11-24", "published_at": "2026-11-10T02:01:21Z",
|
|
31
|
+
"commit": "3b4d6ab3f79651935fba1dd93732f29022a7f5f5",
|
|
32
32
|
"attest": {"repo": "ggml-org/llama.cpp", "signer_workflow": "ggml-org/llama.cpp/.github/workflows/release-publish.yml",
|
|
33
|
-
"source_digest": "
|
|
33
|
+
"source_digest": "3b4d6ab3f79651935fba1dd93732f29022a7f5f5"}},
|
|
34
34
|
"license": {"spdx": "MIT", "evidence": "LICENSE in archive", "redistribute": "yes"},
|
|
35
35
|
"install": "default",
|
|
36
36
|
"consumers": ["aurora", "portal", "arena"],
|
|
37
37
|
"previous": {
|
|
38
38
|
"version": "10964",
|
|
39
|
-
"until": "2026-
|
|
39
|
+
"until": "2026-12-08",
|
|
40
40
|
"artifacts": {"darwin-arm64": [{"url": "https://github.com/ggml-org/llama.cpp/releases/download/b10964/llama-b10964-bin-macos-arm64.tar.gz",
|
|
41
41
|
"sha256": "033c845c1df9bf945ff37bb193238b40910b2244be3e1e637b2ceb5878f1a6f5", "size": 11149739,
|
|
42
42
|
"role": "payload"}]},
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// How a shell result says its command went to a background job, and how bash_output says that job ended. One definition
|
|
2
2
|
// for the tool layer that writes the text (registry.ts) and the engine that reads it (verify-gate.ts): on 11/24 the gate
|
|
3
|
-
// knew only the first prefix, so an auto-backgrounded `npm test` counted as a passed check. Dependency-free leaf, like
|
|
3
|
+
// knew only the first prefix, so an auto-backgrounded `npm test` counted as a passed check. Dependency-free leaf, like classes.ts.
|
|
4
4
|
export const MOVED_TO_BACKGROUND = "moved to background as ";
|
|
5
5
|
export const AUTO_BACKGROUNDED = "[auto-backgrounded: ";
|
|
6
6
|
export const STARTED_BACKGROUND_JOB = "started background job ";
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
const set = (...groups) => new Set(groups.flatMap((g) => (typeof g === "string" ? [g] : [...g])));
|
|
2
|
+
// ── Shell ─────────────────────────────────────────────────────────────────────────────────────────────────
|
|
3
|
+
/** Foreground shells: the turn waits on the command. They may overlap in one round (batch-scheduler), switch to
|
|
4
|
+
* one-shot shells when two share a round (executor), count as a verification run (verify-gate), offer ctrl+b to
|
|
5
|
+
* background a slow one (liveTools), and poll-style commands in them are legitimate repeats (loop-guard). */
|
|
6
|
+
export const SHELL_FOREGROUND = set("bash", "shell_exec");
|
|
7
|
+
/** Every tool that runs a shell command the call supplies in `command`, foreground or not: shown as `$ command`,
|
|
8
|
+
* counted as a command, and read for mutating commands by the decision-point and delegate guards. */
|
|
9
|
+
export const SHELL_ANY = set(SHELL_FOREGROUND, "shell_background", "shell_task_start");
|
|
10
|
+
/** Command tools whose optional `cwd` defaults to a rooted executor's root. */
|
|
11
|
+
export const CWD_DEFAULTED = set("bash", "shell_exec", "shell_background", "git_command", "git_status");
|
|
12
|
+
/** Tools that take an optional `workspace` and otherwise fall back to process.cwd(): a rooted session defaults it to its root. */
|
|
13
|
+
export const WORKSPACE_DEFAULTED = set("checkpoint");
|
|
14
|
+
/** Search tools whose omitted `path` means "the current dir": a rooted call searches its root. find_files is left out on
|
|
15
|
+
* purpose: its default is the whole home index. */
|
|
16
|
+
export const DIR_DEFAULTED = set("search", "grep_search", "glob", "list_directory", "code_search", "codebase_search");
|
|
17
|
+
// ── Files ─────────────────────────────────────────────────────────────────────────────────────────────────
|
|
18
|
+
/** Tools that create, change or delete files in the workspace. A landed one resets the loop-guard counts, arms
|
|
19
|
+
* verify-before-done, zeroes the no-edit streak and is the first change the decision point holds back. */
|
|
20
|
+
export const FILE_WRITE = set("file_write", "file_edit", "file_create", "file_delete");
|
|
21
|
+
/** Reads of named files (`path`, or `paths` for read_files). */
|
|
22
|
+
export const FILE_READ = set("file_read", "read_files");
|
|
23
|
+
/** Single-file reads whose `path` arg is the file read (the stale-reread tracker). */
|
|
24
|
+
export const PATH_READ = set("file_read", "image_inspect");
|
|
25
|
+
// ── Lookups ───────────────────────────────────────────────────────────────────────────────────────────────
|
|
26
|
+
/** Searches over local code, files, memory and sessions. */
|
|
27
|
+
export const LOCAL_SEARCH = set("grep_search", "search", "code_search", "codebase_search", "find_files", "glob", "knowledge_search", "memory_search", "session_search");
|
|
28
|
+
export const WEB_SEARCH = set("web_search", "deep_research");
|
|
29
|
+
export const WEB_FETCH = set("web_fetch", "browser", "browser_read", "http_request");
|
|
30
|
+
/** Everything that only looks something up: the "reads" a sub-agent's activity counters add up. */
|
|
31
|
+
export const LOOKUP = set(FILE_READ, "list_directory", LOCAL_SEARCH, WEB_SEARCH, WEB_FETCH);
|
|
32
|
+
/** Read-only tools: the same call returning the same result again is no new information. */
|
|
33
|
+
export const IDEMPOTENT = set("file_read", "read_files", "search", "grep_search", "list_directory", "find_files", "locate", "web_search", "web_fetch", "git_status", "memory_search", "session_search", "session_read", "skill_catalog", "skill_fetch", "skill_list");
|
|
34
|
+
// ── Plan, agents, polling ─────────────────────────────────────────────────────────────────────────────────
|
|
35
|
+
export const PLAN_TOOLS = set("task_add", "task_update", "task_list", "task_clear");
|
|
36
|
+
/** The plan calls that change the plan. */
|
|
37
|
+
export const PLAN_WRITE = set("task_add", "task_update", "task_clear");
|
|
38
|
+
/** Every hand-off of work to another agent. */
|
|
39
|
+
export const DELEGATION = set("spawn_agent", "delegate_task", "delegate_to_agent");
|
|
40
|
+
/** Operator sub-agents, counted against the per-turn sub-agent cap. */
|
|
41
|
+
export const SUBAGENT_SPAWN = set("delegate_task", "spawn_agent");
|
|
42
|
+
/** A dispatch that leaves sub-agents running after it returns (delegate_* block until the child is done). */
|
|
43
|
+
export const DISPATCH = set("spawn_agent");
|
|
44
|
+
/** Calls that only book-keep around a dispatch (the plan pane, the agent panel). */
|
|
45
|
+
export const DISPATCH_BOOKKEEPING = set(PLAN_TOOLS, "agent_status", "message_agent");
|
|
46
|
+
/** Supervising is progress: stopping a sub-agent or asking the owner never counts as idling. */
|
|
47
|
+
export const SUPERVISION = set("stop_agent", "ask_user");
|
|
48
|
+
/** Pollers: re-invoked with identical args while waiting on async work. Never loop-guarded. */
|
|
49
|
+
export const POLLERS = set("agent_status", "bash_output");
|
|
50
|
+
/** Pollers whose answers the engine also posts on its own, so polling them is spin. */
|
|
51
|
+
export const AUTOPOST_POLLERS = set("agent_status");
|
|
52
|
+
/** Status tools: the same facts all turn, so a repeat is refused early. */
|
|
53
|
+
export const STATUS_TOOLS = set("self_status");
|
|
54
|
+
// ── Loop guard ────────────────────────────────────────────────────────────────────────────────────────────
|
|
55
|
+
/** A successful call to one of these is progress: failing calls still counted are retried as new experiments. */
|
|
56
|
+
export const PROGRESS = set(FILE_WRITE, "bash", "shell_exec", "shell_background", "git_command", "delegate_task", "spawn_agent", "email_send", "cronjob", PLAN_WRITE, "memory_store", "checkpoint", "http_request", "browser", "chauffeur");
|
|
57
|
+
/** Tools whose "failure" is normal work output (a red test run, an empty page): a run of different failing calls
|
|
58
|
+
* is diagnosis, so the same-tool failure run only warns for them. */
|
|
59
|
+
export const FAILURE_TOLERANT = set("bash", "shell_exec", "shell_background", "bash_output", "browser", "web_fetch", "http_request", "chauffeur");
|
|
60
|
+
/** Write-progress for the investigate-loop detector. Narrower than PROGRESS: a grep inside bash is the pattern that
|
|
61
|
+
* detector exists for, so shells and git_command are out. */
|
|
62
|
+
export const WRITE_PROGRESS = set(FILE_WRITE, "checkpoint", PLAN_WRITE, "memory_store", DELEGATION, "cronjob");
|
|
63
|
+
// ── Scheduling ────────────────────────────────────────────────────────────────────────────────────────────
|
|
64
|
+
/** Calls that run alone in a batch: each can touch anything. delegate_task is a whole sub-agent session with the full
|
|
65
|
+
* tool set, delegate_to_agent an external CLI agent with write and shell access, spawn_cloud_agent a whole agent in a
|
|
66
|
+
* remote container; the app_/computer_ calls drive the desktop. Prefix matches (computer_, browser, shell, mcp__) live
|
|
67
|
+
* in batch-scheduler. */
|
|
68
|
+
export const SCHED_BARRIER = set("shell_background", "bash_kill", "git_command", "checkpoint", "tool_call", "delegate_task", "delegate_to_agent", "spawn_cloud_agent", "app_open", "app_activate", "computer_applescript", "computer_type", "computer_key", "computer_click", "computer_screenshot");
|
|
69
|
+
const FAILED_HEAD = /^(?:error|loop guard|\[interrupted|\[timed out)/i;
|
|
70
|
+
export function toolOutcome(result, refused) {
|
|
71
|
+
if (refused)
|
|
72
|
+
return refused;
|
|
73
|
+
const s = result.trim();
|
|
74
|
+
if (FAILED_HEAD.test(s))
|
|
75
|
+
return "fail";
|
|
76
|
+
const exit = exitCode(s);
|
|
77
|
+
if ((exit !== undefined && exit !== 0) || /^\(no output; exit \?\)/.test(s))
|
|
78
|
+
return "fail";
|
|
79
|
+
if (/\n\[timed out after [^\n]*\]$/.test(s))
|
|
80
|
+
return "fail";
|
|
81
|
+
return "ok";
|
|
82
|
+
}
|
|
83
|
+
/** A shell call's exit code from its result (registry.ts shellExec), or undefined: output then an `[exit N]` line —
|
|
84
|
+
* which shellResultNotes' `[note: …]`/`[hint: …]` lines and the result guard's notes may follow — or, for a command
|
|
85
|
+
* that printed nothing, `(no output; exit N)`. */
|
|
86
|
+
export function exitCode(result) {
|
|
87
|
+
const m = /(?:^|\n)\[exit (\d+)\](?:\n+\[[^\n]*\])*\s*$/.exec(result) ?? /^\s*\(no output; exit (\d+)\)/.exec(result);
|
|
88
|
+
return m ? Number(m[1]) : undefined;
|
|
89
|
+
}
|
|
90
|
+
/** The engine's own words for a call it answered instead of running (a guard, the permission gate, the interrupt).
|
|
91
|
+
* Only for engine code that has the result and no report: the TUI reads refusals from the report, because a command
|
|
92
|
+
* that ran can print the same first words. */
|
|
93
|
+
export const refusedResult = (result) => /^(?:loop guard|repeated action|blocked |permission denied|cancelled|\[interrupted)/i.test(result.trimStart());
|
|
94
|
+
/** The call ran and failed: the loop guard's test. A call the engine answered for never ran, so it is no failure of
|
|
95
|
+
* the tool's; the TUI, which has the report, shows those as blocked or cancelled instead. */
|
|
96
|
+
export const resultFailed = (result) => !refusedResult(result) && toolOutcome(result) === "fail";
|
|
97
|
+
/** The call ran and did not fail. */
|
|
98
|
+
export const ranOk = (result, refused) => !refusedResult(result) && toolOutcome(result, refused) === "ok";
|
|
99
|
+
export const isMutatingTool = (name) => FILE_WRITE.has(name ?? "");
|
|
100
|
+
/** True when a file write actually LANDED. The file tools report failure as a returned `error: …` string, and a
|
|
101
|
+
* gated, guarded or cancelled call never ran, so the name alone proves nothing: a failing edit must not grant a
|
|
102
|
+
* spinning model a fresh loop-guard runway. */
|
|
103
|
+
export const mutationLanded = (name, result, refused) => isMutatingTool(name) && ranOk(result, refused);
|
package/dist/tools/contract.js
CHANGED
|
@@ -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
|
|
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");
|
package/dist/tools/craft.js
CHANGED
|
@@ -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
|
|
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) {
|
|
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,6 +56,7 @@ 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" },
|
package/dist/tools/executor.js
CHANGED
|
@@ -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 {
|
|
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 &&
|
|
45
|
+
else if (a.cwd == null && CWD_DEFAULTED.has(name))
|
|
50
46
|
a.cwd = root;
|
|
51
|
-
if (a.workspace == null &&
|
|
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
|
|
84
|
-
|
|
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.
|
|
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
|
|
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
|
+
}
|