@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
|
@@ -0,0 +1,1525 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { openaiRefusal, refusalError } from "../core/refusal.js";
|
|
3
|
+
import { canonical, inside } from "../core/config.js";
|
|
4
|
+
import { overlapsPart, relayCodexProtected } from "../core/protected-config.js";
|
|
5
|
+
import { executable } from "../core/executables.js";
|
|
6
|
+
import readline from "node:readline";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { activityOf, openAgentLog, usageFrom, watchProcess } from "./types.js";
|
|
9
|
+
import { drainGroup, isGroupSignalRefusal, killProcs, procStart, sendGroupSignal, stopProcs } from "../core/procs.js";
|
|
10
|
+
import { clipped } from "../core/shown.js";
|
|
11
|
+
import { diagnosticTail } from "../core/redact.js";
|
|
12
|
+
import { speedRank } from "../targets/index.js";
|
|
13
|
+
import { skipDaybreak } from "./codex-daybreak.js";
|
|
14
|
+
import { codexShellPolicyNote } from "./codex-shell-policy.js";
|
|
15
|
+
import { CodexSubagents } from "./codex-subagents.js";
|
|
16
|
+
import { stage2BrokerConfigProblem } from "./codex-stage2.js";
|
|
17
|
+
import { BROKER_SERVER_NAME } from "../confine/broker-names.js";
|
|
18
|
+
import { assertOverlayLaunch, markOverlayLaunched } from "../core/restart-overlay.js";
|
|
19
|
+
import { canaryProblem, CANARY_SCRIPT, codexRuleFolders, networkRuleFiles, openCanaryTargets, ownPublicAddress } from "./codex-network.js";
|
|
20
|
+
/** Streaming deltas are not needed; the completed items carry the same text. */
|
|
21
|
+
const OPT_OUT = [
|
|
22
|
+
"item/agentMessage/delta", "item/reasoning/summaryTextDelta", "item/reasoning/summaryPartAdded",
|
|
23
|
+
"item/reasoning/textDelta", "item/commandExecution/outputDelta",
|
|
24
|
+
];
|
|
25
|
+
/**
|
|
26
|
+
* A command or file change the agent was refused (an approval declined), described in a line, or
|
|
27
|
+
* null. Takes a completed item in either dialect: the app server's (commandExecution, fileChange)
|
|
28
|
+
* or `codex exec`'s (command_execution, file_change). A command that failed inside the sandbox is
|
|
29
|
+
* not a refusal Codex reports as such, and is not counted. Nor is a file change under `codex exec`,
|
|
30
|
+
* which reports a declined change as failed (upstream test file_change_declined_maps_to_failed_status,
|
|
31
|
+
* rust-v0.160.1), the same as one that did not apply: counting failures would report ordinary
|
|
32
|
+
* retried patches as refusals. `codex exec` has no approval requests, so only its sandbox refuses.
|
|
33
|
+
*/
|
|
34
|
+
export function declinedItem(item) {
|
|
35
|
+
const i = (item ?? {});
|
|
36
|
+
if (i.status !== "declined")
|
|
37
|
+
return null;
|
|
38
|
+
if (i.type !== "commandExecution" && i.type !== "command_execution" && i.type !== "fileChange" && i.type !== "file_change")
|
|
39
|
+
return null;
|
|
40
|
+
return activityOf(i.type, i);
|
|
41
|
+
}
|
|
42
|
+
const isTable = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
43
|
+
const onlyKeys = (v, keys) => Object.keys(v).every((k) => keys.includes(k));
|
|
44
|
+
/** A path entry of Codex's FileSystemPath (app-server v2) in words, the agent's own text quoted; null for one relay does not know. */
|
|
45
|
+
function permissionPlace(p) {
|
|
46
|
+
// A key relay does not know could narrow or widen what the entry means, so the entry is unread.
|
|
47
|
+
if (!isTable(p))
|
|
48
|
+
return null;
|
|
49
|
+
if (p.type === "path" && onlyKeys(p, ["type", "path"]) && typeof p.path === "string")
|
|
50
|
+
return JSON.stringify(p.path);
|
|
51
|
+
if (p.type === "glob_pattern" && onlyKeys(p, ["type", "pattern"]) && typeof p.pattern === "string")
|
|
52
|
+
return `files matching ${JSON.stringify(p.pattern)}`;
|
|
53
|
+
if (p.type !== "special" || !onlyKeys(p, ["type", "value"]) || !isTable(p.value))
|
|
54
|
+
return null;
|
|
55
|
+
const v = p.value;
|
|
56
|
+
if (v.kind === "project_roots" && onlyKeys(v, ["kind", "subpath"])) {
|
|
57
|
+
return v.subpath == null ? "its workspace roots" : typeof v.subpath === "string" ? `${JSON.stringify(v.subpath)} in each of its workspace roots` : null;
|
|
58
|
+
}
|
|
59
|
+
if (!onlyKeys(v, ["kind"]))
|
|
60
|
+
return null;
|
|
61
|
+
if (v.kind === "root")
|
|
62
|
+
return "the whole filesystem";
|
|
63
|
+
if (v.kind === "minimal")
|
|
64
|
+
return "Codex's minimal system paths";
|
|
65
|
+
if (v.kind === "tmpdir")
|
|
66
|
+
return "its temporary directory (TMPDIR)";
|
|
67
|
+
if (v.kind === "slash_tmp")
|
|
68
|
+
return "/tmp";
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* What a command approval request asks to have added to the agent's sandbox for that one command
|
|
73
|
+
* (its `additionalPermissions`: AdditionalPermissionProfile of Codex 0.164.0's experimental API,
|
|
74
|
+
* which relay turns on), in plain words, or null where it asks for nothing. `complete` is false
|
|
75
|
+
* where relay could not read all of it (a key, shape or kind of path it does not know): `words` is
|
|
76
|
+
* then the request's own JSON, and relay vouches for nothing narrower than full access (commandAsk).
|
|
77
|
+
*/
|
|
78
|
+
export function addedPermissions(raw) {
|
|
79
|
+
if (raw === undefined || raw === null)
|
|
80
|
+
return null;
|
|
81
|
+
const places = { write: [], read: [], deny: [] };
|
|
82
|
+
let network = false;
|
|
83
|
+
let complete = isTable(raw) && onlyKeys(raw, ["network", "fileSystem"]);
|
|
84
|
+
if (isTable(raw)) {
|
|
85
|
+
const { network: net, fileSystem: files } = raw;
|
|
86
|
+
if (isTable(net) && onlyKeys(net, ["enabled"]) && [true, false, null, undefined].includes(net.enabled))
|
|
87
|
+
network = net.enabled === true;
|
|
88
|
+
else if (net != null)
|
|
89
|
+
complete = false;
|
|
90
|
+
if (isTable(files) && onlyKeys(files, ["read", "write", "entries", "globScanMaxDepth"])) {
|
|
91
|
+
// Codex goes by `entries` where they are given (its TryFrom<AdditionalFileSystemPermissions>);
|
|
92
|
+
// read and write are the legacy spelling of the same, sent beside them where they can say it.
|
|
93
|
+
if (Array.isArray(files.entries)) {
|
|
94
|
+
for (const e of files.entries) {
|
|
95
|
+
const at = isTable(e) && onlyKeys(e, ["path", "access"]) ? permissionPlace(e.path) : null;
|
|
96
|
+
const how = isTable(e) && (e.access === "read" || e.access === "write" || e.access === "deny") ? e.access : null;
|
|
97
|
+
if (at && how)
|
|
98
|
+
places[how].push(at);
|
|
99
|
+
else
|
|
100
|
+
complete = false;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
else if (files.entries != null)
|
|
104
|
+
complete = false;
|
|
105
|
+
else
|
|
106
|
+
for (const how of ["write", "read"]) {
|
|
107
|
+
const list = files[how];
|
|
108
|
+
if (Array.isArray(list) && list.every((p) => typeof p === "string"))
|
|
109
|
+
places[how].push(...list.map((p) => JSON.stringify(p)));
|
|
110
|
+
else if (list != null)
|
|
111
|
+
complete = false;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
else if (files != null)
|
|
115
|
+
complete = false;
|
|
116
|
+
}
|
|
117
|
+
if (!complete) {
|
|
118
|
+
// Shown escaped where it is shown (shown.ts), like the rest of the agent's request.
|
|
119
|
+
const json = JSON.stringify(raw) ?? String(raw);
|
|
120
|
+
return { words: json.length > 600 ? `${json.slice(0, 600)}…` : json, complete };
|
|
121
|
+
}
|
|
122
|
+
const words = [
|
|
123
|
+
places.write.length ? `write access to ${places.write.join(", ")}` : "",
|
|
124
|
+
places.read.length ? `read access to ${places.read.join(", ")}` : "",
|
|
125
|
+
network ? "network access" : "",
|
|
126
|
+
places.deny.length ? `no access to ${places.deny.join(", ")}` : "",
|
|
127
|
+
].filter(Boolean).join("; ");
|
|
128
|
+
return words ? { words, complete } : null;
|
|
129
|
+
}
|
|
130
|
+
/** Native Codex's for_approved_command preserves denied reads, but widens read-only paths to
|
|
131
|
+
* writable. The readable pin store therefore cannot survive a broad outside-sandbox approval.
|
|
132
|
+
* Stage 2 does not use this path: its executor's hard denies survive approvals. */
|
|
133
|
+
export function codexRuntimeApprovalProblem(p, cfg) {
|
|
134
|
+
if (p.kind === "writeStdin")
|
|
135
|
+
return null; // Input to an already authorised terminal adds no authority.
|
|
136
|
+
const added = addedPermissions(p.additionalPermissions);
|
|
137
|
+
if (!added?.complete || p.approvalId != null || p.networkApprovalContext != null ||
|
|
138
|
+
(p.kind != null && p.kind !== "command")) {
|
|
139
|
+
return "native Codex would grant write access across the filesystem without preserving relay's pin-store write protection; relay cannot approve that request. Use a stage-2 turn, whose executor keeps the hard denials, or work within the current sandbox";
|
|
140
|
+
}
|
|
141
|
+
const files = p.additionalPermissions.fileSystem;
|
|
142
|
+
const paths = [];
|
|
143
|
+
if (files) {
|
|
144
|
+
if (Array.isArray(files.entries)) {
|
|
145
|
+
for (const e of files.entries) {
|
|
146
|
+
if (e.access === "deny")
|
|
147
|
+
continue;
|
|
148
|
+
if (e.path.type !== "path" || !path.isAbsolute(e.path.path))
|
|
149
|
+
return "relay cannot prove that this native Codex permission addition leaves its credential home and pin store protected; only explicit absolute paths may be added";
|
|
150
|
+
paths.push(e.path.path);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
else {
|
|
154
|
+
for (const at of [...(files.read ?? []), ...(files.write ?? [])]) {
|
|
155
|
+
if (!path.isAbsolute(at))
|
|
156
|
+
return "relay cannot prove that this native Codex permission addition leaves its credential home and pin store protected; only explicit absolute paths may be added";
|
|
157
|
+
paths.push(at);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
const protectedPaths = relayCodexProtected(cfg);
|
|
162
|
+
for (const at of paths) {
|
|
163
|
+
const denied = [...protectedPaths.homes, ...protectedPaths.stores].find((d) => overlapsPart(at, d.path));
|
|
164
|
+
if (denied)
|
|
165
|
+
return `${at} overlaps ${denied.what} (${denied.path}), which no approval may cover`;
|
|
166
|
+
}
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* The ask for a command approval request (item/commandExecution/requestApproval): the command, and
|
|
171
|
+
* what it asks to have added to its sandbox for it, if anything (addedPermissions). What allowing it
|
|
172
|
+
* does, as Codex 0.164.0 does it:
|
|
173
|
+
* Runtime-root policy declines broad and unknown confined requests before this function is used;
|
|
174
|
+
* their effect descriptions remain here for historical requests and the explicit sandbox waiver.
|
|
175
|
+
*
|
|
176
|
+
* - a request with additionalPermissions comes from a command the agent asked to run inside its
|
|
177
|
+
* sandbox with that access added ("with_additional_permissions", which needs Codex's
|
|
178
|
+
* exec_permission_approvals feature, off by default, and the on-request approval policy relay
|
|
179
|
+
* sets: core tools/handlers/mod.rs normalize_and_validate_additional_permissions). Allowed, it
|
|
180
|
+
* runs in the turn's sandbox (tools/sandboxing.rs sandbox_override_for_first_attempt: no
|
|
181
|
+
* override) with exactly that added to relay's profile for this command (sandboxing
|
|
182
|
+
* policy_transforms.rs effective_permission_profile: entries appended, the network on if asked).
|
|
183
|
+
* Should the sandbox still refuse it, Codex does not run it again outside the sandbox on that
|
|
184
|
+
* allow: an exec tool asks nothing more under on-request and the command fails, and a retry for a
|
|
185
|
+
* blocked host asks again, as a request of its own without additionalPermissions
|
|
186
|
+
* (tools/orchestrator.rs). The ask's detail says so (adds_to_sandbox), and the request's effect
|
|
187
|
+
* follows (core/approvals.ts);
|
|
188
|
+
* - a plain request to run the command outside the sandbox, without additions, on a confined turn
|
|
189
|
+
* (relay 1.0.5): relay's profile denies reads of credential stores, and while it does Codex lets no
|
|
190
|
+
* command leave the sandbox. Allowed, the command runs sandboxed with write access to the whole
|
|
191
|
+
* disk, still without those credential stores, and with the turn's own network: not full access,
|
|
192
|
+
* but writing anywhere in the home directory still acts with the person's authority. The ask's
|
|
193
|
+
* detail says so (escalates_restricted), and the request's effect follows (core/approvals.ts);
|
|
194
|
+
* - any other request is taken to run the command outside the sandbox with full access: relay keeps
|
|
195
|
+
* that effect wherever it cannot vouch for a narrower one: additions it cannot read in full, a
|
|
196
|
+
* request of a kind or shape relay has not checked (one with an approvalId, or a kind other than a
|
|
197
|
+
* plain command), or a turn without a sandbox (allow_dangerous). A retry for a blocked host
|
|
198
|
+
* (networkApprovalContext) relay declines itself (autoDenial).
|
|
199
|
+
*
|
|
200
|
+
* A request with additionalPermissions is allowed once only (once_only), never for the rest of the
|
|
201
|
+
* job: Codex offers only accept and cancel for one (protocol approvals.rs default_available_decisions),
|
|
202
|
+
* and Codex 0.163.0, which relay still supports, asks its blocked-host retry under the same approval
|
|
203
|
+
* cache key (tools/orchestrator.rs keeps the action; tools/approvals.rs cache_keys), so an allow held
|
|
204
|
+
* for the session would let that retry run outside the sandbox without asking. 0.164.0 asks the
|
|
205
|
+
* retry as a request of its own.
|
|
206
|
+
*
|
|
207
|
+
* Input for a terminal already running (kind "writeStdin") is left as it was: its
|
|
208
|
+
* additionalPermissions are those the terminal kept from its launch, not something added, and
|
|
209
|
+
* Codex's own reason names them.
|
|
210
|
+
*/
|
|
211
|
+
export function commandAsk(p, permissions) {
|
|
212
|
+
const command = String(p.command ?? "(command not given)");
|
|
213
|
+
const cwd = typeof p.cwd === "string" ? { cwd: p.cwd } : {};
|
|
214
|
+
const added = p.kind === "writeStdin" ? null : addedPermissions(p.additionalPermissions);
|
|
215
|
+
// A plain request to run the command outside the sandbox, on a confined turn: relay's profile
|
|
216
|
+
// denies reads (codex.ts deniedCredentials), so Codex runs it in a sandbox with write access to
|
|
217
|
+
// the whole disk, the denials kept and the turn's own network (core tools/sandboxing.rs
|
|
218
|
+
// sandbox_override_for_first_attempt: EscalatedSandboxWithRestrictions; protocol
|
|
219
|
+
// permissions/target.rs for_approved_command). The ask's detail says so (escalates_restricted).
|
|
220
|
+
const plainKind = (p.kind === undefined || p.kind === null || p.kind === "command") && p.approvalId == null;
|
|
221
|
+
if (!added) {
|
|
222
|
+
const restricted = plainKind && permissions.profile !== null && p.networkApprovalContext == null && p.additionalPermissions == null;
|
|
223
|
+
// escalates_restricted names the network the command keeps (the turn's): none, strict or local.
|
|
224
|
+
return { kind: "command", summary: command, reason: p.reason ?? undefined, detail: { ...cwd, ...(restricted ? { escalates_restricted: permissions.proxy ?? "none" } : {}) } };
|
|
225
|
+
}
|
|
226
|
+
// The plain command request is the only kind whose additions Codex 0.164.0 sends (core
|
|
227
|
+
// tools/approvals.rs request_command_approval: ExecApprovalKind::Command, approval_id None).
|
|
228
|
+
const stays = plainKind && added.complete && permissions.profile !== null && !p.networkApprovalContext;
|
|
229
|
+
return {
|
|
230
|
+
kind: "command",
|
|
231
|
+
summary: `${command} (asks to add for this command${added.complete ? `: ${added.words}` : `, in terms relay cannot read in full: ${added.words}`})`,
|
|
232
|
+
reason: p.reason ?? undefined,
|
|
233
|
+
// The command alone, for what reads the request as one (core/relay-command.ts): the summary is not.
|
|
234
|
+
detail: { ...cwd, command, once_only: true, ...(stays ? { adds_to_sandbox: true } : {}) },
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Whether a command approval request's additionalPermissions ask for the network: a network entry
|
|
239
|
+
* that is anything but off, or additions relay cannot read at all.
|
|
240
|
+
*/
|
|
241
|
+
export function addsNetwork(raw) {
|
|
242
|
+
if (raw === undefined || raw === null)
|
|
243
|
+
return false;
|
|
244
|
+
if (!isTable(raw))
|
|
245
|
+
return true;
|
|
246
|
+
const net = raw.network;
|
|
247
|
+
if (net === undefined || net === null)
|
|
248
|
+
return false;
|
|
249
|
+
return !(isTable(net) && onlyKeys(net, ["enabled"]) && (net.enabled === false || net.enabled === null || net.enabled === undefined));
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Why relay declines a command approval request itself, before anyone is asked, or null:
|
|
253
|
+
*
|
|
254
|
+
* - network added to one command (additionalPermissions.network) on a confined session whose shell
|
|
255
|
+
* has no proxy. Codex starts its proxy only for a profile with the network on (core
|
|
256
|
+
* config/network_config.rs), so the command would get Seatbelt's open network policy: every
|
|
257
|
+
* outbound connection, all of loopback and Unix sockets anywhere (sandboxing/src/seatbelt.rs
|
|
258
|
+
* dynamic_network_policy_for_network, its no-proxy branch). On a proxied session the command keeps
|
|
259
|
+
* the proxy, and the request goes on as before;
|
|
260
|
+
* - a blocked host (networkApprovalContext), on any confined session. On a proxied one, with every
|
|
261
|
+
* public host allowed, Codex asks only for a host that is not on the allowlist, which relay's leaves
|
|
262
|
+
* none, and never for loopback or private addresses (network-proxy/src/network_policy.rs
|
|
263
|
+
* evaluate_host_policy): relay has no case in which to allow one. Without the proxy Codex sends
|
|
264
|
+
* none (core tools/orchestrator.rs builds the context only with a managed network), and if one came,
|
|
265
|
+
* allowing it could not give the network: with relay's denied reads (codex.ts deniedCredentials) an
|
|
266
|
+
* approved retry stays in the sandbox with the turn's own network, which has none.
|
|
267
|
+
*/
|
|
268
|
+
export function autoDenial(p, permissions) {
|
|
269
|
+
if (permissions.profile === null)
|
|
270
|
+
return null;
|
|
271
|
+
if (!permissions.proxy && p.kind !== "writeStdin" && addsNetwork(p.additionalPermissions)) {
|
|
272
|
+
return "it asked to add network access to one command, and this session's shell has no network proxy: Codex would give that command every outbound connection, this Mac's loopback and its Unix sockets";
|
|
273
|
+
}
|
|
274
|
+
if (p.networkApprovalContext != null) {
|
|
275
|
+
return permissions.proxy
|
|
276
|
+
? "it asked to reach a host Codex's network proxy refused, which relay never allows: the proxy already allows every public host, and refuses only this Mac's own and private addresses"
|
|
277
|
+
: "it asked for network access, and this job has no shell network, which no approval can give it; ask the caller for a network grant";
|
|
278
|
+
}
|
|
279
|
+
return null;
|
|
280
|
+
}
|
|
281
|
+
/** The name of the permission profile relay defines, for this server only, for every Codex turn it confines (codex.ts codexPermissions). */
|
|
282
|
+
export const CODEX_PROFILE = "relay";
|
|
283
|
+
/** Asks the server how it is signed in. Costs no model request. Returns what is wrong, or null. */
|
|
284
|
+
async function loginProblem(rpc, expect) {
|
|
285
|
+
if (!expect.accountLogin)
|
|
286
|
+
return null;
|
|
287
|
+
let type;
|
|
288
|
+
try {
|
|
289
|
+
type = (await rpc.request("account/read", { refreshToken: false }))?.account?.type;
|
|
290
|
+
}
|
|
291
|
+
catch (err) {
|
|
292
|
+
return `relay could not find out how Codex is signed in (${err.message}), and it is set not to run on API keys ("child_auth": "any" skips this check)`;
|
|
293
|
+
}
|
|
294
|
+
if (type === "chatgpt")
|
|
295
|
+
return null;
|
|
296
|
+
return `Codex is ${type ? `signed in with ${type === "apiKey" ? "an API key" : String(type)}` : "not signed in"}, not with a ChatGPT account, and relay is set not to run on API keys ("child_auth": "any" allows it)`;
|
|
297
|
+
}
|
|
298
|
+
/** Codex's own default for chatgpt_base_url (codex-rs core config): leaving it so redirects nothing. */
|
|
299
|
+
const CHATGPT_BASE_URL = "https://chatgpt.com/backend-api/";
|
|
300
|
+
/**
|
|
301
|
+
* Compares Codex's effective configuration for the child's directory with what relay set. The
|
|
302
|
+
* app server reports the outcome of every layer (packaged, system, managed, user, project,
|
|
303
|
+
* session flags), so this checks the result rather than guessing at the sources. Returns what is
|
|
304
|
+
* wrong, or null.
|
|
305
|
+
*/
|
|
306
|
+
export function configProblem(eff, expect) {
|
|
307
|
+
const wrong = [];
|
|
308
|
+
// A profile named in the config can set the provider and endpoint in place of the top level.
|
|
309
|
+
// Only these keys are read: never auth or anything else a provider entry may carry. (Seen with
|
|
310
|
+
// Codex 0.162.1's config/read: `profile` in config.toml and a [model_providers.openai] table are
|
|
311
|
+
// hard errors there, and profiles.<name>.openai_base_url is ignored. The checks stay, harmless,
|
|
312
|
+
// for other versions.)
|
|
313
|
+
const profileName = typeof eff.profile === "string" ? eff.profile : null;
|
|
314
|
+
const profile = profileName ? (eff.profiles?.[profileName] ?? {}) : {};
|
|
315
|
+
const fromProfile = profile.model_provider != null;
|
|
316
|
+
if (expect.daybreak !== undefined) {
|
|
317
|
+
if (eff.daybreak !== undefined && eff.daybreak !== expect.daybreak)
|
|
318
|
+
wrong.push(`daybreak is ${JSON.stringify(eff.daybreak)} where relay set ${expect.daybreak}`);
|
|
319
|
+
if (profile.daybreak != null && profile.daybreak !== expect.daybreak)
|
|
320
|
+
wrong.push(`profiles.${profileName}.daybreak differs from relay's setting`);
|
|
321
|
+
}
|
|
322
|
+
const provider = fromProfile ? profile.model_provider : eff.model_provider;
|
|
323
|
+
// Which family answers: Codex's own provider (OpenAI) only. Unset means that default.
|
|
324
|
+
if (provider != null && provider !== "openai") {
|
|
325
|
+
wrong.push(`model_provider is ${JSON.stringify(provider)}${fromProfile ? ` (profile ${profileName})` : ""}, not OpenAI's, so relay cannot tell which family of model would answer`);
|
|
326
|
+
}
|
|
327
|
+
else if (!expect.endpointOverride) {
|
|
328
|
+
// OpenAI's provider sent to another endpoint is no longer known to answer with OpenAI's models.
|
|
329
|
+
const redirected = [
|
|
330
|
+
["openai_base_url", eff.openai_base_url],
|
|
331
|
+
...(profileName ? [[`profiles.${profileName}.openai_base_url`, profile.openai_base_url]] : []),
|
|
332
|
+
["model_providers.openai.base_url", eff.model_providers?.openai?.base_url],
|
|
333
|
+
// Under a ChatGPT login, the ChatGPT backend and the realtime endpoints can be sent elsewhere
|
|
334
|
+
// too; Codex's own default for the backend is no redirect.
|
|
335
|
+
["chatgpt_base_url", eff.chatgpt_base_url === CHATGPT_BASE_URL ? null : eff.chatgpt_base_url],
|
|
336
|
+
...Object.keys(eff).filter((k) => /^experimental_realtime_\w*base_url$/.test(k)).sort().map((k) => [k, eff[k]]),
|
|
337
|
+
].filter(([, v]) => v != null);
|
|
338
|
+
if (redirected.length) {
|
|
339
|
+
wrong.push(`${redirected.map(([key, v]) => `${key} is set (${JSON.stringify(v)})`).join(", ")}, which sends Codex to another endpoint than OpenAI's, where relay cannot tell which family of model answers ("codex_endpoint_override": "accept" in relay's config launches it anyway)`);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
// The sandbox: relay's permission profile, selected and exactly as relay defined it. Relay's flags
|
|
343
|
+
// (Codex's session flags, precedence 30) outrank the person's own configuration key by key, but
|
|
344
|
+
// a lower layer can still add keys to a table relay sets (a person's own [permissions.relay] could
|
|
345
|
+
// add a writable path), and Codex's legacy managed layers (managed_config.toml and its MDM form,
|
|
346
|
+
// precedences 40 and 50; config/src/config_layer_source.rs) outrank the flags outright. So the
|
|
347
|
+
// effective profile must be exactly relay's, no key added or changed, whichever layer did it. A
|
|
348
|
+
// legacy sandbox_mode elsewhere does not count: selecting a profile in relay's flags makes Codex
|
|
349
|
+
// ignore it (core/src/config/mod.rs resolve_permission_config_syntax).
|
|
350
|
+
const p = expect.permissions;
|
|
351
|
+
if (eff.default_permissions !== p.id)
|
|
352
|
+
wrong.push(`default_permissions is ${JSON.stringify(eff.default_permissions ?? null)} where relay set ${JSON.stringify(p.id)}`);
|
|
353
|
+
if (p.profile) {
|
|
354
|
+
const got = withoutNulls(eff.permissions?.[CODEX_PROFILE]);
|
|
355
|
+
if (canonicalJson(got) !== canonicalJson(p.profile))
|
|
356
|
+
wrong.push(`the permission profile ${JSON.stringify(CODEX_PROFILE)} is ${JSON.stringify(got ?? null)} where relay set ${JSON.stringify(p.profile)}`);
|
|
357
|
+
}
|
|
358
|
+
// The network proxy, as a boolean: a table there ([features.network_proxy] from a layer relay's flag
|
|
359
|
+
// did not replace) carries settings of its own that Codex applies over the profile's.
|
|
360
|
+
if (p.proxy && eff.features?.network_proxy !== true)
|
|
361
|
+
wrong.push(`features.network_proxy is ${JSON.stringify(eff.features?.network_proxy ?? null)} where relay set true, so the agent's commands would not go through Codex's network proxy as relay set it`);
|
|
362
|
+
for (const name of ["request_permissions_tool", "exec_permission_approvals"]) {
|
|
363
|
+
if (expect.features?.[name] === false && eff.features?.[name] === true)
|
|
364
|
+
wrong.push(`features.${name} is true where relay set false`);
|
|
365
|
+
}
|
|
366
|
+
// The speed: what a turn costs. A server that does not report the key is judged by its thread's report instead (startCodexAppTurn).
|
|
367
|
+
if (expect.speed) {
|
|
368
|
+
const tier = expect.speed.tier;
|
|
369
|
+
if (eff.service_tier !== undefined && eff.service_tier !== tier)
|
|
370
|
+
wrong.push(`service_tier is ${JSON.stringify(eff.service_tier)} where relay set ${JSON.stringify(tier)}`);
|
|
371
|
+
if (profile.service_tier != null && profile.service_tier !== tier)
|
|
372
|
+
wrong.push(`profiles.${profileName}.service_tier is ${JSON.stringify(profile.service_tier)} where relay set ${JSON.stringify(tier)}`);
|
|
373
|
+
// Standard turns fast mode on for the "default" pin to hold (codex.ts codexFlags); a faster speed with it off is refused by fastModeProblem.
|
|
374
|
+
if (expect.speed.name === "standard" && eff.features?.fast_mode === false)
|
|
375
|
+
wrong.push(`features.fast_mode is false where relay set true, so Codex would drop the "default" service tier relay pins for standard speed`);
|
|
376
|
+
}
|
|
377
|
+
if (eff.approvals_reviewer !== "user")
|
|
378
|
+
wrong.push(`approvals_reviewer is ${JSON.stringify(eff.approvals_reviewer)} where relay set "user"`);
|
|
379
|
+
// A search could carry what the agent read (a credential, for a turn given MCP servers) past relay's gate.
|
|
380
|
+
if (expect.webSearch && eff.web_search !== expect.webSearch)
|
|
381
|
+
wrong.push(`web_search is ${JSON.stringify(eff.web_search ?? null)} where relay set ${JSON.stringify(expect.webSearch)}`);
|
|
382
|
+
const servers = (eff.mcp_servers ?? {});
|
|
383
|
+
const r = servers.relay;
|
|
384
|
+
if (expect.relay) {
|
|
385
|
+
// The server the agent will get must be the one carrying this turn's identity, not some other entry named relay.
|
|
386
|
+
if (!r || r.enabled === false)
|
|
387
|
+
wrong.push("relay's own MCP server is missing or off where it should be on");
|
|
388
|
+
else {
|
|
389
|
+
if (r.command !== expect.relay.command || JSON.stringify(r.args ?? []) !== JSON.stringify(expect.relay.args))
|
|
390
|
+
wrong.push("relay's MCP server entry is not the command relay injected");
|
|
391
|
+
const envOff = Object.entries(expect.relay.env).filter(([k, v]) => r.env?.[k] !== v).map(([k]) => k);
|
|
392
|
+
if (envOff.length)
|
|
393
|
+
wrong.push(`relay's MCP server entry does not carry the identity relay injected (${envOff.join(", ")})`);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
else if (r && r.enabled !== false) {
|
|
397
|
+
wrong.push("a relay MCP server is on where this turn should have none");
|
|
398
|
+
}
|
|
399
|
+
if (expect.broker) {
|
|
400
|
+
const problem = stage2BrokerConfigProblem(servers[BROKER_SERVER_NAME], expect.broker);
|
|
401
|
+
if (problem)
|
|
402
|
+
wrong.push(problem);
|
|
403
|
+
}
|
|
404
|
+
if (expect.relayOnly) {
|
|
405
|
+
const on = Object.entries(servers).filter(([name, s]) => name !== "relay" && !(expect.broker && name === BROKER_SERVER_NAME) && s?.enabled !== false).map(([name]) => name);
|
|
406
|
+
if (on.length)
|
|
407
|
+
wrong.push(`other MCP servers are still enabled (${on.join(", ")})`);
|
|
408
|
+
if (eff.features?.plugins !== false)
|
|
409
|
+
wrong.push("plugins are still enabled");
|
|
410
|
+
}
|
|
411
|
+
if (expect.skills && eff.features?.skill_mcp_dependency_install !== false)
|
|
412
|
+
wrong.push("skills could still install MCP servers they depend on (skill_mcp_dependency_install)");
|
|
413
|
+
return wrong.length ? `relay will not start a Codex agent, because Codex's effective configuration is not what relay set: ${wrong.join("; ")}.` : null;
|
|
414
|
+
}
|
|
415
|
+
/** A value with every null and undefined left out, at any depth: how Codex reports a key nothing set (config/read). */
|
|
416
|
+
function withoutNulls(v) {
|
|
417
|
+
if (v === null || v === undefined)
|
|
418
|
+
return undefined;
|
|
419
|
+
if (Array.isArray(v))
|
|
420
|
+
return v.map(withoutNulls);
|
|
421
|
+
if (typeof v !== "object")
|
|
422
|
+
return v;
|
|
423
|
+
const out = {};
|
|
424
|
+
for (const [k, x] of Object.entries(v)) {
|
|
425
|
+
const kept = withoutNulls(x);
|
|
426
|
+
if (kept !== undefined)
|
|
427
|
+
out[k] = kept;
|
|
428
|
+
}
|
|
429
|
+
return out;
|
|
430
|
+
}
|
|
431
|
+
/** JSON with every object's keys sorted, for comparing two values whatever their key order. */
|
|
432
|
+
function canonicalJson(v) {
|
|
433
|
+
if (Array.isArray(v))
|
|
434
|
+
return `[${v.map(canonicalJson).join(",")}]`;
|
|
435
|
+
if (v && typeof v === "object")
|
|
436
|
+
return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${canonicalJson(v[k])}`).join(",")}}`;
|
|
437
|
+
return JSON.stringify(v ?? null);
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* Whether an administrator's requirements (requirements.toml, managed preferences) let Codex use
|
|
441
|
+
* relay's profile, or null. Where they list the profiles allowed and relay's is not one, Codex
|
|
442
|
+
* falls back to the one they require and only warns (core/src/config/mod.rs
|
|
443
|
+
* resolve_default_permissions); where they list the sandbox modes allowed, a profile whose mode is
|
|
444
|
+
* not one is not used either. Relay refuses the turn rather than run it in a sandbox it did not
|
|
445
|
+
* set. Asked of the server (configRequirements/read): the `codex exec` fallback has no thread to
|
|
446
|
+
* read the active profile from.
|
|
447
|
+
*/
|
|
448
|
+
export async function requirementsProblem(rpc, p) {
|
|
449
|
+
const refuse = (why) => `relay will not start a Codex agent, because ${why}.`;
|
|
450
|
+
let req;
|
|
451
|
+
try {
|
|
452
|
+
req = (await rpc.request("configRequirements/read", {}))?.requirements;
|
|
453
|
+
}
|
|
454
|
+
catch (err) {
|
|
455
|
+
return refuse(`relay could not read the requirements an administrator may have set for Codex (${err.message}), which decide whether Codex uses relay's sandbox`);
|
|
456
|
+
}
|
|
457
|
+
const allowed = req?.allowedPermissionProfiles;
|
|
458
|
+
if (allowed && allowed[p.id] !== true)
|
|
459
|
+
return refuse(`an administrator's requirements for Codex allow only the permission profiles ${Object.keys(allowed).filter((k) => allowed[k] === true).map((k) => JSON.stringify(k)).join(", ") || "(none)"}, not relay's ${JSON.stringify(p.id)}, so Codex would run the agent in another sandbox than relay's`);
|
|
460
|
+
const modes = req?.allowedSandboxModes;
|
|
461
|
+
if (Array.isArray(modes) && !modes.includes(p.sandbox))
|
|
462
|
+
return refuse(`an administrator's requirements for Codex allow only the sandbox modes ${modes.map((m) => JSON.stringify(m)).join(", ")}, not the ${JSON.stringify(p.sandbox)} of relay's sandbox`);
|
|
463
|
+
return null;
|
|
464
|
+
}
|
|
465
|
+
/**
|
|
466
|
+
* What is wrong with the features Codex reports it runs with (experimentalFeature/list, every page),
|
|
467
|
+
* against those relay set (Expected.features), or null. The feature list is the server's own: a key
|
|
468
|
+
* Codex does not know is absent from it, where config/read would echo any key it was given. So the
|
|
469
|
+
* network proxy must be listed and on; any other feature relay set must, where it is listed, be as
|
|
470
|
+
* relay set it (a Codex that does not list it does not have it).
|
|
471
|
+
*/
|
|
472
|
+
export async function featuresProblem(rpc, expect) {
|
|
473
|
+
const want = expect.features;
|
|
474
|
+
if (!want || !Object.keys(want).length)
|
|
475
|
+
return null;
|
|
476
|
+
const listed = new Map();
|
|
477
|
+
try {
|
|
478
|
+
let cursor;
|
|
479
|
+
for (let page = 0; page < 50; page++) {
|
|
480
|
+
const r = await rpc.request("experimentalFeature/list", { limit: 500, ...(cursor ? { cursor } : {}) });
|
|
481
|
+
for (const f of (r?.data ?? []))
|
|
482
|
+
if (typeof f?.name === "string")
|
|
483
|
+
listed.set(f.name, f.enabled);
|
|
484
|
+
cursor = typeof r?.nextCursor === "string" && r.nextCursor ? r.nextCursor : null;
|
|
485
|
+
if (!cursor)
|
|
486
|
+
break;
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
catch (err) {
|
|
490
|
+
return `relay could not read the features Codex runs with (experimentalFeature/list: ${err.message})`;
|
|
491
|
+
}
|
|
492
|
+
const wrong = [];
|
|
493
|
+
for (const [name, on] of Object.entries(want)) {
|
|
494
|
+
if (!listed.has(name)) {
|
|
495
|
+
if (name === "network_proxy")
|
|
496
|
+
wrong.push("Codex does not list its network_proxy feature, so this Codex has no network proxy relay can rely on");
|
|
497
|
+
}
|
|
498
|
+
else if (listed.get(name) !== on)
|
|
499
|
+
wrong.push(`Codex reports its ${name} feature ${listed.get(name) === true ? "on" : "off"} where relay set it ${on ? "on" : "off"}`);
|
|
500
|
+
}
|
|
501
|
+
return wrong.length ? wrong.join("; ") : null;
|
|
502
|
+
}
|
|
503
|
+
/**
|
|
504
|
+
* Whether an administrator's requirements decide Codex's network instead of relay's profile, or
|
|
505
|
+
* null: managed network settings (requirements.toml [experimental_network], reported as
|
|
506
|
+
* requirements.network) can enable the proxy with their own allowlist and allow_local_binding, and a
|
|
507
|
+
* feature requirement can hold the proxy off.
|
|
508
|
+
*/
|
|
509
|
+
async function networkRequirementsProblem(rpc) {
|
|
510
|
+
let req;
|
|
511
|
+
try {
|
|
512
|
+
req = (await rpc.request("configRequirements/read", {}))?.requirements;
|
|
513
|
+
}
|
|
514
|
+
catch (err) {
|
|
515
|
+
return `relay could not read the requirements an administrator may have set for Codex (${err.message})`;
|
|
516
|
+
}
|
|
517
|
+
if (req?.network != null)
|
|
518
|
+
return "an administrator's requirements for Codex set its network policy (requirements.network), which relay's profile does not decide";
|
|
519
|
+
if (req?.featureRequirements?.network_proxy === false)
|
|
520
|
+
return "an administrator's requirements for Codex hold its network proxy off";
|
|
521
|
+
return null;
|
|
522
|
+
}
|
|
523
|
+
/**
|
|
524
|
+
* Has Codex itself run a short check in the turn's sandbox, before any agent runs: a command started
|
|
525
|
+
* with relay's profile (command/exec), whose network Codex sets up as it would for the agent's
|
|
526
|
+
* commands, tries a loopback port and a Unix socket of relay's own, and loopback through the proxy
|
|
527
|
+
* (CANARY_SCRIPT). Returns what is wrong for `mode`, or null.
|
|
528
|
+
*/
|
|
529
|
+
async function networkCanary(rpc, cwd, mode) {
|
|
530
|
+
let targets;
|
|
531
|
+
try {
|
|
532
|
+
targets = await openCanaryTargets();
|
|
533
|
+
}
|
|
534
|
+
catch (err) {
|
|
535
|
+
return `relay could not open its own test listener (${err.message})`;
|
|
536
|
+
}
|
|
537
|
+
try {
|
|
538
|
+
const r = await rpc.request("command/exec", { command: [process.execPath, "-e", CANARY_SCRIPT, String(targets.port), targets.sock], cwd, permissionProfile: CODEX_PROFILE, timeoutMs: 20_000 });
|
|
539
|
+
// Connections that reached relay's listeners are counted as the event loop takes them.
|
|
540
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
541
|
+
if (r?.exitCode !== 0)
|
|
542
|
+
return `its sandbox check exited with ${JSON.stringify(r?.exitCode ?? null)} (${String(r?.stderr ?? "").trim().split("\n").pop() ?? ""})`;
|
|
543
|
+
return canaryProblem(String(r?.stdout ?? ""), mode, targets.hits());
|
|
544
|
+
}
|
|
545
|
+
catch (err) {
|
|
546
|
+
return `Codex could not run relay's sandbox check (command/exec: ${err.message})`;
|
|
547
|
+
}
|
|
548
|
+
finally {
|
|
549
|
+
targets.close();
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
/**
|
|
553
|
+
* The checks of a turn's features and, where its shell network goes through Codex's proxy, of that
|
|
554
|
+
* network, on a given server: the preflight's (codexNetworkPreflight) and again the one that will
|
|
555
|
+
* run the turn (startCodexAppTurn; codexPreflight for the exec fallback, whose turn has no server to
|
|
556
|
+
* ask). The features (featuresProblem); for a proxied turn no administrator's network requirements
|
|
557
|
+
* (networkRequirementsProblem); for a strict one no public address of this Mac's own
|
|
558
|
+
* (ownPublicAddress) and no network_rule in the rules files Codex loads (networkRuleFiles, from
|
|
559
|
+
* the layers config/read reported); then Codex's own run of the sandbox check (networkCanary).
|
|
560
|
+
* Returns what is wrong, or null.
|
|
561
|
+
*/
|
|
562
|
+
async function proxiedProblem(rpc, o) {
|
|
563
|
+
const features = await featuresProblem(rpc, o.expect);
|
|
564
|
+
if (features)
|
|
565
|
+
return features;
|
|
566
|
+
const mode = o.expect.permissions.proxy;
|
|
567
|
+
if (!mode)
|
|
568
|
+
return null;
|
|
569
|
+
const required = await networkRequirementsProblem(rpc);
|
|
570
|
+
if (required)
|
|
571
|
+
return required;
|
|
572
|
+
if (mode === "strict") {
|
|
573
|
+
const own = ownPublicAddress(o.interfaces);
|
|
574
|
+
if (own)
|
|
575
|
+
return own.why;
|
|
576
|
+
const rules = networkRuleFiles(codexRuleFolders({ layers: o.layers, env: o.env, cwd: o.cwd }));
|
|
577
|
+
if ("error" in rules)
|
|
578
|
+
return rules.error;
|
|
579
|
+
if (rules.files.length)
|
|
580
|
+
return `Codex's exec-policy rules hold network_rule (${rules.files.join(", ")}), which can open a host of this Mac's own to the proxy`;
|
|
581
|
+
}
|
|
582
|
+
return networkCanary(rpc, o.cwd, mode);
|
|
583
|
+
}
|
|
584
|
+
/**
|
|
585
|
+
* Before a turn whose shell network would go through Codex's proxy: a short-lived app server,
|
|
586
|
+
* started with exactly the turn's settings and the agent's environment, asked whether that is what
|
|
587
|
+
* Codex will do (codex.ts chooseNetwork). Returns why relay cannot verify it, or null. Where it
|
|
588
|
+
* cannot, the turn gets Codex's hosted web search and no shell network.
|
|
589
|
+
*
|
|
590
|
+
* - strict mode only: no address of this Mac's own that the proxy would treat as public
|
|
591
|
+
* (ownPublicAddress), and no `network_rule` in any rules file Codex would load (networkRuleFiles);
|
|
592
|
+
* - the effective configuration exactly as relay set it (configProblem) and the profile Codex
|
|
593
|
+
* uses (requirementsProblem), no administrator's network requirements;
|
|
594
|
+
* - the features (featuresProblem) and Codex's own run of relay's sandbox check (networkCanary).
|
|
595
|
+
*/
|
|
596
|
+
export async function codexNetworkPreflight(o) {
|
|
597
|
+
if (o.mode === "strict") {
|
|
598
|
+
const own = ownPublicAddress(o.interfaces);
|
|
599
|
+
if (own)
|
|
600
|
+
return own.why;
|
|
601
|
+
}
|
|
602
|
+
if (o.signal?.aborted)
|
|
603
|
+
return "the turn was stopped";
|
|
604
|
+
const rpc = connect(o.bin, o.args, o.cwd, o.env, () => { });
|
|
605
|
+
const stderrTail = diagnosticTail(600);
|
|
606
|
+
rpc.child.stderr.on("data", (d) => stderrTail.write(d.toString()));
|
|
607
|
+
const unprefixed = (problem) => problem.replace(/^relay will not start a Codex agent, because /, "").replace(/\.$/, "");
|
|
608
|
+
const check = async () => {
|
|
609
|
+
try {
|
|
610
|
+
await rpc.request("initialize", HELLO);
|
|
611
|
+
rpc.send({ method: "initialized" });
|
|
612
|
+
const read = await rpc.request("config/read", { cwd: o.cwd, includeLayers: true });
|
|
613
|
+
const problem = configProblem(read?.config ?? {}, o.expect) ?? (await requirementsProblem(rpc, o.expect.permissions));
|
|
614
|
+
if (problem)
|
|
615
|
+
return unprefixed(problem);
|
|
616
|
+
return await proxiedProblem(rpc, { cwd: o.cwd, expect: o.expect, env: o.env, layers: read?.layers, interfaces: o.interfaces });
|
|
617
|
+
}
|
|
618
|
+
catch (err) {
|
|
619
|
+
const stderr = stderrTail.text().trim();
|
|
620
|
+
return `relay could not ask Codex (${err.message}${stderr ? `: ${stderr.split("\n").pop()}` : ""})`;
|
|
621
|
+
}
|
|
622
|
+
};
|
|
623
|
+
let timer;
|
|
624
|
+
let onAbort;
|
|
625
|
+
const cut = new Promise((resolve) => {
|
|
626
|
+
timer = setTimeout(() => resolve("Codex did not answer in time"), PREFLIGHT_MS);
|
|
627
|
+
onAbort = () => resolve("the turn was stopped");
|
|
628
|
+
o.signal?.addEventListener("abort", onAbort, { once: true });
|
|
629
|
+
});
|
|
630
|
+
try {
|
|
631
|
+
return await Promise.race([check(), cut]);
|
|
632
|
+
}
|
|
633
|
+
finally {
|
|
634
|
+
clearTimeout(timer);
|
|
635
|
+
if (onAbort)
|
|
636
|
+
o.signal?.removeEventListener("abort", onAbort);
|
|
637
|
+
rpc.child.stdin.end();
|
|
638
|
+
if (!await drainGroup(rpc.pid))
|
|
639
|
+
process.stderr.write(`relay could not clean up Codex network preflight: cleanup refused for process group ${rpc.pid}\n`);
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
/** The kind of sandbox Codex reports for a thread (its legacy SandboxPolicy, thread/start `sandbox`), for each kind relay asks for. */
|
|
643
|
+
const SANDBOX_TYPE = { "read-only": "readOnly", "workspace-write": "workspaceWrite", "danger-full-access": "dangerFullAccess" };
|
|
644
|
+
/**
|
|
645
|
+
* What is wrong with the permissions a started or resumed thread reports it runs with, or null:
|
|
646
|
+
* the active profile must be relay's (an administrator's requirements can make Codex fall back to
|
|
647
|
+
* another, with only a warning), and Codex's description of the sandbox must be of the kind relay
|
|
648
|
+
* set, with the network as relay set it and only the turn's TMPDIR of the temporary directories.
|
|
649
|
+
* That description cannot show relay's read-only names; config/read has checked the profile that
|
|
650
|
+
* holds them.
|
|
651
|
+
*
|
|
652
|
+
* Its workspace roots must be the turn's directory alone, and the directories it may write only
|
|
653
|
+
* that and the profile's own roots: relay's profile makes every workspace root writable
|
|
654
|
+
* (`:workspace_roots`), and a resumed thread restores the roots it stored unless the thread is told
|
|
655
|
+
* others (app-server thread_processor.rs, thread/resume). One started under relay's earlier
|
|
656
|
+
* settings stored its grants among them, so without this a grant taken away on resume would stay
|
|
657
|
+
* writable. Relay names the roots on every start and resume (runtimeWorkspaceRoots), and checks
|
|
658
|
+
* here that Codex took them.
|
|
659
|
+
*/
|
|
660
|
+
export function threadPermissionsProblem(t, p, cwd) {
|
|
661
|
+
const refuse = (why) => `relay will not start a Codex agent, because its thread ${why}.`;
|
|
662
|
+
const active = t?.activePermissionProfile?.id;
|
|
663
|
+
if (active !== p.id)
|
|
664
|
+
return refuse(active === undefined || active === null ? `does not report which permission profile it runs with, so relay cannot tell that it is relay's ${JSON.stringify(p.id)}` : `runs with the permission profile ${JSON.stringify(active)}, not relay's ${JSON.stringify(p.id)} (an administrator's requirements can make Codex replace it)`);
|
|
665
|
+
const s = t?.sandbox ?? {};
|
|
666
|
+
if (s.type !== SANDBOX_TYPE[p.sandbox])
|
|
667
|
+
return refuse(`reports a ${JSON.stringify(s.type ?? null)} sandbox where relay set ${JSON.stringify(SANDBOX_TYPE[p.sandbox])}`);
|
|
668
|
+
// Stage 2 (enforcement "relay", codex-stage2.ts): Codex's sandbox is off because relay's Seatbelt
|
|
669
|
+
// around the executor confines. The thread's roots and environments are checked by
|
|
670
|
+
// stage2ThreadProblem, which knows a resumed thread: on an app server without Codex's `local`
|
|
671
|
+
// environment it reports no environment and so no roots until relay's turn binds it. Allow_dangerous
|
|
672
|
+
// is not confined, and nothing more is read.
|
|
673
|
+
if (p.sandbox === "danger-full-access")
|
|
674
|
+
return null;
|
|
675
|
+
if (s.networkAccess !== p.network)
|
|
676
|
+
return refuse(`reports network access ${JSON.stringify(s.networkAccess ?? null)} where relay set ${p.network}`);
|
|
677
|
+
if (p.sandbox === "workspace-write" && (s.excludeSlashTmp !== true || s.excludeTmpdirEnvVar !== false))
|
|
678
|
+
return refuse(`reports temporary directories other than the turn's own as writable (excludeSlashTmp ${JSON.stringify(s.excludeSlashTmp ?? null)}, excludeTmpdirEnvVar ${JSON.stringify(s.excludeTmpdirEnvVar ?? null)})`);
|
|
679
|
+
const here = canonical(cwd);
|
|
680
|
+
const roots = t?.runtimeWorkspaceRoots;
|
|
681
|
+
if (!Array.isArray(roots) || roots.length !== 1 || typeof roots[0] !== "string" || canonical(roots[0]) !== here) {
|
|
682
|
+
return refuse(`reports the workspace roots ${JSON.stringify(roots ?? null)} where relay set only the turn's directory ${JSON.stringify(cwd)}, and every workspace root is writable under relay's profile`);
|
|
683
|
+
}
|
|
684
|
+
const allowed = new Set([here, ...Object.keys(p.profile?.workspace_roots ?? {}).map((r) => canonical(r))]);
|
|
685
|
+
const writable = Array.isArray(s.writableRoots) ? s.writableRoots : [];
|
|
686
|
+
const extra = writable.filter((r) => typeof r !== "string" || !allowed.has(canonical(r)));
|
|
687
|
+
if (extra.length)
|
|
688
|
+
return refuse(`reports ${JSON.stringify(extra)} as writable, which relay did not grant this turn`);
|
|
689
|
+
return null;
|
|
690
|
+
}
|
|
691
|
+
/**
|
|
692
|
+
* What is wrong with the model a started or resumed thread reports, or null. A provider other than
|
|
693
|
+
* OpenAI's is refused whenever it is reported. When relay asked for a model, the thread's identity
|
|
694
|
+
* is what proves that model answers, so both fields must be reported and match: a server that
|
|
695
|
+
* leaves either out is refused, not trusted. When no model was asked for, config/read has checked
|
|
696
|
+
* the provider and any model the thread names is accepted.
|
|
697
|
+
*/
|
|
698
|
+
function threadProblem(t, expect) {
|
|
699
|
+
const refuse = (why) => `relay will not start a Codex agent, because its thread ${why}.`;
|
|
700
|
+
if (typeof t?.modelProvider === "string" && t.modelProvider !== "openai") {
|
|
701
|
+
return refuse(`reports the model provider ${JSON.stringify(t.modelProvider)}, not OpenAI's, so relay cannot tell which family of model would answer`);
|
|
702
|
+
}
|
|
703
|
+
if (!expect.model)
|
|
704
|
+
return null;
|
|
705
|
+
if (typeof t?.modelProvider !== "string")
|
|
706
|
+
return refuse(`does not report its model provider, so relay cannot tell that OpenAI's ${JSON.stringify(expect.model)} answers`);
|
|
707
|
+
if (typeof t?.model !== "string")
|
|
708
|
+
return refuse(`does not report its model, so relay cannot tell that the ${JSON.stringify(expect.model)} it asked for answers`);
|
|
709
|
+
if (t.model !== expect.model)
|
|
710
|
+
return refuse(`reports the model ${JSON.stringify(t.model)}, not the ${JSON.stringify(expect.model)} relay asked for`);
|
|
711
|
+
return null;
|
|
712
|
+
}
|
|
713
|
+
/** The account's model catalog, every page, hidden models included (one a person configured may be hidden). Costs no model request. */
|
|
714
|
+
async function readCatalog(rpc) {
|
|
715
|
+
const out = [];
|
|
716
|
+
let cursor = null;
|
|
717
|
+
for (let page = 0; page < 50; page++) {
|
|
718
|
+
const r = (await rpc.request("model/list", { includeHidden: true, ...(cursor ? { cursor } : {}) }));
|
|
719
|
+
out.push(...(Array.isArray(r?.data) ? r.data : []));
|
|
720
|
+
cursor = typeof r?.nextCursor === "string" && r.nextCursor ? r.nextCursor : null;
|
|
721
|
+
if (!cursor)
|
|
722
|
+
break;
|
|
723
|
+
}
|
|
724
|
+
return out;
|
|
725
|
+
}
|
|
726
|
+
/** Recheck the cached opt-in against this server's current catalog before submitting a turn.
|
|
727
|
+
* A stale cache, revoked access or unavailable discovery downgrades to standard, never a model
|
|
728
|
+
* eligibility rejection from Codex. The catalog cannot enable what the person did not enable.
|
|
729
|
+
*/
|
|
730
|
+
async function daybreakSkip(rpc, model) {
|
|
731
|
+
try {
|
|
732
|
+
const matches = (await readCatalog(rpc)).filter((m) => (m.model ?? m.id) === model);
|
|
733
|
+
if (model && matches.length === 1 && matches[0].availableAccessPrograms?.cyber?.includes("daybreakBlue"))
|
|
734
|
+
return null;
|
|
735
|
+
}
|
|
736
|
+
catch { /* An unavailable catalog also runs standard. */ }
|
|
737
|
+
return `Daybreak was requested, but Codex's current catalog does not confirm daybreak_blue for ${JSON.stringify(model ?? "unknown model")}; this turn runs without Daybreak.`;
|
|
738
|
+
}
|
|
739
|
+
/**
|
|
740
|
+
* For a faster speed on a turn that carries on a thread and names no model: the thread's own model
|
|
741
|
+
* (thread/read, metadata only: it runs nothing and costs no model request), which Codex resumes it
|
|
742
|
+
* on (rather than whatever its default is now). Undefined otherwise, or when it cannot be read,
|
|
743
|
+
* and then the configured or catalog default is checked; on the app server the thread's reported
|
|
744
|
+
* model is checked again after it resumes.
|
|
745
|
+
*/
|
|
746
|
+
async function continuedModel(rpc, expect, sessionId) {
|
|
747
|
+
if (!sessionId || !expect.speed || expect.speed.name === "standard")
|
|
748
|
+
return undefined;
|
|
749
|
+
try {
|
|
750
|
+
const model = (await rpc.request("thread/read", { threadId: sessionId, includeTurns: false }))?.thread?.model;
|
|
751
|
+
return typeof model === "string" && model ? model : undefined;
|
|
752
|
+
}
|
|
753
|
+
catch {
|
|
754
|
+
return undefined;
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
/** Relay's name for each of Codex's service tiers that relay asks for (targets/codex.ts), for messages. */
|
|
758
|
+
const SPEED_OF_TIER = { priority: "fast", ultrafast: "ultrafast" };
|
|
759
|
+
/** Codex plan types (account/read planType) as OpenAI names the plans, where the research of 2026-10-16 named them; for messages only, never to decide. */
|
|
760
|
+
const PLAN_NAMES = { prolite: "Pro $100", promax: "Pro $500" };
|
|
761
|
+
/**
|
|
762
|
+
* Why the account's catalog does not offer the speed relay asked for, with the model the thread
|
|
763
|
+
* would run, or null. Decided from the catalog alone (model/list serviceTiers), never from the
|
|
764
|
+
* plan (decided 2026-10-16): the plan is named only to explain a refusal. Standard needs no catalog.
|
|
765
|
+
* `model`: the one relay asked for, or Codex's configured one; else the catalog's default. The
|
|
766
|
+
* remedy names a speed to pass, never leaving speed out: the speed may not be the call's own (a
|
|
767
|
+
* session's, a launched agent's inherited one, targets.<id>.speed), and then leaving it out gets it
|
|
768
|
+
* again. `continues`: the turn carries on a session, whose model a call cannot change.
|
|
769
|
+
*/
|
|
770
|
+
export function tierProblem(catalog, model, speed, o = {}) {
|
|
771
|
+
if (speed.name === "standard")
|
|
772
|
+
return null;
|
|
773
|
+
const refuse = (why) => `relay will not start a Codex agent at ${speed.name} speed, because ${why}`;
|
|
774
|
+
const named = (m) => m.model ?? m.id;
|
|
775
|
+
const entry = model ? catalog.find((m) => named(m) === model || m.id === model) : catalog.find((m) => m.isDefault);
|
|
776
|
+
if (!entry) {
|
|
777
|
+
const remedy = (naming) => (o.continues ? 'Pass speed: "standard".' : `${naming}, or pass speed: "standard".`);
|
|
778
|
+
return refuse(model
|
|
779
|
+
? `${JSON.stringify(model)} is not in this account's Codex catalog (model/list), so relay cannot tell whether it is offered ${speed.name} there. ${remedy("Name a model the catalog lists")}`
|
|
780
|
+
: `this account's Codex catalog (model/list) names no default model, so relay cannot tell which model would run or whether it is offered that speed. ${remedy("Name the model")}`);
|
|
781
|
+
}
|
|
782
|
+
const tiers = (entry.serviceTiers ?? []).map((t) => t?.id).filter((t) => typeof t === "string");
|
|
783
|
+
if (tiers.includes(speed.tier))
|
|
784
|
+
return null;
|
|
785
|
+
const offers = tiers.map((t) => SPEED_OF_TIER[t] ?? t);
|
|
786
|
+
const elsewhere = catalog.filter((m) => m !== entry && (m.serviceTiers ?? []).some((t) => t?.id === speed.tier)).map(named).filter(Boolean);
|
|
787
|
+
const planText = o.plan ? `Codex plan: ${PLAN_NAMES[o.plan] ? `${PLAN_NAMES[o.plan]} (${o.plan})` : o.plan}` : "";
|
|
788
|
+
const where = speed.name === "ultrafast" ? "OpenAI offers ultrafast on Pro $500 and eligible Enterprise and Edu plans, for GPT-6 Astra and GPT-6.1 Sol" : "";
|
|
789
|
+
// The slower speeds relay can ask for that the catalog offers for this model, fastest first, and
|
|
790
|
+
// standard: a refusal never points at a speed that costs more than the one refused.
|
|
791
|
+
const passable = [...["ultrafast", "fast"].filter((s) => offers.includes(s) && speedRank(s) < speedRank(speed.name)), "standard"];
|
|
792
|
+
return refuse(`${speed.name} isn't offered to this account for ${named(entry)}${planText || where ? ` (${[planText, where].filter(Boolean).join("; ")})` : ""}: ` +
|
|
793
|
+
`the account's catalog offers ${offers.length ? `${offers.join(" and ")} for it` : "no faster speed for it"}${elsewhere.length ? `, and ${speed.name} for ${elsewhere.join(", ")}` : ""}. ` +
|
|
794
|
+
`Pass speed: ${passable.map((s) => JSON.stringify(s)).join(" or ")}${elsewhere.length && !o.continues ? ", or name one of those models" : ""}.`);
|
|
795
|
+
}
|
|
796
|
+
/**
|
|
797
|
+
* Why a faster speed cannot be served while fast mode is turned off in Codex's own configuration
|
|
798
|
+
* (features.fast_mode = false: Codex 0.163.0 then drops every service tier), or null. Relay leaves
|
|
799
|
+
* that switch as the person set it for a faster turn, so the turn is refused, before any thread
|
|
800
|
+
* exists, rather than run at standard while billed as asked for fast.
|
|
801
|
+
*/
|
|
802
|
+
export function fastModeProblem(eff, expect) {
|
|
803
|
+
if (!expect.speed || expect.speed.name === "standard" || eff?.features?.fast_mode !== false)
|
|
804
|
+
return null;
|
|
805
|
+
return `relay will not start a Codex agent at ${expect.speed.name} speed, because fast mode is turned off in Codex's own configuration (features.fast_mode = false), and Codex then drops every service tier, the ${JSON.stringify(expect.speed.tier)} relay would ask for included. Relay's own Codex home does not set it, so a configuration layer relay does not write does (an administrator's /etc/codex or managed configuration, say): turn it back on there, or pass speed: "standard".`;
|
|
806
|
+
}
|
|
807
|
+
/** The account's plan type (account/read), for a refusal's message; null when it cannot be read. */
|
|
808
|
+
async function planOf(rpc) {
|
|
809
|
+
try {
|
|
810
|
+
const plan = (await rpc.request("account/read", { refreshToken: false }))?.account?.planType;
|
|
811
|
+
return typeof plan === "string" ? plan : null;
|
|
812
|
+
}
|
|
813
|
+
catch {
|
|
814
|
+
return null;
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
/** tierProblem against the account's catalog, read from the server, with the plan named in a refusal. Null without reading anything for standard. */
|
|
818
|
+
async function catalogProblem(rpc, expect, model, o) {
|
|
819
|
+
if (!expect.speed || expect.speed.name === "standard")
|
|
820
|
+
return null;
|
|
821
|
+
const listed = o.catalog ?? (await readCatalog(rpc));
|
|
822
|
+
if (!tierProblem(listed, model, expect.speed))
|
|
823
|
+
return null;
|
|
824
|
+
return tierProblem(listed, model, expect.speed, { plan: await planOf(rpc), continues: o.continues });
|
|
825
|
+
}
|
|
826
|
+
/**
|
|
827
|
+
* What is wrong with the service tier a started or resumed thread reports (ThreadStartResponse
|
|
828
|
+
* serviceTier), or null. It must be the tier relay asked for, standard's "default" included: Codex
|
|
829
|
+
* 0.163.0 reports null both for a tier it dropped (one the account does not have) and for none, and
|
|
830
|
+
* with none a model's catalog default applies (priority, for some). A server that leaves the key
|
|
831
|
+
* out is judged by its effective configuration alone (configProblem).
|
|
832
|
+
*/
|
|
833
|
+
function threadTierProblem(t, expect) {
|
|
834
|
+
if (!expect.speed || !t || !("serviceTier" in t))
|
|
835
|
+
return null;
|
|
836
|
+
const { tier, name } = expect.speed;
|
|
837
|
+
return t.serviceTier === tier ? null : `relay will not start a Codex agent, because its thread reports the service tier ${JSON.stringify(t.serviceTier)}, not the ${JSON.stringify(tier)} (${name} speed) relay asked for.`;
|
|
838
|
+
}
|
|
839
|
+
/** Starts `codex app-server` and speaks its JSON-RPC over stdio. onMessage sees everything that is not a reply. */
|
|
840
|
+
export function connect(bin, args, cwd, env, onMessage) {
|
|
841
|
+
const child = spawn(executable(bin, env.PATH), args, { cwd, env, detached: true, stdio: ["pipe", "pipe", "pipe"] });
|
|
842
|
+
child.stdin.on("error", () => { });
|
|
843
|
+
let id = 1;
|
|
844
|
+
const waiting = new Map();
|
|
845
|
+
const send = (m) => void child.stdin.write(JSON.stringify(m) + "\n");
|
|
846
|
+
readline.createInterface({ input: child.stdout }).on("line", (line) => {
|
|
847
|
+
let m;
|
|
848
|
+
try {
|
|
849
|
+
m = JSON.parse(line);
|
|
850
|
+
}
|
|
851
|
+
catch {
|
|
852
|
+
return;
|
|
853
|
+
}
|
|
854
|
+
if (m.id !== undefined && m.method === undefined) {
|
|
855
|
+
const w = waiting.get(m.id);
|
|
856
|
+
waiting.delete(m.id);
|
|
857
|
+
if (m.error)
|
|
858
|
+
w?.reject(new Error(m.error.message ?? JSON.stringify(m.error)));
|
|
859
|
+
else
|
|
860
|
+
w?.resolve(m.result);
|
|
861
|
+
return;
|
|
862
|
+
}
|
|
863
|
+
onMessage(m, line);
|
|
864
|
+
});
|
|
865
|
+
// Once the server is gone, a request can never be answered: it is refused at once rather than
|
|
866
|
+
// left waiting (a preflight that went on after its server exited would never settle, nor release
|
|
867
|
+
// what it held, the canary's listeners among them).
|
|
868
|
+
let closed = null;
|
|
869
|
+
const rejectPending = (err) => {
|
|
870
|
+
closed ??= err;
|
|
871
|
+
for (const w of waiting.values())
|
|
872
|
+
w.reject(err);
|
|
873
|
+
waiting.clear();
|
|
874
|
+
};
|
|
875
|
+
child.on("error", rejectPending);
|
|
876
|
+
child.on("close", () => rejectPending(new Error("codex app-server exited")));
|
|
877
|
+
return {
|
|
878
|
+
child, pid: child.pid ?? -1, send, nextId: () => id++,
|
|
879
|
+
disconnect: () => rejectPending(new Error("relay disconnected the Codex app server after cleanup was refused")),
|
|
880
|
+
request: (method, params) => new Promise((resolve, reject) => {
|
|
881
|
+
if (closed)
|
|
882
|
+
return reject(closed);
|
|
883
|
+
const n = id++;
|
|
884
|
+
waiting.set(n, { resolve, reject });
|
|
885
|
+
send({ id: n, method, params });
|
|
886
|
+
}),
|
|
887
|
+
};
|
|
888
|
+
}
|
|
889
|
+
/**
|
|
890
|
+
* Codex's experimental API is on for every server relay starts: a thread is told to use relay's
|
|
891
|
+
* permission profile (thread/start and thread/resume `permissions`), Daybreak is pinned per turn,
|
|
892
|
+
* and the thread reports its active profile, all of which 0.163.0 gates behind it.
|
|
893
|
+
*
|
|
894
|
+
* Do not advertise `requiredHumanApproval` here until relay enforces person-only, one-time
|
|
895
|
+
* decisions for such requests. From 0.167.0 a managed `prompt_user` exec-policy rule asks for a
|
|
896
|
+
* human-only approval (ExecApprovalKind::HumanCommand, core/src/exec_policy.rs
|
|
897
|
+
* NeedsHumanApproval), which Codex sends only to a client that advertises that capability;
|
|
898
|
+
* without it Codex turns the request into a denial. Relay's approval paths let the root agent,
|
|
899
|
+
* a standing grant or a session-wide answer decide, so advertising it would let something other
|
|
900
|
+
* than a fresh human decision answer a request Codex reserves for one
|
|
901
|
+
* (test/codex-network.test.ts; docs/qualification/codex-0.167.0-hand-checks.md).
|
|
902
|
+
*/
|
|
903
|
+
const HELLO = { clientInfo: { name: "relay", title: "relay", version: "0.1.0" }, capabilities: { experimentalApi: true, optOutNotificationMethods: OPT_OUT } };
|
|
904
|
+
/**
|
|
905
|
+
* For every launched turn: adds relay's package of
|
|
906
|
+
* skills, if the turn has one, as an extra skill root of this server only, then asks the server,
|
|
907
|
+
* re-scanning, which skills it will load in the turn's directory. Every enabled skill must be
|
|
908
|
+
* one of relay's copies, by exactly the name relay gave it at
|
|
909
|
+
* <root>/<name>/SKILL.md (a skill elsewhere under the root, or under another name there, was not
|
|
910
|
+
* what the person consented to), and every copy must be there and enabled. A turn given
|
|
911
|
+
* no skills has no copies: none may be enabled. Returns what is wrong, or null.
|
|
912
|
+
*/
|
|
913
|
+
export async function skillsProblem(rpc, cwd, skills) {
|
|
914
|
+
const refuse = (why) => `relay will not start a Codex agent, because ${why}.`;
|
|
915
|
+
let listed;
|
|
916
|
+
try {
|
|
917
|
+
if (skills.root)
|
|
918
|
+
await rpc.request("skills/extraRoots/set", { extraRoots: [skills.root] });
|
|
919
|
+
listed = await rpc.request("skills/list", { cwds: [cwd], forceReload: true });
|
|
920
|
+
}
|
|
921
|
+
catch (err) {
|
|
922
|
+
return refuse(`relay could not give it its skills or read which skills it would load (${err.message})`);
|
|
923
|
+
}
|
|
924
|
+
const entry = listed?.data?.[0];
|
|
925
|
+
if (listed?.data?.length !== 1 || !entry || typeof entry.cwd !== "string" || canonical(entry.cwd) !== canonical(cwd) || !Array.isArray(entry.skills))
|
|
926
|
+
return refuse("it did not say which skills it would load in the turn's directory");
|
|
927
|
+
if (!Array.isArray(entry.errors) || entry.errors.length)
|
|
928
|
+
return refuse("it reported errors reading its skills, so relay cannot establish exactly what it would load");
|
|
929
|
+
const mine = skills.root ? canonical(skills.root) : null;
|
|
930
|
+
const at = new Map(mine ? skills.names.map((n) => [n, path.join(mine, n, "SKILL.md")]) : []);
|
|
931
|
+
const given = new Set();
|
|
932
|
+
const stray = [];
|
|
933
|
+
const unnamed = [];
|
|
934
|
+
for (const s of entry.skills) {
|
|
935
|
+
if (typeof s?.enabled !== "boolean" || typeof s?.name !== "string" || typeof s?.path !== "string")
|
|
936
|
+
return refuse("it reported a skill without its name, path or enabled state");
|
|
937
|
+
const file = typeof s?.path === "string" ? s.path : "";
|
|
938
|
+
const ours = mine !== null && file !== "" && inside(file, mine);
|
|
939
|
+
if (s?.enabled === false)
|
|
940
|
+
continue;
|
|
941
|
+
const name = String(s?.name);
|
|
942
|
+
if (!ours)
|
|
943
|
+
stray.push(`${name} (${file || "no path given"})`);
|
|
944
|
+
else if (at.get(name) === canonical(file) && !given.has(name))
|
|
945
|
+
given.add(name);
|
|
946
|
+
else
|
|
947
|
+
unnamed.push(`${name} (${file})`);
|
|
948
|
+
}
|
|
949
|
+
if (stray.length)
|
|
950
|
+
return refuse(`it would also load skills relay did not give it and could not switch off: ${stray.join(", ")}. Check Codex's skill configuration and version`);
|
|
951
|
+
if (unnamed.length)
|
|
952
|
+
return refuse(`it would load skills from relay's package other than the ones relay gave it, each by its own name at <package>/<name>/SKILL.md: ${unnamed.join(", ")}`);
|
|
953
|
+
const missing = skills.names.filter((n) => !given.has(n));
|
|
954
|
+
if (missing.length) {
|
|
955
|
+
const errors = (entry.errors ?? []).filter((e) => mine !== null && typeof e?.path === "string" && inside(e.path, mine)).map((e) => String(e.message));
|
|
956
|
+
return refuse(`it did not load the skills relay gave it (${missing.join(", ")})${errors.length ? `: ${errors.join("; ")}` : ""}`);
|
|
957
|
+
}
|
|
958
|
+
return null;
|
|
959
|
+
}
|
|
960
|
+
/** Older relay sessions may still be active. Codex's unarchive call is not idempotent. */
|
|
961
|
+
async function unarchiveThread(rpc, threadId) {
|
|
962
|
+
try {
|
|
963
|
+
await rpc.request("thread/unarchive", { threadId });
|
|
964
|
+
}
|
|
965
|
+
catch (err) {
|
|
966
|
+
if (!err.message.includes(`no archived rollout found for thread id ${threadId}`))
|
|
967
|
+
throw err;
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
/** Token-free cleanup, also used after exec or a crashed server. No login material is read by relay. */
|
|
971
|
+
export async function archiveCodexThread(o) {
|
|
972
|
+
const rpc = connect(o.bin, o.args, o.cwd, o.env, () => { });
|
|
973
|
+
rpc.child.stderr.resume();
|
|
974
|
+
let timer;
|
|
975
|
+
try {
|
|
976
|
+
await Promise.race([
|
|
977
|
+
(async () => {
|
|
978
|
+
await rpc.request("initialize", HELLO);
|
|
979
|
+
rpc.send({ method: "initialized" });
|
|
980
|
+
await rpc.request("thread/archive", { threadId: o.threadId });
|
|
981
|
+
})(),
|
|
982
|
+
new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("archive timed out")), 10000); }),
|
|
983
|
+
]);
|
|
984
|
+
return null;
|
|
985
|
+
}
|
|
986
|
+
catch (err) {
|
|
987
|
+
return `Could not archive Codex thread ${o.threadId}; it may remain in your Codex history: ${err.message}`;
|
|
988
|
+
}
|
|
989
|
+
finally {
|
|
990
|
+
clearTimeout(timer);
|
|
991
|
+
rpc.child.stdin.end();
|
|
992
|
+
if (!await drainGroup(rpc.pid))
|
|
993
|
+
process.stderr.write(`relay could not clean up Codex thread archive: cleanup refused for process group ${rpc.pid}\n`);
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
/** How long the `codex exec` fallback's configuration check may take, as when it ran as a subprocess. */
|
|
997
|
+
const PREFLIGHT_MS = 30_000;
|
|
998
|
+
/**
|
|
999
|
+
* Used by the `codex exec` fallback: asks a short-lived app server, started with the agent's own
|
|
1000
|
+
* environment, for the effective configuration and checks it. Returns the problem, or null. At its
|
|
1001
|
+
* deadline (PREFLIGHT_MS) it gives up with what the turn has always said then, and an aborted
|
|
1002
|
+
* `signal` (the worker is stopping) ends it at once. Either way its app server is stopped before
|
|
1003
|
+
* it returns.
|
|
1004
|
+
*/
|
|
1005
|
+
export async function codexPreflight(o) {
|
|
1006
|
+
if (o.signal?.aborted)
|
|
1007
|
+
return "the turn was stopped before relay checked Codex's effective configuration";
|
|
1008
|
+
const rpc = connect(o.bin, o.args, o.cwd, o.env, () => { });
|
|
1009
|
+
// Cut of secrets a line at a time before it is clipped (diagnosticTail): what it says is quoted in a refusal.
|
|
1010
|
+
const stderrTail = diagnosticTail(600);
|
|
1011
|
+
rpc.child.stderr.on("data", (d) => stderrTail.write(d.toString()));
|
|
1012
|
+
const check = async () => {
|
|
1013
|
+
try {
|
|
1014
|
+
await rpc.request("initialize", HELLO);
|
|
1015
|
+
rpc.send({ method: "initialized" });
|
|
1016
|
+
const read = await rpc.request("config/read", { cwd: o.cwd, includeLayers: true });
|
|
1017
|
+
const eff = read.config;
|
|
1018
|
+
const problem = configProblem(eff, o.expect) ?? (await requirementsProblem(rpc, o.expect.permissions)) ?? (await loginProblem(rpc, o.expect)) ?? fastModeProblem(eff, o.expect)
|
|
1019
|
+
?? (o.expect.skills ? await skillsProblem(rpc, o.cwd, o.expect.skills) : null);
|
|
1020
|
+
if (problem)
|
|
1021
|
+
return problem;
|
|
1022
|
+
// The features relay set and, for a proxied turn, Codex's own run of the sandbox check: as
|
|
1023
|
+
// codexNetworkPreflight found them, or the configuration changed since, and the turn is refused.
|
|
1024
|
+
const unproved = await proxiedProblem(rpc, { cwd: o.cwd, expect: o.expect, env: o.env, layers: read.layers });
|
|
1025
|
+
if (unproved)
|
|
1026
|
+
return `relay will not start a Codex agent, because ${unproved}.`;
|
|
1027
|
+
if (o.expect.endpointOverride && configProblem(eff, { ...o.expect, endpointOverride: false }))
|
|
1028
|
+
o.onWaived?.("codex_endpoint_override");
|
|
1029
|
+
const policyNote = codexShellPolicyNote(eff?.shell_environment_policy, o.released ?? []);
|
|
1030
|
+
if (policyNote)
|
|
1031
|
+
o.onShellPolicyNote?.(policyNote);
|
|
1032
|
+
if (o.expect.daybreak) {
|
|
1033
|
+
const note = await daybreakSkip(rpc, o.model);
|
|
1034
|
+
if (note)
|
|
1035
|
+
o.onDaybreakSkipped?.(note);
|
|
1036
|
+
}
|
|
1037
|
+
if (o.sessionId)
|
|
1038
|
+
await unarchiveThread(rpc, o.sessionId);
|
|
1039
|
+
const model = o.model ?? (await continuedModel(rpc, o.expect, o.sessionId));
|
|
1040
|
+
const unoffered = await catalogProblem(rpc, o.expect, model ?? eff.model, { continues: Boolean(o.sessionId) });
|
|
1041
|
+
if (unoffered) {
|
|
1042
|
+
// No turn follows to archive the thread again (codex.ts finish), so it is put back here.
|
|
1043
|
+
if (o.sessionId)
|
|
1044
|
+
await rpc.request("thread/archive", { threadId: o.sessionId }).catch(() => { });
|
|
1045
|
+
return unoffered;
|
|
1046
|
+
}
|
|
1047
|
+
// The model checked is the one exec is to run: a thread's own, which relay then names (codex.ts invocation).
|
|
1048
|
+
if (!o.model && model)
|
|
1049
|
+
o.onModel?.(model);
|
|
1050
|
+
return null;
|
|
1051
|
+
}
|
|
1052
|
+
catch (err) {
|
|
1053
|
+
const stderr = stderrTail.text().trim();
|
|
1054
|
+
return `relay could not read Codex's effective configuration (${err.message}${stderr ? `: ${stderr.split("\n").pop()}` : ""}), so it will not start a Codex agent.`;
|
|
1055
|
+
}
|
|
1056
|
+
};
|
|
1057
|
+
let timer;
|
|
1058
|
+
let onAbort;
|
|
1059
|
+
const cut = new Promise((resolve) => {
|
|
1060
|
+
timer = setTimeout(() => resolve("relay could not check Codex's effective configuration"), PREFLIGHT_MS);
|
|
1061
|
+
onAbort = () => resolve("the turn was stopped while relay checked Codex's effective configuration");
|
|
1062
|
+
o.signal?.addEventListener("abort", onAbort, { once: true });
|
|
1063
|
+
});
|
|
1064
|
+
try {
|
|
1065
|
+
return await Promise.race([check(), cut]);
|
|
1066
|
+
}
|
|
1067
|
+
finally {
|
|
1068
|
+
clearTimeout(timer);
|
|
1069
|
+
if (onAbort)
|
|
1070
|
+
o.signal?.removeEventListener("abort", onAbort);
|
|
1071
|
+
rpc.child.stdin.end();
|
|
1072
|
+
if (!await drainGroup(rpc.pid))
|
|
1073
|
+
process.stderr.write(`relay could not clean up Codex configuration check: cleanup refused for process group ${rpc.pid}\n`);
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
/**
|
|
1077
|
+
* Runs one Codex turn through `codex app-server` (JSON-RPC over stdio). The app server is the only
|
|
1078
|
+
* Codex entry point that sends approval requests to its client, and the only one that reports the
|
|
1079
|
+
* effective configuration. One server process per turn, so there is no long-lived broker to go
|
|
1080
|
+
* stale; sessions are the same threads `codex exec` uses.
|
|
1081
|
+
*/
|
|
1082
|
+
/** `stage2`: the hooks of a stage-2 turn (codex-env.ts), called at the points marked; undefined for every other turn. */
|
|
1083
|
+
export function startCodexAppTurn(spec, flags, env, stage2) {
|
|
1084
|
+
if (spec.overlay) {
|
|
1085
|
+
if (spec.signal?.aborted)
|
|
1086
|
+
throw new Error("overlay deadline expired before app-server launch");
|
|
1087
|
+
assertOverlayLaunch(spec.overlay, spec.turnId);
|
|
1088
|
+
}
|
|
1089
|
+
// Stage 2: the app server runs with exactly the environment admission checked, never another.
|
|
1090
|
+
if (stage2 && env !== stage2.env)
|
|
1091
|
+
throw new Error("relay will not start a Codex agent with raw network in an environment other than the one its admission checked.");
|
|
1092
|
+
const { log, warnings: logWarnings } = openAgentLog(spec.logPath, { env });
|
|
1093
|
+
const args = ["app-server", ...flags.off, ...flags.c];
|
|
1094
|
+
log.write(`\n# ${new Date().toISOString()} ${spec.config.targets.codex.bin} ${args.map((a) => JSON.stringify(a)).join(" ")}\n`);
|
|
1095
|
+
let threadId = spec.sessionId;
|
|
1096
|
+
let turnId;
|
|
1097
|
+
let finalMessage = "";
|
|
1098
|
+
let cancelled = false;
|
|
1099
|
+
/** Whether turn/start handed the prompt to the thread. Until then a thread's id is not the session's. */
|
|
1100
|
+
let delivered = false;
|
|
1101
|
+
const stderrTail = diagnosticTail();
|
|
1102
|
+
/** Set once the turn's result is known; the handle resolves only after the server process has gone. */
|
|
1103
|
+
let outcome = null;
|
|
1104
|
+
let resolveDone;
|
|
1105
|
+
const done = new Promise((r) => (resolveDone = r));
|
|
1106
|
+
/** Files each pending file change would touch, by thread and item, including native children. */
|
|
1107
|
+
const fileChanges = new Map();
|
|
1108
|
+
const fileKey = (p, id) => JSON.stringify([p?.threadId ?? threadId, String(id)]);
|
|
1109
|
+
/** Commands and file changes the agent was refused. */
|
|
1110
|
+
const denials = [];
|
|
1111
|
+
const subagents = new CodexSubagents();
|
|
1112
|
+
let groupRefused = false;
|
|
1113
|
+
let cleanupRefusal;
|
|
1114
|
+
const stopTimers = [];
|
|
1115
|
+
const signalGroup = (sig) => {
|
|
1116
|
+
if (groupRefused)
|
|
1117
|
+
return false;
|
|
1118
|
+
if (sig === "SIGKILL")
|
|
1119
|
+
stage2?.disarmTools();
|
|
1120
|
+
if (rpc.pid <= 1)
|
|
1121
|
+
return false;
|
|
1122
|
+
// Every relay-initiated stop needs its last snapshot before signalling: a killed or
|
|
1123
|
+
// zombified server can no longer identify descendants, even before its exit event arrives.
|
|
1124
|
+
settled = watch.look() || settled;
|
|
1125
|
+
try {
|
|
1126
|
+
sendGroupSignal(rpc.pid, sig);
|
|
1127
|
+
}
|
|
1128
|
+
catch (err) {
|
|
1129
|
+
if (isGroupSignalRefusal(err)) {
|
|
1130
|
+
groupRefused = true;
|
|
1131
|
+
cleanupRefusal = `Agent cleanup refused for group ${rpc.pid}: ${err.message}`;
|
|
1132
|
+
// The refused process may never exit. Settle independently, without derived cleanup.
|
|
1133
|
+
void Promise.resolve().then(() => settle(null));
|
|
1134
|
+
return false;
|
|
1135
|
+
}
|
|
1136
|
+
// Already gone.
|
|
1137
|
+
}
|
|
1138
|
+
return true;
|
|
1139
|
+
};
|
|
1140
|
+
let watch;
|
|
1141
|
+
/** True once a look has found the server alive after the turn stopped starting things. */
|
|
1142
|
+
let settled = false;
|
|
1143
|
+
const finish = (r) => {
|
|
1144
|
+
if (outcome)
|
|
1145
|
+
return;
|
|
1146
|
+
stage2?.disarmTools();
|
|
1147
|
+
const warning = subagents.warning();
|
|
1148
|
+
outcome = warning ? { ...r, warnings: [...(r.warnings ?? []), warning] } : r;
|
|
1149
|
+
// The last look, while what the server started can still be traced to it.
|
|
1150
|
+
settled = watch.look() || settled;
|
|
1151
|
+
rpc.child.stdin.end();
|
|
1152
|
+
// No grace period in which the harness could retry a vendor safety stop.
|
|
1153
|
+
if (r.status === "refused")
|
|
1154
|
+
signalGroup("SIGKILL");
|
|
1155
|
+
// The server has no reason to outlive its one turn.
|
|
1156
|
+
stopTimers.push(setTimeout(() => signalGroup("SIGTERM"), 200).unref());
|
|
1157
|
+
stopTimers.push(setTimeout(() => {
|
|
1158
|
+
if (signalGroup("SIGKILL"))
|
|
1159
|
+
killProcs(watch.procs());
|
|
1160
|
+
}, 200 + spec.config.cancel_grace_ms).unref());
|
|
1161
|
+
};
|
|
1162
|
+
const onServerRequest = async (m) => {
|
|
1163
|
+
const p = m.params ?? {};
|
|
1164
|
+
// Stage 2: before anything is shown or answered, the Mac's addresses held and a command is bound to
|
|
1165
|
+
// relay's executor (review R4). Otherwise: declined, the app server killed, the turn failed.
|
|
1166
|
+
if (stage2 && (m.method === "item/commandExecution/requestApproval" || m.method === "item/fileChange/requestApproval")) {
|
|
1167
|
+
const unsafe = stage2.approvalProblem(m.method === "item/fileChange/requestApproval" ? "file" : "command", p.environmentId);
|
|
1168
|
+
if (unsafe) {
|
|
1169
|
+
rpc.send({ id: m.id, result: { decision: "decline" } });
|
|
1170
|
+
signalGroup("SIGKILL");
|
|
1171
|
+
return finish({ status: "failed", error: unsafe });
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
let ask;
|
|
1175
|
+
if (m.method === "item/commandExecution/requestApproval") {
|
|
1176
|
+
const refused = autoDenial(p, flags.expect.permissions) ?? (!stage2 && flags.expect.permissions.profile !== null ? codexRuntimeApprovalProblem(p, spec.config) : null);
|
|
1177
|
+
if (refused) {
|
|
1178
|
+
// Nobody is asked. The request is declined, recorded with the turn's refusals and in its log,
|
|
1179
|
+
// and the agent is told why.
|
|
1180
|
+
if (outcome)
|
|
1181
|
+
return;
|
|
1182
|
+
rpc.send({ id: m.id, result: { decision: "decline" } });
|
|
1183
|
+
const what = clipped(String(p.command ?? (p.networkApprovalContext ? `network access to ${p.networkApprovalContext.host ?? "a host"}` : "a command")), 200);
|
|
1184
|
+
denials.push(`${what} (declined by relay: ${refused})`);
|
|
1185
|
+
if (!log.writableEnded)
|
|
1186
|
+
log.write(`# relay: declined an approval request without asking: ${refused}\n`);
|
|
1187
|
+
const requestingThread = p.threadId ?? threadId, requestingTurn = p.turnId ?? turnId;
|
|
1188
|
+
if (requestingThread && requestingTurn) {
|
|
1189
|
+
const text = `[relay] Your approval request (${what}) was declined by relay without asking anyone: ${refused}. Work without it, or say in your report what you needed.`;
|
|
1190
|
+
rpc.request("turn/steer", { threadId: requestingThread, expectedTurnId: requestingTurn, input: [{ type: "text", text, text_elements: [] }] }).catch(() => { });
|
|
1191
|
+
}
|
|
1192
|
+
return;
|
|
1193
|
+
}
|
|
1194
|
+
ask = commandAsk(p, flags.expect.permissions);
|
|
1195
|
+
// Stage 2: the command runs in relay's executor, so allowing it lifts nothing (C9).
|
|
1196
|
+
if (stage2)
|
|
1197
|
+
ask = { ...ask, detail: { ...(ask.detail ?? {}), ...stage2.approvalDetail("command") } };
|
|
1198
|
+
}
|
|
1199
|
+
else if (m.method === "item/fileChange/requestApproval") {
|
|
1200
|
+
const paths = fileChanges.get(fileKey(p, p.itemId)) ?? [];
|
|
1201
|
+
// Nobody can decide a change they cannot see: without the files, the answer is no.
|
|
1202
|
+
if (!paths.length)
|
|
1203
|
+
return rpc.send({ id: m.id, result: { decision: "decline" } });
|
|
1204
|
+
ask = { kind: "file", summary: `change files: ${paths.join(", ")}`, reason: p.reason ?? undefined, paths };
|
|
1205
|
+
if (stage2)
|
|
1206
|
+
ask = { ...ask, detail: { ...(ask.detail ?? {}), ...stage2.approvalDetail("file") } };
|
|
1207
|
+
}
|
|
1208
|
+
else if (m.method === "mcpServer/elicitation/request") {
|
|
1209
|
+
return rpc.send({ id: m.id, result: { action: "decline" } });
|
|
1210
|
+
}
|
|
1211
|
+
else {
|
|
1212
|
+
return rpc.send({ id: m.id, error: { message: `relay does not handle ${m.method}` } });
|
|
1213
|
+
}
|
|
1214
|
+
// Anything going wrong while asking counts as a refusal.
|
|
1215
|
+
let decision = "decline";
|
|
1216
|
+
let note;
|
|
1217
|
+
let decider;
|
|
1218
|
+
try {
|
|
1219
|
+
const answer = spec.onApproval ? await spec.onApproval(ask, () => outcome !== null) : { allow: false };
|
|
1220
|
+
// Relay refuses "for the rest of the job" on a once-only request (core/approvals.ts decide); never sent regardless.
|
|
1221
|
+
const onceOnly = ask.detail?.once_only === true;
|
|
1222
|
+
if (answer.allow)
|
|
1223
|
+
decision = answer.forJob && !onceOnly ? "acceptForSession" : "accept";
|
|
1224
|
+
note = answer.deciderNote;
|
|
1225
|
+
decider = answer.decider;
|
|
1226
|
+
}
|
|
1227
|
+
catch {
|
|
1228
|
+
decision = "decline";
|
|
1229
|
+
}
|
|
1230
|
+
if (outcome)
|
|
1231
|
+
return;
|
|
1232
|
+
rpc.send({ id: m.id, result: { decision } });
|
|
1233
|
+
// The app server's approval answer carries a decision and nothing else (its
|
|
1234
|
+
// CommandExecutionRequestApprovalResponse and FileChangeRequestApprovalResponse, Codex
|
|
1235
|
+
// 0.162.1), and Codex tells its agent only that the user rejected or approved. A note from
|
|
1236
|
+
// whoever decided reaches the agent as a message steered into its running turn (turn/steer).
|
|
1237
|
+
const requestingThread = p.threadId ?? threadId, requestingTurn = p.turnId ?? turnId;
|
|
1238
|
+
if (note && requestingThread && requestingTurn) {
|
|
1239
|
+
const text = `[relay] Your approval request (${clipped(ask.summary, 200)}) was ${decision === "decline" ? "denied" : "allowed"}${decider ? ` ${decider}` : ""}. The note that came with the decision: ${note}`;
|
|
1240
|
+
rpc.request("turn/steer", { threadId: requestingThread, expectedTurnId: requestingTurn, input: [{ type: "text", text, text_elements: [] }] })
|
|
1241
|
+
.then(() => log.writableEnded || log.write("# relay: the decision's note was steered into the turn\n"))
|
|
1242
|
+
.catch((err) => log.writableEnded || log.write(`# relay: the decision's note could not be steered into the turn: ${err.message}\n`));
|
|
1243
|
+
}
|
|
1244
|
+
};
|
|
1245
|
+
const rpc = connect(spec.config.targets.codex.bin, args, spec.cwd, env, (m, line) => {
|
|
1246
|
+
// The server can still emit a line or two after the turn has been reported.
|
|
1247
|
+
if (!log.writableEnded && m.method !== "mcpServer/startupStatus/updated" && m.method !== "thread/tokenUsage/updated")
|
|
1248
|
+
log.write(line + "\n");
|
|
1249
|
+
if (m.id !== undefined && m.method)
|
|
1250
|
+
return void onServerRequest(m).catch(() => { });
|
|
1251
|
+
const p = m.params ?? {};
|
|
1252
|
+
// Stage 2: a turn relay did not ask for is not bound to its executor (Stage2TurnGuard): the app server is killed first.
|
|
1253
|
+
if (stage2 && !outcome && m.method === "turn/started") {
|
|
1254
|
+
const foreign = stage2.guard.started(p.threadId, threadId, p.turn?.id);
|
|
1255
|
+
if (foreign) {
|
|
1256
|
+
signalGroup("SIGKILL");
|
|
1257
|
+
return finish({ status: "failed", error: foreign });
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
if (!outcome && (m.method === "item/started" || m.method === "item/completed"))
|
|
1261
|
+
subagents.activity(p.item, threadId);
|
|
1262
|
+
// Approval metadata and denials belong to every thread. Keep thread identity in the key:
|
|
1263
|
+
// a child's item id must not replace another thread's pending file-change paths.
|
|
1264
|
+
if (m.method === "item/started" && p.item?.type === "fileChange" && p.item.id) {
|
|
1265
|
+
fileChanges.set(fileKey(p, p.item.id), (p.item.changes ?? []).map((c) => c.path).filter((x) => typeof x === "string"));
|
|
1266
|
+
}
|
|
1267
|
+
if (m.method === "item/completed") {
|
|
1268
|
+
// A completed file change may leave its paths out; they were announced when it started.
|
|
1269
|
+
const refused = declinedItem(p.item?.type === "fileChange" && !p.item.changes ? { ...p.item, changes: (fileChanges.get(fileKey(p, p.item.id)) ?? []).map((path) => ({ path })) } : p.item);
|
|
1270
|
+
if (refused)
|
|
1271
|
+
denials.push(refused);
|
|
1272
|
+
}
|
|
1273
|
+
if (m.method === "item/started" && typeof p.item?.type === "string") {
|
|
1274
|
+
const text = activityOf(p.item.type, p.item);
|
|
1275
|
+
if (text)
|
|
1276
|
+
spec.onActivity?.(text);
|
|
1277
|
+
}
|
|
1278
|
+
// The app server also streams native children's notifications. Their final messages,
|
|
1279
|
+
// usage, refusal and turn lifecycle belong to them, not to the parent relay is running.
|
|
1280
|
+
if (typeof p.threadId === "string" && p.threadId !== threadId)
|
|
1281
|
+
return;
|
|
1282
|
+
const refusal = m.method === "error" ? openaiRefusal(p.error) : undefined;
|
|
1283
|
+
if (refusal)
|
|
1284
|
+
return finish({ status: "refused", refusal, error: refusalError(refusal) });
|
|
1285
|
+
// The thread's running total, as Codex reports it after each model response.
|
|
1286
|
+
if (m.method === "thread/tokenUsage/updated") {
|
|
1287
|
+
const usage = usageFrom(p.tokenUsage?.total ?? p.tokenUsage, { cumulative: true });
|
|
1288
|
+
if (usage)
|
|
1289
|
+
spec.onUsage?.(usage);
|
|
1290
|
+
}
|
|
1291
|
+
if (m.method === "item/completed" && p.item?.type === "agentMessage" && typeof p.item.text === "string")
|
|
1292
|
+
finalMessage = p.item.text;
|
|
1293
|
+
if (m.method === "turn/started" && p.turn?.id) {
|
|
1294
|
+
turnId = p.turn.id;
|
|
1295
|
+
delivered = true;
|
|
1296
|
+
}
|
|
1297
|
+
if (m.method === "turn/completed") {
|
|
1298
|
+
stage2?.disarmTools();
|
|
1299
|
+
const status = p.turn?.status;
|
|
1300
|
+
const refusal = status === "failed" ? openaiRefusal(p.turn?.error) : undefined;
|
|
1301
|
+
if (refusal)
|
|
1302
|
+
return finish({ status: "refused", refusal, error: refusalError(refusal) });
|
|
1303
|
+
if (status === "completed")
|
|
1304
|
+
finish({ status: "ok" });
|
|
1305
|
+
else if (status === "interrupted")
|
|
1306
|
+
finish({ status: "interrupted", error: "cancelled" });
|
|
1307
|
+
else
|
|
1308
|
+
finish({ status: "failed", error: `codex turn ${status}: ${p.turn?.error?.message ?? "unknown error"}` });
|
|
1309
|
+
}
|
|
1310
|
+
});
|
|
1311
|
+
rpc.child.stderr.on("data", (chunk) => {
|
|
1312
|
+
stderrTail.write(chunk.toString());
|
|
1313
|
+
});
|
|
1314
|
+
watch = watchProcess(rpc.pid);
|
|
1315
|
+
let settling;
|
|
1316
|
+
const settle = (code) => settling ??= (async () => {
|
|
1317
|
+
for (const timer of stopTimers)
|
|
1318
|
+
clearTimeout(timer);
|
|
1319
|
+
const unseenMs = watch.stop();
|
|
1320
|
+
if (!outcome) {
|
|
1321
|
+
outcome = cancelled
|
|
1322
|
+
? { status: "interrupted", error: "cancelled" }
|
|
1323
|
+
: { status: "failed", error: `codex app-server exited (code ${code}) before the turn finished. ${stderrTail.text().trim().split("\n").slice(-3).join(" ")}`.trim() };
|
|
1324
|
+
const warning = subagents.warning();
|
|
1325
|
+
if (warning)
|
|
1326
|
+
outcome.warnings = [warning];
|
|
1327
|
+
}
|
|
1328
|
+
log.end();
|
|
1329
|
+
// Whatever the server started may be holding its output open. The streams get a moment to
|
|
1330
|
+
// drain and are then closed, so that neither the turn nor this worker waits on them.
|
|
1331
|
+
rpc.child.stdin.end();
|
|
1332
|
+
if (groupRefused)
|
|
1333
|
+
rpc.disconnect();
|
|
1334
|
+
else {
|
|
1335
|
+
// Cleared once the streams have closed, so that it does not keep the worker alive for a second after its last turn.
|
|
1336
|
+
let drained;
|
|
1337
|
+
await Promise.race([new Promise((r) => rpc.child.once("close", r)), new Promise((r) => { drained = setTimeout(r, 1000); })]);
|
|
1338
|
+
clearTimeout(drained);
|
|
1339
|
+
}
|
|
1340
|
+
rpc.child.stdout?.destroy();
|
|
1341
|
+
rpc.child.stderr?.destroy();
|
|
1342
|
+
// The turn is over only when nothing of the agent is left: children can outlive the server.
|
|
1343
|
+
if (!groupRefused && rpc.pid > 1)
|
|
1344
|
+
groupRefused = !await drainGroup(rpc.pid);
|
|
1345
|
+
if (groupRefused) {
|
|
1346
|
+
cleanupRefusal ??= `Agent cleanup refused for group ${rpc.pid}`;
|
|
1347
|
+
rpc.child.unref();
|
|
1348
|
+
}
|
|
1349
|
+
const appSurvivors = groupRefused ? [rpc.pid, ...watch.procs().map(p => p.pid)] : await stopProcs(watch.procs());
|
|
1350
|
+
// Stage 2: the executor and its descendants, after the app server (WP-C).
|
|
1351
|
+
const s2 = stage2 ? await stage2.teardown({ survivors: appSurvivors, descendants: watch.procs().filter(p => appSurvivors.includes(p.pid)), uncertain: groupRefused || (!settled && rpc.pid > 1), ...(cleanupRefusal ? { refused: cleanupRefusal } : {}) }).catch((err) => ({ survivors: [], uncertain: true, warnings: [`relay could not tear down the stage-2 executor/provider: ${err.message}`] })) : null;
|
|
1352
|
+
const survivors = s2 ? [...appSurvivors, ...s2.survivors] : appSurvivors;
|
|
1353
|
+
const warnings = [...(outcome.warnings ?? []), ...logWarnings(), ...(cleanupRefusal ? [cleanupRefusal] : []), ...(s2?.warnings ?? [])];
|
|
1354
|
+
resolveDone({
|
|
1355
|
+
...outcome, sessionId: threadId, finalMessage, exitCode: code, ...(denials.length ? { denials } : {}),
|
|
1356
|
+
...(delivered ? {} : { delivered: false }),
|
|
1357
|
+
...(warnings.length ? { warnings } : {}),
|
|
1358
|
+
...(survivors.length ? { survivors } : {}), ...(s2?.uncertain ? { unseenMs: unseenMs ?? 0 } : settled || rpc.pid <= 1 ? {} : { unseenMs }),
|
|
1359
|
+
});
|
|
1360
|
+
})();
|
|
1361
|
+
rpc.child.on("error", (err) => {
|
|
1362
|
+
outcome = { status: "failed", error: `could not start ${spec.config.targets.codex.bin}: ${err.message}` };
|
|
1363
|
+
if (rpc.pid <= 1)
|
|
1364
|
+
void settle(null);
|
|
1365
|
+
});
|
|
1366
|
+
// "exit", not "close": something the server started can hold its output open, and the turn must not wait on that.
|
|
1367
|
+
rpc.child.on("exit", (code) => void settle(code));
|
|
1368
|
+
// Stage 2: the executor's exit or a change of this Mac's addresses fails the turn, the app server killed first (C5, C7).
|
|
1369
|
+
stage2?.watch((error) => {
|
|
1370
|
+
signalGroup("SIGKILL");
|
|
1371
|
+
finish({ status: "failed", error });
|
|
1372
|
+
});
|
|
1373
|
+
(async () => {
|
|
1374
|
+
// Pin the HTTP peer before initialize can cause any MCP connection.
|
|
1375
|
+
if (stage2 && rpc.pid > 1) {
|
|
1376
|
+
stage2.bindAppServer(rpc.pid);
|
|
1377
|
+
}
|
|
1378
|
+
if (outcome)
|
|
1379
|
+
return;
|
|
1380
|
+
await rpc.request("initialize", HELLO);
|
|
1381
|
+
rpc.send({ method: "initialized" });
|
|
1382
|
+
// Stage 2: bind the thread's only environment, relay's executor, before anything else (WP-C).
|
|
1383
|
+
if (stage2) {
|
|
1384
|
+
const unbound = await stage2.bind(rpc);
|
|
1385
|
+
if (unbound)
|
|
1386
|
+
return finish({ status: "failed", error: unbound });
|
|
1387
|
+
}
|
|
1388
|
+
// Before anything runs: is the confinement relay asked for the one Codex will actually apply here?
|
|
1389
|
+
const read = await rpc.request("config/read", { cwd: spec.cwd, includeLayers: true });
|
|
1390
|
+
const eff = read.config;
|
|
1391
|
+
const problem = configProblem(eff, flags.expect) ?? (await requirementsProblem(rpc, flags.expect.permissions)) ?? (await loginProblem(rpc, flags.expect)) ?? fastModeProblem(eff, flags.expect)
|
|
1392
|
+
?? (flags.expect.skills ? await skillsProblem(rpc, spec.cwd, flags.expect.skills) : null);
|
|
1393
|
+
if (problem)
|
|
1394
|
+
return finish({ status: "failed", error: problem });
|
|
1395
|
+
// Stage 2: the app server's own local actions off, as relay set them (WP-D, review C1, C6).
|
|
1396
|
+
const unsafe = stage2 ? await stage2.readback(rpc, eff) : null;
|
|
1397
|
+
if (unsafe)
|
|
1398
|
+
return finish({ status: "failed", error: unsafe });
|
|
1399
|
+
// The features relay set and, for a proxied turn, Codex's own run of the sandbox check on this
|
|
1400
|
+
// very server. The preflight found them so (codex.ts chooseNetwork); a mismatch now means the
|
|
1401
|
+
// configuration changed since, and the turn is refused rather than given less.
|
|
1402
|
+
const unproved = await proxiedProblem(rpc, { cwd: spec.cwd, expect: flags.expect, env, layers: read.layers });
|
|
1403
|
+
if (unproved)
|
|
1404
|
+
return finish({ status: "failed", error: `relay will not start a Codex agent, because ${unproved}.` });
|
|
1405
|
+
if (flags.expect.endpointOverride && configProblem(eff, { ...flags.expect, endpointOverride: false }))
|
|
1406
|
+
spec.onWaived?.("codex_endpoint_override");
|
|
1407
|
+
// Released names Codex's own shell_environment_policy keeps from its commands: said, never overridden.
|
|
1408
|
+
const policyNote = codexShellPolicyNote(eff?.shell_environment_policy, flags.released ?? []);
|
|
1409
|
+
if (policyNote)
|
|
1410
|
+
spec.onNote?.(policyNote);
|
|
1411
|
+
if (flags.expect.daybreak) {
|
|
1412
|
+
const note = await daybreakSkip(rpc, spec.model);
|
|
1413
|
+
if (note)
|
|
1414
|
+
skipDaybreak(flags, spec.onNote, note);
|
|
1415
|
+
}
|
|
1416
|
+
if (spec.sessionId)
|
|
1417
|
+
await unarchiveThread(rpc, spec.sessionId);
|
|
1418
|
+
// Stage 2: nothing Codex would start by itself on resume, before the turn is bound (stage2QueueProblem).
|
|
1419
|
+
if (stage2 && spec.sessionId) {
|
|
1420
|
+
const queued = await stage2.resumeProblem(rpc, spec.sessionId);
|
|
1421
|
+
if (queued)
|
|
1422
|
+
return finish({ status: "failed", error: queued });
|
|
1423
|
+
}
|
|
1424
|
+
// A faster speed only where the account's catalog offers it for the model that would run, before
|
|
1425
|
+
// any thread runs: the one asked for, else a continued thread's own, else Codex's configured one.
|
|
1426
|
+
const catalog = flags.expect.speed && flags.expect.speed.name !== "standard" ? await readCatalog(rpc) : undefined;
|
|
1427
|
+
const checked = spec.model ?? (await continuedModel(rpc, flags.expect, spec.sessionId)) ?? (typeof eff?.model === "string" ? eff.model : undefined);
|
|
1428
|
+
const unoffered = await catalogProblem(rpc, flags.expect, checked, { catalog, continues: Boolean(spec.sessionId) });
|
|
1429
|
+
if (unoffered)
|
|
1430
|
+
return finish({ status: "failed", error: unoffered });
|
|
1431
|
+
// Sandbox, approval policy and speed are set on every turn, so a resumed session never keeps wider access or a faster tier.
|
|
1432
|
+
// The sandbox is relay's permission profile, named here so that no profile a resumed thread stored outranks it.
|
|
1433
|
+
const tier = flags.expect.speed?.tier;
|
|
1434
|
+
const thread = {
|
|
1435
|
+
...(flags.expect.daybreak !== undefined ? { config: { daybreak: flags.expect.daybreak } } : {}),
|
|
1436
|
+
// Its workspace roots too: a resumed thread would otherwise restore the ones it stored (threadPermissionsProblem).
|
|
1437
|
+
cwd: spec.cwd, runtimeWorkspaceRoots: [spec.cwd], permissions: flags.expect.permissions.id, approvalPolicy: spec.escalate ? "on-request" : "never", approvalsReviewer: "user",
|
|
1438
|
+
...(spec.model ? { model: spec.model } : {}),
|
|
1439
|
+
...(tier ? { serviceTier: tier } : {}),
|
|
1440
|
+
// Stage 2: the executor as the thread's only environment, and approvals always on-request (C1).
|
|
1441
|
+
...(stage2 ? stage2.threadParams(spec.cwd) : {}),
|
|
1442
|
+
};
|
|
1443
|
+
// A resumed thread's past turns are left out of the reply (excludeTurns, not experimental in 0.163.0 or 0.164.0), as
|
|
1444
|
+
// `codex exec` resumes: relay reads only the thread's settings from it, and Codex deprecates the full history for paginated threads.
|
|
1445
|
+
const checkpoint = stage2?.sessionsServed() ?? 0;
|
|
1446
|
+
const t = spec.sessionId ? await rpc.request("thread/resume", { threadId: spec.sessionId, ...thread, excludeTurns: true }) : await rpc.request("thread/start", thread);
|
|
1447
|
+
threadId = t?.thread?.id ?? threadId;
|
|
1448
|
+
// What the thread says it will use, before the first turn: OpenAI's models, and the one relay asked for.
|
|
1449
|
+
const served = threadPermissionsProblem(t, flags.expect.permissions, spec.cwd) ?? threadProblem(t, flags.expect) ?? threadTierProblem(t, flags.expect)
|
|
1450
|
+
?? (stage2 ? stage2.threadProblem(t, spec.cwd, Boolean(spec.sessionId)) : null)
|
|
1451
|
+
// The model the thread reports is the one that runs: checked against the catalog too, if it is another.
|
|
1452
|
+
?? (typeof t?.model === "string" && t.model !== checked ? await catalogProblem(rpc, flags.expect, t.model, { catalog, continues: Boolean(spec.sessionId) }) : null);
|
|
1453
|
+
if (served)
|
|
1454
|
+
return finish({ status: "failed", error: served });
|
|
1455
|
+
if (outcome)
|
|
1456
|
+
return;
|
|
1457
|
+
if (stage2) {
|
|
1458
|
+
const problem = threadId ? await stage2.threadMcpProblem(rpc, eff, threadId, checkpoint) : "Codex did not name its thread for the MCP readback";
|
|
1459
|
+
if (problem) {
|
|
1460
|
+
signalGroup("SIGKILL");
|
|
1461
|
+
return finish({ status: "failed", error: problem });
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
if (outcome)
|
|
1465
|
+
return;
|
|
1466
|
+
log.write(`# relay: the thread runs with the permission profile ${JSON.stringify(t?.activePermissionProfile?.id)}, sandbox ${JSON.stringify(t?.sandbox ?? null)}, workspace roots ${JSON.stringify(t?.runtimeWorkspaceRoots ?? null)}\n`);
|
|
1467
|
+
// Preparation may have grown the never floor for any turn, including one without an overlay.
|
|
1468
|
+
spec.checkEnvironment?.(env);
|
|
1469
|
+
stage2?.guard.request();
|
|
1470
|
+
const started = await rpc.request("turn/start", {
|
|
1471
|
+
// 0.163.0's per-turn selection, distinct from a thread's saved Daybreak preference.
|
|
1472
|
+
// Explicit standard also prevents a resumed thread from retaining its old selection.
|
|
1473
|
+
...(flags.expect.daybreak !== undefined ? { cyberAccessProgram: flags.expect.daybreak ? "daybreakBlue" : "standard" } : {}),
|
|
1474
|
+
threadId,
|
|
1475
|
+
input: [{ type: "text", text: spec.prompt, text_elements: [] }],
|
|
1476
|
+
...(spec.effort ? { effort: spec.effort } : {}),
|
|
1477
|
+
...(spec.model ? { model: spec.model } : {}),
|
|
1478
|
+
...(tier ? { serviceTier: tier } : {}),
|
|
1479
|
+
// Stage 2: every turn, fresh or resumed, bound to relay's executor in the request that carries the prompt (stage2TurnParams).
|
|
1480
|
+
...(stage2 ? stage2.turnParams(spec.cwd) : {}),
|
|
1481
|
+
});
|
|
1482
|
+
turnId = started?.turn?.id ?? turnId;
|
|
1483
|
+
delivered = true;
|
|
1484
|
+
// Stage 2: relay's prompt started its own turn, and the thread reads back as bound to the executor only.
|
|
1485
|
+
if (stage2 && !outcome) {
|
|
1486
|
+
const foreign = stage2.guard.replied(started?.turn?.id);
|
|
1487
|
+
if (foreign) {
|
|
1488
|
+
signalGroup("SIGKILL");
|
|
1489
|
+
return finish({ status: "failed", error: foreign });
|
|
1490
|
+
}
|
|
1491
|
+
// §14: the binding went in turn/start. The model may call tools during this readback's
|
|
1492
|
+
// rollout retries, so arm as soon as the reply confirms relay's requested turn.
|
|
1493
|
+
stage2.armTools(threadId, turnId);
|
|
1494
|
+
if (spec.overlay)
|
|
1495
|
+
markOverlayLaunched(spec.overlay, spec.turnId);
|
|
1496
|
+
const unbound = threadId ? await stage2.turnProblem(rpc, threadId, spec.cwd) : "relay stopped the Codex agent with raw network and failed the turn, because Codex did not say which thread it runs.";
|
|
1497
|
+
if (unbound && !outcome) {
|
|
1498
|
+
signalGroup("SIGKILL");
|
|
1499
|
+
return finish({ status: "failed", error: unbound });
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
})().catch((err) => finish({ status: "failed", error: `codex app-server: ${err.message}` }));
|
|
1503
|
+
const cancel = async () => {
|
|
1504
|
+
if (cancelled || rpc.pid <= 1) {
|
|
1505
|
+
await done;
|
|
1506
|
+
return;
|
|
1507
|
+
}
|
|
1508
|
+
cancelled = true;
|
|
1509
|
+
settled = watch.look() || settled;
|
|
1510
|
+
// The clean way to stop a turn is to ask the server, which then stops what it started. A
|
|
1511
|
+
// signal is used only when there is no turn to interrupt yet.
|
|
1512
|
+
if (threadId && turnId)
|
|
1513
|
+
rpc.send({ id: rpc.nextId(), method: "turn/interrupt", params: { threadId, turnId } });
|
|
1514
|
+
else
|
|
1515
|
+
signalGroup("SIGINT");
|
|
1516
|
+
const timer = setTimeout(() => {
|
|
1517
|
+
watch.look();
|
|
1518
|
+
if (signalGroup("SIGKILL"))
|
|
1519
|
+
killProcs(watch.procs());
|
|
1520
|
+
}, spec.config.cancel_grace_ms);
|
|
1521
|
+
await done;
|
|
1522
|
+
clearTimeout(timer);
|
|
1523
|
+
};
|
|
1524
|
+
return { pid: rpc.pid, pgid: rpc.pid, startedAt: procStart(rpc.pid), done, cancel };
|
|
1525
|
+
}
|