@jbkjr/relay 0.0.0-stage → 1.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/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 +386 -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 +1525 -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 +320 -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 +637 -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 +329 -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 +629 -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 +1502 -0
- package/docs/pinned-codex.md +321 -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
package/dist/core/ops.js
ADDED
|
@@ -0,0 +1,959 @@
|
|
|
1
|
+
import { escalationEnabled } from "./config.js";
|
|
2
|
+
import { escalationDecisionAuthentication } from "./escalation-authority.js";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import { verifyNotice } from "./notices.js";
|
|
5
|
+
import { requestRunsRelayCommand } from "./relay-command.js";
|
|
6
|
+
import { recordStart, addContribution, callerLabel, familiesOf } from "./families.js";
|
|
7
|
+
import { targetDef, targetLabel } from "../targets/index.js";
|
|
8
|
+
import { dirIdentity } from "../confine/index.js";
|
|
9
|
+
import { decide, elicitationState, expireRequests, getRequest, requestView } from "./approvals.js";
|
|
10
|
+
import { noteCall, once } from "./calls.js";
|
|
11
|
+
import { recordEnvironmentRequest } from "./env-broker.js";
|
|
12
|
+
import { canReadItem, canReadRun, UNAVAILABLE, admitExisting, admitExtensions, admitNew, admitSpeed, admitWork, authority, changeSpeed, claimRun, expand, grantOf, knownCaller, liveChild, ownsRun, persistentGrant, publicGrant, refused, subagentRefusal, } from "./caller.js";
|
|
13
|
+
import { loadConfig, networkOn } from "./config.js";
|
|
14
|
+
import { writeWorktreeContext } from "./context.js";
|
|
15
|
+
import { extensionsView, holdsServers, PERSON_ROUTES, personOnly } from "./extensions.js";
|
|
16
|
+
import { ACTIVE, ancestors, busy, cancelledAbove, closeTurns, db, descendants, getNode, getRun, getTurn, insertNode, insertTurn, newId, now, reap, relayProcs, runConfig, runNodes, setParam, speedAfter, tx, turnSettled, updateNode, workerLive, workCwd } from "./db.js";
|
|
17
|
+
import { dispatch, mayDispatch, queueTurn, redispatch } from "./dispatch.js";
|
|
18
|
+
import { groupAlive, sameProcess, stopSupervised } from "./procs.js";
|
|
19
|
+
import { branchChanges, checkpoint, continueMerge, deleteBranchIfMerged, filterRefusal, jobTree, mergeBranch, treeState, worktreeChanges } from "./git.js";
|
|
20
|
+
import { discussionParams, localNetworkKey, reviewParams, sessionParams, speedOf } from "./params.js";
|
|
21
|
+
import { rawNetworkKey } from "./raw-network.js";
|
|
22
|
+
import { stopNodeExecutorsNow } from "./stage2-executors.js";
|
|
23
|
+
import { consultHeader, contextBlock, delegationPreamble } from "./prompts.js";
|
|
24
|
+
import { BLOCKED_NOTE, denialsOf, removedBranch, shownWork } from "./outcome.js";
|
|
25
|
+
import { refusalNote } from "./refusal.js";
|
|
26
|
+
import { recordsReport, sweepTemps } from "./retention.js";
|
|
27
|
+
import { registryBackups } from "./storage.js";
|
|
28
|
+
import { approvalsFor, nodeView, notesView, pendingHandle, renderTree, runRecovery } from "./views.js";
|
|
29
|
+
import { settled, waitFor, waitOpts, waitUntil } from "./wait.js";
|
|
30
|
+
import { checkoutAt, discardJobWorktree, nodeTree, openJobWorktree, retire } from "./worktree.js";
|
|
31
|
+
import { discuss as holdDiscussion, discussionView, LEGACY_NOTE, legacyTwoSided, settleDiscussion } from "../modes/discussion.js";
|
|
32
|
+
import { openReviewOf, review as runReview, reviewOnly, reviewView } from "../modes/review.js";
|
|
33
|
+
// Kept for tests that build a server from ops (broker.ts imports it from core/caller.ts since E16).
|
|
34
|
+
export { newInstance } from "./caller.js";
|
|
35
|
+
/** The task of the topmost item above the node that the registry still has. */
|
|
36
|
+
const rootTaskOf = (node) => ancestors(node, { self: true }).at(-1).task;
|
|
37
|
+
/**
|
|
38
|
+
* Where the person was working, for a new write job's prompt: the caller's position in its checkout,
|
|
39
|
+
* or, for a caller at a job's worktree root (a nested job, which always starts there), the position
|
|
40
|
+
* that job recorded.
|
|
41
|
+
*/
|
|
42
|
+
function subdirFor(wt, parent) {
|
|
43
|
+
if (wt?.subdir)
|
|
44
|
+
return wt.subdir;
|
|
45
|
+
if (!wt || !parent?.worktree)
|
|
46
|
+
return undefined;
|
|
47
|
+
const inherited = sessionParams(parent).subdir;
|
|
48
|
+
return typeof inherited === "string" && inherited ? inherited : undefined;
|
|
49
|
+
}
|
|
50
|
+
/** What a call that gave extensions is told about consent. */
|
|
51
|
+
const EXTENSIONS_NOTE = `The agent starts only once the user consents to these extensions: relay files a request (kind extensions, marked person_only) that only they can allow, ${PERSON_ROUTES}. You may deny it. ` +
|
|
52
|
+
"A session given MCP servers gets no network and no write paths outside its worktree, and may not start or steer other relay agents.";
|
|
53
|
+
/** A turn that is itself read-only cannot cause writes through someone else. */
|
|
54
|
+
const READ_ONLY_START = "your current turn is read-only, so you can start only read-only work. Do the reading yourself or delegate it in read mode, and report what would need changing.";
|
|
55
|
+
export async function delegate(inst, a, w = {}) {
|
|
56
|
+
const seen = await once(inst, "delegate", a, w, () => delegate(inst, a, w), (c) => replay(inst, c, a, w));
|
|
57
|
+
if (seen)
|
|
58
|
+
return seen;
|
|
59
|
+
const admitted = admitNew(inst, { target: a.target, model: a.model, cwd: a.cwd });
|
|
60
|
+
if ("reason" in admitted)
|
|
61
|
+
return refused(admitted.reason);
|
|
62
|
+
const { caller, to } = admitted;
|
|
63
|
+
if (caller.node && caller.access === "read" && a.mode === "write")
|
|
64
|
+
return refused(READ_ONLY_START);
|
|
65
|
+
const cfg = runConfig(caller.runId);
|
|
66
|
+
const g = admitWork(caller, to.target, { mode: a.mode, grant: a.grant, continues: false }, w);
|
|
67
|
+
if ("reason" in g)
|
|
68
|
+
return refused(g.reason);
|
|
69
|
+
const sp = admitSpeed(caller, to.target, { speed: a.speed, model: to.model ?? a.model }, w);
|
|
70
|
+
if ("reason" in sp)
|
|
71
|
+
return refused(sp.reason);
|
|
72
|
+
let ext;
|
|
73
|
+
if (a.extensions) {
|
|
74
|
+
const e = admitExtensions(inst, caller, to.target, { network: networkOn(cfg, g.grant), writePaths: a.mode === "write" && Boolean(g.grant?.write_paths?.length), allowDelegation: a.allow_delegation }, w);
|
|
75
|
+
if ("reason" in e)
|
|
76
|
+
return refused(e.reason);
|
|
77
|
+
ext = e.extensions;
|
|
78
|
+
}
|
|
79
|
+
// A job given MCP servers may not delegate (admitExtensions): an agent it started would not have its limits.
|
|
80
|
+
const allowDelegation = a.allow_delegation !== false && !ext?.mcp_servers.length;
|
|
81
|
+
const id = newId("job");
|
|
82
|
+
let wt = null;
|
|
83
|
+
if (a.mode === "write") {
|
|
84
|
+
const opened = openJobWorktree(caller.cwd, caller.runId, id, cfg.trust_git_filters);
|
|
85
|
+
if ("refusal" in opened)
|
|
86
|
+
return refused(opened.refusal);
|
|
87
|
+
wt = opened;
|
|
88
|
+
}
|
|
89
|
+
const rootTask = caller.node ? rootTaskOf(caller.node) : "(this assignment is the top-level delegated task)";
|
|
90
|
+
const parentTask = caller.node ? caller.node.task : "(the root session; its own task is not known to relay)";
|
|
91
|
+
const canAsk = escalationEnabled(cfg) && !cfg.allow_dangerous;
|
|
92
|
+
let node;
|
|
93
|
+
try {
|
|
94
|
+
// The identity file first: one that cannot be written fails the call before anything is recorded.
|
|
95
|
+
if (wt)
|
|
96
|
+
writeWorktreeContext(wt.worktree, { run_id: caller.runId, node_id: id, depth: caller.depth + 1 });
|
|
97
|
+
// The job, its first turn and the request_id's binding are committed together (review X1): a
|
|
98
|
+
// repeat finds either the whole job, ready to run, or nothing, and then starts it afresh.
|
|
99
|
+
node = tx(() => {
|
|
100
|
+
const n = insertNode({
|
|
101
|
+
id, run_id: caller.runId, parent_id: caller.node?.id ?? null, kind: "job", target: to.target, mode: a.mode,
|
|
102
|
+
depth: caller.depth + 1, allow_delegation: allowDelegation ? 1 : 0, task: a.task,
|
|
103
|
+
cwd: wt ? wt.worktree : caller.cwd, repo: wt?.repo ?? null, worktree: wt?.worktree ?? null, branch: wt?.branch ?? null,
|
|
104
|
+
// A harness of several families' models keeps the model its family was judged by, for every turn.
|
|
105
|
+
base_sha: wt?.baseSha ?? null, model: to.model ?? a.model ?? null, effort: a.effort ?? null,
|
|
106
|
+
// subdir: where the caller was in its checkout, which the prompt names. worktree_pin: the
|
|
107
|
+
// worktree as relay just made it, which a relay-enforced turn checks is still the same directory.
|
|
108
|
+
params_json: JSON.stringify({
|
|
109
|
+
scope: a.scope ?? null, grant: persistentGrant(g.grant), speed: sp.speed,
|
|
110
|
+
...(subdirFor(wt, caller.node) ? { subdir: subdirFor(wt, caller.node) } : {}),
|
|
111
|
+
...(wt ? { worktree_pin: dirIdentity(wt.worktree) } : {}),
|
|
112
|
+
...(ext ? { extensions: ext } : {}),
|
|
113
|
+
}),
|
|
114
|
+
});
|
|
115
|
+
recordStart(id, inst, w, to.target, n.model, cfg);
|
|
116
|
+
const firstTurn = insertTurn(id, "caller", delegationPreamble(n, cfg, rootTask, parentTask, a.scope, g.grant, canAsk, ext) + a.task, a.mode);
|
|
117
|
+
recordEnvironmentRequest(firstTurn, g.grant?.env);
|
|
118
|
+
noteCall(inst, a, id);
|
|
119
|
+
return n;
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
catch (err) {
|
|
123
|
+
// Nothing was recorded, so the worktree and branch made for the job belong to nothing.
|
|
124
|
+
if (wt)
|
|
125
|
+
discardJobWorktree(wt, cfg.trust_git_filters);
|
|
126
|
+
throw err;
|
|
127
|
+
}
|
|
128
|
+
const notStarted = dispatch(id);
|
|
129
|
+
const started = {
|
|
130
|
+
job_id: id, ...runRecovery(caller.runId), target: to.target, families: familiesOf(getNode(id)), mode: a.mode, depth: node.depth,
|
|
131
|
+
...(!targetDef(to.target).qualified ? { target_label: targetLabel(targetDef(to.target)) } : {}),
|
|
132
|
+
...(g.grant ? { grant: publicGrant(g.grant) } : {}),
|
|
133
|
+
...(ext ? { extensions: extensionsView(ext, { consent: false }), extensions_note: EXTENSIONS_NOTE } : {}),
|
|
134
|
+
// The shape status gives it (views.ts speedView): what was requested, since no harness says what tier served a turn.
|
|
135
|
+
...(sp.speed !== "standard" ? { speed: { requested: sp.speed } } : {}),
|
|
136
|
+
};
|
|
137
|
+
if (wt) {
|
|
138
|
+
started.branch = wt.branch;
|
|
139
|
+
started.base_sha = wt.baseSha;
|
|
140
|
+
if (wt.callerDirty)
|
|
141
|
+
started.note = "The job's worktree was branched from your HEAD commit. Your uncommitted changes are not visible to it.";
|
|
142
|
+
}
|
|
143
|
+
if (notStarted)
|
|
144
|
+
return { ...started, status: "queued", warning: notStarted };
|
|
145
|
+
if (a.background !== false)
|
|
146
|
+
return { ...started, status: "queued" };
|
|
147
|
+
const done = await waitUntil(() => settled(id), waitOpts(inst, caller.runId, w, { progressOf: id }));
|
|
148
|
+
if (!done)
|
|
149
|
+
return pendingHandle(id, started, inst);
|
|
150
|
+
const view = nodeView(getNode(id));
|
|
151
|
+
// A job that changed nothing may no longer have the branch announced when it started.
|
|
152
|
+
if (removedBranch(view.result ?? null))
|
|
153
|
+
delete started.branch;
|
|
154
|
+
return { ...started, ...view, ...runRecovery(caller.runId) };
|
|
155
|
+
}
|
|
156
|
+
/** The session doing the work a discussion or review waits on: the participant, or the reviewer job. */
|
|
157
|
+
function awaitedPart(n) {
|
|
158
|
+
if (n.kind === "discussion")
|
|
159
|
+
return discussionParams(n).participant;
|
|
160
|
+
const p = reviewParams(n);
|
|
161
|
+
return p.discussion && p.discussion !== "opening" ? (getNode(p.discussion) ? discussionParams(getNode(p.discussion)).participant : p.reviewer) : p.reviewer;
|
|
162
|
+
}
|
|
163
|
+
export async function status(inst, a, w = {}) {
|
|
164
|
+
// Check the pointer before any lookup, wait, reap or redispatch requested by untrusted text.
|
|
165
|
+
// Verification is a separate read: only the returned event tells the model what to call next.
|
|
166
|
+
if (a.notice)
|
|
167
|
+
return { notice_verification: verifyNotice(inst, a.notice) };
|
|
168
|
+
if (a.id && !canReadItem(inst, a.id))
|
|
169
|
+
return UNAVAILABLE();
|
|
170
|
+
if (!a.id) {
|
|
171
|
+
const runId = inst.ctx.kind === "child" ? inst.ctx.runId : inst.runId;
|
|
172
|
+
if (runId && !canReadRun(inst, runId))
|
|
173
|
+
return UNAVAILABLE();
|
|
174
|
+
if (!runId)
|
|
175
|
+
return { run_id: null, nodes: [], note: "Nothing has been started from this session yet." };
|
|
176
|
+
reap(runId);
|
|
177
|
+
// One reading of the run serves the item list and the tree, each item's view built once.
|
|
178
|
+
const nodes = runNodes(runId);
|
|
179
|
+
const views = nodes.map((n) => nodeView(n, false));
|
|
180
|
+
return { ...runRecovery(runId, nodes.length), run_status: getRun(runId)?.status, nodes: views, tree: renderTree(runId, { nodes, views }), ...approvalsFor(runId, inst) };
|
|
181
|
+
}
|
|
182
|
+
if (a.id.startsWith("run_")) {
|
|
183
|
+
if (!getRun(a.id))
|
|
184
|
+
return { error: `unknown run ${a.id}` };
|
|
185
|
+
return { ...runRecovery(a.id), run_status: getRun(a.id).status, nodes: runNodes(a.id).map((n) => nodeView(n, false)), tree: renderTree(a.id), ...approvalsFor(a.id, inst) };
|
|
186
|
+
}
|
|
187
|
+
const node = getNode(a.id);
|
|
188
|
+
if (!node)
|
|
189
|
+
return { error: `unknown id ${a.id}` };
|
|
190
|
+
reap(node.run_id);
|
|
191
|
+
// Work its call committed but could not start is started now (review X1), by a session of the run
|
|
192
|
+
// only, so that its worker runs with that session's environment as the first call's would have.
|
|
193
|
+
const notStarted = mayDispatch(inst, node.run_id) && !legacyTwoSided(node) ? redispatch(node.kind === "discussion" || node.kind === "review" ? awaitedPart(node) : node.id) : null;
|
|
194
|
+
if (notStarted)
|
|
195
|
+
return { ...nodeView(getNode(node.id)), warning: notStarted, ...approvalsFor(node.run_id, inst) };
|
|
196
|
+
if (legacyTwoSided(node)) {
|
|
197
|
+
const fresh = getNode(node.id);
|
|
198
|
+
return { ...nodeView(fresh), note: LEGACY_NOTE, children: descendants(fresh.id).map((n) => nodeView(n, false)), ...approvalsFor(fresh.run_id, inst) };
|
|
199
|
+
}
|
|
200
|
+
// A discussion or review has nothing running of its own: what can be waited for is the other agent's part in it.
|
|
201
|
+
if (node.kind === "discussion" || node.kind === "review") {
|
|
202
|
+
const part = () => {
|
|
203
|
+
const now_ = getNode(node.id);
|
|
204
|
+
if (now_.kind === "discussion")
|
|
205
|
+
return settleDiscussion(now_.id);
|
|
206
|
+
const p = reviewParams(now_);
|
|
207
|
+
return p.discussion ? settleDiscussion(p.discussion) : settled(p.reviewer);
|
|
208
|
+
};
|
|
209
|
+
const ended = a.wait_s && a.wait_s > 0 ? await waitFor(a.id, a.wait_s, part, waitOpts(inst, node.run_id, w, { seconds: a.wait_s, long: true, progressOf: awaitedPart(node), awaits: [node.id] })) : (part(), {});
|
|
210
|
+
if (!canReadItem(inst, node.id))
|
|
211
|
+
return UNAVAILABLE();
|
|
212
|
+
const view = node.kind === "discussion" ? discussionView(node.id) : reviewView(node.id);
|
|
213
|
+
return { ...view, ...ended, children: descendants(node.id).map((n) => nodeView(n, false)), ...approvalsFor(node.run_id, inst) };
|
|
214
|
+
}
|
|
215
|
+
const ended = a.wait_s && a.wait_s > 0 ? await waitFor(a.id, a.wait_s, () => settled(a.id), waitOpts(inst, node.run_id, w, { seconds: a.wait_s, long: true, progressOf: node.id })) : {};
|
|
216
|
+
if (!canReadItem(inst, node.id))
|
|
217
|
+
return UNAVAILABLE();
|
|
218
|
+
const fresh = getNode(a.id);
|
|
219
|
+
return { ...nodeView(fresh), ...ended, children: descendants(fresh.id).map((n) => nodeView(n, false)), ...approvalsFor(fresh.run_id, inst) };
|
|
220
|
+
}
|
|
221
|
+
export function result(inst, a) {
|
|
222
|
+
if (inst && !canReadItem(inst, a.job_id))
|
|
223
|
+
return UNAVAILABLE();
|
|
224
|
+
const node = getNode(a.job_id);
|
|
225
|
+
if (!node)
|
|
226
|
+
return { error: `unknown id ${a.job_id}` };
|
|
227
|
+
reap(node.run_id);
|
|
228
|
+
const fresh = getNode(a.job_id);
|
|
229
|
+
if (legacyTwoSided(fresh))
|
|
230
|
+
return { ...nodeView(fresh), note: LEGACY_NOTE };
|
|
231
|
+
if (fresh.kind === "discussion") {
|
|
232
|
+
settleDiscussion(fresh.id);
|
|
233
|
+
return discussionView(fresh.id);
|
|
234
|
+
}
|
|
235
|
+
if (fresh.kind === "review") {
|
|
236
|
+
const p = reviewParams(fresh);
|
|
237
|
+
if (p.discussion)
|
|
238
|
+
settleDiscussion(p.discussion);
|
|
239
|
+
return reviewView(fresh.id);
|
|
240
|
+
}
|
|
241
|
+
if (ACTIVE.includes(fresh.status))
|
|
242
|
+
return { ...nodeView(fresh), note: "Not finished yet. Use status with wait_s to wait." };
|
|
243
|
+
const open = descendants(fresh.id).filter((n) => busy(n)).map((n) => n.id);
|
|
244
|
+
return { ...nodeView(fresh), ...(open.length ? { children_still_running: open } : {}) };
|
|
245
|
+
}
|
|
246
|
+
export function resume(inst, a, w = {}) {
|
|
247
|
+
if (!canReadItem(inst, a.job_id))
|
|
248
|
+
return UNAVAILABLE();
|
|
249
|
+
const node = getNode(a.job_id);
|
|
250
|
+
if (!node || node.kind !== "job")
|
|
251
|
+
return { error: `${a.job_id} is not a job` };
|
|
252
|
+
const caller = admitExisting(inst, node, "resume");
|
|
253
|
+
if ("reason" in caller)
|
|
254
|
+
return refused(caller.reason);
|
|
255
|
+
const unknown = knownCaller(inst);
|
|
256
|
+
if (unknown)
|
|
257
|
+
return refused(unknown);
|
|
258
|
+
const review = openReviewOf(node);
|
|
259
|
+
if (review)
|
|
260
|
+
return refused(reviewOnly(node, review, "resume"));
|
|
261
|
+
const g = admitWork(caller, node.target, { mode: node.mode, grant: a.grant, kept: grantOf(node), continues: true, servers: holdsServers(node), worktree: node.worktree ?? workCwd(node) }, w);
|
|
262
|
+
if ("reason" in g)
|
|
263
|
+
return refused(g.reason);
|
|
264
|
+
// The job goes on at its own speed unless the call names one; a launched agent may not carry on a job faster than itself.
|
|
265
|
+
const sp = admitSpeed(caller, node.target, { speed: a.speed, current: speedAfter(node), model: node.model }, w);
|
|
266
|
+
if ("reason" in sp)
|
|
267
|
+
return refused(sp.reason);
|
|
268
|
+
if (node.status === "cancelled") {
|
|
269
|
+
// Cancel, then resume, is how a job is redirected at once. It works once the cancel has finished.
|
|
270
|
+
if (cancelledAbove(node))
|
|
271
|
+
return refused(`${a.job_id} sits under something that was cancelled, so it cannot be resumed. Start a new job instead.`);
|
|
272
|
+
if (workerLive(node) || groupAlive(node.agent_pgid))
|
|
273
|
+
return refused(`${a.job_id} is still stopping after its cancel. Try again in a moment.`);
|
|
274
|
+
db().prepare("UPDATE nodes SET status = 'done', error = NULL WHERE id = ? AND status = 'cancelled'").run(node.id);
|
|
275
|
+
}
|
|
276
|
+
let message = a.message;
|
|
277
|
+
if (g.grant?.network || g.grant?.write_paths?.length) {
|
|
278
|
+
const extras = [g.grant.network ? "network access" : "", g.grant.local_network ? "this Mac's loopback and the local network, once the user consents" : "", g.grant.raw_network ? "raw network from your shell (TCP, UDP, ssh, DNS) inside relay's sandbox, once the user consents" : "", ...(g.grant.write_paths ?? []).map((p) => `write access to ${p}`)].filter(Boolean);
|
|
279
|
+
message = `[relay] You have now been granted: ${extras.join("; ")}.\n\n${a.message}`;
|
|
280
|
+
}
|
|
281
|
+
// The grant, the message and the requeue together: the job's worker sees all of them or none.
|
|
282
|
+
const { turnId, wasActive } = tx(() => {
|
|
283
|
+
// The grant replaces the job's previous one and applies from its next turn; the speed, from the turn this queues.
|
|
284
|
+
if (g.grant) {
|
|
285
|
+
setParam(node.id, "grant", persistentGrant(g.grant));
|
|
286
|
+
// Consent to local network is for the grant it was given under (session.ts localNetworkConsent).
|
|
287
|
+
const given = sessionParams(node).local_network_consent;
|
|
288
|
+
if (given && (!g.grant.local_network || localNetworkKey(g.grant) !== given.grant))
|
|
289
|
+
setParam(node.id, "local_network_consent", null);
|
|
290
|
+
// Consent to raw network is for the grant it was given under (raw-network.ts rawNetworkConsent; review r_17565c33 C4).
|
|
291
|
+
const raw = sessionParams(node).raw_network_consent;
|
|
292
|
+
if (raw && (!g.grant.raw_network || rawNetworkKey(g.grant) !== raw.grant))
|
|
293
|
+
setParam(node.id, "raw_network_consent", null);
|
|
294
|
+
}
|
|
295
|
+
addContribution(node.id, callerLabel(inst, w));
|
|
296
|
+
const q = queueTurn(node.id, "caller", message, node.mode);
|
|
297
|
+
recordEnvironmentRequest(q.turnId, g.grant?.env);
|
|
298
|
+
changeSpeed(node.id, q.turnId, sp.speed);
|
|
299
|
+
return q;
|
|
300
|
+
});
|
|
301
|
+
const notStarted = dispatch(node.id);
|
|
302
|
+
return {
|
|
303
|
+
job_id: node.id, families: familiesOf(getNode(node.id)), turn_id: turnId, status: wasActive ? "queued_behind_current_turn" : "queued",
|
|
304
|
+
note: wasActive ? "The job is mid-turn. Your message will be delivered as its next turn when the current one ends." : "The job is continuing with your message.",
|
|
305
|
+
...(notStarted ? { warning: notStarted } : {}),
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
/** inst is null when the user cancels from a terminal. */
|
|
309
|
+
export async function cancel(inst, a) {
|
|
310
|
+
if (inst && !canReadItem(inst, a.id))
|
|
311
|
+
return UNAVAILABLE();
|
|
312
|
+
if (inst?.ctx.kind === "poisoned")
|
|
313
|
+
return refused(`relay context for this agent could not be loaded (${inst.ctx.reason}).`);
|
|
314
|
+
const me = inst?.ctx.kind === "child" ? inst.ctx : null;
|
|
315
|
+
let caller = null;
|
|
316
|
+
if (me) {
|
|
317
|
+
caller = liveChild(me);
|
|
318
|
+
if (!caller)
|
|
319
|
+
return refused("the turn this relay connection belonged to has ended, so it can no longer cancel anything.");
|
|
320
|
+
if (a.id.startsWith("run_"))
|
|
321
|
+
return refused("only the root session or the user can cancel a whole run. You can cancel work that you started.");
|
|
322
|
+
}
|
|
323
|
+
let nodes;
|
|
324
|
+
let runId;
|
|
325
|
+
// A session cancels only in runs it owns; the administrative terminal is not bound by this.
|
|
326
|
+
const foreignRun = (id) => (inst?.ctx.kind === "root" ? claimRun(inst, id) : null);
|
|
327
|
+
if (a.id.startsWith("run_")) {
|
|
328
|
+
if (!getRun(a.id))
|
|
329
|
+
return { error: `unknown run ${a.id}` };
|
|
330
|
+
const no = foreignRun(a.id);
|
|
331
|
+
if (no)
|
|
332
|
+
return refused(`${a.id} cannot be cancelled from this session: ${no}.`);
|
|
333
|
+
runId = a.id;
|
|
334
|
+
db().prepare("UPDATE runs SET status = 'cancelled' WHERE id = ?").run(runId);
|
|
335
|
+
nodes = runNodes(runId);
|
|
336
|
+
}
|
|
337
|
+
else {
|
|
338
|
+
const node = getNode(a.id);
|
|
339
|
+
if (!node)
|
|
340
|
+
return { error: `unknown id ${a.id}` };
|
|
341
|
+
const no = caller ? authority(caller, node, "cancel") : foreignRun(node.run_id);
|
|
342
|
+
if (no)
|
|
343
|
+
return refused(caller ? no : `${a.id} cannot be cancelled from this session: ${no}.`);
|
|
344
|
+
runId = node.run_id;
|
|
345
|
+
nodes = [node, ...descendants(node.id)];
|
|
346
|
+
}
|
|
347
|
+
// A discussion being cancelled may be waiting on a reply from a session it did not start. Its
|
|
348
|
+
// turn there (source discussion:<id>) is dropped while it is still queued, whatever else the
|
|
349
|
+
// session has queued or running. Only once the session is running that turn is the session stopped
|
|
350
|
+
// with the discussion (it can be resumed afterwards). Only where the caller could cancel that
|
|
351
|
+
// session directly: otherwise the discussion is closed and the reply simply goes unread.
|
|
352
|
+
const borrowedParts = [];
|
|
353
|
+
for (const d of nodes.filter((n) => n.kind === "discussion" && n.status === "open")) {
|
|
354
|
+
const p = discussionParams(d);
|
|
355
|
+
const part = p.borrowed ? getNode(p.participant) : undefined;
|
|
356
|
+
if (!part || nodes.some((n) => n.id === part.id) || (caller && authority(caller, part, "cancel")))
|
|
357
|
+
continue;
|
|
358
|
+
borrowedParts.push({ discussion: d.id, part });
|
|
359
|
+
}
|
|
360
|
+
// Dead workers are marked lost first, and agents left without one are stopped.
|
|
361
|
+
reap(runId);
|
|
362
|
+
const grace = runConfig(runId).cancel_grace_ms;
|
|
363
|
+
/** Worker pid and agent group leader, each with the start time recorded for it, so a later signal goes only to the same process. */
|
|
364
|
+
const workers = new Map();
|
|
365
|
+
const groups = new Map();
|
|
366
|
+
const groupWorkers = new Map();
|
|
367
|
+
/** Agent groups with no live worker to stop them cleanly. */
|
|
368
|
+
const unsupervised = new Set();
|
|
369
|
+
const cancelled = [];
|
|
370
|
+
const signalled = new Map();
|
|
371
|
+
tx(() => {
|
|
372
|
+
// Classified in the transaction that cancels: the session's worker starts a turn only if it is
|
|
373
|
+
// still queued (runSessionTurn), so it either started the turn before this, and is stopped with
|
|
374
|
+
// it, or never starts it.
|
|
375
|
+
for (const { discussion, part } of borrowedParts) {
|
|
376
|
+
const own = db().prepare("SELECT id, status FROM turns WHERE node_id = ? AND source = ? AND status IN ('queued', 'running')").all(part.id, `discussion:${discussion}`);
|
|
377
|
+
if (own.some((t) => t.status === "running"))
|
|
378
|
+
nodes.push(part);
|
|
379
|
+
else
|
|
380
|
+
for (const t of own)
|
|
381
|
+
db().prepare("UPDATE turns SET status = 'cancelled', ended_at = ? WHERE id = ? AND status = 'queued'").run(now(), t.id);
|
|
382
|
+
}
|
|
383
|
+
for (const stale of nodes) {
|
|
384
|
+
const n = getNode(stale.id);
|
|
385
|
+
db().prepare("UPDATE turns SET status = 'cancelled', ended_at = ? WHERE node_id = ? AND status = 'queued'").run(now(), n.id);
|
|
386
|
+
// A discussion or review that is open has nothing running; it is simply closed.
|
|
387
|
+
if (n.status === "open") {
|
|
388
|
+
updateNode(n.id, { status: "cancelled", ended_at: now(), result_json: JSON.stringify({ outcome: "cancelled" }) });
|
|
389
|
+
if (n.kind === "discussion") {
|
|
390
|
+
const reviewId = discussionParams(n).review_id;
|
|
391
|
+
const review = reviewId ? getNode(reviewId) : undefined;
|
|
392
|
+
const reconciliation = review ? reviewParams(review).discussion : undefined;
|
|
393
|
+
if (review?.status === "open" && (!reconciliation || reconciliation === "opening" || reconciliation === n.id)) {
|
|
394
|
+
updateNode(review.id, { status: "cancelled", ended_at: now(), result_json: JSON.stringify({ outcome: "cancelled", discussion_id: n.id, reason: "reconciliation cancelled" }) });
|
|
395
|
+
cancelled.push(review.id);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
cancelled.push(n.id);
|
|
399
|
+
continue;
|
|
400
|
+
}
|
|
401
|
+
// Only nodes that are active right now are signalled: a pid recorded on a finished node
|
|
402
|
+
// could since have been reused by an unrelated process.
|
|
403
|
+
if (!ACTIVE.includes(n.status))
|
|
404
|
+
continue;
|
|
405
|
+
updateNode(n.id, { status: "cancelled", ended_at: now() });
|
|
406
|
+
// The turn in progress ends here and now, in the same transaction: its relay connection
|
|
407
|
+
// loses its authority at once, and nothing done later in this cancel can touch a turn that
|
|
408
|
+
// a resume starts in the meantime.
|
|
409
|
+
closeTurns(n.id, "cancelled", "cancelled");
|
|
410
|
+
expireRequests(n.id);
|
|
411
|
+
cancelled.push(n.id);
|
|
412
|
+
const supervised = Boolean(n.worker_pid && n.worker_pid > 1 && sameProcess(n.worker_pid, n.worker_start));
|
|
413
|
+
if (supervised)
|
|
414
|
+
workers.set(n.worker_pid, n.worker_start);
|
|
415
|
+
if (n.agent_pgid && n.agent_pgid > 1) {
|
|
416
|
+
groups.set(n.agent_pgid, n.agent_pid === n.agent_pgid ? n.agent_start : null);
|
|
417
|
+
if (supervised)
|
|
418
|
+
groupWorkers.set(n.agent_pgid, n.worker_pid);
|
|
419
|
+
if (!supervised)
|
|
420
|
+
unsupervised.add(n.agent_pgid);
|
|
421
|
+
}
|
|
422
|
+
signalled.set(n.id, { worker: n.worker_pid, group: n.agent_pgid });
|
|
423
|
+
}
|
|
424
|
+
});
|
|
425
|
+
const { stillOurs, refused: groupRefusals } = await stopSupervised({ workers, groups, groupWorkers, unsupervised, graceMs: grace, spared: relayProcs });
|
|
426
|
+
const refusedWorkers = new Set([...groupRefusals.keys()].map(g => groupWorkers.get(g)));
|
|
427
|
+
// Clear only what this cancel signalled: the item may already have been resumed under a new worker.
|
|
428
|
+
for (const [id, was] of signalled) {
|
|
429
|
+
if (was.group !== null && groupRefusals.has(was.group))
|
|
430
|
+
continue;
|
|
431
|
+
if (was.worker !== null && !refusedWorkers.has(was.worker))
|
|
432
|
+
db().prepare("UPDATE nodes SET worker_pid = NULL, worker_start = NULL WHERE id = ? AND worker_pid IS ?").run(id, was.worker);
|
|
433
|
+
if (was.group !== null && !stillOurs(was.group)) {
|
|
434
|
+
db().prepare("UPDATE nodes SET agent_pid = NULL, agent_pgid = NULL, agent_start = NULL WHERE id = ? AND agent_pgid IS ?").run(id, was.group);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
// Stage 2: an executor whose worker had to be killed (or died) is stopped here, after its app
|
|
438
|
+
// server. One whose worker is still alive is that worker's to stop (a resumed turn's, say).
|
|
439
|
+
// An app group that did not exit may still reconnect to its executor's port: the executor is
|
|
440
|
+
// still stopped, but its record and leases stay quarantined, as after a refusal (reap does the same).
|
|
441
|
+
const executorNotes = [...signalled].filter(([, was]) => was.group === null || !groupRefusals.has(was.group))
|
|
442
|
+
.map(([id, was]) => stopNodeExecutorsNow(id, undefined, was.group !== null && stillOurs(was.group) ? `untraceable app-server cleanup: process group ${was.group} did not exit` : undefined).trim()).filter(Boolean);
|
|
443
|
+
const survivors = [...groups.keys()].filter((g) => stillOurs(g));
|
|
444
|
+
const unstopped = survivors.filter(g => !groupRefusals.has(g));
|
|
445
|
+
const warning = [...groupRefusals.values(), ...(unstopped.length ? [`process group(s) ${unstopped.join(", ")} did not exit`] : []), ...executorNotes].join("; ");
|
|
446
|
+
return {
|
|
447
|
+
cancelled, killed_process_groups: groups.size - survivors.length, run_cancelled: a.id.startsWith("run_"),
|
|
448
|
+
...(warning ? { warning } : {}),
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* The person's choices when merge will not take work that no result showed. `obj`: what the work is
|
|
453
|
+
* called ("them", the changes; "it", the work); `look`: where to look at it; `root`: whether the
|
|
454
|
+
* caller is the root session, the only one that may merge it anyway.
|
|
455
|
+
*/
|
|
456
|
+
function unshownChoices(job, look, obj, worktree, root) {
|
|
457
|
+
const as = obj === "them" ? "as they are" : "as it is";
|
|
458
|
+
const take = worktree ? `commits what is in the worktree to ${job.branch} and merges the branch as it then is` : `merges ${job.branch} as it is`;
|
|
459
|
+
const anyway = root
|
|
460
|
+
? `or, if the user wants ${obj} merged ${as}, call merge again with include_changes_since_result: true, which ${take}`
|
|
461
|
+
: `or report this to whoever started you: only the root session can merge ${obj} ${as}`;
|
|
462
|
+
return `${look}; resume the job, whose next turn commits ${obj} and ends with a result that shows ${obj}; ${anyway}.`;
|
|
463
|
+
}
|
|
464
|
+
/** Merge's refusal when the job's worktree or branch holds more than the commit its result showed. */
|
|
465
|
+
function changedRefusal(job, commit, c, where, root) {
|
|
466
|
+
const listed = c.files.length > 20 ? `${c.files.slice(0, 20).join(", ")} and ${c.files.length - 20} more` : c.files.join(", ");
|
|
467
|
+
const what = where === "branch"
|
|
468
|
+
? `${job.id}'s branch ${job.branch} has moved since the end of the turn its result is from: that result's diff summary is of commit ${commit}, and the branch is now at ${c.now}. ` +
|
|
469
|
+
"Something was committed to it after that turn: relay clean commits what it finds in a worktree before removing it, which may be the work of a process the job started"
|
|
470
|
+
: `${job.id}'s worktree has changed since the end of the turn its result is from: that result's diff summary is of commit ${commit}, and the worktree ` +
|
|
471
|
+
`${c.now === commit ? "has uncommitted changes" : c.uncommitted ? `is now at commit ${c.now}, with uncommitted changes` : `is now at commit ${c.now}`}. ` +
|
|
472
|
+
"A process the job started may still be running there, or a later turn of the job may have been stopped before it ended";
|
|
473
|
+
const look = where === "branch" ? `Look at them with git diff ${commit} ${c.now}` : `Look at them in ${job.worktree}`;
|
|
474
|
+
return {
|
|
475
|
+
...refused(`nothing was merged, because ${what}. Changed since that commit: ${listed || "(git listed no file)"}. ${unshownChoices(job, look, "them", where === "worktree", root)}`),
|
|
476
|
+
job_id: job.id, branch: job.branch, result_commit: commit, now_at: c.now, uncommitted: c.uncommitted, changed_files: c.files, diff_stat: c.stat,
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
export function merge(inst, a) {
|
|
480
|
+
if (!canReadItem(inst, a.job_id))
|
|
481
|
+
return UNAVAILABLE();
|
|
482
|
+
if (inst.ctx.kind === "poisoned")
|
|
483
|
+
return refused(`relay context for this agent could not be loaded (${inst.ctx.reason}).`);
|
|
484
|
+
const ctx = inst.ctx.kind === "child" ? inst.ctx : null;
|
|
485
|
+
const child = ctx ? liveChild(ctx) : null;
|
|
486
|
+
const me = child?.node ?? null;
|
|
487
|
+
if (ctx) {
|
|
488
|
+
if (!child)
|
|
489
|
+
return refused("the turn this relay connection belonged to has ended, so it can no longer merge.");
|
|
490
|
+
if (ctx.access !== "write")
|
|
491
|
+
return refused("your current turn is read-only, so you cannot merge. Report the branch name to whoever started you.");
|
|
492
|
+
if (a.cwd)
|
|
493
|
+
return refused("cwd can only be set by the root session.");
|
|
494
|
+
// Merging work that no result showed is the user's call, as merging into their checkout is.
|
|
495
|
+
if (a.include_changes_since_result) {
|
|
496
|
+
return refused("include_changes_since_result can only be set by the root session. Resume the job, so that its next turn ends with a result that shows its work, or report what merge said to whoever started you.");
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
const job = getNode(a.job_id);
|
|
500
|
+
if (!job || !job.branch)
|
|
501
|
+
return { error: `${a.job_id} is not a write job with a branch` };
|
|
502
|
+
if (!ctx) {
|
|
503
|
+
// Merging removes the job's worktree and can commit in it, so it follows the same ownership as resume.
|
|
504
|
+
const foreign = claimRun(inst, job.run_id);
|
|
505
|
+
if (foreign)
|
|
506
|
+
return refused(`${a.job_id} cannot be merged from this session: ${foreign}. Its branch ${job.branch} can still be merged with git.`);
|
|
507
|
+
}
|
|
508
|
+
if (child) {
|
|
509
|
+
const no = authority(child, job, "merge");
|
|
510
|
+
if (no)
|
|
511
|
+
return refused(no);
|
|
512
|
+
}
|
|
513
|
+
if (ACTIVE.includes(job.status))
|
|
514
|
+
return refused(`${a.job_id} is still ${job.status}. Wait for it with status, then merge.`);
|
|
515
|
+
if (removedBranch(JSON.parse(job.result_json ?? "{}")))
|
|
516
|
+
return { job_id: job.id, status: "up_to_date", outcome: "no_changes", note: "The job has no changes to merge." };
|
|
517
|
+
// Where the branch goes: a launched agent's own worktree, or the root's checkout.
|
|
518
|
+
const into = checkoutAt(me?.worktree ?? (a.cwd ? expand(a.cwd) : inst.cwd));
|
|
519
|
+
if (!into)
|
|
520
|
+
return { error: "the current directory is not inside a git repository" };
|
|
521
|
+
if ("error" in into)
|
|
522
|
+
return { job_id: job.id, branch: job.branch, status: "error", error: `nothing was merged: ${into.error}` };
|
|
523
|
+
const trust = runConfig(job.run_id).trust_git_filters;
|
|
524
|
+
if (a.continue)
|
|
525
|
+
return { job_id: job.id, branch: job.branch, ...afterMerge(job, continueMerge(into.at, trust)) };
|
|
526
|
+
const out = { job_id: job.id, branch: job.branch };
|
|
527
|
+
const worktree = job.worktree && fs.existsSync(job.worktree) ? job.worktree : null;
|
|
528
|
+
// Every git command for the job's worktree runs with the git directory the repository records for it.
|
|
529
|
+
const tree = worktree ? nodeTree(job) : null;
|
|
530
|
+
if (tree && "error" in tree)
|
|
531
|
+
return { ...out, status: "error", error: `nothing was merged, because relay will not run git in ${job.id}'s worktree: ${tree.error} (worktree: ${worktree})` };
|
|
532
|
+
// What merge takes is what the job's result showed: the commit its diff summary is of, and only
|
|
533
|
+
// while the worktree (or, once that is gone, the branch) holds nothing more. A process the job
|
|
534
|
+
// started can outlive its turn and go on writing there; include_changes_since_result is the
|
|
535
|
+
// user's say-so to take that too.
|
|
536
|
+
const shown = a.include_changes_since_result ? null : shownWork(job);
|
|
537
|
+
let commit;
|
|
538
|
+
let note;
|
|
539
|
+
if (shown && "unshown" in shown) {
|
|
540
|
+
const look = tree ? `Look at it in ${worktree}` : `Look at it on ${job.branch} (git log ${job.base_sha ? `${job.base_sha}..` : ""}${job.branch})`;
|
|
541
|
+
return { ...refused(`nothing was merged, because ${shown.unshown}, and merging now would commit it and merge it unseen. ${unshownChoices(job, look, "it", Boolean(tree), !ctx)}`), ...out };
|
|
542
|
+
}
|
|
543
|
+
if (shown && "commit" in shown) {
|
|
544
|
+
let changes;
|
|
545
|
+
if (tree) {
|
|
546
|
+
// `git status` can run the clean filter.
|
|
547
|
+
const filters = filterRefusal(tree, trust);
|
|
548
|
+
if (filters)
|
|
549
|
+
return { ...out, status: "error", error: `nothing was merged, because ${filters}` };
|
|
550
|
+
changes = worktreeChanges(tree, shown.commit);
|
|
551
|
+
}
|
|
552
|
+
else {
|
|
553
|
+
changes = branchChanges(into.at, job.branch, shown.commit);
|
|
554
|
+
}
|
|
555
|
+
if (changes && "error" in changes)
|
|
556
|
+
return { ...out, status: "error", error: `nothing was merged, because ${changes.error}` };
|
|
557
|
+
if (changes)
|
|
558
|
+
return changedRefusal(job, shown.commit, changes, tree ? "worktree" : "branch", !ctx);
|
|
559
|
+
commit = shown.commit;
|
|
560
|
+
}
|
|
561
|
+
else {
|
|
562
|
+
// As before 0.9.1: anything the job left uncommitted is committed to its branch first, and the
|
|
563
|
+
// branch is merged as it then is. Committing it afterwards would create work the merge never
|
|
564
|
+
// included; if it cannot be committed, nothing is merged.
|
|
565
|
+
if (tree) {
|
|
566
|
+
const src = checkpoint(tree, job.id, trust);
|
|
567
|
+
if (src.error)
|
|
568
|
+
return { ...out, status: "error", error: `nothing was merged, because ${job.id}'s uncommitted work could not be committed first: ${src.error} (worktree: ${worktree})` };
|
|
569
|
+
}
|
|
570
|
+
const took = tree ? `committed anything left in ${job.id}'s worktree to ${job.branch} and took the branch as it then was` : `took ${job.branch} as it was`;
|
|
571
|
+
note = shown
|
|
572
|
+
? `${job.id}'s result was written by a relay older than 0.9.1, which did not record the commit a result's diff summary is of, so relay could not check that the branch holds only what the result showed. As before, it ${took}.`
|
|
573
|
+
: `With include_changes_since_result, relay ${took}, not only the commit the job's result showed.`;
|
|
574
|
+
}
|
|
575
|
+
// The caller's own uncommitted work is committed too, so the merge starts from a clean tree.
|
|
576
|
+
if (me?.worktree && typeof into.at !== "string") {
|
|
577
|
+
const cp = checkpoint(into.at, `${me.id} before merging ${job.id}`, trust);
|
|
578
|
+
if (cp.error)
|
|
579
|
+
return { ...out, status: "error", error: cp.error };
|
|
580
|
+
}
|
|
581
|
+
return { ...out, ...afterMerge(job, mergeBranch(into.at, job.branch, trust, commit)), ...(note ? { note } : {}) };
|
|
582
|
+
}
|
|
583
|
+
/** Once a job's branch is merged its worktree is no longer needed; it is restored if the job is resumed. */
|
|
584
|
+
function afterMerge(job, res) {
|
|
585
|
+
if (res.status !== "merged" && res.status !== "up_to_date")
|
|
586
|
+
return res;
|
|
587
|
+
if (!job.worktree || !job.repo)
|
|
588
|
+
return res;
|
|
589
|
+
// Agents the job started may still be working inside its worktree (read jobs and consults run in place).
|
|
590
|
+
if (descendants(job.id).some((d) => busy(d)))
|
|
591
|
+
return { ...res, worktree_kept: "agents this job started are still running in it" };
|
|
592
|
+
const kept = retire(job, runConfig(job.run_id).trust_git_filters);
|
|
593
|
+
return kept ? { ...res, worktree_kept: `${kept} (${job.worktree})` } : { ...res, worktree_removed: true };
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* Removes the worktrees of runs with nothing in use, and deletes relay branches that are already
|
|
597
|
+
* merged. Uncommitted work is committed to the job's branch first; a worktree whose work cannot be
|
|
598
|
+
* committed is kept and listed, as are unmerged branches. Cleaning never discards work. Then the
|
|
599
|
+
* temporary directories relay made and no longer needs go (retention.ts sweepTemps), and, only
|
|
600
|
+
* where keep_records_days is set, the records of runs with no activity for that many days that
|
|
601
|
+
* nothing uses any more.
|
|
602
|
+
*/
|
|
603
|
+
export async function clean(runId) {
|
|
604
|
+
const runs = runId ? [runId] : db().prepare("SELECT id FROM runs").all().map((r) => r.id);
|
|
605
|
+
let removed = 0;
|
|
606
|
+
const deleted = [];
|
|
607
|
+
const kept = [];
|
|
608
|
+
const keptTrees = [];
|
|
609
|
+
const skipped = [];
|
|
610
|
+
for (const id of runs) {
|
|
611
|
+
if (!getRun(id)) {
|
|
612
|
+
if (runId)
|
|
613
|
+
return { error: `unknown run ${id}` };
|
|
614
|
+
// Forgotten meanwhile by another relay process's keep_records_days.
|
|
615
|
+
continue;
|
|
616
|
+
}
|
|
617
|
+
reap(id);
|
|
618
|
+
const nodes = runNodes(id);
|
|
619
|
+
// Nothing is removed until every agent in the run is known to have stopped.
|
|
620
|
+
if (nodes.some((n) => busy(n) || workerLive(n) || groupAlive(n.agent_pgid))) {
|
|
621
|
+
skipped.push(id);
|
|
622
|
+
continue;
|
|
623
|
+
}
|
|
624
|
+
for (const n of nodes) {
|
|
625
|
+
if (!n.worktree || !n.repo || !fs.existsSync(n.repo))
|
|
626
|
+
continue;
|
|
627
|
+
if (fs.existsSync(n.worktree)) {
|
|
628
|
+
const trust = runConfig(id).trust_git_filters;
|
|
629
|
+
// Before anything runs git in it: whether it is still the worktree git made, and whether
|
|
630
|
+
// `git status` there could run a filter.
|
|
631
|
+
const tree = jobTree(n.repo, n.worktree);
|
|
632
|
+
const refusal = "error" in tree ? tree.error : filterRefusal(tree, trust);
|
|
633
|
+
if ("error" in tree || refusal) {
|
|
634
|
+
keptTrees.push(`${n.id}: ${refusal} (${n.worktree})`);
|
|
635
|
+
continue;
|
|
636
|
+
}
|
|
637
|
+
// A cancelled, failed or lost job can leave work its worker never got to commit.
|
|
638
|
+
if (treeState(tree) !== "clean")
|
|
639
|
+
checkpoint(tree, `${n.id} (saved by relay clean)`, trust);
|
|
640
|
+
const why = retire(n, trust);
|
|
641
|
+
if (why) {
|
|
642
|
+
keptTrees.push(`${n.id}: ${why} (${n.worktree})`);
|
|
643
|
+
continue;
|
|
644
|
+
}
|
|
645
|
+
removed++;
|
|
646
|
+
}
|
|
647
|
+
if (!n.branch)
|
|
648
|
+
continue;
|
|
649
|
+
const r = deleteBranchIfMerged(n.repo, n.branch);
|
|
650
|
+
if (r === "deleted")
|
|
651
|
+
deleted.push(n.branch);
|
|
652
|
+
else if (r === "unmerged")
|
|
653
|
+
kept.push(`${n.branch} (${n.repo})`);
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
const out = { worktrees_removed: removed, branches_deleted: deleted, unmerged_branches_kept: kept, worktrees_kept: keptTrees, runs_skipped_still_active: skipped };
|
|
657
|
+
// The sweep says what it could not do rather than throw; whatever happens to it, keep_records_days
|
|
658
|
+
// is still applied and this report still made.
|
|
659
|
+
let swept;
|
|
660
|
+
try {
|
|
661
|
+
swept = await sweepTemps();
|
|
662
|
+
}
|
|
663
|
+
catch (err) {
|
|
664
|
+
swept = { removed: [], problems: [`relay's leftover temporary directories were not swept (${err.message})`] };
|
|
665
|
+
}
|
|
666
|
+
out.temp_dirs_removed = swept.removed;
|
|
667
|
+
if (swept.problems.length)
|
|
668
|
+
out.temp_dirs_left = swept.problems;
|
|
669
|
+
// Never removed by relay, keep_records_days or not: each is a whole copy of the registry from before an upgrade.
|
|
670
|
+
const backups = registryBackups();
|
|
671
|
+
if (backups.length) {
|
|
672
|
+
out.registry_backups_kept = backups;
|
|
673
|
+
out.registry_backups_note = "copies of the registry relay made before upgrading it, each holding every run it held then, prompts included; delete them once you will not go back to the relay that wrote them";
|
|
674
|
+
}
|
|
675
|
+
let cfg;
|
|
676
|
+
try {
|
|
677
|
+
cfg = loadConfig();
|
|
678
|
+
}
|
|
679
|
+
catch (err) {
|
|
680
|
+
return { ...out, records_note: `kept: relay's config did not load, so keep_records_days was not applied (${err.message})` };
|
|
681
|
+
}
|
|
682
|
+
return { ...out, ...recordsReport(cfg, runId ? [runId] : undefined) };
|
|
683
|
+
}
|
|
684
|
+
export async function ask(inst, a, w = {}) {
|
|
685
|
+
if (a.thread_id && !canReadItem(inst, a.thread_id))
|
|
686
|
+
return UNAVAILABLE();
|
|
687
|
+
const seen = await once(inst, "ask", a, w, () => ask(inst, a, w), (c) => replay(inst, c, a, w));
|
|
688
|
+
if (seen)
|
|
689
|
+
return seen;
|
|
690
|
+
/** The thread a follow-up continues, or the row of the one a new question starts. */
|
|
691
|
+
let existing;
|
|
692
|
+
let row;
|
|
693
|
+
/** A follow-up's grant, which replaces the thread's from its next turn. */
|
|
694
|
+
let regrant;
|
|
695
|
+
/** A new thread's extensions. */
|
|
696
|
+
let ext;
|
|
697
|
+
/** A follow-up's speed, which the thread goes on at from the turn it queues. */
|
|
698
|
+
let respeed;
|
|
699
|
+
let body;
|
|
700
|
+
let caller;
|
|
701
|
+
if (a.thread_id) {
|
|
702
|
+
existing = getNode(a.thread_id);
|
|
703
|
+
if (!existing || existing.kind !== "thread")
|
|
704
|
+
return { error: `${a.thread_id} is not a consult thread` };
|
|
705
|
+
const c = admitExisting(inst, existing, "continue", a.cwd);
|
|
706
|
+
if ("reason" in c)
|
|
707
|
+
return refused(c.reason);
|
|
708
|
+
caller = c;
|
|
709
|
+
if (a.target && existing.target !== a.target)
|
|
710
|
+
return { error: `${a.thread_id} is a ${targetLabel(targetDef(existing.target), existing.target)} thread, not ${targetLabel(targetDef(a.target), a.target)}` };
|
|
711
|
+
const unknown = knownCaller(inst);
|
|
712
|
+
if (unknown)
|
|
713
|
+
return refused(unknown);
|
|
714
|
+
if (existing.status === "cancelled")
|
|
715
|
+
return refused(`${a.thread_id} was cancelled. Start a new thread by omitting thread_id.`);
|
|
716
|
+
if (a.extensions)
|
|
717
|
+
return refused("a thread is given its extensions when it starts, and keeps them; omit extensions on a follow-up, or start a new thread with them.");
|
|
718
|
+
body = contextBlock(a.context) + a.message;
|
|
719
|
+
const g = admitWork(caller, existing.target, { mode: "read", grant: a.grant, kept: grantOf(existing), continues: true, servers: holdsServers(existing) }, w);
|
|
720
|
+
if ("reason" in g)
|
|
721
|
+
return refused(g.reason);
|
|
722
|
+
if (g.grant) {
|
|
723
|
+
regrant = g.grant;
|
|
724
|
+
if (g.grant.network)
|
|
725
|
+
body = `[relay] You now have web access for the rest of this consult.\n\n${body}`;
|
|
726
|
+
}
|
|
727
|
+
// Asked whether or not the call names a speed: a launched agent may not carry on a thread faster than itself.
|
|
728
|
+
const sp = admitSpeed(caller, existing.target, { speed: a.speed, current: speedAfter(existing), model: existing.model }, w);
|
|
729
|
+
if ("reason" in sp)
|
|
730
|
+
return refused(sp.reason);
|
|
731
|
+
respeed = sp.speed;
|
|
732
|
+
}
|
|
733
|
+
else {
|
|
734
|
+
const admitted = admitNew(inst, { target: a.target, model: a.model, cwd: a.cwd, consult: true });
|
|
735
|
+
if ("reason" in admitted)
|
|
736
|
+
return refused(admitted.reason);
|
|
737
|
+
caller = admitted.caller;
|
|
738
|
+
const to = admitted.to;
|
|
739
|
+
const g = admitWork(caller, to.target, { mode: "read", grant: a.grant, continues: false }, w);
|
|
740
|
+
if ("reason" in g)
|
|
741
|
+
return refused(g.reason);
|
|
742
|
+
const sp = admitSpeed(caller, to.target, { speed: a.speed, model: to.model ?? a.model }, w);
|
|
743
|
+
if ("reason" in sp)
|
|
744
|
+
return refused(sp.reason);
|
|
745
|
+
const cfg = runConfig(caller.runId);
|
|
746
|
+
if (a.extensions) {
|
|
747
|
+
const e = admitExtensions(inst, caller, to.target, { network: networkOn(cfg, g.grant), allowDelegation: a.allow_delegation }, w);
|
|
748
|
+
if ("reason" in e)
|
|
749
|
+
return refused(e.reason);
|
|
750
|
+
ext = e.extensions;
|
|
751
|
+
}
|
|
752
|
+
row = {
|
|
753
|
+
id: newId("thread"), run_id: caller.runId, parent_id: caller.node?.id ?? null, kind: "thread", target: to.target,
|
|
754
|
+
mode: "read", depth: caller.depth + 1, allow_delegation: a.allow_delegation && !ext?.mcp_servers.length ? 1 : 0, task: a.message, cwd: caller.cwd,
|
|
755
|
+
model: to.model ?? a.model ?? null, effort: a.effort ?? null, params_json: JSON.stringify({ grant: persistentGrant(g.grant), speed: sp.speed, ...(ext ? { extensions: ext } : {}) }),
|
|
756
|
+
};
|
|
757
|
+
const who = caller.node ? `a ${targetLabel(targetDef(caller.node.target), caller.node.target)} agent, ${caller.node.id}` : "the root session";
|
|
758
|
+
body = consultHeader(who, to.target, row.allow_delegation === 1 && row.depth < cfg.max_depth, {
|
|
759
|
+
canAsk: escalationEnabled(cfg) && !cfg.allow_dangerous, network: networkOn(cfg, g.grant), cfg, model: row.model, extensions: ext,
|
|
760
|
+
}) + contextBlock(a.context) + a.message;
|
|
761
|
+
}
|
|
762
|
+
// The thread (a new one), the question and the request_id's binding are committed together
|
|
763
|
+
// (review X1): a repeat finds the question on its way, or nothing, and then asks it afresh.
|
|
764
|
+
const { node, turnId } = tx(() => {
|
|
765
|
+
const n = row ? insertNode(row) : getNode(existing.id);
|
|
766
|
+
if (row)
|
|
767
|
+
recordStart(n.id, inst, w, n.target, n.model, runConfig(n.run_id));
|
|
768
|
+
else
|
|
769
|
+
addContribution(n.id, callerLabel(inst, w));
|
|
770
|
+
if (regrant)
|
|
771
|
+
setParam(n.id, "grant", persistentGrant(regrant));
|
|
772
|
+
// Consults are always read-only, whatever the session did before.
|
|
773
|
+
const t = queueTurn(n.id, "caller", body, "read").turnId;
|
|
774
|
+
recordEnvironmentRequest(t, a.grant?.env);
|
|
775
|
+
if (respeed)
|
|
776
|
+
changeSpeed(n.id, t, respeed);
|
|
777
|
+
noteCall(inst, a, n.id, t);
|
|
778
|
+
return { node: n, turnId: t };
|
|
779
|
+
});
|
|
780
|
+
const notStarted = dispatch(node.id);
|
|
781
|
+
// A new thread given extensions says which, and that the user is asked first, as delegate does.
|
|
782
|
+
const given = ext ? { extensions: extensionsView(ext, { consent: false }), extensions_note: EXTENSIONS_NOTE } : {};
|
|
783
|
+
if (notStarted)
|
|
784
|
+
return { ...pendingHandle(node.id, { thread_id: node.id, turn_id: turnId }, inst), warning: notStarted, ...given };
|
|
785
|
+
return { ...(await consultReply(inst, node, turnId, w)), ...given };
|
|
786
|
+
}
|
|
787
|
+
/** Waits for a consult turn and returns its reply, or a pending handle. */
|
|
788
|
+
async function consultReply(inst, node, turnId, w = {}) {
|
|
789
|
+
// The reply is returned with the thread settled with it (or gone on to its next turn), so that a
|
|
790
|
+
// follow-up sent at once finds it as the reply left it.
|
|
791
|
+
const turnDone = () => turnSettled(getTurn(turnId)) || !workerLive(getNode(node.id)) && settled(node.id);
|
|
792
|
+
const done = await waitUntil(turnDone, waitOpts(inst, node.run_id, w, { progressOf: node.id }));
|
|
793
|
+
if (!canReadItem(inst, node.id))
|
|
794
|
+
return UNAVAILABLE();
|
|
795
|
+
if (!done)
|
|
796
|
+
return pendingHandle(node.id, { thread_id: node.id, turn_id: turnId }, inst);
|
|
797
|
+
const t = getTurn(turnId);
|
|
798
|
+
if (t.status !== "done") {
|
|
799
|
+
const refusal = t.status === "refused" && t.refusal_json ? JSON.parse(t.refusal_json) : null;
|
|
800
|
+
return { thread_id: node.id, ...runRecovery(node.run_id), families: familiesOf(getNode(node.id)), error: t.error ?? `the consult turn ended as ${t.status}`, ...(refusal ? { status: "refused", outcome: "refused", refusal, unfinished: true, note: refusalNote(refusal) } : {}) };
|
|
801
|
+
}
|
|
802
|
+
// A reply can come with a warning about processes the agent left behind, and with what it was refused.
|
|
803
|
+
const blocked = denialsOf(t);
|
|
804
|
+
return { reply: t.reply, thread_id: node.id, ...runRecovery(node.run_id), families: familiesOf(getNode(node.id)), ...notesView(getNode(node.id)), ...(t.error ? { warning: t.error } : {}), ...(blocked.length ? { blocked, note: BLOCKED_NOTE } : {}) };
|
|
805
|
+
}
|
|
806
|
+
// Discuss and review: the flows are modes/discussion.ts and modes/review.ts. The tools answer a
|
|
807
|
+
// call that repeats an earlier request_id from what that call started (replay, below).
|
|
808
|
+
export async function discuss(inst, a, w = {}) {
|
|
809
|
+
if ([a.discussion_id, a.with].some((id) => id && !canReadItem(inst, id)))
|
|
810
|
+
return UNAVAILABLE();
|
|
811
|
+
const seen = a.discussion_id ? null : await once(inst, "discuss", a, w, () => discuss(inst, a, w), (c) => replay(inst, c, a, w));
|
|
812
|
+
return seen ?? holdDiscussion(inst, a, w);
|
|
813
|
+
}
|
|
814
|
+
export async function review(inst, a, w = {}) {
|
|
815
|
+
if (a.review_id && !canReadItem(inst, a.review_id))
|
|
816
|
+
return UNAVAILABLE();
|
|
817
|
+
const seen = a.review_id ? null : await once(inst, "review", a, w, () => review(inst, a, w), (c) => replay(inst, c, a, w));
|
|
818
|
+
return seen ?? runReview(inst, a, w);
|
|
819
|
+
}
|
|
820
|
+
/**
|
|
821
|
+
* Decides an approval request. Only the root session can: a launched agent is itself confined, so
|
|
822
|
+
* it cannot hand a descendant more than it holds. The user can also decide from a terminal, except
|
|
823
|
+
* to allow a person-only request (docs/extensions.md), which only their own session's question or
|
|
824
|
+
* permission prompt can.
|
|
825
|
+
*/
|
|
826
|
+
export function approve(inst, a, call = {}) {
|
|
827
|
+
const access = getRequest(a.request_id);
|
|
828
|
+
if (!access || !canReadRun(inst, access.run_id))
|
|
829
|
+
return UNAVAILABLE();
|
|
830
|
+
// A Codex subagent thread may deny but never allow, whatever else holds.
|
|
831
|
+
const sub = a.decision === "allow" ? subagentRefusal(call, "allow") : null;
|
|
832
|
+
if (sub)
|
|
833
|
+
return refused(sub);
|
|
834
|
+
if (inst.ctx.kind !== "root") {
|
|
835
|
+
return refused("only the root session, or the user with `relay approve`, can decide approval requests. Carry on with your own work.");
|
|
836
|
+
}
|
|
837
|
+
const r = getRequest(a.request_id);
|
|
838
|
+
if (!r)
|
|
839
|
+
return { error: `unknown request ${a.request_id}` };
|
|
840
|
+
// A session decides only for agents in runs it owns; recovery is explicit.
|
|
841
|
+
const foreign = claimRun(inst, r.run_id);
|
|
842
|
+
if (foreign)
|
|
843
|
+
return refused(`${a.request_id} cannot be decided from here: ${foreign}.`);
|
|
844
|
+
// Consent to extensions, a call of an extension's tool, and any request of a session holding MCP
|
|
845
|
+
// servers are the person's alone to allow (docs/extensions.md): the root agent's word, even that
|
|
846
|
+
// the user confirmed, is not their consent. It may deny them.
|
|
847
|
+
if (a.decision === "allow" && personOnly(r)) {
|
|
848
|
+
return refused(`only the user can allow ${a.request_id}: it ${r.kind === "extensions" ? "gives a launched agent extensions" : r.kind === "env" ? "releases named environment values for one turn" : r.kind === "local_network" ? "opens this Mac's loopback and the local network to a job's shell" : r.kind === "raw_network" ? "gives a job's shell raw network, with the local network and tailnet reachable" : r.kind === "mcp" ? "calls a tool of an MCP server" : "comes from a session that holds MCP servers"}, and relay takes no agent's word for their consent. ` +
|
|
849
|
+
`They allow it ${PERSON_ROUTES}${inst.host.confirmTool ? " (call confirm with the request as shown)" : ""}; relay takes it from no command, relay approve included. You may deny it.`);
|
|
850
|
+
}
|
|
851
|
+
const requester = getNode(r.node_id);
|
|
852
|
+
if (a.decision === "allow" && requestRunsRelayCommand(r, requester ? workCwd(requester) : inst.cwd)) {
|
|
853
|
+
return refused("this command runs relay's CLI, so only the person can allow it, through the host's approval dialog, confirm, or `relay approve` in their own terminal. You may deny it.");
|
|
854
|
+
}
|
|
855
|
+
// Where the user has been asked directly, their answer is the one that counts. The agent can
|
|
856
|
+
// still pass on an answer they gave in conversation, by saying so.
|
|
857
|
+
const state = elicitationState(r.id);
|
|
858
|
+
if (a.decision === "allow" && !a.user_confirmed && (state === "asking" || state === "dismissed")) {
|
|
859
|
+
return refused((state === "asking" ? "the user is being asked about this request directly right now" : "the user was shown this request and closed it without answering") +
|
|
860
|
+
", so you cannot allow it on your own judgment. Ask them in conversation; if they tell you to allow it, call approve again with user_confirmed: true. You may deny it without asking.");
|
|
861
|
+
}
|
|
862
|
+
return decide(a.request_id, a.decision === "allow", a.user_confirmed ? "root session, stating that the user confirmed" : "root session", a.note, a.scope ?? "once", escalationDecisionAuthentication(r, "owning-run-root", inst));
|
|
863
|
+
}
|
|
864
|
+
/**
|
|
865
|
+
* Allows a request on the user's own say-so (a confirmation): the tool is offered only to hosts that ask the user
|
|
866
|
+
* before every call of it (Claude Code's permission prompt for a tool marked
|
|
867
|
+
* anthropic/requiresUserInteraction), so a call that arrives here is one the user let through.
|
|
868
|
+
* The request must be pending and in a run this session owns, and from and wants must be the
|
|
869
|
+
* request's own, so that what the prompt showed is what is allowed.
|
|
870
|
+
*/
|
|
871
|
+
export function confirm(inst, a) {
|
|
872
|
+
const access = getRequest(a.request_id);
|
|
873
|
+
if (!access || !canReadRun(inst, access.run_id))
|
|
874
|
+
return UNAVAILABLE();
|
|
875
|
+
const r = getRequest(a.request_id);
|
|
876
|
+
// A person-only request is allowed by no command: the user allows it only in relay's question or through confirm.
|
|
877
|
+
const personal = r ? personOnly(r) : false;
|
|
878
|
+
if (inst.ctx.kind !== "root" || !inst.host.confirmTool) {
|
|
879
|
+
return refused(personal
|
|
880
|
+
? `confirm is only for a root session in a host that asks the user before every call of it. ${a.request_id} is person_only: only the user can allow it, ${PERSON_ROUTES}. You may deny it with approve.`
|
|
881
|
+
: "confirm is only for a root session in a host that asks the user before every call of it. Use approve, or ask the user to decide from a terminal.");
|
|
882
|
+
}
|
|
883
|
+
if (!r)
|
|
884
|
+
return { error: `unknown request ${a.request_id}` };
|
|
885
|
+
if (!ownsRun(inst, r.run_id)) {
|
|
886
|
+
return refused(personal
|
|
887
|
+
? `${a.request_id} is not in a run of this session. Its own session decides it: only the user can allow it, ${PERSON_ROUTES}, and relay deny ${a.request_id} denies it from a terminal.`
|
|
888
|
+
: `${a.request_id} is not in a run of this session. Its own session, or the user from a terminal (relay approve ${a.request_id}), decides it.`);
|
|
889
|
+
}
|
|
890
|
+
if (r.status !== "pending")
|
|
891
|
+
return { error: `request ${a.request_id} is already ${r.status}` };
|
|
892
|
+
// Compared exactly, whitespace and all: a prompt showing "a b" must not allow a request for
|
|
893
|
+
// "a\nb", which a shell runs as two commands. The effect and kind are relay's own, so that the
|
|
894
|
+
// prompt shows what allowing does, not only what the agent says it wants. The directory is the
|
|
895
|
+
// agent's own text too (a Codex agent names it), so it is compared the same way.
|
|
896
|
+
const view = requestView(r);
|
|
897
|
+
const differs = [["from", a.from !== r.node_id], ["kind", a.kind !== view.kind], ["effect", a.effect !== view.effect], ["in_directory", a.in_directory !== view.in_directory], ["wants", a.wants !== r.summary]]
|
|
898
|
+
.filter(([, off]) => off).map(([field]) => field);
|
|
899
|
+
if (differs.length) {
|
|
900
|
+
const fields = differs.length === 1 ? differs[0] : `${differs.slice(0, -1).join(", ")} and ${differs.at(-1)}`;
|
|
901
|
+
return refused(`what you passed differs in ${fields}: it does not match ${a.request_id}, which is from ${r.node_id}, of kind ${JSON.stringify(view.kind)}, with effect ${JSON.stringify(view.effect)}, in directory ${JSON.stringify(view.in_directory)}, and wants ${JSON.stringify(r.summary)}. Call confirm again with from, kind, effect, in_directory and wants exactly as needs_approval shows them (the same characters, line breaks included), so that the user sees what they are allowing.`);
|
|
902
|
+
}
|
|
903
|
+
return decide(r.id, true, "user, through the host's permission prompt (confirm)", a.note, a.scope ?? "once", escalationDecisionAuthentication(r, "person-confirm", inst));
|
|
904
|
+
}
|
|
905
|
+
/** Records a human message for a live discussion. The other agent sees it on its next turn, the calling agent on its next call. */
|
|
906
|
+
export function inject(discussionId, body) {
|
|
907
|
+
const n = getNode(discussionId);
|
|
908
|
+
if (!n || n.kind !== "discussion")
|
|
909
|
+
return { error: `${discussionId} is not a discussion` };
|
|
910
|
+
if (n.status !== "open")
|
|
911
|
+
return { error: `${discussionId} has ended (${n.status}), so the message would not be delivered` };
|
|
912
|
+
db().prepare("INSERT INTO injections (discussion_id, body, created_at) VALUES (?, ?, ?)").run(discussionId, body, now());
|
|
913
|
+
return { injected: true, discussion_id: discussionId };
|
|
914
|
+
}
|
|
915
|
+
/** Answers a repeated call as the first one would have, from the item it started. A delegate repeated with background: false waits for it. */
|
|
916
|
+
async function replay(inst, call, a, w = {}) {
|
|
917
|
+
const n = getNode(call.node_id);
|
|
918
|
+
if (!n)
|
|
919
|
+
return { error: `the earlier call with request_id "${call.request_id}" started ${call.node_id}, which is no longer in the registry` };
|
|
920
|
+
const again = { repeated: true, repeated_note: `An earlier call with request_id "${call.request_id}" already started ${n.id}. This is that item; nothing new was started.` };
|
|
921
|
+
// The session doing the work is started if the first call committed it but left it without a
|
|
922
|
+
// worker (review X1): the item, or the session a discussion or review waits on.
|
|
923
|
+
const session = call.tool === "discuss" ? discussionParams(n).participant : call.tool === "review" ? reviewParams(n).reviewer : n.id;
|
|
924
|
+
const notStarted = redispatch(session);
|
|
925
|
+
const warned = notStarted ? { warning: notStarted } : {};
|
|
926
|
+
// A job or new thread given extensions says which, and that the user is asked first, as the
|
|
927
|
+
// first answer did. A follow-up on a thread was not given them, and its answer did not say so.
|
|
928
|
+
const startedThread = () => db().prepare("SELECT MIN(id) AS id FROM turns WHERE node_id = ?").get(n.id).id === call.turn_id;
|
|
929
|
+
const ext = call.tool === "delegate" || (call.tool === "ask" && startedThread()) ? sessionParams(n).extensions : undefined;
|
|
930
|
+
const given = ext ? { extensions: extensionsView(ext, { consent: false }), extensions_note: EXTENSIONS_NOTE } : {};
|
|
931
|
+
if (call.tool === "ask") {
|
|
932
|
+
if (notStarted)
|
|
933
|
+
return { ...pendingHandle(n.id, { thread_id: n.id, turn_id: call.turn_id }, inst), ...warned, ...given, ...again };
|
|
934
|
+
return { ...(await consultReply(inst, n, call.turn_id, w)), ...given, ...again };
|
|
935
|
+
}
|
|
936
|
+
if (call.tool === "review")
|
|
937
|
+
return { ...reviewView(n.id), ...warned, ...again };
|
|
938
|
+
if (call.tool === "discuss") {
|
|
939
|
+
const done = !notStarted && (await waitUntil(() => settleDiscussion(n.id), waitOpts(inst, n.run_id, w, { awaits: [n.id] })));
|
|
940
|
+
return { ...(done ? discussionView(n.id) : pendingHandle(n.id, { discussion_id: n.id }, inst)), ...warned, ...again };
|
|
941
|
+
}
|
|
942
|
+
const grant = sessionParams(n).grant;
|
|
943
|
+
const started = {
|
|
944
|
+
// The caller-visible grant, without the per-directory pins (as the first response gave it — review C7/X5).
|
|
945
|
+
job_id: n.id, ...runRecovery(n.run_id), target: n.target, mode: n.mode, depth: n.depth, families: familiesOf(n), ...(grant ? { grant: publicGrant(grant) } : {}),
|
|
946
|
+
...given,
|
|
947
|
+
...(speedOf(n) !== "standard" ? { speed: { requested: speedOf(n) } } : {}),
|
|
948
|
+
...(n.branch ? { branch: n.branch, base_sha: n.base_sha } : {}),
|
|
949
|
+
};
|
|
950
|
+
if (notStarted)
|
|
951
|
+
return { ...started, status: n.status, warning: notStarted, ...again };
|
|
952
|
+
if (a.background === false && !(await waitUntil(() => settled(n.id), waitOpts(inst, n.run_id, w, { progressOf: n.id })))) {
|
|
953
|
+
return { ...pendingHandle(n.id, started, inst), ...again };
|
|
954
|
+
}
|
|
955
|
+
const view = nodeView(getNode(n.id));
|
|
956
|
+
if (removedBranch(view.result ?? null))
|
|
957
|
+
delete started.branch;
|
|
958
|
+
return { ...started, ...view, ...again };
|
|
959
|
+
}
|