@jbkjr/relay 0.0.0-stage → 1.2.2
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/LICENSE +21 -0
- package/LICENSES/Apache-2.0.txt +201 -0
- package/LICENSES/README.md +19 -0
- package/LICENSES/codex-NOTICE.txt +6 -0
- package/README.md +393 -2
- package/SECURITY.md +145 -0
- package/adapters/briefs/claude.md +43 -0
- package/adapters/briefs/codex.md +56 -0
- package/adapters/briefs/models.json +33 -0
- package/adapters/build.mjs +8 -0
- package/adapters/claude/.claude-plugin/marketplace.json +13 -0
- package/adapters/claude/relay/.claude-plugin/plugin.json +5 -0
- package/adapters/claude/relay/agents/codex.md +21 -0
- package/adapters/claude/relay/agents/operator.md +21 -0
- package/adapters/claude/relay/skills/ask/SKILL.md +20 -0
- package/adapters/claude/relay/skills/chat/SKILL.md +13 -0
- package/adapters/claude/relay/skills/delegate/SKILL.md +21 -0
- package/adapters/claude/relay/skills/discuss/SKILL.md +19 -0
- package/adapters/claude/relay/skills/review/SKILL.md +21 -0
- package/adapters/claude/relay/skills/tree/SKILL.md +10 -0
- package/adapters/claude/relay/skills/write-for-codex/SKILL.md +78 -0
- package/adapters/codex/.agents/plugins/marketplace.json +20 -0
- package/adapters/codex/AGENTS.snippet.md +5 -0
- package/adapters/codex/relay/.codex-plugin/plugin.json +6 -0
- package/adapters/codex/relay/skills/relay-ask/SKILL.md +20 -0
- package/adapters/codex/relay/skills/relay-chat/SKILL.md +13 -0
- package/adapters/codex/relay/skills/relay-delegate/SKILL.md +21 -0
- package/adapters/codex/relay/skills/relay-discuss/SKILL.md +19 -0
- package/adapters/codex/relay/skills/relay-review/SKILL.md +21 -0
- package/adapters/codex/relay/skills/relay-tree/SKILL.md +10 -0
- package/adapters/codex/relay/skills/relay-write-for-claude/SKILL.md +66 -0
- package/adapters/generate.mjs +124 -0
- package/bin/relay +59 -0
- package/codex-pin.json +12 -0
- package/dist/backends/acp.js +1424 -0
- package/dist/backends/claude.js +890 -0
- package/dist/backends/cli-version.js +112 -0
- package/dist/backends/codex-app.js +1539 -0
- package/dist/backends/codex-daybreak.js +75 -0
- package/dist/backends/codex-env.js +656 -0
- package/dist/backends/codex-network.js +304 -0
- package/dist/backends/codex-pin.js +345 -0
- package/dist/backends/codex-shell-policy.js +182 -0
- package/dist/backends/codex-stage2.js +998 -0
- package/dist/backends/codex-subagents.js +47 -0
- package/dist/backends/codex.js +641 -0
- package/dist/backends/copilot.js +246 -0
- package/dist/backends/env.js +147 -0
- package/dist/backends/gemini.js +607 -0
- package/dist/backends/grok.js +337 -0
- package/dist/backends/index.js +8 -0
- package/dist/backends/native-temp.js +187 -0
- package/dist/backends/never-admission.js +90 -0
- package/dist/backends/run.js +67 -0
- package/dist/backends/stream.js +230 -0
- package/dist/backends/tool-discovery.js +15 -0
- package/dist/backends/types.js +264 -0
- package/dist/build-info.json +5 -0
- package/dist/cli.js +344 -0
- package/dist/confine/bridge.js +113 -0
- package/dist/confine/broker-core.js +76 -0
- package/dist/confine/broker-http.js +650 -0
- package/dist/confine/broker-names.js +9 -0
- package/dist/confine/broker.js +258 -0
- package/dist/confine/canary.js +380 -0
- package/dist/confine/diagnostics.js +122 -0
- package/dist/confine/gemini-tools-main.js +8 -0
- package/dist/confine/gemini-tools.js +181 -0
- package/dist/confine/hardlinks.js +58 -0
- package/dist/confine/harness-config.js +16 -0
- package/dist/confine/index.js +117 -0
- package/dist/confine/leases.js +217 -0
- package/dist/confine/paths.js +6 -0
- package/dist/confine/peer.js +115 -0
- package/dist/confine/port-policy.js +8 -0
- package/dist/confine/ports.js +365 -0
- package/dist/confine/private-root.js +208 -0
- package/dist/confine/probe-stage2.js +501 -0
- package/dist/confine/probe.js +1109 -0
- package/dist/confine/proxy.js +783 -0
- package/dist/confine/sbcheck.js +208 -0
- package/dist/confine/seatbelt-never.js +41 -0
- package/dist/confine/seatbelt-stage2.js +139 -0
- package/dist/confine/seatbelt.js +1129 -0
- package/dist/confine/sockets.js +36 -0
- package/dist/confine/turn-probe.js +19 -0
- package/dist/confine/turn.js +86 -0
- package/dist/core/adoption.js +124 -0
- package/dist/core/api-keys.js +423 -0
- package/dist/core/approvals.js +740 -0
- package/dist/core/build-identity.js +248 -0
- package/dist/core/caller.js +749 -0
- package/dist/core/calls.js +102 -0
- package/dist/core/claude-settings.js +1045 -0
- package/dist/core/config.js +453 -0
- package/dist/core/context.js +186 -0
- package/dist/core/db.js +753 -0
- package/dist/core/dispatch.js +110 -0
- package/dist/core/env-broker.js +505 -0
- package/dist/core/env-policy.js +182 -0
- package/dist/core/escalation-authority.js +76 -0
- package/dist/core/escalation-contract.js +13 -0
- package/dist/core/escalation-person-path.js +131 -0
- package/dist/core/escalation-policy.js +79 -0
- package/dist/core/escalation-runtime.js +135 -0
- package/dist/core/escalation-state.js +42 -0
- package/dist/core/escalations.js +191 -0
- package/dist/core/events.js +235 -0
- package/dist/core/executables.js +147 -0
- package/dist/core/extensions.js +645 -0
- package/dist/core/families.js +204 -0
- package/dist/core/git.js +657 -0
- package/dist/core/identity.js +113 -0
- package/dist/core/liveness.js +68 -0
- package/dist/core/mediated-network-provider.js +81 -0
- package/dist/core/never-checkpoint.js +76 -0
- package/dist/core/never-coverage.js +97 -0
- package/dist/core/never-network.js +49 -0
- package/dist/core/never-policy.js +302 -0
- package/dist/core/never-proxy-policy.js +109 -0
- package/dist/core/never-schema.js +61 -0
- package/dist/core/never-tools.js +56 -0
- package/dist/core/notices.js +48 -0
- package/dist/core/ops.js +959 -0
- package/dist/core/outcome.js +224 -0
- package/dist/core/params.js +32 -0
- package/dist/core/presence.js +174 -0
- package/dist/core/procs.js +546 -0
- package/dist/core/prompts.js +363 -0
- package/dist/core/protected-config.js +238 -0
- package/dist/core/raw-network.js +192 -0
- package/dist/core/redact.js +152 -0
- package/dist/core/refusal.js +33 -0
- package/dist/core/relay-command.js +310 -0
- package/dist/core/reported.js +3 -0
- package/dist/core/restart-overlay.js +651 -0
- package/dist/core/retention.js +1135 -0
- package/dist/core/secrets.js +329 -0
- package/dist/core/session-token.js +175 -0
- package/dist/core/session.js +744 -0
- package/dist/core/shell.js +2 -0
- package/dist/core/shipped-pin.js +47 -0
- package/dist/core/shown.js +42 -0
- package/dist/core/slots.js +67 -0
- package/dist/core/stage2-executors.js +453 -0
- package/dist/core/stage2-switch.js +5 -0
- package/dist/core/steering.js +149 -0
- package/dist/core/storage.js +358 -0
- package/dist/core/toml.js +175 -0
- package/dist/core/views.js +324 -0
- package/dist/core/wait.js +114 -0
- package/dist/core/wake.js +207 -0
- package/dist/core/watch.js +247 -0
- package/dist/core/worktree.js +213 -0
- package/dist/hosts/claude-desktop.js +274 -0
- package/dist/hosts/claude.js +249 -0
- package/dist/hosts/codex.js +345 -0
- package/dist/hosts/desktop-shared.js +20 -0
- package/dist/hosts/index.js +11 -0
- package/dist/hosts/types.js +4 -0
- package/dist/install/basics.js +18 -0
- package/dist/install/claude-init.js +133 -0
- package/dist/install/common.js +655 -0
- package/dist/install/doctor.js +635 -0
- package/dist/install/qualify-codex.js +205 -0
- package/dist/install.js +524 -0
- package/dist/mcp/elicit.js +209 -0
- package/dist/mcp/gateway.js +218 -0
- package/dist/mcp/host.js +253 -0
- package/dist/mcp/server.js +1124 -0
- package/dist/mcp/stdio.js +37 -0
- package/dist/modes/discussion.js +393 -0
- package/dist/modes/review.js +722 -0
- package/dist/native/relay-sbcheck +0 -0
- package/dist/targets/briefs.js +86 -0
- package/dist/targets/claude.js +94 -0
- package/dist/targets/codex.js +66 -0
- package/dist/targets/copilot.js +93 -0
- package/dist/targets/gemini.js +119 -0
- package/dist/targets/grok.js +126 -0
- package/dist/targets/index.js +192 -0
- package/dist/targets/types.js +18 -0
- package/dist/targets/verified.js +35 -0
- package/dist/worker.js +113 -0
- package/docs/UPGRADING.md +1518 -0
- package/docs/pinned-codex.md +333 -0
- package/experiments/stage2-redteam/lib/oracles.mjs +214 -0
- package/experiments/stage2-redteam/lib/report.mjs +35 -0
- package/npm-shrinkwrap.json +1632 -0
- package/package.json +82 -4
- package/scripts/codex-qualify/codex-pin-store.mjs +353 -0
- package/scripts/codex-qualify/codex-qualifier-process.mjs +265 -0
- package/scripts/codex-qualify/codex-qualifier.example.json +5 -0
- package/scripts/codex-qualify/codex-qualifier.mjs +281 -0
- package/scripts/codex-qualify/codex-shipped-pin.mjs +158 -0
- package/scripts/codex-qualify/codex-stage2-pin.mjs +48 -0
- package/scripts/codex-qualify/codex-stage2.mjs +2381 -0
- package/scripts/codex-qualify/install-codex-qualifier.mjs +98 -0
- package/scripts/codex-qualify/main-module.mjs +14 -0
- package/scripts/codex-qualify/relay-codex-qualifier.plist +37 -0
- package/scripts/codex-qualify/scratch-env.mjs +31 -0
- package/scripts/codex-qualify/session.mjs +96 -0
- package/scripts/codex-qualify/stage2-escalation-cases.mjs +125 -0
- package/test/codex-permissions.test.ts +875 -0
- package/test/fixtures/boundary-probes.mjs +17 -0
- package/test/fixtures/denial-stream-host.mjs +7 -0
- package/test/fixtures/families.json +246 -0
- package/test/fixtures/install-snapshots/claude-desktop-foreign.txt +158 -0
- package/test/fixtures/install-snapshots/claude-desktop-fresh.txt +101 -0
- package/test/fixtures/install-snapshots/claude-desktop-installed.txt +161 -0
- package/test/fixtures/install-snapshots/claude-foreign.txt +133 -0
- package/test/fixtures/install-snapshots/claude-fresh.txt +77 -0
- package/test/fixtures/install-snapshots/claude-installed.txt +133 -0
- package/test/fixtures/install-snapshots/codex-foreign.txt +159 -0
- package/test/fixtures/install-snapshots/codex-fresh.txt +107 -0
- package/test/fixtures/install-snapshots/codex-installed.txt +161 -0
- package/test/fixtures/link-parent.mjs +6 -0
- package/test/fixtures/mediated-command.cjs +72 -0
- package/test/fixtures/native-skill-isolation.json +280 -0
- package/test/fixtures/pinned-codex-app-server.mjs +25 -0
- package/test/fixtures/qualified-ext-adapters.mjs +36 -0
- package/test/fixtures/refusals/README.md +52 -0
- package/test/fixtures/refusals/claude-source-result.json +7 -0
- package/test/fixtures/refusals/openai-app-capacity.json +24 -0
- package/test/fixtures/refusals/openai-app-cyberPolicy.json +24 -0
- package/test/fixtures/refusals/openai-gpt-6-astra-max.json +12 -0
- package/test/fixtures/refusals/openai-gpt-6.1-sol-xhigh.json +12 -0
- package/test/fixtures/refusals/openai-review-capacity.json +24 -0
- package/test/fixtures/relay-0.2.0.sql +57 -0
- package/test/fixtures/relay-0.9.1.gen.mjs +212 -0
- package/test/fixtures/relay-0.9.1.sql +340 -0
- package/test/fixtures/slow-boundary-probes.mjs +37 -0
- package/test/fixtures/stable-surfaces/config.json +1122 -0
- package/test/fixtures/stable-surfaces/escalation.json +128 -0
- package/test/fixtures/stable-surfaces/events.json +37 -0
- package/test/fixtures/stable-surfaces/gemini-native-resume.json +4 -0
- package/test/fixtures/stable-surfaces/inbox.jsonl +2 -0
- package/test/fixtures/stable-surfaces/notice.txt +1 -0
- package/test/fixtures/stable-surfaces/refusal-item.json +28 -0
- package/test/fixtures/stable-surfaces/refusal-review.json +23 -0
- package/test/fixtures/stable-surfaces/registry.json +49 -0
- package/test/fixtures/stable-surfaces/tools-desktop.json +575 -0
- package/test/fixtures/stable-surfaces/tools.json +716 -0
- package/test/fixtures/stable-surfaces/usage.txt +46 -0
- package/test/fixtures/stage2-acp-native.mjs +138 -0
- package/test/fixtures/stage2-app-server.mjs +23 -0
- package/test/fixtures/stage2-catalog.json +91 -0
- package/test/fixtures/stage2-hostile-web.mjs +35 -0
- package/test/fixtures/stage2-native-network.mjs +62 -0
- package/test/fixtures/stage2-worker.ts +87 -0
- package/test/fixtures/status-views/expected.json +7825 -0
- package/test/fixtures/status-views/registries.json +1 -0
- package/test/fixtures/steering.json +209 -0
- package/test/helpers.ts +740 -0
- package/test/host-env.ts +7 -0
- package/test/keychain-decoy.ts +197 -0
- package/test/live-scope.ts +44 -0
- package/test/mediated-network.test.ts +192 -0
- package/test/mediated-proxy.test.ts +264 -0
- package/test/native-temp-alias.ts +10 -0
- package/test/never-policy.test.ts +629 -0
- package/test/never-tools.test.ts +136 -0
- package/test/process-home.ts +18 -0
- package/test/proxy.test.ts +531 -0
- package/test/restart-overlay-live.test.ts +85 -0
- package/test/restart-overlay-profile.test.ts +66 -0
- package/test/restart-overlay.test.ts +416 -0
- package/test/stable-surfaces.test.ts +249 -0
- package/test/stage2-escalation-live.test.ts +544 -0
- package/test/stage2-escalation-qualification.test.ts +170 -0
- package/test/stage2-escalation.test.ts +747 -0
- package/test/stage2-executor.test.ts +849 -0
- package/test/stage2-grant.test.ts +603 -0
- package/test/stage2-native-live.test.ts +647 -0
- package/test/stage2-network-decisions.test.ts +70 -0
- package/test/stage2-probe.test.ts +845 -0
- package/test/stage2-standing-live.test.ts +203 -0
- package/test/stubs/broker-host.mjs +59 -0
- package/test/stubs/broker-peer.mjs +20 -0
- package/test/stubs/confined-harness.mjs +91 -0
- package/test/stubs/ext-broken-server.mjs +2 -0
- package/test/stubs/ext-odd-server.mjs +21 -0
- package/test/stubs/ext-server.mjs +31 -0
- package/test/stubs/fake-host-cli.mjs +218 -0
- package/test/stubs/procargs.mjs +30 -0
- package/test/stubs/stub-acp +4 -0
- package/test/stubs/stub-agent.mjs +322 -0
- package/test/stubs/stub-claude +4 -0
- package/test/stubs/stub-codex +4 -0
- package/test/stubs/targets/acp.mjs +307 -0
- package/test/stubs/targets/claude.mjs +149 -0
- package/test/stubs/targets/codex.mjs +479 -0
- package/test/stubs/targets/gemini.mjs +604 -0
- package/test/temp-root.ts +11 -0
- package/test/wp4-adapters.test.ts +353 -0
- package/test/wp4-interlock.test.ts +136 -0
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { parse, TomlError } from "smol-toml";
|
|
2
|
+
const RELAY_BLOCK_COMMENT = "# Deciding a launched agent's approval request";
|
|
3
|
+
/** The only spelling of relay's table headers that relay writes, and so the only one it removes. */
|
|
4
|
+
const RELAY_HEADER = /^\s*\[mcp_servers\.relay(?:\.[^\]]*)?\]\s*(?:#.*)?$/;
|
|
5
|
+
/** Lines with their own endings attached, so that a line relay does not touch stays byte for byte what it was. */
|
|
6
|
+
const splitLines = (text) => text.match(/[^\n]*\n|[^\n]+$/g) ?? [];
|
|
7
|
+
const body = (line) => line.replace(/\r?\n$/, "");
|
|
8
|
+
const blank = (line) => /^\s*$/.test(body(line));
|
|
9
|
+
/** The line ending most of the file uses; relay's own lines are written with it. */
|
|
10
|
+
function eolOf(text) {
|
|
11
|
+
const crlf = (text.match(/\r\n/g) ?? []).length;
|
|
12
|
+
const lf = (text.match(/\n/g) ?? []).length - crlf;
|
|
13
|
+
return crlf > lf ? "\r\n" : "\n";
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Removes every [mcp_servers.relay…] table, line by line. Comments and blank lines sitting
|
|
17
|
+
* directly above the next table belong to that table and are kept, as is anything after relay's
|
|
18
|
+
* last key at the end of the file. A blank line that only set relay's block apart goes with it.
|
|
19
|
+
*/
|
|
20
|
+
function stripLines(lines) {
|
|
21
|
+
const out = [];
|
|
22
|
+
let held = [];
|
|
23
|
+
let inRelay = false;
|
|
24
|
+
// Lines that followed relay's tables are put back without doubling the blank line before them.
|
|
25
|
+
const keep = (ls) => {
|
|
26
|
+
for (const l of ls)
|
|
27
|
+
if (!(blank(l) && (!out.length || blank(out[out.length - 1]))))
|
|
28
|
+
out.push(l);
|
|
29
|
+
};
|
|
30
|
+
for (const line of lines) {
|
|
31
|
+
const text = body(line);
|
|
32
|
+
if (/^\s*\[/.test(text)) {
|
|
33
|
+
const relay = RELAY_HEADER.test(text);
|
|
34
|
+
if (inRelay && !relay)
|
|
35
|
+
keep(held);
|
|
36
|
+
else if (!inRelay && relay)
|
|
37
|
+
while (out.length && body(out[out.length - 1]).startsWith(RELAY_BLOCK_COMMENT))
|
|
38
|
+
out.pop();
|
|
39
|
+
held = [];
|
|
40
|
+
inRelay = relay;
|
|
41
|
+
if (!relay)
|
|
42
|
+
out.push(line);
|
|
43
|
+
}
|
|
44
|
+
else if (!inRelay) {
|
|
45
|
+
out.push(line);
|
|
46
|
+
}
|
|
47
|
+
else if (/^\s*(#.*)?$/.test(text)) {
|
|
48
|
+
if (!text.startsWith(RELAY_BLOCK_COMMENT))
|
|
49
|
+
held.push(line);
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
held = [];
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (inRelay) {
|
|
56
|
+
const comments = held.some((l) => !blank(l));
|
|
57
|
+
keep(held);
|
|
58
|
+
if (!comments && out.length && blank(out[out.length - 1]))
|
|
59
|
+
out.pop();
|
|
60
|
+
}
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
export function readToml(text) {
|
|
64
|
+
try {
|
|
65
|
+
// Integers too large for a JavaScript number are valid TOML; they must not make the file unreadable.
|
|
66
|
+
return { ok: true, data: parse(text, { integersAsBigInt: "asNeeded" }) };
|
|
67
|
+
}
|
|
68
|
+
catch (err) {
|
|
69
|
+
if (err instanceof TomlError)
|
|
70
|
+
return { ok: false, error: `line ${err.line}, column ${err.column}: ${err.message.split("\n")[0]}` };
|
|
71
|
+
return { ok: false, error: err.message };
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
export const isTable = (v) => typeof v === "object" && v !== null && !Array.isArray(v) && !(v instanceof Date);
|
|
75
|
+
/** The mcp_servers.relay table of a parsed config, however it was written; undefined if there is none. */
|
|
76
|
+
export function relayServer(data) {
|
|
77
|
+
return isTable(data.mcp_servers) ? data.mcp_servers.relay : undefined;
|
|
78
|
+
}
|
|
79
|
+
/** A plain, key-sorted form in which two parsed documents can be compared exactly. */
|
|
80
|
+
function canon(v) {
|
|
81
|
+
if (typeof v === "bigint")
|
|
82
|
+
return { "\u0000int": v.toString() };
|
|
83
|
+
if (typeof v === "number")
|
|
84
|
+
return Number.isFinite(v) && !Object.is(v, -0) ? v : { "\u0000float": Object.is(v, -0) ? "-0" : String(v) };
|
|
85
|
+
// A TOML date prints in the form it was written, so a local date and a date-time stay distinct.
|
|
86
|
+
if (v instanceof Date)
|
|
87
|
+
return { "\u0000date": v.toISOString() };
|
|
88
|
+
if (Array.isArray(v))
|
|
89
|
+
return v.map(canon);
|
|
90
|
+
if (isTable(v))
|
|
91
|
+
return Object.fromEntries(Object.keys(v).sort().map((k) => [k, canon(v[k])]));
|
|
92
|
+
return v;
|
|
93
|
+
}
|
|
94
|
+
export function sameData(a, b) {
|
|
95
|
+
return JSON.stringify(canon(a)) === JSON.stringify(canon(b));
|
|
96
|
+
}
|
|
97
|
+
/** Where a relay entry is written in a way relay will not edit, for the message that says so. */
|
|
98
|
+
function unusualForms(text) {
|
|
99
|
+
const key = (name) => `(?:${name}|"${name}"|'${name}')`;
|
|
100
|
+
const servers = new RegExp(`^\\s*\\[\\s*${key("mcp_servers")}\\s*\\]`);
|
|
101
|
+
const header = new RegExp(`^\\s*\\[\\[?\\s*${key("mcp_servers")}\\s*\\.\\s*${key("relay")}\\s*[.\\]]`);
|
|
102
|
+
const dotted = new RegExp(`^\\s*${key("mcp_servers")}\\s*\\.\\s*${key("relay")}\\s*[.=]`);
|
|
103
|
+
const inline = new RegExp(`^\\s*${key("mcp_servers")}\\s*=`);
|
|
104
|
+
const child = new RegExp(`^\\s*${key("relay")}\\s*[.=]`);
|
|
105
|
+
const found = [];
|
|
106
|
+
let inServers = false;
|
|
107
|
+
splitLines(text).forEach((line, i) => {
|
|
108
|
+
const t = body(line);
|
|
109
|
+
if (/^\s*\[/.test(t))
|
|
110
|
+
inServers = servers.test(t);
|
|
111
|
+
if ((header.test(t) && !RELAY_HEADER.test(t)) || dotted.test(t) || inline.test(t) || (inServers && child.test(t)))
|
|
112
|
+
found.push(`line ${i + 1}: ${t.trim()}`);
|
|
113
|
+
});
|
|
114
|
+
return found.slice(0, 8);
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Replaces relay's block in a Codex config, or removes it when block is null, and proves the
|
|
118
|
+
* result before anyone writes it: the new text must parse, mcp_servers.relay must be exactly
|
|
119
|
+
* what the block says (or gone), and every other setting must be what it was. Anything else is
|
|
120
|
+
* a refusal with the reason, and the caller writes nothing.
|
|
121
|
+
*/
|
|
122
|
+
export function editCodexConfig(current, block) {
|
|
123
|
+
const before = readToml(current);
|
|
124
|
+
if (!before.ok)
|
|
125
|
+
return { ok: false, reason: `it does not parse as TOML (${before.error})` };
|
|
126
|
+
const bom = current.startsWith("\uFEFF") ? "\uFEFF" : "";
|
|
127
|
+
const eol = eolOf(current);
|
|
128
|
+
// With no relay entry there is nothing to take out, and so no line of the file to touch.
|
|
129
|
+
let text = current.slice(bom.length);
|
|
130
|
+
if (relayServer(before.data) !== undefined)
|
|
131
|
+
text = stripLines(splitLines(text)).join("");
|
|
132
|
+
const stripped = readToml(text);
|
|
133
|
+
if (stripped.ok && relayServer(stripped.data) !== undefined) {
|
|
134
|
+
const where = unusualForms(current.slice(bom.length));
|
|
135
|
+
return {
|
|
136
|
+
ok: false,
|
|
137
|
+
reason: "it defines mcp_servers.relay in a form relay does not edit: a quoted or spaced table name, an inline table, or dotted keys. "
|
|
138
|
+
+ "Relay only removes tables written as [mcp_servers.relay] and [mcp_servers.relay.<name>]. Remove that definition by hand, then run this again."
|
|
139
|
+
+ (where.length ? `\n Look at:\n${where.map((w) => ` ${w}`).join("\n")}` : ""),
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
let intended;
|
|
143
|
+
if (block !== null) {
|
|
144
|
+
const parsed = readToml(block);
|
|
145
|
+
intended = parsed.ok ? relayServer(parsed.data) : undefined;
|
|
146
|
+
if (intended === undefined)
|
|
147
|
+
return { ok: false, reason: "relay's own block does not parse; this is a bug in relay" };
|
|
148
|
+
if (text && !text.endsWith("\n"))
|
|
149
|
+
text += eol;
|
|
150
|
+
if (text)
|
|
151
|
+
text += eol;
|
|
152
|
+
text += block.replace(/\r?\n/g, eol);
|
|
153
|
+
}
|
|
154
|
+
text = bom + text;
|
|
155
|
+
const after = readToml(text);
|
|
156
|
+
const unsafe = "relay's line-by-line edit would not leave the file as intended, so it was not made and has to be made by hand";
|
|
157
|
+
if (!after.ok)
|
|
158
|
+
return { ok: false, reason: `${unsafe} (the result would not parse: ${after.error})` };
|
|
159
|
+
const want = canon(before.data);
|
|
160
|
+
const got = canon(after.data);
|
|
161
|
+
if (isTable(want.mcp_servers) || block !== null) {
|
|
162
|
+
const servers = { ...(isTable(want.mcp_servers) ? want.mcp_servers : {}) };
|
|
163
|
+
delete servers.relay;
|
|
164
|
+
if (block !== null)
|
|
165
|
+
servers.relay = intended;
|
|
166
|
+
want.mcp_servers = servers;
|
|
167
|
+
}
|
|
168
|
+
// A table that is empty and a table that is not there mean the same thing to Codex.
|
|
169
|
+
for (const doc of [want, got])
|
|
170
|
+
if (isTable(doc.mcp_servers) && !Object.keys(doc.mcp_servers).length)
|
|
171
|
+
delete doc.mcp_servers;
|
|
172
|
+
if (JSON.stringify(canon(want)) !== JSON.stringify(canon(got)))
|
|
173
|
+
return { ok: false, reason: `${unsafe} (settings other than mcp_servers.relay would change)` };
|
|
174
|
+
return { ok: true, text };
|
|
175
|
+
}
|
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
import { escalationAccounting } from "./escalations.js";
|
|
2
|
+
// Views: what relay shows of an item in status, result and relay tree, and the approval note and
|
|
3
|
+
// pending handle that come with them. A reviewer's result is withheld until the caller hands in
|
|
4
|
+
// its own, and so is anything that would show it (its log, what it is doing, what it was refused).
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
import { familiesOf } from "./families.js";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { elicitationState, pendingRequests, requestView } from "./approvals.js";
|
|
9
|
+
import { harnessHome } from "./config.js";
|
|
10
|
+
import { ACTIVE, getNode, getRun, nodeTurns, now, reap, runNodes, speedAfter, turnReports, workCwd } from "./db.js";
|
|
11
|
+
import { liveness } from "./liveness.js";
|
|
12
|
+
import { outcomeView, removedBranch, resultNow } from "./outcome.js";
|
|
13
|
+
import { discussionParams, reviewParams, sessionParams, speedOf } from "./params.js";
|
|
14
|
+
import { extensionsSummary, extensionsView, PERSON_ROUTES } from "./extensions.js";
|
|
15
|
+
import { clipped, oneLine } from "./shown.js";
|
|
16
|
+
import { targetDef, targetLabel } from "../targets/index.js";
|
|
17
|
+
import { REPORTED_COMPLETION } from "./reported.js";
|
|
18
|
+
/**
|
|
19
|
+
* One line on how an item is getting on, for progress notifications: its status, how long it has
|
|
20
|
+
* run, which turn, what its agent last started (command, tool or file) and when, and any approval
|
|
21
|
+
* request it is waiting on. Never the agent's own words, and not what a reviewer whose result is
|
|
22
|
+
* withheld is doing, which status leaves out too (review C19).
|
|
23
|
+
*/
|
|
24
|
+
export function progressLine(nodeId) {
|
|
25
|
+
const n = getNode(nodeId);
|
|
26
|
+
if (!n)
|
|
27
|
+
return `relay: ${nodeId} is not in the registry`;
|
|
28
|
+
const turns = nodeTurns(n.id);
|
|
29
|
+
const cur = turns.find((t) => t.status === "running") ?? turns.find((t) => t.status === "queued") ?? turns.at(-1);
|
|
30
|
+
const secs = (ms) => (ms >= 3600_000 ? `${Math.floor(ms / 3600_000)}h${Math.floor((ms % 3600_000) / 60_000)}m` : ms >= 60_000 ? `${Math.floor(ms / 60_000)}m${Math.floor((ms % 60_000) / 1000)}s` : `${Math.round(ms / 1000)}s`);
|
|
31
|
+
const parts = [`relay: ${n.id} ${n.status}`, secs(now() - (n.started_at ?? n.created_at))];
|
|
32
|
+
if (cur)
|
|
33
|
+
parts.push(`turn ${turns.indexOf(cur) + 1}${turns.length > 1 ? ` of ${turns.length}` : ""}`);
|
|
34
|
+
const asking = pendingRequests(n.run_id).find((r) => r.node_id === n.id);
|
|
35
|
+
const tokens = usageOf(n.id, turns)?.total_tokens;
|
|
36
|
+
if (typeof tokens === "number")
|
|
37
|
+
parts.push(`${tokens >= 1000 ? `${(tokens / 1000).toFixed(1)}k` : tokens} tokens`);
|
|
38
|
+
if (asking)
|
|
39
|
+
parts.push(`waiting for approval ${asking.id}: ${clipped(asking.summary, 80)}`);
|
|
40
|
+
else if (cur?.status === "running" && cur.activity && !withheld(n))
|
|
41
|
+
parts.push(`now: ${oneLine(cur.activity, 100)} (${secs(now() - (cur.activity_at ?? now()))} ago)`);
|
|
42
|
+
return parts.join(" · ");
|
|
43
|
+
}
|
|
44
|
+
/** What the pending requests want, by what allowing them would actually do (their effect), and how to decide. */
|
|
45
|
+
function approvalNote(effects) {
|
|
46
|
+
const distinct = [...new Set(effects.filter((e) => typeof e === "string"))];
|
|
47
|
+
const what = distinct.length === 1
|
|
48
|
+
? `${effects.length === 1 ? "A launched agent is" : "Launched agents are"} waiting for approval: allowing ${effects.length === 1 ? "it" : "each"} ${distinct[0]}.`
|
|
49
|
+
: "Launched agents are waiting for approval; each request's effect says what allowing it would do.";
|
|
50
|
+
return `${what} Decide with the approve tool: allow what the user has clearly authorized for this task, deny what they would not want, and ask the user when unsure. The agent stays blocked until then.`;
|
|
51
|
+
}
|
|
52
|
+
const CONFIRM_NOTE = " To allow something the user has not clearly authorized, call confirm with the request's request_id, from, kind, effect, in_directory and wants exactly as shown: your host then asks the user before the call goes ahead, so the decision is theirs.";
|
|
53
|
+
const PERSON_ONLY_NOTE = ` A request marked person_only (consent to extensions, a call of an MCP server's tool, or any request of a session holding MCP servers) can be allowed only by the user, ${PERSON_ROUTES}; relay takes it from no command, relay approve included. approve can only deny it.`;
|
|
54
|
+
const FORM_STAYS_NOTE = " Your host keeps relay's form on the user's screen, and holds your turn, until they answer it or press Esc, even after the request is decided elsewhere (by you or from a terminal); if you decide one they are being asked about, tell them to press Esc. An answer given after the decision changes nothing, and relay tells you if one comes.";
|
|
55
|
+
export function approvalsFor(runId, inst) {
|
|
56
|
+
const open = pendingRequests(runId);
|
|
57
|
+
if (!open.length)
|
|
58
|
+
return {};
|
|
59
|
+
const views = open.map((r) => {
|
|
60
|
+
const state = elicitationState(r.id);
|
|
61
|
+
return {
|
|
62
|
+
...requestView(r),
|
|
63
|
+
...(state === "asking" ? { user_is_being_asked: true } : state === "dismissed" ? { user_dismissed_prompt: true } : state ? { host_answered_prompt: state.unattributed } : {}),
|
|
64
|
+
};
|
|
65
|
+
});
|
|
66
|
+
const isPersonal = (v) => v.person_only === true;
|
|
67
|
+
const asked = views.filter((v) => "user_is_being_asked" in v || "user_dismissed_prompt" in v);
|
|
68
|
+
// A person-only request is never allowed with user_confirmed (approve refuses it), so the advice to do so is only for the others.
|
|
69
|
+
const direct = asked.some((v) => !isPersonal(v));
|
|
70
|
+
const directPersonal = asked.some(isPersonal);
|
|
71
|
+
const personal = views.some(isPersonal);
|
|
72
|
+
const unattributed = views.some((v) => "host_answered_prompt" in v);
|
|
73
|
+
const confirmable = Boolean(inst?.host.confirmTool);
|
|
74
|
+
return {
|
|
75
|
+
needs_approval: views,
|
|
76
|
+
approval_note: approvalNote(views.map((v) => v.effect)) + (confirmable ? CONFIRM_NOTE : "") + (personal ? PERSON_ONLY_NOTE : "") +
|
|
77
|
+
(direct
|
|
78
|
+
? ` For a request marked user_is_being_asked (the question is on their screen now) or user_dismissed_prompt (they closed it without answering)${directPersonal ? " and not person_only" : ""}, do not allow it on your own judgment: wait, or ask them in conversation, and allow only with user_confirmed once they say so` +
|
|
79
|
+
(confirmable ? ", or use confirm, which puts it to them in a permission prompt" : "") + ". You may still deny."
|
|
80
|
+
: "") +
|
|
81
|
+
(directPersonal
|
|
82
|
+
? ` For a person_only request marked user_is_being_asked or user_dismissed_prompt, user_confirmed allows nothing: wait for the user's answer to relay's question${confirmable ? ", or use confirm, which puts it to them in a permission prompt" : ""}. You may still deny.`
|
|
83
|
+
: "") +
|
|
84
|
+
(asked.length && inst?.host.formStays ? FORM_STAYS_NOTE : "") +
|
|
85
|
+
(unattributed
|
|
86
|
+
? " A request marked host_answered_prompt was put to the user, but the host answered it in a way that decides nothing and that relay cannot attribute to them (for example Codex, which declines on its own when its approval policy is never): decide it as any other, and ask the user when unsure, mindful that a decline may have been theirs."
|
|
87
|
+
: "") +
|
|
88
|
+
// Why the user is not asked directly, or confirm is not offered, so that the agent can tell them.
|
|
89
|
+
(inst?.host.noElicit ? ` relay is not putting requests to the user directly in this session: ${inst.host.noElicit}.` : "") +
|
|
90
|
+
(inst?.host.confirmWithheld ? ` confirm is not offered in this session: ${inst.host.confirmWithheld}.` : ""),
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
export const pendingHandle = (id, extra = {}, inst) => {
|
|
94
|
+
const n = getNode(id);
|
|
95
|
+
const runId = n?.run_id;
|
|
96
|
+
return {
|
|
97
|
+
pending: true,
|
|
98
|
+
id,
|
|
99
|
+
...extra,
|
|
100
|
+
...(n ? { families: familiesOf(n) } : {}),
|
|
101
|
+
...(n ? notesView(n) : {}),
|
|
102
|
+
...(n?.target && !targetDef(n.target).qualified ? { target_label: targetLabel(targetDef(n.target)) } : {}),
|
|
103
|
+
...(runId ? { ...runRecovery(runId), ...approvalsFor(runId, inst) } : {}),
|
|
104
|
+
note: `Still running. Call status with id "${id}" and wait_s to wait for it; the work continues in the meantime.`,
|
|
105
|
+
};
|
|
106
|
+
};
|
|
107
|
+
/**
|
|
108
|
+
* Only render after item access is checked. Saved replies can describe a later recovery prompt.
|
|
109
|
+
* `itemCount`: the number of the run's items, where the caller has just read them all.
|
|
110
|
+
*/
|
|
111
|
+
export function runRecovery(runId, itemCount) {
|
|
112
|
+
const run = getRun(runId);
|
|
113
|
+
return { run_id: runId, adoption: { in_directory: run.root_cwd, item_count: itemCount ?? runNodes(runId).length } };
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* A reviewer's result is kept out of relay's replies until the agent that asked for the review
|
|
117
|
+
* has saved its own (or skipped it). This prevents seeing it early through normal use of the tools.
|
|
118
|
+
* Host transcripts, drafts and reviewer files remain outside this safeguard.
|
|
119
|
+
*/
|
|
120
|
+
function withheld(n, params = sessionParams(n)) {
|
|
121
|
+
const rid = params.review_id;
|
|
122
|
+
const r = rid && n.kind === "job" ? getNode(rid) : undefined;
|
|
123
|
+
if (!r || r.status !== "open" || reviewParams(r).own)
|
|
124
|
+
return null;
|
|
125
|
+
return `This reviewer's result is withheld until you hand in your own review: call review with review_id "${r.id}" and own_review (or skip_own).`;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* A session's token usage across its turns, as its agent reported it. Codex reports its thread's
|
|
129
|
+
* running total, so its latest report is the session's; Claude reports each turn's own, so they are added up.
|
|
130
|
+
*/
|
|
131
|
+
function usageOf(nodeId, turns = turnReports(nodeId)) {
|
|
132
|
+
const reports = turns.filter((t) => t.usage_json).map((t) => JSON.parse(t.usage_json));
|
|
133
|
+
if (!reports.length)
|
|
134
|
+
return null;
|
|
135
|
+
const last = reports.at(-1);
|
|
136
|
+
if (last.cumulative) {
|
|
137
|
+
const { cumulative: _, ...rest } = last;
|
|
138
|
+
return { ...rest, as_reported: "the session's running total, as its agent reports it" };
|
|
139
|
+
}
|
|
140
|
+
const sum = {};
|
|
141
|
+
for (const r of reports) {
|
|
142
|
+
for (const [k, v] of Object.entries(r))
|
|
143
|
+
if (typeof v === "number")
|
|
144
|
+
sum[k] = (sum[k] ?? 0) + v;
|
|
145
|
+
}
|
|
146
|
+
if (sum.cost_usd !== undefined)
|
|
147
|
+
sum.cost_usd = Math.round(sum.cost_usd * 1e6) / 1e6;
|
|
148
|
+
return { ...sum, as_reported: `added up over ${reports.length} turn${reports.length === 1 ? "" : "s"}, as its agent reported each` };
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* A session's speed, when it is not standard: the one requested for its turn now running or last
|
|
152
|
+
* started (no harness reports the tier that actually served a turn), the one a call has since asked
|
|
153
|
+
* for its queued turns (`next`, where that differs), and what its harness last reported about its
|
|
154
|
+
* speed, where it reports anything (Claude's fast mode state, its reason, the speed it ran at, and
|
|
155
|
+
* a notice on its stream). That report is shown only if its turn asked for the speed requested now:
|
|
156
|
+
* one from a turn at another speed (the session's speed changed since, and no turn has reported at
|
|
157
|
+
* the new one yet) says nothing about it.
|
|
158
|
+
*/
|
|
159
|
+
export function speedView(n, turns) {
|
|
160
|
+
if (n.kind !== "job" && n.kind !== "thread")
|
|
161
|
+
return null;
|
|
162
|
+
const requested = speedOf(n);
|
|
163
|
+
const next = speedAfter(n);
|
|
164
|
+
if (requested === "standard" && next === "standard")
|
|
165
|
+
return null;
|
|
166
|
+
const last = (turns ?? turnReports(n.id)).filter((t) => t.usage_json).map((t) => JSON.parse(t.usage_json)).filter((u) => u.speed_report).at(-1);
|
|
167
|
+
return { requested, ...(next !== requested ? { next } : {}), ...(last?.speed_requested === requested ? { reported: last.speed_report } : {}) };
|
|
168
|
+
}
|
|
169
|
+
const shellQuote = (p) => `'${p.replace(/'/g, "'\\''")}'`;
|
|
170
|
+
/**
|
|
171
|
+
* How to open a finished job's or thread's session in the user's own CLI, and what that means: it
|
|
172
|
+
* runs under the user's own settings, not the confinement relay gave it, and in the directory it
|
|
173
|
+
* worked in, which for a write job is a worktree that may have been removed since. For a target
|
|
174
|
+
* that withholds it (nativeResumeWithheld), only why.
|
|
175
|
+
*/
|
|
176
|
+
function nativeResume(n) {
|
|
177
|
+
if (!n.session_id || !n.target || (n.kind !== "job" && n.kind !== "thread"))
|
|
178
|
+
return null;
|
|
179
|
+
const def = targetDef(n.target);
|
|
180
|
+
if (def.nativeResumeWithheld)
|
|
181
|
+
return { command: null, note: def.nativeResumeWithheld };
|
|
182
|
+
const dir = workCwd(n);
|
|
183
|
+
const command = `cd ${shellQuote(dir)} && ${def.resumeCommand(n.session_id, { harnessState: path.join(harnessHome(), n.run_id, n.id) })}`;
|
|
184
|
+
const own = `Opens the session in your own ${targetLabel(def, def.product)}, with your own settings and permissions, not the confinement relay gave it.`;
|
|
185
|
+
if (!fs.existsSync(dir)) {
|
|
186
|
+
const where = n.worktree
|
|
187
|
+
? ` Its worktree ${n.worktree} has been removed (after a merge or relay clean, or because the job changed nothing), so the cd fails: continue it with relay's resume, which puts the worktree back, or first run git worktree add ${shellQuote(n.worktree)} ${n.branch ?? ""} in ${n.repo ?? "the repository"}.`
|
|
188
|
+
: ` Its directory ${dir} no longer exists.`;
|
|
189
|
+
return { command, note: own + where, directory_exists: false };
|
|
190
|
+
}
|
|
191
|
+
return { command, note: own + (n.worktree ? ` It works in the job's worktree, which still exists; changes made there are on branch ${n.branch}.` : ""), directory_exists: true };
|
|
192
|
+
}
|
|
193
|
+
/** Plain launch notes also accompany the discussion or review that uses this session. */
|
|
194
|
+
export function notesView(n) {
|
|
195
|
+
// A discussion or review row can be listed before its params are written: no notes then.
|
|
196
|
+
const id = n.kind === "discussion" ? discussionParams(n)?.participant
|
|
197
|
+
: n.kind === "review" ? reviewParams(n)?.reviewer : n.id;
|
|
198
|
+
const session = typeof id === "string" ? getNode(id) : undefined;
|
|
199
|
+
const params = session ? sessionParams(session) : undefined;
|
|
200
|
+
const notes = params?.notes;
|
|
201
|
+
const never = params?.never_policy;
|
|
202
|
+
const escalations = session ? escalationAccounting(session.id) : [];
|
|
203
|
+
return { ...(notes?.length ? { notes } : {}), ...(never ? { never_policy: never } : {}), ...(escalations.length ? { escalations } : {}) };
|
|
204
|
+
}
|
|
205
|
+
export function nodeView(n, withResult = true) {
|
|
206
|
+
const end = n.ended_at ?? now();
|
|
207
|
+
const view = {
|
|
208
|
+
id: n.id, kind: n.kind, target: n.target, families: familiesOf(n), mode: n.mode, depth: n.depth, status: n.status,
|
|
209
|
+
parent: n.parent_id, elapsed_s: Math.round((end - (n.started_at ?? n.created_at)) / 1000), task: oneLine(n.task, 100),
|
|
210
|
+
...notesView(n),
|
|
211
|
+
};
|
|
212
|
+
if (n.target && !targetDef(n.target).qualified)
|
|
213
|
+
view.target_label = targetLabel(targetDef(n.target));
|
|
214
|
+
// A Codex session whose latest turn ran with raw network (stage 2): its commands were confined by
|
|
215
|
+
// relay's own sandbox, not Codex's (backends/codex-stage2.ts recordEnforcement). Written only while
|
|
216
|
+
// stage 2 is switched on, so other sessions' views are unchanged.
|
|
217
|
+
const params = sessionParams(n);
|
|
218
|
+
const enforced = params.codex_confinement;
|
|
219
|
+
if (enforced?.enforcement === "relay")
|
|
220
|
+
view.confinement = { by: "relay", turn: enforced.turn, note: "confined by relay: its commands ran in relay's own sandbox, not Codex's" };
|
|
221
|
+
if (Array.isArray(view.escalations) && view.escalations.length)
|
|
222
|
+
view.confinement = { ...(enforced?.enforcement === "relay" ? { by: "relay" } : { enforcement: "unreported" }), scope: "per-turn escalation accounting", note: "Read escalations for each turn's effective scope, launch outcome and cleanup; baseline-only confinement is not claimed." };
|
|
223
|
+
const res = resultNow(n, n.result_json ? JSON.parse(n.result_json) : null);
|
|
224
|
+
const settledNow = !ACTIVE.includes(n.status);
|
|
225
|
+
if (settledNow && n.status !== "open")
|
|
226
|
+
Object.assign(view, { [REPORTED_COMPLETION]: { id: n.id, status: n.status, endedAt: n.ended_at } });
|
|
227
|
+
// A job that changed nothing may have had its empty branch removed; do not advertise it.
|
|
228
|
+
if (n.branch && !(settledNow && removedBranch(res)))
|
|
229
|
+
view.branch = n.branch;
|
|
230
|
+
if (n.error)
|
|
231
|
+
view.error = n.error;
|
|
232
|
+
// While a reviewer's result is withheld, so is the way to its log: someone looking into a slow
|
|
233
|
+
// reviewer would follow that path without meaning to read the review. What it was refused would
|
|
234
|
+
// show where it looked, so that is held back too; its status still says blocked.
|
|
235
|
+
const held = withheld(n, params);
|
|
236
|
+
const outcome = settledNow && !held ? outcomeView(n, res) : null;
|
|
237
|
+
if (outcome)
|
|
238
|
+
Object.assign(view, outcome);
|
|
239
|
+
if (held)
|
|
240
|
+
view.note = held;
|
|
241
|
+
if (n.log_path && !held)
|
|
242
|
+
view.log_path = n.log_path;
|
|
243
|
+
if (n.transcript_path && !held)
|
|
244
|
+
view.transcript_path = n.transcript_path;
|
|
245
|
+
// What it is doing is left out while held, as its log is.
|
|
246
|
+
const live = liveness(n, { activity: !held });
|
|
247
|
+
if (live)
|
|
248
|
+
view.liveness = live;
|
|
249
|
+
if (withResult && settledNow && res && !held)
|
|
250
|
+
view.result = { ...res, ...notesView(n) };
|
|
251
|
+
// The session's turns, read once for its usage, its speed and what is queued.
|
|
252
|
+
const turns = turnReports(n.id);
|
|
253
|
+
const usage = usageOf(n.id, turns);
|
|
254
|
+
if (usage && !held)
|
|
255
|
+
view.usage = usage;
|
|
256
|
+
const speed = speedView(n, turns);
|
|
257
|
+
if (speed)
|
|
258
|
+
view.speed = speed;
|
|
259
|
+
if (withResult && settledNow && !held) {
|
|
260
|
+
const native = nativeResume(n);
|
|
261
|
+
if (native)
|
|
262
|
+
view.resume_natively = native;
|
|
263
|
+
}
|
|
264
|
+
const queued = turns.filter((t) => t.status === "queued").length;
|
|
265
|
+
if (queued)
|
|
266
|
+
view.queued_messages = queued;
|
|
267
|
+
// Every extension the session was given, and whether the person has consented (docs/extensions.md).
|
|
268
|
+
const ext = n.kind === "job" || n.kind === "thread" ? params.extensions : undefined;
|
|
269
|
+
if (ext)
|
|
270
|
+
view.extensions = extensionsView(ext);
|
|
271
|
+
return view;
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* The run as a tree. `built`: the run's items and their views (nodeView, without results) that the
|
|
275
|
+
* caller has just made from the registry after reaping the run, as status does, so that they are
|
|
276
|
+
* not reaped and built a second time; otherwise the run is reaped and read here.
|
|
277
|
+
*/
|
|
278
|
+
export function renderTree(runId, built) {
|
|
279
|
+
if (!built)
|
|
280
|
+
reap(runId);
|
|
281
|
+
const nodes = built?.nodes ?? runNodes(runId);
|
|
282
|
+
const views = built?.views;
|
|
283
|
+
const run = getRun(runId);
|
|
284
|
+
const lines = [`${run.id} ${run.status} ${run.root_cwd}`];
|
|
285
|
+
const open = pendingRequests(runId);
|
|
286
|
+
// Each item's children in the order runNodes gives them.
|
|
287
|
+
const children = new Map();
|
|
288
|
+
nodes.forEach((n, at) => {
|
|
289
|
+
const list = children.get(n.parent_id);
|
|
290
|
+
if (list)
|
|
291
|
+
list.push({ n, at });
|
|
292
|
+
else
|
|
293
|
+
children.set(n.parent_id, [{ n, at }]);
|
|
294
|
+
});
|
|
295
|
+
const walk = (parent, indent) => {
|
|
296
|
+
const kids = children.get(parent) ?? [];
|
|
297
|
+
kids.forEach(({ n, at }, i) => {
|
|
298
|
+
const last = i === kids.length - 1;
|
|
299
|
+
const v = views?.[at] ?? nodeView(n, false);
|
|
300
|
+
const relation = v.families.relation;
|
|
301
|
+
const tag = relation === "cross-family" ? "" : relation === "same-family" ? " [same-family]" : " [family unknown]";
|
|
302
|
+
lines.push(`${indent}${last ? "└─" : "├─"} ${n.id} ${n.kind}${n.target ? `:${targetLabel(targetDef(n.target), n.target)}` : ""}${tag} ${n.mode} d${n.depth} ${n.status}${v.outcome ? ` (${v.outcome})` : ""} ${v.elapsed_s}s ${oneLine(n.task, 60)}`);
|
|
303
|
+
// Every extension the session was given (docs/extensions.md): names from the person's own config.
|
|
304
|
+
const ext = n.kind === "job" || n.kind === "thread" ? sessionParams(n).extensions : undefined;
|
|
305
|
+
if (ext)
|
|
306
|
+
lines.push(`${indent}${last ? " " : "│ "} + extensions: ${extensionsSummary(ext)}`);
|
|
307
|
+
const live = v.liveness;
|
|
308
|
+
if (live) {
|
|
309
|
+
const files = (live.files_touched?.length ?? 0) + (live.files_touched_more ?? 0);
|
|
310
|
+
lines.push(`${indent}${last ? " " : "│ "} · ${live.activity ? `${oneLine(live.activity, 70)}, ` : ""}quiet ${live.quiet_s}s${live.files_touched ? `, ${files} file${files === 1 ? "" : "s"} changed` : ""}`);
|
|
311
|
+
}
|
|
312
|
+
for (const r of open.filter((r) => r.node_id === n.id)) {
|
|
313
|
+
lines.push(`${indent}${last ? " " : "│ "} ! needs approval ${r.id}: ${clipped(r.summary, 80)}`);
|
|
314
|
+
}
|
|
315
|
+
if (n.status === "lost" && n.agent_pgid)
|
|
316
|
+
lines.push(`${indent}${last ? " " : "│ "} ! an agent process (group ${n.agent_pgid}) may still be running`);
|
|
317
|
+
walk(n.id, indent + (last ? " " : "│ "));
|
|
318
|
+
});
|
|
319
|
+
};
|
|
320
|
+
walk(null, "");
|
|
321
|
+
if (nodes.length === 0)
|
|
322
|
+
lines.push("(nothing started yet)");
|
|
323
|
+
return lines.join("\n");
|
|
324
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// Waiting: how long one call may wait, and the wait itself, which lends the caller's slot, reports
|
|
2
|
+
// progress, and returns early for a root session when an approval request needs its agent.
|
|
3
|
+
import { elicitationState, pendingRequests } from "./approvals.js";
|
|
4
|
+
import { ownsRun } from "./caller.js";
|
|
5
|
+
import { busy, getNode, now, runConfig } from "./db.js";
|
|
6
|
+
import { lendSlot } from "./slots.js";
|
|
7
|
+
import { progressLine } from "./views.js";
|
|
8
|
+
import { registryPoll } from "./wake.js";
|
|
9
|
+
import { watchRequests } from "./watch.js";
|
|
10
|
+
/** The longest a status call waits where the host moves long calls to the background (HostView.longWaits, in Instance.host). */
|
|
11
|
+
export const LONG_WAIT_S = 6 * 3600;
|
|
12
|
+
/** How often a waiting call reports progress. RELAY_TICK_MS shortens it for tests. */
|
|
13
|
+
const tickMs = () => Number(process.env.RELAY_TICK_MS) || 15000;
|
|
14
|
+
/**
|
|
15
|
+
* How often a waiting call looks at everything: the item, approval requests (putting new ones to
|
|
16
|
+
* the user), its limit and its progress. Between these looks, a commit by another process to the
|
|
17
|
+
* registry (registryPoll) brings a quick look at what could end the wait now: the item settling,
|
|
18
|
+
* or a request newly filed.
|
|
19
|
+
*/
|
|
20
|
+
const LOOK_MS = 200;
|
|
21
|
+
let waitIds = 0;
|
|
22
|
+
export async function waitUntil(done, opts) {
|
|
23
|
+
const giveBack = lendSlot(opts.lender);
|
|
24
|
+
const start = now();
|
|
25
|
+
let lastTick = start;
|
|
26
|
+
const poll = registryPoll();
|
|
27
|
+
const me = ++waitIds;
|
|
28
|
+
// A launched agent is asking to act outside its sandbox. The user is asked directly where the
|
|
29
|
+
// host allows it; anything they are not being asked about now goes to the calling agent, by
|
|
30
|
+
// returning early, once per request.
|
|
31
|
+
const unasked = (root) => pendingRequests(root.runId).filter((r) => !root.inst.handedOff.has(r.id) && !root.inst.asking.has(r.id) && elicitationState(r.id) !== "asking");
|
|
32
|
+
if (opts.root)
|
|
33
|
+
opts.root.inst.waiting.set(me, { runId: opts.root.runId, items: new Set([...(opts.awaits ?? []), ...(opts.progressOf ? [opts.progressOf] : [])]) });
|
|
34
|
+
try {
|
|
35
|
+
for (;;) {
|
|
36
|
+
if (done())
|
|
37
|
+
return true;
|
|
38
|
+
if (now() - start >= opts.ms)
|
|
39
|
+
return false;
|
|
40
|
+
// The caller no longer wants the answer. Only the wait ends: nothing it was waiting for is touched.
|
|
41
|
+
if (opts.signal?.aborted)
|
|
42
|
+
return false;
|
|
43
|
+
if (opts.root) {
|
|
44
|
+
watchRequests(opts.root.inst);
|
|
45
|
+
// The transport commits the handoff only after this result reaches the caller.
|
|
46
|
+
if (unasked(opts.root).length)
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
if (opts.onTick && now() - lastTick >= tickMs()) {
|
|
50
|
+
lastTick = now();
|
|
51
|
+
let line;
|
|
52
|
+
try {
|
|
53
|
+
line = opts.progressOf ? progressLine(opts.progressOf) : undefined;
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
// Progress only.
|
|
57
|
+
}
|
|
58
|
+
opts.onTick(now() - start, line);
|
|
59
|
+
}
|
|
60
|
+
// Never past the call's limit: a wait that has used it up looks once more and returns.
|
|
61
|
+
const next = Math.min(start + opts.ms, now() + LOOK_MS);
|
|
62
|
+
while (await poll.nap(next - now(), opts.signal)) {
|
|
63
|
+
if (done())
|
|
64
|
+
return true;
|
|
65
|
+
// A request not yet put to the user: the full look puts it to them first, where the host can ask.
|
|
66
|
+
if (opts.root && unasked(opts.root).length)
|
|
67
|
+
break;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
finally {
|
|
72
|
+
opts.root?.inst.waiting.delete(me);
|
|
73
|
+
giveBack();
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
/** Finished: neither queued nor running a turn. */
|
|
77
|
+
export const settled = (id) => {
|
|
78
|
+
const n = getNode(id);
|
|
79
|
+
return !n || !busy(n);
|
|
80
|
+
};
|
|
81
|
+
/**
|
|
82
|
+
* How long one call waits, in seconds: `seconds` (block_s if not given), capped at block_s, or for a
|
|
83
|
+
* status wait (`long`) in a host that moves long calls to the background, at LONG_WAIT_S; and never
|
|
84
|
+
* past the host's own cap (`capS`, HostProfile.waitCapS), whatever else allows.
|
|
85
|
+
*/
|
|
86
|
+
export function waitLimitS(block, seconds, o = {}) {
|
|
87
|
+
const cap = o.long && o.longWaits ? Math.max(block, LONG_WAIT_S) : block;
|
|
88
|
+
return Math.min(seconds ?? block, cap, o.capS ?? Infinity);
|
|
89
|
+
}
|
|
90
|
+
/** A call's wait, as waitLimitS says, and never past the tool call's one shared deadline (w.deadline). */
|
|
91
|
+
export function waitOpts(inst, runId, w, o = {}) {
|
|
92
|
+
const root = inst.ctx.kind === "root";
|
|
93
|
+
const limit = waitLimitS(runConfig(runId).block_s, o.seconds, { long: o.long, longWaits: root && inst.host.longWaits, capS: inst.host.waitCapS });
|
|
94
|
+
// One deadline for the whole tool call: nested waits share it, so together they stay under the
|
|
95
|
+
// host's tool-call timeout. A wait that reaches it gets no time, and the caller returns a pending handle.
|
|
96
|
+
const ms = w.deadline !== undefined ? Math.min(limit * 1000, Math.max(0, w.deadline - now())) : limit * 1000;
|
|
97
|
+
return {
|
|
98
|
+
ms, lender: inst.ctx.kind === "child" ? inst.ctx.nodeId : null, onTick: w.onTick, signal: w.signal,
|
|
99
|
+
progressOf: o.progressOf, awaits: o.awaits, root: inst.ctx.kind === "root" && ownsRun(inst, runId) ? { inst, runId } : undefined,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* A status wait. If relay ended it at its limit, short of the wait_s asked for and before the item
|
|
104
|
+
* finished, the result says so, and how to go on waiting (wait_ended).
|
|
105
|
+
*/
|
|
106
|
+
export async function waitFor(id, seconds, done, opts) {
|
|
107
|
+
const start = now();
|
|
108
|
+
if (await waitUntil(done, opts))
|
|
109
|
+
return {};
|
|
110
|
+
if (seconds * 1000 <= opts.ms || now() - start < opts.ms)
|
|
111
|
+
return {};
|
|
112
|
+
// Whole seconds: a wait clamped to the call's shared deadline can end at any fraction of one.
|
|
113
|
+
return { wait_ended: `Relay ends a wait after ${Math.ceil(opts.ms / 1000)} s here, and ${id} has not finished. Call status with id "${id}" and wait_s again to go on waiting.` };
|
|
114
|
+
}
|