@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,650 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import http from "node:http";
|
|
3
|
+
import net from "node:net";
|
|
4
|
+
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
5
|
+
import { brokerCore, MAX_MESSAGE, TURN_ENDED } from "./broker-core.js";
|
|
6
|
+
import { tcpPeerLookup } from "./peer.js";
|
|
7
|
+
import { sameProcess } from "../core/procs.js";
|
|
8
|
+
import { redactor, registerTurnSecret } from "../core/secrets.js";
|
|
9
|
+
import { BROKER_SERVER_NAME, BROKER_TOKEN_ENV } from "./broker-names.js";
|
|
10
|
+
export { BROKER_SERVER_NAME, BROKER_TOKEN_ENV };
|
|
11
|
+
export const BROKER_SESSION_CAP = 8;
|
|
12
|
+
const PENDING_CAP = 16, HEAD_CAP = 8192, DEADLINE_MS = 2000;
|
|
13
|
+
// Each lsof invocation has its own 2 s kill timeout. Allow callback/reap overhead,
|
|
14
|
+
// and at most one retry: a connection holds the semaphore for at most 4.5 s.
|
|
15
|
+
const PEER_ATTEMPT_MS = 2250, PEER_DEADLINE_MS = 2 * PEER_ATTEMPT_MS;
|
|
16
|
+
const systemClock = {
|
|
17
|
+
setTimeout: (run, ms) => setTimeout(run, ms),
|
|
18
|
+
clearTimeout: (handle) => clearTimeout(handle),
|
|
19
|
+
};
|
|
20
|
+
/** Gate each delivered message (including batches), after the HTTP body has been read. */
|
|
21
|
+
export class SessionGate {
|
|
22
|
+
inner;
|
|
23
|
+
refusal;
|
|
24
|
+
retired;
|
|
25
|
+
onmessage;
|
|
26
|
+
onerror;
|
|
27
|
+
onclose;
|
|
28
|
+
constructor(inner, refusal, retired) {
|
|
29
|
+
this.inner = inner;
|
|
30
|
+
this.refusal = refusal;
|
|
31
|
+
this.retired = retired;
|
|
32
|
+
}
|
|
33
|
+
get sessionId() { return this.inner.sessionId; }
|
|
34
|
+
async start() {
|
|
35
|
+
this.inner.onmessage = (message, extra) => {
|
|
36
|
+
const why = this.refusal(message);
|
|
37
|
+
if (why === null)
|
|
38
|
+
return this.onmessage?.(message, extra);
|
|
39
|
+
if ("method" in message && "id" in message) {
|
|
40
|
+
void this.send({ jsonrpc: "2.0", id: message.id, error: { code: TURN_ENDED, message: why } })
|
|
41
|
+
.catch((err) => this.onerror?.(err));
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
this.inner.onerror = (err) => this.onerror?.(err);
|
|
45
|
+
this.inner.onclose = () => { this.retired(); this.onclose?.(); };
|
|
46
|
+
await this.inner.start();
|
|
47
|
+
}
|
|
48
|
+
writes = new Map();
|
|
49
|
+
/** SDK send resolves when it queues SSE bytes. For escalation, require the Node response
|
|
50
|
+
* to finish writing those bytes; close/error before finish is failed delivery, never consent. */
|
|
51
|
+
trackReceipt(id, res) {
|
|
52
|
+
if (this.writes.has(id))
|
|
53
|
+
throw new Error("duplicate in-flight escalation transport id");
|
|
54
|
+
this.writes.set(id, new Promise(resolve => {
|
|
55
|
+
const settle = (ok) => {
|
|
56
|
+
res.off("finish", finish);
|
|
57
|
+
res.off("close", close);
|
|
58
|
+
res.off("error", close);
|
|
59
|
+
resolve(ok);
|
|
60
|
+
};
|
|
61
|
+
const finish = () => settle(true), close = () => settle(res.writableFinished);
|
|
62
|
+
res.once("finish", finish);
|
|
63
|
+
res.once("close", close);
|
|
64
|
+
res.once("error", close);
|
|
65
|
+
}));
|
|
66
|
+
}
|
|
67
|
+
async send(message, options) {
|
|
68
|
+
const id = "id" in message && ("result" in message || "error" in message) ? message.id : undefined;
|
|
69
|
+
const written = id === undefined ? undefined : this.writes.get(id);
|
|
70
|
+
try {
|
|
71
|
+
let receipt = false;
|
|
72
|
+
if ("result" in message) {
|
|
73
|
+
const content = message.result.content?.[0];
|
|
74
|
+
try {
|
|
75
|
+
receipt = !!content?.text && JSON.parse(content.text).state === "restart_pending";
|
|
76
|
+
}
|
|
77
|
+
catch { /* ordinary tool result */ }
|
|
78
|
+
}
|
|
79
|
+
if (receipt && !written)
|
|
80
|
+
throw new Error("escalation receipt has no bound HTTP response write");
|
|
81
|
+
await this.inner.send(message, options);
|
|
82
|
+
if (written && !await written)
|
|
83
|
+
throw new Error("escalation HTTP response did not finish writing");
|
|
84
|
+
}
|
|
85
|
+
finally {
|
|
86
|
+
if (id !== undefined && written)
|
|
87
|
+
this.writes.delete(id);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
close() { return this.inner.close(); }
|
|
91
|
+
}
|
|
92
|
+
class OversizedInput extends Error {
|
|
93
|
+
}
|
|
94
|
+
/** Read at most one stdio-sized message; do not let the SDK buffer an unbounded body. */
|
|
95
|
+
function readBody(req) {
|
|
96
|
+
return new Promise((resolve, reject) => {
|
|
97
|
+
let size = 0;
|
|
98
|
+
const chunks = [];
|
|
99
|
+
const cleanup = () => { req.off("data", data); req.off("end", end); req.off("aborted", aborted); req.off("error", aborted); };
|
|
100
|
+
const aborted = () => { cleanup(); reject(new Error("HTTP input aborted")); };
|
|
101
|
+
const oversized = () => { cleanup(); req.resume(); reject(new OversizedInput()); };
|
|
102
|
+
const data = (chunk) => {
|
|
103
|
+
size += chunk.length;
|
|
104
|
+
if (size > MAX_MESSAGE)
|
|
105
|
+
return oversized();
|
|
106
|
+
chunks.push(chunk);
|
|
107
|
+
};
|
|
108
|
+
const end = () => {
|
|
109
|
+
cleanup();
|
|
110
|
+
try {
|
|
111
|
+
resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
reject(new Error("invalid JSON input"));
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
if (Number(req.headers["content-length"]) > MAX_MESSAGE)
|
|
118
|
+
return oversized();
|
|
119
|
+
req.on("data", data);
|
|
120
|
+
req.once("end", end);
|
|
121
|
+
req.once("aborted", aborted);
|
|
122
|
+
req.once("error", aborted);
|
|
123
|
+
if (req.aborted || req.destroyed)
|
|
124
|
+
aborted();
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
/** Preserve duplicates, unlike IncomingMessage.headers which coalesces/discards some of them. */
|
|
128
|
+
function headers(lines) {
|
|
129
|
+
const out = new Map();
|
|
130
|
+
for (const line of lines) {
|
|
131
|
+
const i = line.indexOf(":");
|
|
132
|
+
if (i < 1 || !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(line.slice(0, i)))
|
|
133
|
+
return null;
|
|
134
|
+
const name = line.slice(0, i).toLowerCase();
|
|
135
|
+
out.set(name, [...(out.get(name) ?? []), line.slice(i + 1).trim()]);
|
|
136
|
+
}
|
|
137
|
+
return out;
|
|
138
|
+
}
|
|
139
|
+
/** A paused TCP front authenticates without a process before handing a socket to Node HTTP. */
|
|
140
|
+
export async function openHttpBroker(turn, port, o = {}) {
|
|
141
|
+
if (!Number.isSafeInteger(port) || port < 1 || port > 65535)
|
|
142
|
+
throw new Error("invalid broker port");
|
|
143
|
+
const core = brokerCore(turn, { toolHandler: o.toolHandler });
|
|
144
|
+
const token = crypto.randomBytes(32).toString("hex");
|
|
145
|
+
registerTurnSecret(token, "broker token");
|
|
146
|
+
const cut = redactor();
|
|
147
|
+
const env = Object.freeze({ [BROKER_TOKEN_ENV]: token });
|
|
148
|
+
const clock = o.clock ?? systemClock;
|
|
149
|
+
const network = o.network ?? { createServer: net.createServer, connect: net.createConnection };
|
|
150
|
+
const matches = o.processMatches ?? ((p) => sameProcess(p.pid, p.start, { fresh: true }));
|
|
151
|
+
const log = o.onRefusal ?? ((why) => { process.stderr.write(`[broker-http] refused: ${why}\n`); });
|
|
152
|
+
let closed = false, opening = true, armed = false;
|
|
153
|
+
let app = null;
|
|
154
|
+
let fatalReason = null;
|
|
155
|
+
let failed;
|
|
156
|
+
const fatal = (why) => {
|
|
157
|
+
if (closed || fatalReason)
|
|
158
|
+
return;
|
|
159
|
+
fatalReason = why;
|
|
160
|
+
armed = false;
|
|
161
|
+
failed?.(why);
|
|
162
|
+
};
|
|
163
|
+
const refusal = () => closed || fatalReason ? "relay's turn has ended" : core.refusal();
|
|
164
|
+
const authStatus = (h) => {
|
|
165
|
+
if (!h)
|
|
166
|
+
return 400;
|
|
167
|
+
const host = h.get("host");
|
|
168
|
+
if (host?.length !== 1 || host[0] !== `127.0.0.1:${port}`)
|
|
169
|
+
return 421;
|
|
170
|
+
if (h.has("origin"))
|
|
171
|
+
return 403;
|
|
172
|
+
const auth = h.get("authorization");
|
|
173
|
+
const given = Buffer.from(auth?.length === 1 && auth[0].startsWith("Bearer ") ? auth[0].slice(7) : "");
|
|
174
|
+
const want = Buffer.from(token);
|
|
175
|
+
if (given.length !== want.length || !crypto.timingSafeEqual(given, want))
|
|
176
|
+
return 401;
|
|
177
|
+
return [...h.values()].some((v) => v.length !== 1) ? 400 : 0;
|
|
178
|
+
};
|
|
179
|
+
const sockets = new Set();
|
|
180
|
+
const pending = new Set();
|
|
181
|
+
const timers = new Set();
|
|
182
|
+
const later = (run, ms) => {
|
|
183
|
+
const handle = clock.setTimeout(() => { timers.delete(handle); run(); }, ms);
|
|
184
|
+
timers.add(handle);
|
|
185
|
+
return handle;
|
|
186
|
+
};
|
|
187
|
+
const clear = (h) => { clock.clearTimeout(h); timers.delete(h); };
|
|
188
|
+
const reply = (s, status, code) => {
|
|
189
|
+
log(`HTTP ${status}${code ? ` (${code})` : ""}`);
|
|
190
|
+
if (s.destroyed || !s.writable || s.writableEnded) {
|
|
191
|
+
s.destroy();
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
s.end(`HTTP/1.1 ${status} Refused\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
|
|
195
|
+
// A peer that never reads cannot retain a pending slot indefinitely.
|
|
196
|
+
const deadline = later(() => s.destroy(), 50);
|
|
197
|
+
s.once("close", () => clear(deadline));
|
|
198
|
+
};
|
|
199
|
+
let active = 0;
|
|
200
|
+
const waiters = [];
|
|
201
|
+
const drain = () => { while (active < 2 && waiters.length)
|
|
202
|
+
waiters.shift()(); };
|
|
203
|
+
const acquire = (sock) => new Promise((resolve) => {
|
|
204
|
+
const grant = () => {
|
|
205
|
+
sock.off("close", disconnected);
|
|
206
|
+
if (closed || fatalReason || sock.destroyed) {
|
|
207
|
+
resolve(null);
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
active++;
|
|
211
|
+
resolve(() => { active--; drain(); });
|
|
212
|
+
};
|
|
213
|
+
const disconnected = () => {
|
|
214
|
+
const i = waiters.indexOf(grant);
|
|
215
|
+
if (i >= 0)
|
|
216
|
+
waiters.splice(i, 1);
|
|
217
|
+
resolve(null);
|
|
218
|
+
};
|
|
219
|
+
if (active < 2)
|
|
220
|
+
grant();
|
|
221
|
+
else {
|
|
222
|
+
waiters.push(grant);
|
|
223
|
+
sock.once("close", disconnected);
|
|
224
|
+
}
|
|
225
|
+
});
|
|
226
|
+
const check = async (p, sock) => {
|
|
227
|
+
// Node may clear the ports on close. Both attempts must inspect the same tuple,
|
|
228
|
+
// while the disconnect flags remain live for the empty-exit-1 race.
|
|
229
|
+
const peerSocket = {
|
|
230
|
+
localPort: sock.localPort, remotePort: sock.remotePort,
|
|
231
|
+
get destroyed() { return sock.destroyed; },
|
|
232
|
+
get readableEnded() { return sock.readableEnded; },
|
|
233
|
+
get writableEnded() { return sock.writableEnded; },
|
|
234
|
+
};
|
|
235
|
+
const release = await acquire(sock);
|
|
236
|
+
if (!release)
|
|
237
|
+
return "foreign";
|
|
238
|
+
let deadline, expired = false;
|
|
239
|
+
const totalDeadline = new Promise((resolve) => {
|
|
240
|
+
deadline = later(() => {
|
|
241
|
+
expired = true;
|
|
242
|
+
resolve({ error: 'TCP peer checker total deadline exceeded (code=none, signal=none, stderr="")' });
|
|
243
|
+
}, PEER_DEADLINE_MS);
|
|
244
|
+
});
|
|
245
|
+
try {
|
|
246
|
+
const failures = [];
|
|
247
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
248
|
+
let timeout;
|
|
249
|
+
let result;
|
|
250
|
+
try {
|
|
251
|
+
result = await Promise.race([
|
|
252
|
+
(o.peer ?? tcpPeerLookup)(p, peerSocket),
|
|
253
|
+
totalDeadline,
|
|
254
|
+
new Promise((resolve) => {
|
|
255
|
+
timeout = later(() => resolve({
|
|
256
|
+
error: 'TCP peer checker timed out (code=none, signal=none, stderr="")',
|
|
257
|
+
}), PEER_ATTEMPT_MS);
|
|
258
|
+
}),
|
|
259
|
+
]);
|
|
260
|
+
}
|
|
261
|
+
catch (error) {
|
|
262
|
+
result = { error: `TCP peer checker threw (code=none, signal=none, stderr=""): ${error instanceof Error ? error.message : "unknown error"}` };
|
|
263
|
+
}
|
|
264
|
+
finally {
|
|
265
|
+
clear(timeout);
|
|
266
|
+
}
|
|
267
|
+
if (typeof result !== "object" || closed)
|
|
268
|
+
return result;
|
|
269
|
+
failures.push(cut(result.error).slice(0, 1024));
|
|
270
|
+
if (expired)
|
|
271
|
+
break;
|
|
272
|
+
}
|
|
273
|
+
// Disconnection cannot hide a real operational failure or rescue partial output.
|
|
274
|
+
const error = `relay could not check the TCP peer of its tools after ${failures.length} attempts: ${failures.join("; ")}`;
|
|
275
|
+
fatal(error);
|
|
276
|
+
return { error };
|
|
277
|
+
}
|
|
278
|
+
finally {
|
|
279
|
+
clear(deadline);
|
|
280
|
+
release();
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
const rpcError = (res, id, message) => {
|
|
284
|
+
if (res.destroyed || res.writableEnded)
|
|
285
|
+
return;
|
|
286
|
+
// Codex's HTTP adapter accepts JSON-RPC errors on 4xx too, but rmcp drops
|
|
287
|
+
// id:null errors and keeps waiting for the call's id. If input cannot be
|
|
288
|
+
// correlated, fail the HTTP send instead of delivering an id-less message.
|
|
289
|
+
const uncorrelated = id === null && res.req.method === "POST";
|
|
290
|
+
res.writeHead(uncorrelated ? 400 : 200, { "content-type": uncorrelated ? "text/plain; charset=utf-8" : "application/json" });
|
|
291
|
+
res.end(JSON.stringify({ jsonrpc: "2.0", id, error: { code: TURN_ENDED, message } }));
|
|
292
|
+
};
|
|
293
|
+
const live = new Map();
|
|
294
|
+
// Keep all issued ids for the whole turn, including ones lost before initialize answered.
|
|
295
|
+
const issued = new Set(), tombstones = new Set();
|
|
296
|
+
const sessions = new Set(); // Includes initialization reservations: never overcommit.
|
|
297
|
+
let served = 0;
|
|
298
|
+
const retire = (session) => {
|
|
299
|
+
if (!session.retired) {
|
|
300
|
+
session.retired = true;
|
|
301
|
+
sessions.delete(session);
|
|
302
|
+
if (session.id) {
|
|
303
|
+
const wasLive = live.delete(session.id);
|
|
304
|
+
tombstones.add(session.id);
|
|
305
|
+
if (wasLive)
|
|
306
|
+
o.onSession?.({ id: session.id, state: "closed", live: live.size });
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
session.closing ??= Promise.resolve().then(() => session.server.close()).catch(() => { });
|
|
310
|
+
return session.closing;
|
|
311
|
+
};
|
|
312
|
+
const newSession = () => {
|
|
313
|
+
let session;
|
|
314
|
+
const transport = new StreamableHTTPServerTransport({
|
|
315
|
+
sessionIdGenerator: () => {
|
|
316
|
+
let id;
|
|
317
|
+
do {
|
|
318
|
+
id = crypto.randomUUID();
|
|
319
|
+
} while (issued.has(id));
|
|
320
|
+
issued.add(id);
|
|
321
|
+
session.id = id;
|
|
322
|
+
return id;
|
|
323
|
+
},
|
|
324
|
+
onsessioninitialized: (id) => {
|
|
325
|
+
if (session.retired || refusal()) {
|
|
326
|
+
tombstones.add(id);
|
|
327
|
+
throw new Error("relay's turn has ended");
|
|
328
|
+
}
|
|
329
|
+
live.set(id, session);
|
|
330
|
+
served++;
|
|
331
|
+
o.onSession?.({ id, state: "opened", live: live.size });
|
|
332
|
+
},
|
|
333
|
+
onsessionclosed: () => { void retire(session); },
|
|
334
|
+
});
|
|
335
|
+
const gate = new SessionGate(transport, (message) => {
|
|
336
|
+
let why;
|
|
337
|
+
try {
|
|
338
|
+
why = session.retired ? "this relay session is closed" : refusal();
|
|
339
|
+
}
|
|
340
|
+
catch {
|
|
341
|
+
why = "relay could not check its turn";
|
|
342
|
+
}
|
|
343
|
+
if (!why && "method" in message && message.method === "tools/call" && !armed)
|
|
344
|
+
why = "relay's turn has not started";
|
|
345
|
+
if (why)
|
|
346
|
+
log(why);
|
|
347
|
+
return why;
|
|
348
|
+
}, () => { void retire(session); });
|
|
349
|
+
session = { transport, gate, server: core.serve(), retired: false };
|
|
350
|
+
sessions.add(session);
|
|
351
|
+
return { session, gate };
|
|
352
|
+
};
|
|
353
|
+
const handleRequest = async (req, res) => {
|
|
354
|
+
// SDK validation errors have id:null. Keep their diagnostic body, but make
|
|
355
|
+
// POST rejections HTTP failures: Codex otherwise accepts then drops them.
|
|
356
|
+
// A concurrent DELETE can also produce 404; use 400 so Codex cannot replay
|
|
357
|
+
// the tool call by reinitializing a deliberately closed session.
|
|
358
|
+
const writeHead = res.writeHead;
|
|
359
|
+
let standaloneStream = false;
|
|
360
|
+
res.writeHead = function (status, ...rest) {
|
|
361
|
+
// The SDK passes headers directly to writeHead; Node's getHeader need not
|
|
362
|
+
// retain them. Capture the successful GET stream while they are available.
|
|
363
|
+
const headerIndex = typeof rest[0] === "string" ? 1 : 0;
|
|
364
|
+
const responseHeaders = rest[headerIndex];
|
|
365
|
+
const contentType = res.getHeader("content-type")
|
|
366
|
+
?? Object.entries(responseHeaders ?? {}).find(([name]) => name.toLowerCase() === "content-type")?.[1];
|
|
367
|
+
standaloneStream = req.method === "GET" && status === 200 && String(contentType).startsWith("text/event-stream");
|
|
368
|
+
if (req.method === "POST" && status >= 400) {
|
|
369
|
+
log(`HTTP ${status} (MCP request rejected)`);
|
|
370
|
+
const type = "text/plain; charset=utf-8";
|
|
371
|
+
res.setHeader("content-type", type);
|
|
372
|
+
if (responseHeaders) {
|
|
373
|
+
const h = { ...responseHeaders };
|
|
374
|
+
for (const name of Object.keys(h))
|
|
375
|
+
if (name.toLowerCase() === "content-type")
|
|
376
|
+
delete h[name];
|
|
377
|
+
rest[headerIndex] = { ...h, "content-type": type };
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
return Reflect.apply(writeHead, this, [status === 404 ? (req.method === "POST" ? 400 : 200) : status, ...rest]);
|
|
381
|
+
};
|
|
382
|
+
const pairs = [];
|
|
383
|
+
for (let i = 0; i < req.rawHeaders.length; i += 2)
|
|
384
|
+
pairs.push(`${req.rawHeaders[i]}:${req.rawHeaders[i + 1]}`);
|
|
385
|
+
const status = authStatus(headers(pairs));
|
|
386
|
+
if (status) {
|
|
387
|
+
log(`HTTP ${status}`);
|
|
388
|
+
res.writeHead(status, { connection: "close" });
|
|
389
|
+
res.end();
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
if (req.url !== "/mcp") {
|
|
393
|
+
rpcError(res, null, "unknown relay endpoint");
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
const sid = req.headers["mcp-session-id"];
|
|
397
|
+
let session = sid ? live.get(sid) : undefined;
|
|
398
|
+
const aborted = () => { if (session)
|
|
399
|
+
void retire(session); };
|
|
400
|
+
req.once("aborted", aborted);
|
|
401
|
+
res.once("close", () => {
|
|
402
|
+
// The SDK cancels its GET stream mapping without closing the transport, and
|
|
403
|
+
// its Node adapter can finish the response before emitting close. A successful
|
|
404
|
+
// standalone SSE stream is the session's lifetime anchor; its end retires the
|
|
405
|
+
// session even in that order. Ordinary POST/keep-alive closure is not teardown.
|
|
406
|
+
if (!res.writableFinished || standaloneStream)
|
|
407
|
+
aborted();
|
|
408
|
+
});
|
|
409
|
+
let body, id = null;
|
|
410
|
+
try {
|
|
411
|
+
if (req.method === "POST")
|
|
412
|
+
body = await readBody(req);
|
|
413
|
+
id = body && typeof body === "object" && "id" in body && (typeof body.id === "number" || typeof body.id === "string") ? body.id : null;
|
|
414
|
+
const why = refusal();
|
|
415
|
+
if (why) {
|
|
416
|
+
log(why);
|
|
417
|
+
rpcError(res, id, why);
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
if (sid) {
|
|
421
|
+
// Recheck after the body wait: DELETE, an abort or oversized input may have retired it.
|
|
422
|
+
if (!session || session.retired || live.get(sid) !== session) {
|
|
423
|
+
log(tombstones.has(sid) ? "closed session" : "unknown session");
|
|
424
|
+
rpcError(res, id, "this relay session is closed");
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
else {
|
|
429
|
+
if (req.method !== "POST") {
|
|
430
|
+
res.writeHead(405);
|
|
431
|
+
res.end();
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
434
|
+
if (!body || typeof body !== "object" || !("method" in body) || body.method !== "initialize") {
|
|
435
|
+
rpcError(res, id, "this relay session is closed");
|
|
436
|
+
return;
|
|
437
|
+
}
|
|
438
|
+
if (sessions.size >= BROKER_SESSION_CAP) {
|
|
439
|
+
log("session cap");
|
|
440
|
+
rpcError(res, id, "relay's session limit for this turn is reached");
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
443
|
+
const created = newSession();
|
|
444
|
+
session = created.session;
|
|
445
|
+
await session.server.connect(created.gate);
|
|
446
|
+
if (req.aborted || session.retired || refusal()) {
|
|
447
|
+
await retire(session);
|
|
448
|
+
rpcError(res, id, "relay's turn has ended");
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
if (id !== null && body && typeof body === "object" && "method" in body && body.method === "tools/call"
|
|
453
|
+
&& "params" in body && body.params?.name === "escalate")
|
|
454
|
+
session.gate.trackReceipt(id, res);
|
|
455
|
+
await session.transport.handleRequest(req, res, body);
|
|
456
|
+
// Invalid initialize must not leave an unissued reservation in the live cap.
|
|
457
|
+
if (!session.id)
|
|
458
|
+
await retire(session);
|
|
459
|
+
}
|
|
460
|
+
catch (err) {
|
|
461
|
+
if (session)
|
|
462
|
+
await retire(session);
|
|
463
|
+
if (err instanceof OversizedInput)
|
|
464
|
+
res.setHeader("connection", "close");
|
|
465
|
+
log(err instanceof OversizedInput ? "oversized input" : "invalid or aborted input");
|
|
466
|
+
rpcError(res, id, err instanceof OversizedInput ? "relay input is too large; this relay session is closed" : "this relay session is closed");
|
|
467
|
+
}
|
|
468
|
+
finally {
|
|
469
|
+
req.off("aborted", aborted);
|
|
470
|
+
}
|
|
471
|
+
};
|
|
472
|
+
// All keep-alive requests repeat the free checks; only the first one needs a peer lookup.
|
|
473
|
+
const responses = new WeakMap();
|
|
474
|
+
const httpServer = http.createServer({ maxHeaderSize: HEAD_CAP, connectionsCheckingInterval: DEADLINE_MS }, (req, res) => {
|
|
475
|
+
let activeResponses = responses.get(req.socket);
|
|
476
|
+
if (!activeResponses)
|
|
477
|
+
responses.set(req.socket, activeResponses = new Set());
|
|
478
|
+
activeResponses.add(res);
|
|
479
|
+
res.once("close", () => activeResponses.delete(res));
|
|
480
|
+
void handleRequest(req, res).catch(() => { res.destroy(); fatal("relay's HTTP broker dispatch failed"); });
|
|
481
|
+
});
|
|
482
|
+
httpServer.requestTimeout = 0;
|
|
483
|
+
httpServer.headersTimeout = DEADLINE_MS;
|
|
484
|
+
httpServer.keepAliveTimeout = 5000;
|
|
485
|
+
httpServer.on("clientError", (err, sock) => {
|
|
486
|
+
const code = err.code ?? "unknown";
|
|
487
|
+
// Node's default handler also refuses to write a status line once a response
|
|
488
|
+
// has started. In particular, raw HTTP bytes would corrupt an SSE POST.
|
|
489
|
+
// rmcp fails an outstanding POST when its response stream closes unfinished.
|
|
490
|
+
if ([...(responses.get(sock) ?? [])].some((res) => res.headersSent && !res.writableFinished)) {
|
|
491
|
+
log(`HTTP 400 (${code})`);
|
|
492
|
+
sock.destroy();
|
|
493
|
+
}
|
|
494
|
+
else
|
|
495
|
+
reply(sock, 400, code);
|
|
496
|
+
});
|
|
497
|
+
httpServer.on("error", () => fatal("relay's HTTP broker failed"));
|
|
498
|
+
// Node starts its headersTimeout connection tracker on 'listening', not on
|
|
499
|
+
// 'connection'. This server receives authenticated sockets without listen().
|
|
500
|
+
// Start that lifecycle explicitly, including for subsequent keep-alive heads.
|
|
501
|
+
httpServer.emit("listening");
|
|
502
|
+
let selfDone;
|
|
503
|
+
const front = network.createServer({ pauseOnConnect: true }, (sock) => {
|
|
504
|
+
sock.on("error", () => { });
|
|
505
|
+
if (closed || sock.localAddress !== "127.0.0.1" || pending.size >= PENDING_CAP) {
|
|
506
|
+
log("connection refused");
|
|
507
|
+
sock.destroy();
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
sockets.add(sock);
|
|
511
|
+
pending.add(sock);
|
|
512
|
+
let done = false;
|
|
513
|
+
let buf = Buffer.alloc(0);
|
|
514
|
+
const finish = () => { done = true; clear(timer); sock.off("data", data); };
|
|
515
|
+
const timer = later(() => { finish(); log("head deadline"); sock.destroy(); }, DEADLINE_MS);
|
|
516
|
+
sock.once("close", () => { finish(); pending.delete(sock); sockets.delete(sock); });
|
|
517
|
+
const data = (chunk) => {
|
|
518
|
+
if (done)
|
|
519
|
+
return;
|
|
520
|
+
buf = Buffer.concat([buf, chunk]);
|
|
521
|
+
const end = buf.indexOf("\r\n\r\n");
|
|
522
|
+
if (end < 0 && buf.length <= HEAD_CAP)
|
|
523
|
+
return;
|
|
524
|
+
finish();
|
|
525
|
+
sock.pause();
|
|
526
|
+
if (end < 0 || end + 4 > HEAD_CAP)
|
|
527
|
+
return reply(sock, 431);
|
|
528
|
+
const h = headers(buf.subarray(0, end).toString("latin1").split("\r\n").slice(1));
|
|
529
|
+
const status = authStatus(h);
|
|
530
|
+
if (status)
|
|
531
|
+
return reply(sock, status);
|
|
532
|
+
if (fatalReason)
|
|
533
|
+
return reply(sock, 503);
|
|
534
|
+
const p = opening ? { pid: process.pid, start: "self-check" } : app;
|
|
535
|
+
if (!p)
|
|
536
|
+
return reply(sock, 403);
|
|
537
|
+
void (async () => {
|
|
538
|
+
const result = await check(p, sock);
|
|
539
|
+
if (closed || sock.destroyed)
|
|
540
|
+
return;
|
|
541
|
+
if (opening) {
|
|
542
|
+
pending.delete(sock);
|
|
543
|
+
sock.destroy();
|
|
544
|
+
selfDone?.(result);
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
547
|
+
if (sock.readableEnded || sock.writableEnded) {
|
|
548
|
+
sock.destroy();
|
|
549
|
+
return;
|
|
550
|
+
}
|
|
551
|
+
if (typeof result === "object") {
|
|
552
|
+
reply(sock, 503);
|
|
553
|
+
fatal("relay could not check the TCP peer of its tools");
|
|
554
|
+
return;
|
|
555
|
+
}
|
|
556
|
+
if (result !== "ok" || !matches(p))
|
|
557
|
+
return reply(sock, 403);
|
|
558
|
+
if (fatalReason)
|
|
559
|
+
return reply(sock, 503);
|
|
560
|
+
pending.delete(sock);
|
|
561
|
+
sock.unshift(buf);
|
|
562
|
+
httpServer.emit("connection", sock);
|
|
563
|
+
sock.resume();
|
|
564
|
+
})().catch(() => { reply(sock, 503); fatal("relay's broker authentication failed"); });
|
|
565
|
+
};
|
|
566
|
+
sock.on("data", data);
|
|
567
|
+
sock.resume();
|
|
568
|
+
});
|
|
569
|
+
const listeners = [front];
|
|
570
|
+
let closePromise;
|
|
571
|
+
const close = () => closePromise ??= (async () => {
|
|
572
|
+
closed = true;
|
|
573
|
+
armed = false;
|
|
574
|
+
for (const s of sockets)
|
|
575
|
+
s.destroy();
|
|
576
|
+
for (const t of timers)
|
|
577
|
+
clock.clearTimeout(t);
|
|
578
|
+
timers.clear();
|
|
579
|
+
waiters.splice(0).forEach((r) => r());
|
|
580
|
+
httpServer.close(); // Also stops Node's headersTimeout checking interval.
|
|
581
|
+
httpServer.closeAllConnections();
|
|
582
|
+
await Promise.all([...sessions].map(retire));
|
|
583
|
+
await Promise.all(listeners.map((s) => new Promise((resolve) => s.close(() => resolve()))));
|
|
584
|
+
})();
|
|
585
|
+
const listen = async (server, host, ipv6Only) => {
|
|
586
|
+
server.on("error", () => fatal("relay's broker listener or holder failed"));
|
|
587
|
+
server.on("close", () => { if (!closed)
|
|
588
|
+
fatal("relay's broker listener or holder was lost"); });
|
|
589
|
+
await new Promise((resolve, reject) => {
|
|
590
|
+
server.once("error", reject);
|
|
591
|
+
// Plain listeners: never opt into port sharing. exclusive controls Node cluster handle
|
|
592
|
+
// sharing, not SO_REUSEPORT; ipv6Only:false keeps the [::] holder dual-stack.
|
|
593
|
+
server.listen({ port, host, exclusive: true, reusePort: false, ...(ipv6Only === undefined ? {} : { ipv6Only }) }, () => {
|
|
594
|
+
server.off("error", reject);
|
|
595
|
+
resolve();
|
|
596
|
+
});
|
|
597
|
+
});
|
|
598
|
+
};
|
|
599
|
+
try {
|
|
600
|
+
await listen(front, "127.0.0.1");
|
|
601
|
+
for (const [host, ipv6Only] of [["0.0.0.0", undefined], ["::", false]]) {
|
|
602
|
+
const holder = network.createServer({ pauseOnConnect: true }, (s) => { log("wildcard connection refused"); s.destroy(); });
|
|
603
|
+
listeners.push(holder);
|
|
604
|
+
await listen(holder, host, ipv6Only);
|
|
605
|
+
}
|
|
606
|
+
// Prove the checker works on a connection relay itself owns before starting the app server.
|
|
607
|
+
await new Promise((resolve, reject) => {
|
|
608
|
+
const deadline = later(() => { client.destroy(); reject(new Error("broker TCP peer self-check timed out")); }, PEER_DEADLINE_MS + DEADLINE_MS);
|
|
609
|
+
selfDone = (result) => {
|
|
610
|
+
clear(deadline);
|
|
611
|
+
client.destroy();
|
|
612
|
+
result === "ok" && !fatalReason ? resolve() : reject(new Error("broker TCP peer self-check failed"));
|
|
613
|
+
};
|
|
614
|
+
const client = network.connect(port, "127.0.0.1");
|
|
615
|
+
client.on("error", () => { clear(deadline); reject(new Error("broker TCP peer self-check could not connect")); });
|
|
616
|
+
client.once("connect", () => client.write(`GET /mcp HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nAuthorization: Bearer ${token}\r\n\r\n`));
|
|
617
|
+
});
|
|
618
|
+
selfDone = undefined;
|
|
619
|
+
opening = false;
|
|
620
|
+
if (fatalReason)
|
|
621
|
+
throw new Error(fatalReason);
|
|
622
|
+
}
|
|
623
|
+
catch (err) {
|
|
624
|
+
await close();
|
|
625
|
+
throw err;
|
|
626
|
+
}
|
|
627
|
+
return {
|
|
628
|
+
url: `http://127.0.0.1:${port}/mcp`, env,
|
|
629
|
+
bindAppServer(p) {
|
|
630
|
+
if (closed || fatalReason || app)
|
|
631
|
+
throw new Error("the broker app server is already bound or the broker is closed");
|
|
632
|
+
if (!p.start || !matches(p))
|
|
633
|
+
throw new Error("cannot bind an unknown, dead or reused app server");
|
|
634
|
+
app = { ...p };
|
|
635
|
+
},
|
|
636
|
+
arm() { if (!refusal() && app)
|
|
637
|
+
armed = true; },
|
|
638
|
+
disarm() { armed = false; },
|
|
639
|
+
sessionsServed: () => served,
|
|
640
|
+
async listTools() {
|
|
641
|
+
const why = refusal();
|
|
642
|
+
if (why)
|
|
643
|
+
throw new Error(`relay cannot list this turn's tools: ${why}`);
|
|
644
|
+
return core.listTools();
|
|
645
|
+
},
|
|
646
|
+
onFatal(fail) { failed = fail; if (fatalReason)
|
|
647
|
+
fail(fatalReason); },
|
|
648
|
+
close,
|
|
649
|
+
};
|
|
650
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// The names the brokers are known by in a launched agent's configuration and environment. They live
|
|
2
|
+
// apart from the brokers so that a backend can name them without loading a broker, and with it the
|
|
3
|
+
// MCP server and SDK, into every worker: a turn that opens no broker never loads one.
|
|
4
|
+
/** The MCP server name of the HTTP broker in a Codex turn's configuration (broker-http.ts). */
|
|
5
|
+
export const BROKER_SERVER_NAME = "relay_tools";
|
|
6
|
+
/** The variable that carries the HTTP broker's bearer token to the app server. */
|
|
7
|
+
export const BROKER_TOKEN_ENV = "RELAY_BROKER_TOKEN";
|
|
8
|
+
/** The variable that carries the turn's bridge secret to `relay bridge`, and nothing else (broker.ts). */
|
|
9
|
+
export const BRIDGE_SECRET_ENV = "RELAY_BRIDGE_SECRET";
|