orkestrator 2.36.4-beta → 2.36.6-beta
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/dist/client.js +12052 -10298
- package/dist/main.js +61707 -57456
- package/package.json +3 -3
- package/resources/acp-bridge/dist/index.js +1238 -115
- package/resources/claude-bridge/dist/index.js +1517 -208
- package/resources/codex-bridge/dist/index.js +1521 -290
- package/resources/cursor-bridge/dist/index.js +1210 -91
- package/resources/cursor-bridge/runtime/install.json +1 -1
- package/resources/pi-bridge/dist/index.js +1761 -388
- package/resources/pi-bridge/runtime/install.json +1 -1
|
@@ -1,3 +1,75 @@
|
|
|
1
|
+
// ../protocol/src/node/bridge-launch-environment.ts
|
|
2
|
+
import { closeSync, fstatSync, openSync, readSync, rmSync, constants } from "node:fs";
|
|
3
|
+
var BRIDGE_LAUNCH_ENVIRONMENT_ENV = "ORKESTRATOR_BRIDGE_LAUNCH_ENVIRONMENT";
|
|
4
|
+
var BRIDGE_LAUNCH_KEYS_ENV = "ORKESTRATOR_BRIDGE_LAUNCH_KEYS";
|
|
5
|
+
var BRIDGE_LAUNCH_WORKDIR_ENV = "ORKESTRATOR_BRIDGE_LAUNCH_WORKDIR";
|
|
6
|
+
var MAX_SNAPSHOT_BYTES = 1024 * 1024;
|
|
7
|
+
var MAX_SNAPSHOT_ENTRIES = 4096;
|
|
8
|
+
var NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_%.-]*$/;
|
|
9
|
+
var LAUNCH_ONLY = /(?:_BRIDGE_TOKEN|_TOKEN_SHA256|_AUTHORITY_KEY)$|^ORKESTRATOR_BRIDGE_(?:LAUNCH_|EXECUTION_POLICY$)|^ORKESTRATOR_COORDINATOR_/;
|
|
10
|
+
var NOT_APPLIED = new Set(["PWD", "OLDPWD", "SHLVL", "_", "NODE_PATH"]);
|
|
11
|
+
function readSnapshot(file) {
|
|
12
|
+
let fd;
|
|
13
|
+
try {
|
|
14
|
+
fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
15
|
+
} catch {
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
try {
|
|
19
|
+
const stat = fstatSync(fd);
|
|
20
|
+
if (!stat.isFile() || stat.size > MAX_SNAPSHOT_BYTES)
|
|
21
|
+
return null;
|
|
22
|
+
const buffer = Buffer.alloc(stat.size);
|
|
23
|
+
let offset = 0;
|
|
24
|
+
while (offset < buffer.length) {
|
|
25
|
+
const read = readSync(fd, buffer, offset, buffer.length - offset, offset);
|
|
26
|
+
if (read === 0)
|
|
27
|
+
break;
|
|
28
|
+
offset += read;
|
|
29
|
+
}
|
|
30
|
+
return buffer.subarray(0, offset);
|
|
31
|
+
} finally {
|
|
32
|
+
closeSync(fd);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
function applyBridgeLaunchEnvironment(env = process.env, chdir = (directory) => process.chdir(directory)) {
|
|
36
|
+
const file = env[BRIDGE_LAUNCH_ENVIRONMENT_ENV];
|
|
37
|
+
if (!file)
|
|
38
|
+
return null;
|
|
39
|
+
const trusted = new Set((env[BRIDGE_LAUNCH_KEYS_ENV] ?? "").split(",").map((name) => name.trim()).filter(Boolean));
|
|
40
|
+
const workdir = env[BRIDGE_LAUNCH_WORKDIR_ENV];
|
|
41
|
+
delete env[BRIDGE_LAUNCH_ENVIRONMENT_ENV];
|
|
42
|
+
delete env[BRIDGE_LAUNCH_KEYS_ENV];
|
|
43
|
+
delete env[BRIDGE_LAUNCH_WORKDIR_ENV];
|
|
44
|
+
const result = { applied: 0, refused: 0 };
|
|
45
|
+
const snapshot = readSnapshot(file);
|
|
46
|
+
rmSync(file, { force: true });
|
|
47
|
+
if (snapshot) {
|
|
48
|
+
const entries = snapshot.toString("utf8").split("\x00").slice(0, MAX_SNAPSHOT_ENTRIES);
|
|
49
|
+
for (const entry of entries) {
|
|
50
|
+
const separator = entry.indexOf("=");
|
|
51
|
+
if (separator <= 0)
|
|
52
|
+
continue;
|
|
53
|
+
const name = entry.slice(0, separator);
|
|
54
|
+
if (!NAME_PATTERN.test(name) || NOT_APPLIED.has(name))
|
|
55
|
+
continue;
|
|
56
|
+
if (trusted.has(name) || LAUNCH_ONLY.test(name)) {
|
|
57
|
+
result.refused += 1;
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
env[name] = entry.slice(separator + 1);
|
|
61
|
+
result.applied += 1;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (workdir) {
|
|
65
|
+
try {
|
|
66
|
+
chdir(workdir);
|
|
67
|
+
} catch {}
|
|
68
|
+
}
|
|
69
|
+
return result;
|
|
70
|
+
}
|
|
71
|
+
applyBridgeLaunchEnvironment();
|
|
72
|
+
|
|
1
73
|
// ../protocol/src/log-vocabulary/define.ts
|
|
2
74
|
var ESSENTIAL_ERROR_FIELDS = {
|
|
3
75
|
"error.name": "label",
|
|
@@ -416,6 +488,7 @@ var DESKTOP_LOG_AREAS = defineLogAreas({
|
|
|
416
488
|
events: {
|
|
417
489
|
"attention-failed": "A dialog could not ask for the user's attention.",
|
|
418
490
|
closed: "A native dialog closed.",
|
|
491
|
+
"hidden-cancelled": "A hidden profile cancelled a dialog without opening native UI.",
|
|
419
492
|
"open-failed": "A dialog could not open; it was answered as cancelled.",
|
|
420
493
|
opening: "A native dialog is opening.",
|
|
421
494
|
"preview-beforeunload-ignored": "A browser preview's beforeunload handler was ignored.",
|
|
@@ -501,6 +574,7 @@ var ENVIRONMENT_LOG_AREAS = defineLogAreas({
|
|
|
501
574
|
"orphan-session.reaped": "A native session no tab references was torn down.",
|
|
502
575
|
"handoff-sweep.failed": "Sweeping transferred transcripts no tab references failed.",
|
|
503
576
|
"delete.terminals-survived": "Terminal process trees outlived termination, so the deletion stops.",
|
|
577
|
+
"delete.step-deadline": "A deletion step that runs child processes passed its deadline; they are stopped and the deletion fails once they have.",
|
|
504
578
|
"delete.artifacts-left": "Graph run artifact directories were not removed.",
|
|
505
579
|
"delete.worktrees-kept": "Graph runs kept branch worktrees.",
|
|
506
580
|
"delete.step-failed": "One best-effort part of deleting an environment failed; `step` says which, and the rest goes on.",
|
|
@@ -535,6 +609,7 @@ var GATEWAY_LOG_AREAS = defineLogAreas({
|
|
|
535
609
|
"host.refused": "A request named a host this gateway does not answer to. Logged once per name, up to a limit.",
|
|
536
610
|
"port.fallback": "The preferred port was taken, so a nearby one is used.",
|
|
537
611
|
"port.fallback-distant": "The preferred port and those nearby were taken, so another is used.",
|
|
612
|
+
"request-auth.fallback": "A desktop request-auth hook failed closed. Phase only; no request or error content.",
|
|
538
613
|
"request.failed": "A gateway request failed. Throttled: repeats are counted, not written.",
|
|
539
614
|
"websocket.upgrade-failed": "A WebSocket upgrade failed.",
|
|
540
615
|
"events.client-dropped": "An event-stream client buffered too much and was dropped; it reconnects and refetches.",
|
|
@@ -593,6 +668,11 @@ var LOCAL_SERVER_LOG_AREAS = defineLogAreas({
|
|
|
593
668
|
requested: "boolean"
|
|
594
669
|
}
|
|
595
670
|
},
|
|
671
|
+
"bridge.orphans-reaped": {
|
|
672
|
+
description: "Processes a bridge left in its process group after exiting on its own (its agent CLI, mid-turn) were stopped. `warn` when they left; `error` when one survived SIGKILL.",
|
|
673
|
+
essential: true,
|
|
674
|
+
fields: { key: "label", pid: "number", result: "label" }
|
|
675
|
+
},
|
|
596
676
|
"reaper.tmux-list-failed": "Orphaned claude-tmux sessions could not be listed.",
|
|
597
677
|
"reaper.tmux-kill-failed": "An orphaned tmux session could not be killed.",
|
|
598
678
|
"reaper.tmux-reaped": "Orphaned claude-tmux sessions of a deleted environment were killed.",
|
|
@@ -643,6 +723,8 @@ var LOGGING_LOG_AREAS = defineLogAreas({
|
|
|
643
723
|
},
|
|
644
724
|
"essential.write-failed": "Writing the essential log failed. Its entries are counted, and a marker reports them at the next write that works.",
|
|
645
725
|
"policy.changed": "The logging settings changed: saving, retention and levels, with no content.",
|
|
726
|
+
"policy.detail-expired": "Raised log detail reached its expiry, so the backend set its raised levels back to info. Saving is unchanged.",
|
|
727
|
+
"policy.expiry-failed": "Checking or applying the log detail expiry failed; the next check, a minute later, tries again.",
|
|
646
728
|
"policy.bridge-predates-route": "A running bridge has no logging settings route; it applies them at its next start.",
|
|
647
729
|
"policy.push-failed": "A running bridge did not take the logging settings after retries; its next start resends them.",
|
|
648
730
|
"prune.failed": "Removing expired log files failed; the next sweep retries.",
|
|
@@ -650,6 +732,23 @@ var LOGGING_LOG_AREAS = defineLogAreas({
|
|
|
650
732
|
"unknown-area": "Code outside the type checker asked for an area that is not listed.",
|
|
651
733
|
...THROTTLE_LOG_EVENTS
|
|
652
734
|
}
|
|
735
|
+
},
|
|
736
|
+
"renderer-errors": {
|
|
737
|
+
description: "Renderer failures a desktop window reported from its error ring: class, boundary, surface, count and fingerprint, never a message or stack.",
|
|
738
|
+
events: {
|
|
739
|
+
"error.recorded": {
|
|
740
|
+
description: "A renderer reported `count` new occurrences of one failure since its last report.",
|
|
741
|
+
essential: true,
|
|
742
|
+
fields: {
|
|
743
|
+
errorClass: "label",
|
|
744
|
+
boundary: "label",
|
|
745
|
+
route: "label",
|
|
746
|
+
fingerprint: "label",
|
|
747
|
+
count: "number"
|
|
748
|
+
}
|
|
749
|
+
},
|
|
750
|
+
"report.rate-limited": "Renderer error entries arrived faster than the backend records them, so `dropped` were counted and not written."
|
|
751
|
+
}
|
|
653
752
|
}
|
|
654
753
|
});
|
|
655
754
|
|
|
@@ -707,6 +806,8 @@ var NATIVE_AGENT_LOG_AREAS = defineLogAreas({
|
|
|
707
806
|
"usage-limit.notice-failed": "A usage-limit stop's outcome could not be read for its notice.",
|
|
708
807
|
"usage-limit.resend-failed": "Resending after a usage limit failed. An unknown send stays in the journal.",
|
|
709
808
|
"title.strategy-failed": "A session title strategy failed, so the next is tried. Content-free: the error can quote the prompt.",
|
|
809
|
+
"steer.qualification-failed": "A bridge's steer qualification failed or answered non-OK, so steering is not offered. Agent and status code or error class only.",
|
|
810
|
+
"steer.capability-cleared": "A projection cleared `actions.steer` because its bridge did not qualify. Identifiers and turn status only.",
|
|
710
811
|
...THROTTLE_LOG_EVENTS
|
|
711
812
|
}
|
|
712
813
|
},
|
|
@@ -807,6 +908,9 @@ var RUNTIME_LOG_AREAS = defineLogAreas({
|
|
|
807
908
|
essential: true,
|
|
808
909
|
fields: { origin: "label", ...ESSENTIAL_ERROR_FIELDS }
|
|
809
910
|
},
|
|
911
|
+
"child.reaped": "A macOS child whose exit Bun lost was reaped after its command settled, so it no longer waits as a zombie.",
|
|
912
|
+
"child.reap-abandoned": "A child whose exit Bun lost was left unreaped: `reason` says whether it was never seen as a zombie (`not-a-zombie`), too many were pending (`capacity`), or `waitpid` failed.",
|
|
913
|
+
"child.reap-unavailable": "waitpid could not be loaded, so children whose exit Bun lost stay zombies until this process exits.",
|
|
810
914
|
...THROTTLE_LOG_EVENTS
|
|
811
915
|
}
|
|
812
916
|
}
|
|
@@ -1213,6 +1317,13 @@ var COORDINATOR_LOG_AREAS = defineLogAreas({
|
|
|
1213
1317
|
"store.workflows-cleared": "The workflow store was full, so a batch of its oldest finished records was removed.",
|
|
1214
1318
|
"store.workflows-in-use": "The workflow store was full and every record was still in use, so new work was refused.",
|
|
1215
1319
|
"remote-worker.settle-failed": "A remote worker could not be settled.",
|
|
1320
|
+
"node-release.failed": "Work on a node that was forgotten or handed over could not be closed; the sweep's registry check retries.",
|
|
1321
|
+
"node-release.reconcile-failed": "The sweep could not check records against the node registry; the next sweep retries.",
|
|
1322
|
+
"node-release.unregistered": "Records named a node the registry no longer holds, so their work was closed here.",
|
|
1323
|
+
"node-release.notice-failed": "The notice for work closed on a released node could not be sent; it stays owed and the sweep retries.",
|
|
1324
|
+
"node-release.no-coordinator": "Work closed on a released node belonged to a coordinator that no longer exists, so nobody was told.",
|
|
1325
|
+
"node-offline.notice-failed": "The notice that a node has been unreachable for a day could not be sent; the next failed read retries.",
|
|
1326
|
+
"node-offline.check-failed": "Whether a long-unreachable node's coordinators were told could not be checked; the next read retries.",
|
|
1216
1327
|
"checkout.merge-followed": "After an environment's PR merged, the project checkout was fast-forwarded, or `outcome` says why not.",
|
|
1217
1328
|
"checkout.merge-follow-failed": "Fast-forwarding the project checkout failed, after an environment's PR merged or before mail woke the main coordinator.",
|
|
1218
1329
|
"checkout.mail-follow": "Before mail woke the main coordinator, the project checkout was fast-forwarded (`fast-forwarded-fetched` when the fetch was slow or failed and the upstream commit already fetched was merged), or `outcome` says why not (`timed-out`, `failed`).",
|
|
@@ -1309,6 +1420,7 @@ var DOCKER_LOG_AREAS = defineLogAreas({
|
|
|
1309
1420
|
events: {
|
|
1310
1421
|
"portable-inputs.relay-missing": "Docker is rootless and the image predates the staged-input relay, so the container cannot read them until rebuilt.",
|
|
1311
1422
|
"git-mirror.mount-unavailable": "A new container gets no project Git mirror, so its clone goes to the remote.",
|
|
1423
|
+
"git-mirror.mount-withheld": "A new restricted container gets no project Git mirror because its firewall would not let it reach the project's remote, so it cannot read what the remote serves through the mirror either.",
|
|
1312
1424
|
"git-mirror.refreshed": "A project's Git mirror was built or updated.",
|
|
1313
1425
|
"git-mirror.seeded": "A project's Git mirror was built from its host checkout and only what the remote added to it.",
|
|
1314
1426
|
"git-mirror.seed-skipped": "A project's host checkout could not seed its Git mirror, so the build downloads everything.",
|
|
@@ -1394,7 +1506,11 @@ var DOCKER_LOG_AREAS = defineLogAreas({
|
|
|
1394
1506
|
"network.list-failed": "Docker networks could not be listed.",
|
|
1395
1507
|
"network.inspect-failed": "A Docker network could not be inspected.",
|
|
1396
1508
|
"stale-containers.removing": "Stale probe containers are being removed.",
|
|
1397
|
-
"stale-networks.removing": "Stale probe networks are being removed."
|
|
1509
|
+
"stale-networks.removing": "Stale probe networks are being removed.",
|
|
1510
|
+
"peers.refused": "The agent tools server closed connections from addresses outside loopback and this backend's Docker networks (at most one entry a minute, with a count).",
|
|
1511
|
+
"peers.subnets-loaded": "The Docker subnets the agent tools server admits were reloaded.",
|
|
1512
|
+
"port.loopback-taken": "The agent tools server gave up a port because another process holds it on 127.0.0.1, where host agents call; it moves to a free port.",
|
|
1513
|
+
"peers.subnets-load-failed": "The Docker subnets the agent tools server admits could not be read; cached permissions are cleared and only loopback is admitted until a successful retry."
|
|
1398
1514
|
}
|
|
1399
1515
|
}
|
|
1400
1516
|
});
|
|
@@ -1485,6 +1601,7 @@ var NODES_LOG_AREAS = defineLogAreas({
|
|
|
1485
1601
|
"verification.record-failed": "A node verification could not be recorded.",
|
|
1486
1602
|
"profile.record-failed": "A node profile could not be recorded.",
|
|
1487
1603
|
"detach.unconfirmed": "A forgotten node has not confirmed the detach yet.",
|
|
1604
|
+
"grant.revocation-listener-failed": "A connection could not be told its client grant was removed; the grant is still gone.",
|
|
1488
1605
|
"handover.recovery-pending": "Command handover recovery is still pending.",
|
|
1489
1606
|
"ticket-sync.work-record-failed": "A remote build started but its ticket work location could not be saved.",
|
|
1490
1607
|
"ticket-sync.failed": "A Kanban sync with a node failed; it is retried.",
|
|
@@ -1537,7 +1654,9 @@ var HOST_LOG_AREAS = defineLogAreas({
|
|
|
1537
1654
|
"tool.missing": "A host tool was not found.",
|
|
1538
1655
|
"maintenance.listener-failed": "A host maintenance listener threw; the others still run.",
|
|
1539
1656
|
"suspend.reconcile-failed": "Reconciling due work after a host suspension failed.",
|
|
1540
|
-
"load.sample-failed": "Sampling machine load failed; the next sample retries."
|
|
1657
|
+
"load.sample-failed": "Sampling machine load failed; the next sample retries.",
|
|
1658
|
+
"usage.source-stalled": "A usage source (scope: disk or gpu-sysfs) did not answer in time; its figure is missing from the sample until it does.",
|
|
1659
|
+
...THROTTLE_LOG_EVENTS
|
|
1541
1660
|
}
|
|
1542
1661
|
}
|
|
1543
1662
|
});
|
|
@@ -2114,7 +2233,7 @@ var MAX_FRAME_CHARS = 240;
|
|
|
2114
2233
|
var MAX_RAW_FRAME_CHARS = 1024;
|
|
2115
2234
|
var MAX_CAUSE_DEPTH = 2;
|
|
2116
2235
|
var TRUNCATED_MARKER = "...[truncated]";
|
|
2117
|
-
var
|
|
2236
|
+
var NAME_PATTERN2 = /^[A-Za-z_$][\w$.-]{0,63}$/;
|
|
2118
2237
|
var CODE_PATTERN = /^[\w.:-]{1,64}$/;
|
|
2119
2238
|
var SYSCALL_PATTERN = /^[\w./ -]{1,128}$/;
|
|
2120
2239
|
var COMMAND_OUTPUT_FIELDS = ["stdout", "stderr", "cmd", "spawnargs"];
|
|
@@ -2192,7 +2311,7 @@ function describe(error, includeStack, includeMessage, depth) {
|
|
|
2192
2311
|
if (!(error instanceof Error) && typeof rawMessage !== "string") {
|
|
2193
2312
|
return { name: "NonError", message: "[object]" };
|
|
2194
2313
|
}
|
|
2195
|
-
const name = matching(read(error, "name"),
|
|
2314
|
+
const name = matching(read(error, "name"), NAME_PATTERN2) ?? "Error";
|
|
2196
2315
|
const message = typeof rawMessage === "string" ? rawMessage : undefined;
|
|
2197
2316
|
const commandFailure = isCommandFailure(error, name, message);
|
|
2198
2317
|
const stackHoldsMessage = message !== undefined && String(read(error, "stack") ?? "").includes(message);
|
|
@@ -2247,7 +2366,7 @@ function logErrorKind(error) {
|
|
|
2247
2366
|
const safeCode = finite(code) ?? matching(code, CODE_PATTERN);
|
|
2248
2367
|
if (safeCode !== undefined)
|
|
2249
2368
|
return String(safeCode);
|
|
2250
|
-
return matching(read(error, "name"),
|
|
2369
|
+
return matching(read(error, "name"), NAME_PATTERN2) ?? "Error";
|
|
2251
2370
|
}
|
|
2252
2371
|
|
|
2253
2372
|
// ../protocol/src/log-essential-labels.ts
|
|
@@ -2860,6 +2979,7 @@ function effectiveLogLevel(detail, area) {
|
|
|
2860
2979
|
return detail.level;
|
|
2861
2980
|
}
|
|
2862
2981
|
}
|
|
2982
|
+
var LOG_DETAIL_EXPIRY_MS = 24 * 60 * 60 * 1000;
|
|
2863
2983
|
function logDetailEnablesBridgeDiagnostics(detail) {
|
|
2864
2984
|
return LEVEL_DETAIL[effectiveLogLevel(detail, BRIDGE_DIAGNOSTICS_LOG_AREA)] >= LEVEL_DETAIL.debug;
|
|
2865
2985
|
}
|
|
@@ -8109,10 +8229,13 @@ import { isAbsolute, join as join3 } from "node:path";
|
|
|
8109
8229
|
|
|
8110
8230
|
// ../protocol/src/coordinator.ts
|
|
8111
8231
|
var COORDINATOR_COMMAND_SANDBOX_ENV = "ORKESTRATOR_COORDINATOR_COMMAND_SANDBOX";
|
|
8232
|
+
var COORDINATOR_PROTECTED_DATA_DIR_ENV = "ORKESTRATOR_COORDINATOR_PROTECTED_DATA_DIR";
|
|
8112
8233
|
function coordinatorCommandSandboxFromEnv(env) {
|
|
8113
8234
|
return env[COORDINATOR_COMMAND_SANDBOX_ENV] === "unavailable" ? "unavailable" : "required";
|
|
8114
8235
|
}
|
|
8115
8236
|
var COORDINATOR_CLAUDE_USER_SKILLS_DIR_ENV = "ORKESTRATOR_COORDINATOR_CLAUDE_USER_SKILLS_DIR";
|
|
8237
|
+
var COORDINATOR_OTHER_ENVIRONMENTS_SETTING_LABEL = "Let the coordinator use environments it did not create";
|
|
8238
|
+
var COORDINATOR_ENVIRONMENT_ORIGIN_REFUSAL = `Not done: this coordinator did not create that environment, so it may not send it work. Do not retry. Use an environment this coordinator launched, or start a new one. If the user wants this coordinator to work in environments it did not create, tell them to turn on "${COORDINATOR_OTHER_ENVIRONMENTS_SETTING_LABEL}" in this project's settings, under Coordinator.`;
|
|
8116
8239
|
var COORDINATOR_CONTROL_TOOL_NAMES = Object.freeze([
|
|
8117
8240
|
"ack_message",
|
|
8118
8241
|
"add_ticket_comment",
|
|
@@ -8841,6 +8964,135 @@ function claudeMcpToolPrefix(name) {
|
|
|
8841
8964
|
return `mcp__${normalized}__`;
|
|
8842
8965
|
}
|
|
8843
8966
|
|
|
8967
|
+
// ../../bridges/claude-bridge/src/services/read-only-path-boundary.ts
|
|
8968
|
+
import { join as join6 } from "node:path";
|
|
8969
|
+
|
|
8970
|
+
// ../protocol/src/node/coordinator-read-boundary.ts
|
|
8971
|
+
import { realpathSync } from "node:fs";
|
|
8972
|
+
import { homedir as homedir2 } from "node:os";
|
|
8973
|
+
import { dirname, isAbsolute as isAbsolute2, join as join5, parse, resolve as resolve2, sep } from "node:path";
|
|
8974
|
+
function canonicalPath(path) {
|
|
8975
|
+
let existing = path;
|
|
8976
|
+
const tail = [];
|
|
8977
|
+
for (;; ) {
|
|
8978
|
+
try {
|
|
8979
|
+
return join5(realpathSync.native(existing), ...tail.reverse());
|
|
8980
|
+
} catch {
|
|
8981
|
+
const parent = dirname(existing);
|
|
8982
|
+
if (parent === existing)
|
|
8983
|
+
return path;
|
|
8984
|
+
tail.push(existing.slice(parent.length).replace(/^[/\\]+/, ""));
|
|
8985
|
+
existing = parent;
|
|
8986
|
+
}
|
|
8987
|
+
}
|
|
8988
|
+
}
|
|
8989
|
+
function namedAndCanonicalPaths(paths) {
|
|
8990
|
+
const named = paths.flatMap((path) => path?.trim() && isAbsolute2(path) ? [path] : []);
|
|
8991
|
+
return [...new Set(named.flatMap((path) => [resolve2(path), canonicalPath(path)]))];
|
|
8992
|
+
}
|
|
8993
|
+
function isWithin(root, path) {
|
|
8994
|
+
if (path === root)
|
|
8995
|
+
return true;
|
|
8996
|
+
const prefix = root === parse(root).root ? root : `${root}${sep}`;
|
|
8997
|
+
return path.startsWith(prefix);
|
|
8998
|
+
}
|
|
8999
|
+
function protectedDataDirBoundary(dataDir, allowances) {
|
|
9000
|
+
const trimmed = dataDir?.trim();
|
|
9001
|
+
if (!trimmed || !isAbsolute2(trimmed))
|
|
9002
|
+
return null;
|
|
9003
|
+
const deny = namedAndCanonicalPaths([trimmed]);
|
|
9004
|
+
return {
|
|
9005
|
+
deny,
|
|
9006
|
+
allow: namedAndCanonicalPaths(allowances).filter((path) => !deny.includes(path) && deny.some((root) => isWithin(root, path)))
|
|
9007
|
+
};
|
|
9008
|
+
}
|
|
9009
|
+
function deniedForm(boundary, path) {
|
|
9010
|
+
return boundary.deny.some((root) => isWithin(root, path)) && !boundary.allow.some((root) => isWithin(root, path));
|
|
9011
|
+
}
|
|
9012
|
+
function expandedHome(path) {
|
|
9013
|
+
if (path === "~")
|
|
9014
|
+
return homedir2();
|
|
9015
|
+
return path.startsWith("~/") ? `${homedir2()}${sep}${path.slice(2)}` : path;
|
|
9016
|
+
}
|
|
9017
|
+
function readBoundaryRefuses(boundary, path, cwd, options = {}) {
|
|
9018
|
+
const expanded = expandedHome(path);
|
|
9019
|
+
const raw = isAbsolute2(expanded) ? expanded : `${cwd}${sep}${expanded}`;
|
|
9020
|
+
const lexical = resolve2(raw);
|
|
9021
|
+
const real = canonicalPath(raw);
|
|
9022
|
+
if (deniedForm(boundary, lexical) || deniedForm(boundary, real))
|
|
9023
|
+
return true;
|
|
9024
|
+
return options.traversal === true && boundary.deny.some((root) => isWithin(lexical, root) || isWithin(real, root));
|
|
9025
|
+
}
|
|
9026
|
+
|
|
9027
|
+
// ../../bridges/claude-bridge/src/services/read-only-path-boundary.ts
|
|
9028
|
+
function claudeReadOnlyWorkspacePaths(cwd) {
|
|
9029
|
+
return [...new Set([cwd, canonicalPath(cwd)])];
|
|
9030
|
+
}
|
|
9031
|
+
function coordinatorReadBoundary(workspaces, env = process.env) {
|
|
9032
|
+
const dataDir = env[COORDINATOR_PROTECTED_DATA_DIR_ENV]?.trim();
|
|
9033
|
+
return protectedDataDirBoundary(dataDir, [
|
|
9034
|
+
env.CLAUDE_CONFIG_DIR,
|
|
9035
|
+
env.ORKESTRATOR_BRIDGE_ATTACHMENT_ROOT,
|
|
9036
|
+
env[COORDINATOR_CLAUDE_USER_SKILLS_DIR_ENV],
|
|
9037
|
+
dataDir ? join6(dataDir, "toolchains") : undefined,
|
|
9038
|
+
...workspaces
|
|
9039
|
+
]);
|
|
9040
|
+
}
|
|
9041
|
+
function globRoot(pattern) {
|
|
9042
|
+
if (!pattern.startsWith("/") && !pattern.startsWith("~") && !pattern.startsWith("..")) {
|
|
9043
|
+
return;
|
|
9044
|
+
}
|
|
9045
|
+
const wildcard = pattern.search(/[*?[{]/);
|
|
9046
|
+
return wildcard < 0 ? pattern : pattern.slice(0, wildcard);
|
|
9047
|
+
}
|
|
9048
|
+
function readToolRefused(boundary, tool, input, cwd) {
|
|
9049
|
+
const text = (key) => {
|
|
9050
|
+
const value = input[key];
|
|
9051
|
+
return typeof value === "string" && value.trim() ? value : undefined;
|
|
9052
|
+
};
|
|
9053
|
+
if (tool === "Read") {
|
|
9054
|
+
const path = text("file_path");
|
|
9055
|
+
return path !== undefined && readBoundaryRefuses(boundary, path, cwd);
|
|
9056
|
+
}
|
|
9057
|
+
if (tool !== "Grep" && tool !== "Glob")
|
|
9058
|
+
return false;
|
|
9059
|
+
const roots = [text("path") ?? cwd];
|
|
9060
|
+
const pattern = tool === "Glob" ? text("pattern") : undefined;
|
|
9061
|
+
const root = pattern ? globRoot(pattern) : undefined;
|
|
9062
|
+
if (root)
|
|
9063
|
+
roots.push(root);
|
|
9064
|
+
return roots.some((path) => readBoundaryRefuses(boundary, path, cwd, { traversal: true }));
|
|
9065
|
+
}
|
|
9066
|
+
function shellCommandRefused(boundary, command, cwd, options) {
|
|
9067
|
+
const [program, ...tokens] = command.trim().split(/\s+/);
|
|
9068
|
+
if (options.traversal) {
|
|
9069
|
+
const indirectOption = program === "sort" || program === "wc" ? "--files0-from" : program === "file" ? "--files-from" : ["cksum", "md5sum", "sha1sum", "sha256sum"].includes(program ?? "") ? "--check" : undefined;
|
|
9070
|
+
if (indirectOption && tokens.some((token) => {
|
|
9071
|
+
const option = token.split("=", 1)[0];
|
|
9072
|
+
return option.startsWith("--") && indirectOption.startsWith(option) || program === "file" && /^-[^-]*f/.test(token) || indirectOption === "--check" && /^-[^-]*c/.test(token);
|
|
9073
|
+
}))
|
|
9074
|
+
return true;
|
|
9075
|
+
if (program === "grep" && tokens.some((token) => /^-[^-]*[RS]/.test(token) || token.startsWith("--") && "--dereference-recursive".startsWith(token)) || program === "diff" && tokens.some((token) => /^-[^-]*r/.test(token) || token.startsWith("--") && "--recursive".startsWith(token)) || (program === "rg" || program === "ag" || program === "find" || program === "fd" || program === "du" || program === "ls") && tokens.some((token) => token === "--follow" || token === "--dereference" || /^-[^-]*L/.test(token)))
|
|
9076
|
+
return true;
|
|
9077
|
+
const searches = program === "rg" || program === "ag" || program === "find" || program === "fd" || program === "du" || program === "ls" || program === "tree" || program === "grep";
|
|
9078
|
+
if (searches && readBoundaryRefuses(boundary, cwd, cwd, options))
|
|
9079
|
+
return true;
|
|
9080
|
+
}
|
|
9081
|
+
return tokens.some((token) => {
|
|
9082
|
+
const attached = [];
|
|
9083
|
+
if (token.startsWith("--")) {
|
|
9084
|
+
const equals = token.indexOf("=");
|
|
9085
|
+
if (equals >= 0)
|
|
9086
|
+
attached.push(token.slice(equals + 1));
|
|
9087
|
+
} else if (token.startsWith("-")) {
|
|
9088
|
+
for (let index = 1;index < token.length && /[a-zA-Z0-9]/.test(token[index]); index++) {
|
|
9089
|
+
attached.push(token.slice(index + 1));
|
|
9090
|
+
}
|
|
9091
|
+
}
|
|
9092
|
+
return [token, ...attached].some((candidate) => candidate && readBoundaryRefuses(boundary, candidate, cwd, options));
|
|
9093
|
+
});
|
|
9094
|
+
}
|
|
9095
|
+
|
|
8844
9096
|
// ../../bridges/claude-bridge/src/services/read-only-policy.ts
|
|
8845
9097
|
var CAPABILITY_TOOLS = new Map([
|
|
8846
9098
|
["file.write", ["Write", "NotebookEdit", "EnterWorktree", "ExitWorktree"]],
|
|
@@ -9124,7 +9376,10 @@ function claudeReadOnlySandbox(policy, options = {}) {
|
|
|
9124
9376
|
autoAllowBashIfSandboxed: true,
|
|
9125
9377
|
allowUnsandboxedCommands: false,
|
|
9126
9378
|
excludedCommands: [],
|
|
9127
|
-
filesystem: {
|
|
9379
|
+
filesystem: {
|
|
9380
|
+
denyWrite: [...new Set(options.workspaces ?? [])],
|
|
9381
|
+
...options.readBoundary ? { denyRead: options.readBoundary.deny, allowRead: options.readBoundary.allow } : {}
|
|
9382
|
+
},
|
|
9128
9383
|
network: {
|
|
9129
9384
|
allowLocalBinding: policy.networkAccess === "full",
|
|
9130
9385
|
strictAllowlist: true,
|
|
@@ -9151,7 +9406,8 @@ var REFUSALS = {
|
|
|
9151
9406
|
tool: (tool) => `Coordinator is read-only, so ${tool} is not available. Delegate file changes to a worker environment.`,
|
|
9152
9407
|
waiting: (tool) => `Coordinator turns do not wait, so ${tool} is not available. Delegated work reports back by waking this conversation with a message when it finishes; end your turn instead.`,
|
|
9153
9408
|
mcp: (tool) => `Coordinator sessions may only use Orkestrator's own tools, so ${tool} is not available.`,
|
|
9154
|
-
unsandboxed: "Coordinator commands may not run outside the sandbox."
|
|
9409
|
+
unsandboxed: "Coordinator commands may not run outside the sandbox.",
|
|
9410
|
+
dataDirectory: "Coordinators cannot read Orkestrator's data directory, which holds credentials with wider authority than this conversation. This conversation's own tool results, memory and attachments stay readable."
|
|
9155
9411
|
},
|
|
9156
9412
|
"read-only": {
|
|
9157
9413
|
composition: "Shell commands in this session cannot use quotes, escapes, globs, pipes, redirection, substitution or command chaining, because the command that runs would not be the one checked.",
|
|
@@ -9166,7 +9422,8 @@ var REFUSALS = {
|
|
|
9166
9422
|
tool: (tool) => `This session is read-only, so ${tool} is not available.`,
|
|
9167
9423
|
waiting: (tool) => `This session's turns do not wait, so ${tool} is not available. End your turn instead.`,
|
|
9168
9424
|
mcp: (tool) => `This session may only use Orkestrator's own tools and the MCP servers granted to it, so ${tool} is not available.`,
|
|
9169
|
-
unsandboxed: "Commands in this session may not run outside the sandbox."
|
|
9425
|
+
unsandboxed: "Commands in this session may not run outside the sandbox.",
|
|
9426
|
+
dataDirectory: "This session cannot read Orkestrator's data directory, which holds credentials with wider authority than this session. Its own tool results, memory and attachments stay readable."
|
|
9170
9427
|
}
|
|
9171
9428
|
};
|
|
9172
9429
|
function isReadOnlyShellCommand(command, options = {}) {
|
|
@@ -9279,6 +9536,7 @@ function createCoordinatorReadOnlyHook(policy, researchMcpServerNames = coordina
|
|
|
9279
9536
|
...researchMcpServerNames.map(claudeMcpToolPrefix),
|
|
9280
9537
|
...(nativeAgentUserMcpGrant(policy) ?? []).map(claudeMcpToolPrefix)
|
|
9281
9538
|
];
|
|
9539
|
+
const readBoundary = (cwd) => options.readBoundary !== undefined ? options.readBoundary : process.env[COORDINATOR_PROTECTED_DATA_DIR_ENV] ? coordinatorReadBoundary(claudeReadOnlyWorkspacePaths(cwd)) : null;
|
|
9282
9540
|
return async (input) => {
|
|
9283
9541
|
if (input.hook_event_name !== "PreToolUse")
|
|
9284
9542
|
return {};
|
|
@@ -9307,6 +9565,20 @@ function createCoordinatorReadOnlyHook(policy, researchMcpServerNames = coordina
|
|
|
9307
9565
|
const verdict = isReadOnlyShellCommand(command, options);
|
|
9308
9566
|
if (!verdict.allowed)
|
|
9309
9567
|
return deny(verdict.reason);
|
|
9568
|
+
const boundary = readBoundary(input.cwd);
|
|
9569
|
+
if (boundary && shellCommandRefused(boundary, command, input.cwd, {
|
|
9570
|
+
traversal: options.commandSandbox === "unavailable"
|
|
9571
|
+
})) {
|
|
9572
|
+
return deny(refusals.dataDirectory);
|
|
9573
|
+
}
|
|
9574
|
+
return {};
|
|
9575
|
+
}
|
|
9576
|
+
if (toolName === "Read" || toolName === "Grep" || toolName === "Glob") {
|
|
9577
|
+
const boundary = readBoundary(input.cwd);
|
|
9578
|
+
const toolInput = input.tool_input ?? {};
|
|
9579
|
+
if (boundary && readToolRefused(boundary, toolName, toolInput, input.cwd)) {
|
|
9580
|
+
return deny(refusals.dataDirectory);
|
|
9581
|
+
}
|
|
9310
9582
|
}
|
|
9311
9583
|
return {};
|
|
9312
9584
|
};
|
|
@@ -9445,12 +9717,12 @@ function effectiveClaudeChrome(policy, options) {
|
|
|
9445
9717
|
}
|
|
9446
9718
|
|
|
9447
9719
|
// ../../bridges/claude-bridge/src/services/claude-execution-sandbox.ts
|
|
9448
|
-
import { realpathSync } from "node:fs";
|
|
9720
|
+
import { realpathSync as realpathSync2 } from "node:fs";
|
|
9449
9721
|
|
|
9450
9722
|
// ../protocol/src/node/claude-linux-sandbox.ts
|
|
9451
9723
|
import { spawnSync as spawnSync2 } from "node:child_process";
|
|
9452
|
-
import { accessSync, constants, existsSync, readFileSync as readFileSync2 } from "node:fs";
|
|
9453
|
-
import { delimiter, join as
|
|
9724
|
+
import { accessSync, constants as constants2, existsSync, readFileSync as readFileSync2 } from "node:fs";
|
|
9725
|
+
import { delimiter, join as join7 } from "node:path";
|
|
9454
9726
|
var CLAUDE_LINUX_SANDBOX_PROGRAMS = Object.freeze(["bwrap", "socat"]);
|
|
9455
9727
|
var APPARMOR_BWRAP_PROFILE = "/etc/apparmor.d/bwrap-userns-restrict";
|
|
9456
9728
|
var CLAUDE_LINUX_SANDBOX_PROBE_TIMEOUT_MS = 5000;
|
|
@@ -9484,7 +9756,7 @@ function executableOnPath(name, path = process.env.PATH) {
|
|
|
9484
9756
|
if (!directory)
|
|
9485
9757
|
continue;
|
|
9486
9758
|
try {
|
|
9487
|
-
accessSync(
|
|
9759
|
+
accessSync(join7(directory, name), constants2.X_OK);
|
|
9488
9760
|
return true;
|
|
9489
9761
|
} catch {}
|
|
9490
9762
|
}
|
|
@@ -9577,7 +9849,7 @@ function claudeLinuxSandboxStatus(now = Date.now()) {
|
|
|
9577
9849
|
function claudeReadOnlyWorkspaces(cwd) {
|
|
9578
9850
|
let resolved;
|
|
9579
9851
|
try {
|
|
9580
|
-
resolved =
|
|
9852
|
+
resolved = realpathSync2(cwd);
|
|
9581
9853
|
} catch {
|
|
9582
9854
|
resolved = undefined;
|
|
9583
9855
|
}
|
|
@@ -9604,9 +9876,11 @@ function claudeReadOnlyCommandSandbox(options = {}) {
|
|
|
9604
9876
|
}
|
|
9605
9877
|
function claudeExecutionSandbox(policy, asksForApproval, readOnly = {}) {
|
|
9606
9878
|
if (policy && isCoordinatorReadOnlyPolicy(policy)) {
|
|
9879
|
+
const workspaces = claudeReadOnlyWorkspaces(readOnly.cwd ?? claudeWorkspaceCwd());
|
|
9607
9880
|
return claudeReadOnlySandbox(policy, {
|
|
9608
|
-
workspaces
|
|
9609
|
-
commandSandbox: readOnly.commandSandbox ?? claudeReadOnlyCommandSandbox().commandSandbox
|
|
9881
|
+
workspaces,
|
|
9882
|
+
commandSandbox: readOnly.commandSandbox ?? claudeReadOnlyCommandSandbox().commandSandbox,
|
|
9883
|
+
readBoundary: readOnly.readBoundary ?? coordinatorReadBoundary(workspaces)
|
|
9610
9884
|
});
|
|
9611
9885
|
}
|
|
9612
9886
|
if (policy?.sandbox !== "provider")
|
|
@@ -12067,11 +12341,24 @@ var SYSTEM_SUBTYPE_DISPOSITIONS = {
|
|
|
12067
12341
|
files_persisted: "notice",
|
|
12068
12342
|
elicitation_complete: "notice"
|
|
12069
12343
|
};
|
|
12344
|
+
var INTERNAL_SYSTEM_SUBTYPE_DISPOSITIONS = {
|
|
12345
|
+
session_title_changed: "ignored",
|
|
12346
|
+
vcs_state_changed: "ignored",
|
|
12347
|
+
per_turn_effort_changed: "ignored",
|
|
12348
|
+
permission_check_status: "ignored",
|
|
12349
|
+
peer_message_hold: "ignored",
|
|
12350
|
+
instruction_size_warning: "notice"
|
|
12351
|
+
};
|
|
12070
12352
|
function systemSubtypeDisposition(subtype) {
|
|
12071
|
-
if (typeof subtype !== "string"
|
|
12353
|
+
if (typeof subtype !== "string")
|
|
12072
12354
|
return;
|
|
12355
|
+
if (Object.hasOwn(SYSTEM_SUBTYPE_DISPOSITIONS, subtype)) {
|
|
12356
|
+
return SYSTEM_SUBTYPE_DISPOSITIONS[subtype];
|
|
12357
|
+
}
|
|
12358
|
+
if (Object.hasOwn(INTERNAL_SYSTEM_SUBTYPE_DISPOSITIONS, subtype)) {
|
|
12359
|
+
return INTERNAL_SYSTEM_SUBTYPE_DISPOSITIONS[subtype];
|
|
12073
12360
|
}
|
|
12074
|
-
return
|
|
12361
|
+
return;
|
|
12075
12362
|
}
|
|
12076
12363
|
function sessionHealth(session) {
|
|
12077
12364
|
session.health ??= new RuntimeHealthRecorder;
|
|
@@ -12431,13 +12718,13 @@ function noMessages() {
|
|
|
12431
12718
|
}
|
|
12432
12719
|
|
|
12433
12720
|
// ../../bridges/claude-bridge/src/services/session-manager-persistence.ts
|
|
12434
|
-
import { constants as
|
|
12721
|
+
import { constants as constants3 } from "node:fs";
|
|
12435
12722
|
import { lstat as lstat2, open as open2, realpath as realpath2 } from "node:fs/promises";
|
|
12436
|
-
import { isAbsolute as
|
|
12723
|
+
import { isAbsolute as isAbsolute4, join as join12, relative, resolve as resolve4, sep as sep2 } from "node:path";
|
|
12437
12724
|
|
|
12438
12725
|
// ../protocol/src/node/command-change-journal.ts
|
|
12439
12726
|
import { appendFile, mkdir as mkdir3, readFile as readFile5, rename as rename3, rm as rm3, stat as stat4, writeFile as writeFile3 } from "node:fs/promises";
|
|
12440
|
-
import { dirname } from "node:path";
|
|
12727
|
+
import { dirname as dirname2 } from "node:path";
|
|
12441
12728
|
var MAX_JOURNAL_ENTRIES = 1000;
|
|
12442
12729
|
var MAX_JOURNAL_FILES_PER_ENTRY = 20;
|
|
12443
12730
|
var MAX_JOURNAL_PATH_LENGTH = 1024;
|
|
@@ -12510,7 +12797,7 @@ class CommandChangeJournal {
|
|
|
12510
12797
|
const line = `${JSON.stringify({ id, change: bounded })}
|
|
12511
12798
|
`;
|
|
12512
12799
|
this.writes = this.writes.then(async () => {
|
|
12513
|
-
await mkdir3(
|
|
12800
|
+
await mkdir3(dirname2(this.path), { recursive: true, mode: 448 });
|
|
12514
12801
|
if (!this.sizeChecked) {
|
|
12515
12802
|
this.sizeChecked = true;
|
|
12516
12803
|
const existing = await stat4(this.path).catch(() => {
|
|
@@ -12585,12 +12872,850 @@ async function readJournal(path, maxEntries) {
|
|
|
12585
12872
|
}
|
|
12586
12873
|
|
|
12587
12874
|
// ../protocol/src/node/workspace-change-probe.ts
|
|
12588
|
-
import {
|
|
12589
|
-
import {
|
|
12590
|
-
import { rmSync } from "node:fs";
|
|
12875
|
+
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
12876
|
+
import { rmSync as rmSync2 } from "node:fs";
|
|
12591
12877
|
import { copyFile, lstat, mkdtemp as mkdtemp2, rm as rm4 } from "node:fs/promises";
|
|
12592
12878
|
import { tmpdir as tmpdir2 } from "node:os";
|
|
12593
|
-
import { delimiter as delimiter2, isAbsolute as
|
|
12879
|
+
import { delimiter as delimiter2, isAbsolute as isAbsolute3, join as join8, resolve as resolve3 } from "node:path";
|
|
12880
|
+
|
|
12881
|
+
// ../protocol/src/node/command-capture.ts
|
|
12882
|
+
import { spawn } from "node:child_process";
|
|
12883
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
12884
|
+
import { constants as fsConstants } from "node:fs";
|
|
12885
|
+
import * as captureFs from "node:fs";
|
|
12886
|
+
import os from "node:os";
|
|
12887
|
+
import path3 from "node:path";
|
|
12888
|
+
import { inspect } from "node:util";
|
|
12889
|
+
|
|
12890
|
+
// ../protocol/src/node/command-failure-reason.ts
|
|
12891
|
+
var MAX_MATCHED_CHARS = 16 * 1024;
|
|
12892
|
+
var SIGNAL_PATTERN = /^SIG[A-Z0-9]{1,16}$/;
|
|
12893
|
+
var TOOL_RULES = {
|
|
12894
|
+
git: [
|
|
12895
|
+
["branch-exists", /a branch named .* already exists/i],
|
|
12896
|
+
["ref-conflict", /exists; cannot create|cannot lock ref .* is at .* but expected/i],
|
|
12897
|
+
["lock-held", /could not lock config file [^\n]*: File exists/i],
|
|
12898
|
+
["lock-held", /(?:unable to create '[^\n]*\.lock'|cannot lock ref)[^\n]*: File exists/i],
|
|
12899
|
+
["lock-held", /another git process/i],
|
|
12900
|
+
["worktree-conflict", /already (?:checked out|used by worktree)|used by worktree at/i],
|
|
12901
|
+
["invalid-ref", /not a valid (?:branch name|object name)|bad (?:revision|object)/i],
|
|
12902
|
+
["invalid-ref", /unknown revision|ambiguous argument|invalid reference/i],
|
|
12903
|
+
["branch-not-found", /no branch named|refname .* not found|branch '.*' not found/i],
|
|
12904
|
+
["branch-not-found", /did not match any file\(s\) known to git/i],
|
|
12905
|
+
["dubious-ownership", /detected dubious ownership/i],
|
|
12906
|
+
["no-remote", /does not appear to be a git repository|no such remote/i],
|
|
12907
|
+
["no-remote", /repository (?:.* )?not found/i],
|
|
12908
|
+
["not-a-repository", /not a git repository/i],
|
|
12909
|
+
["remote-ref-missing", /could(?:n't| not) find remote ref|not our ref/i],
|
|
12910
|
+
["merge-conflict", /\bCONFLICT \(|merge conflict|could not apply|unmerged files/i],
|
|
12911
|
+
["dirty-worktree", /local changes .* would be overwritten|commit your changes or stash/i],
|
|
12912
|
+
["nothing-to-commit", /nothing to commit|no changes added to commit/i],
|
|
12913
|
+
["push-rejected", /\[(?:remote )?rejected\]|non-fast-forward/i],
|
|
12914
|
+
["identity-unknown", /please tell me who you are|unable to auto-detect email/i],
|
|
12915
|
+
[
|
|
12916
|
+
"worktree-has-changes",
|
|
12917
|
+
/^fatal: [^\n]*['"] contains modified or untracked files(?:, use --force to delete it)?\.?\s*$/im
|
|
12918
|
+
],
|
|
12919
|
+
["not-a-worktree", /^fatal: [^\n]*['"] is not a working tree\.?\s*$/im],
|
|
12920
|
+
["branch-not-merged", /^(?:error|fatal): [^\n]*['"] is not fully merged\.?\s*$/im]
|
|
12921
|
+
],
|
|
12922
|
+
gh: [
|
|
12923
|
+
["pull-request-exists", /a pull request for branch .* already exists/i],
|
|
12924
|
+
["no-pull-request", /no (?:pull requests? (?:found|match)|open pull requests?\b)/i],
|
|
12925
|
+
["rate-limited", /rate limit|http 429/i],
|
|
12926
|
+
["forbidden", /http 403|resource not accessible/i],
|
|
12927
|
+
["resource-not-found", /http 404|could not resolve to a/i],
|
|
12928
|
+
["server-error", /http 5\d\d/i]
|
|
12929
|
+
],
|
|
12930
|
+
docker: [
|
|
12931
|
+
["daemon-unavailable", /cannot connect to the docker daemon|error during connect/i],
|
|
12932
|
+
[
|
|
12933
|
+
"daemon-unavailable",
|
|
12934
|
+
/is the docker daemon running|docker desktop is (?:not running|unable)/i
|
|
12935
|
+
],
|
|
12936
|
+
["container-not-found", /no such container/i],
|
|
12937
|
+
["container-not-running", /container .* is (?:not running|paused|restarting)/i],
|
|
12938
|
+
["container-name-conflict", /name .* is already in use/i],
|
|
12939
|
+
["image-not-found", /no such image|pull access denied|manifest .* not found/i],
|
|
12940
|
+
["image-not-found", /manifest unknown|repository does not exist/i],
|
|
12941
|
+
["removal-in-progress", /removal of container .* is already in progress/i],
|
|
12942
|
+
[
|
|
12943
|
+
"image-in-use",
|
|
12944
|
+
/image is (?:being used|referenced)|unable to (?:remove|delete) .*must be forced/i
|
|
12945
|
+
],
|
|
12946
|
+
["volume-in-use", /volume is in use/i],
|
|
12947
|
+
["volume-not-found", /no such volume/i],
|
|
12948
|
+
["network-in-use", /has active endpoints/i],
|
|
12949
|
+
["network-not-found", /network .* not found/i]
|
|
12950
|
+
],
|
|
12951
|
+
tmux: [
|
|
12952
|
+
["session-exists", /duplicate session/i],
|
|
12953
|
+
[
|
|
12954
|
+
"server-not-running",
|
|
12955
|
+
/no server running|failed to connect to server|no sessions|server exited|lost server/i
|
|
12956
|
+
],
|
|
12957
|
+
[
|
|
12958
|
+
"server-not-running",
|
|
12959
|
+
/error connecting to \/[^\n]* \((?:No such file or directory|Connection refused)\)/i
|
|
12960
|
+
],
|
|
12961
|
+
["session-not-found", /can't find (?:session|window|pane)|session not found/i]
|
|
12962
|
+
]
|
|
12963
|
+
};
|
|
12964
|
+
var ALL_TOOLS = Object.keys(TOOL_RULES);
|
|
12965
|
+
var SHARED_RULES = [
|
|
12966
|
+
["disk-full", /no space left|enospc|disk quota exceeded/i],
|
|
12967
|
+
["auth-failed", /authentication (?:failed|required)|could not read (?:username|password)/i],
|
|
12968
|
+
["auth-failed", /terminal prompts disabled|invalid username or password|bad credentials/i],
|
|
12969
|
+
["auth-failed", /permission denied \(|permission to \S+ denied|host key verification failed/i],
|
|
12970
|
+
["auth-failed", /gh auth login|not logged in|unauthorized|http 401|returned error: 40[13]/i],
|
|
12971
|
+
["network-failed", /could not resolve host|connection (?:timed out|refused|reset)/i],
|
|
12972
|
+
["network-failed", /network is unreachable|no route to host|temporary failure in name/i],
|
|
12973
|
+
["network-failed", /early eof|failed to connect|remote end hung up/i],
|
|
12974
|
+
["network-failed", /unable to access ['"]?https?:\/\//i],
|
|
12975
|
+
["network-failed", /tls handshake|i\/o timeout/i],
|
|
12976
|
+
[
|
|
12977
|
+
"network-failed",
|
|
12978
|
+
/error connecting to (?:https?:\/\/)?[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?(?::\d+)?(?:[\s/:]|$)/i
|
|
12979
|
+
],
|
|
12980
|
+
["port-in-use", /port is already allocated|address already in use/i],
|
|
12981
|
+
["permission-denied", /permission denied|operation not permitted|read-only file system/i],
|
|
12982
|
+
["command-not-found", /command not found/i],
|
|
12983
|
+
["path-not-found", /no such file or directory/i],
|
|
12984
|
+
["invalid-usage", /^usage: |unknown (?:option|flag|command|shorthand flag)|invalid option/im]
|
|
12985
|
+
];
|
|
12986
|
+
var TOOL_EXIT_CODES = {
|
|
12987
|
+
git: { 129: "invalid-usage" },
|
|
12988
|
+
gh: { 2: "aborted", 4: "auth-failed" },
|
|
12989
|
+
docker: { 125: "daemon-error" },
|
|
12990
|
+
tmux: {}
|
|
12991
|
+
};
|
|
12992
|
+
var SHARED_EXIT_CODES = {
|
|
12993
|
+
124: "timed-out",
|
|
12994
|
+
126: "not-executable",
|
|
12995
|
+
127: "command-not-found",
|
|
12996
|
+
137: "killed",
|
|
12997
|
+
143: "killed"
|
|
12998
|
+
};
|
|
12999
|
+
function read2(target, key) {
|
|
13000
|
+
return target[key];
|
|
13001
|
+
}
|
|
13002
|
+
function boundedForMatching(text) {
|
|
13003
|
+
if (text.length <= MAX_MATCHED_CHARS)
|
|
13004
|
+
return text;
|
|
13005
|
+
const half = MAX_MATCHED_CHARS / 2;
|
|
13006
|
+
return `${text.slice(0, half)}
|
|
13007
|
+
${text.slice(-half)}`;
|
|
13008
|
+
}
|
|
13009
|
+
function failureText(error) {
|
|
13010
|
+
const stderr = read2(error, "stderr");
|
|
13011
|
+
if (Buffer.isBuffer(stderr) && stderr.length > 0) {
|
|
13012
|
+
return boundedForMatching(stderr.subarray(-MAX_MATCHED_CHARS).toString());
|
|
13013
|
+
}
|
|
13014
|
+
if (typeof stderr === "string" && stderr.length > 0)
|
|
13015
|
+
return boundedForMatching(stderr);
|
|
13016
|
+
const message = read2(error, "message");
|
|
13017
|
+
if (typeof message !== "string")
|
|
13018
|
+
return "";
|
|
13019
|
+
return message.startsWith("Command failed") ? "" : boundedForMatching(message);
|
|
13020
|
+
}
|
|
13021
|
+
function isRawSpawnEnoent(error) {
|
|
13022
|
+
const syscall = read2(error, "syscall");
|
|
13023
|
+
return read2(error, "code") === "ENOENT" && typeof syscall === "string" && /^(?:spawn(?:Sync)?(?:\s|$)|posix_spawnp?$)/.test(syscall);
|
|
13024
|
+
}
|
|
13025
|
+
function classifiedReason(error, exitCode, signal, options) {
|
|
13026
|
+
if (read2(error, "aborted") === true)
|
|
13027
|
+
return "aborted";
|
|
13028
|
+
if (read2(error, "outputLimitExceeded") === true)
|
|
13029
|
+
return "output-too-large";
|
|
13030
|
+
if (read2(error, "timedOut") === true)
|
|
13031
|
+
return "timed-out";
|
|
13032
|
+
if (read2(error, "executableMissing") === true || isRawSpawnEnoent(error)) {
|
|
13033
|
+
return "executable-missing";
|
|
13034
|
+
}
|
|
13035
|
+
const named = exitCode === null ? undefined : options.exitCodes?.[exitCode];
|
|
13036
|
+
if (named)
|
|
13037
|
+
return named;
|
|
13038
|
+
if (signal)
|
|
13039
|
+
return "killed";
|
|
13040
|
+
const text = failureText(error);
|
|
13041
|
+
for (const tool of options.tools ?? ALL_TOOLS) {
|
|
13042
|
+
for (const [reason, pattern] of TOOL_RULES[tool]) {
|
|
13043
|
+
if (pattern.test(text))
|
|
13044
|
+
return reason;
|
|
13045
|
+
}
|
|
13046
|
+
}
|
|
13047
|
+
for (const [reason, pattern] of SHARED_RULES) {
|
|
13048
|
+
if (pattern.test(text))
|
|
13049
|
+
return reason;
|
|
13050
|
+
}
|
|
13051
|
+
if (exitCode !== null) {
|
|
13052
|
+
for (const tool of options.tools ?? []) {
|
|
13053
|
+
const reason = TOOL_EXIT_CODES[tool][exitCode];
|
|
13054
|
+
if (reason)
|
|
13055
|
+
return reason;
|
|
13056
|
+
}
|
|
13057
|
+
const reason = SHARED_EXIT_CODES[exitCode];
|
|
13058
|
+
if (reason)
|
|
13059
|
+
return reason;
|
|
13060
|
+
}
|
|
13061
|
+
return "unclassified";
|
|
13062
|
+
}
|
|
13063
|
+
function numericExitCode(error) {
|
|
13064
|
+
for (const key of ["exitCode", "code"]) {
|
|
13065
|
+
const value = read2(error, key);
|
|
13066
|
+
if (typeof value === "number" && Number.isFinite(value))
|
|
13067
|
+
return value;
|
|
13068
|
+
}
|
|
13069
|
+
return null;
|
|
13070
|
+
}
|
|
13071
|
+
function classifyCommandFailure(error, options = {}) {
|
|
13072
|
+
if (typeof error !== "object" || error === null) {
|
|
13073
|
+
return { reason: "unclassified", exitCode: null, signal: null };
|
|
13074
|
+
}
|
|
13075
|
+
try {
|
|
13076
|
+
const exitCode = numericExitCode(error);
|
|
13077
|
+
const rawSignal = read2(error, "signal");
|
|
13078
|
+
const signal = typeof rawSignal === "string" && SIGNAL_PATTERN.test(rawSignal) ? rawSignal : null;
|
|
13079
|
+
return { reason: classifiedReason(error, exitCode, signal, options), exitCode, signal };
|
|
13080
|
+
} catch {
|
|
13081
|
+
return { reason: "unclassified", exitCode: null, signal: null };
|
|
13082
|
+
}
|
|
13083
|
+
}
|
|
13084
|
+
|
|
13085
|
+
// ../protocol/src/node/lost-exit-reaper.ts
|
|
13086
|
+
import { createRequire } from "node:module";
|
|
13087
|
+
|
|
13088
|
+
// ../protocol/src/node/shell-process-state.ts
|
|
13089
|
+
import { spawnSync as spawnSync3 } from "node:child_process";
|
|
13090
|
+
import { readdirSync, readFileSync as readFileSync3 } from "node:fs";
|
|
13091
|
+
import { constants as osConstants } from "node:os";
|
|
13092
|
+
var PROCESS_INSPECTION_OPTIONS = {
|
|
13093
|
+
timeout: 100,
|
|
13094
|
+
killSignal: "SIGKILL",
|
|
13095
|
+
maxBuffer: 1024 * 1024
|
|
13096
|
+
};
|
|
13097
|
+
function bunRuntime() {
|
|
13098
|
+
return globalThis.Bun;
|
|
13099
|
+
}
|
|
13100
|
+
function decodeWaitStatus(status) {
|
|
13101
|
+
const signalNumber = status & 127;
|
|
13102
|
+
if (signalNumber === 0)
|
|
13103
|
+
return { code: status >> 8 & 255, signal: null };
|
|
13104
|
+
const name = Object.entries(osConstants.signals).find(([, value]) => value === signalNumber)?.[0];
|
|
13105
|
+
return { code: null, signal: name ?? "SIGKILL" };
|
|
13106
|
+
}
|
|
13107
|
+
function readZombieExit(pid) {
|
|
13108
|
+
try {
|
|
13109
|
+
const result = bunRuntime()?.spawnSync(["/bin/ps", "-o", "stat=,xstat=", "-p", String(pid)], PROCESS_INSPECTION_OPTIONS);
|
|
13110
|
+
if (!result?.success)
|
|
13111
|
+
return;
|
|
13112
|
+
const { stdout } = result;
|
|
13113
|
+
const match = /^Z\S*\s+([0-9a-f]+)\s*$/i.exec(stdout.toString().trim());
|
|
13114
|
+
return match ? decodeWaitStatus(Number.parseInt(match[1], 16)) : undefined;
|
|
13115
|
+
} catch {
|
|
13116
|
+
return;
|
|
13117
|
+
}
|
|
13118
|
+
}
|
|
13119
|
+
var EXIT_WATCH_MS = 1000;
|
|
13120
|
+
var EXIT_WATCH_MAX_MS = 16000;
|
|
13121
|
+
function watchForLostExit(pid, onExit) {
|
|
13122
|
+
if (process.platform !== "darwin" || pid === undefined || !bunRuntime())
|
|
13123
|
+
return () => {
|
|
13124
|
+
return;
|
|
13125
|
+
};
|
|
13126
|
+
let timer;
|
|
13127
|
+
const watch = (delayMs) => {
|
|
13128
|
+
timer = setTimeout(() => {
|
|
13129
|
+
const exit = readZombieExit(pid);
|
|
13130
|
+
if (exit)
|
|
13131
|
+
onExit(exit);
|
|
13132
|
+
else
|
|
13133
|
+
watch(Math.min(delayMs * 2, EXIT_WATCH_MAX_MS));
|
|
13134
|
+
}, delayMs);
|
|
13135
|
+
};
|
|
13136
|
+
watch(EXIT_WATCH_MS);
|
|
13137
|
+
return () => clearTimeout(timer);
|
|
13138
|
+
}
|
|
13139
|
+
function isLiveMember(state, groupId, pgid) {
|
|
13140
|
+
return Number(groupId) === pgid && state !== undefined && !/^[ZX]/.test(state);
|
|
13141
|
+
}
|
|
13142
|
+
function linuxGroupHasLiveMember(pgid) {
|
|
13143
|
+
for (const entry of readdirSync("/proc")) {
|
|
13144
|
+
if (!/^\d+$/.test(entry))
|
|
13145
|
+
continue;
|
|
13146
|
+
let stat;
|
|
13147
|
+
try {
|
|
13148
|
+
stat = readFileSync3(`/proc/${entry}/stat`, "latin1");
|
|
13149
|
+
} catch {
|
|
13150
|
+
continue;
|
|
13151
|
+
}
|
|
13152
|
+
const [state, , groupId] = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
|
13153
|
+
if (isLiveMember(state, groupId, pgid))
|
|
13154
|
+
return true;
|
|
13155
|
+
}
|
|
13156
|
+
return false;
|
|
13157
|
+
}
|
|
13158
|
+
function psGroupHasLiveMember(pgid) {
|
|
13159
|
+
const argv = ["-A", "-o", "pgid=,stat="];
|
|
13160
|
+
const bun = bunRuntime();
|
|
13161
|
+
const result = bun ? bun.spawnSync(["/bin/ps", ...argv], PROCESS_INSPECTION_OPTIONS) : spawnSync3("/bin/ps", argv, PROCESS_INSPECTION_OPTIONS);
|
|
13162
|
+
const succeeded = "success" in result ? result.success : result.status === 0 && !result.error;
|
|
13163
|
+
if (!succeeded)
|
|
13164
|
+
return true;
|
|
13165
|
+
return result.stdout.toString().split(`
|
|
13166
|
+
`).some((line) => {
|
|
13167
|
+
const [groupId, state] = line.trim().split(/\s+/);
|
|
13168
|
+
return isLiveMember(state, groupId, pgid);
|
|
13169
|
+
});
|
|
13170
|
+
}
|
|
13171
|
+
function groupHasLiveMember(pgid) {
|
|
13172
|
+
try {
|
|
13173
|
+
return process.platform === "linux" ? linuxGroupHasLiveMember(pgid) : psGroupHasLiveMember(pgid);
|
|
13174
|
+
} catch {
|
|
13175
|
+
return true;
|
|
13176
|
+
}
|
|
13177
|
+
}
|
|
13178
|
+
|
|
13179
|
+
// ../protocol/src/node/lost-exit-reaper.ts
|
|
13180
|
+
var log7 = createLogger("process");
|
|
13181
|
+
var REAP_GRACE_MS = 2000;
|
|
13182
|
+
var REAP_MAX_CHECK_MS = 30000;
|
|
13183
|
+
var REAP_MAX_CHECKS = 12;
|
|
13184
|
+
var REAP_MAX_PENDING = 256;
|
|
13185
|
+
function createLostExitReaper(options) {
|
|
13186
|
+
const { system } = options;
|
|
13187
|
+
const graceMs = options.graceMs ?? REAP_GRACE_MS;
|
|
13188
|
+
const maxCheckMs = options.maxCheckMs ?? REAP_MAX_CHECK_MS;
|
|
13189
|
+
const maxChecks = options.maxChecks ?? REAP_MAX_CHECKS;
|
|
13190
|
+
const maxPending = options.maxPending ?? REAP_MAX_PENDING;
|
|
13191
|
+
const pending = new Map;
|
|
13192
|
+
let reaped = 0;
|
|
13193
|
+
let abandoned = 0;
|
|
13194
|
+
const abandon = (pid, reason) => {
|
|
13195
|
+
abandoned += 1;
|
|
13196
|
+
log7.warn("child.reap-abandoned", { pid, reason });
|
|
13197
|
+
};
|
|
13198
|
+
const check = (pid, reported, startedAt) => {
|
|
13199
|
+
if (reported())
|
|
13200
|
+
return false;
|
|
13201
|
+
const found = system.inspect(pid);
|
|
13202
|
+
if (found === undefined)
|
|
13203
|
+
return true;
|
|
13204
|
+
if (found === "gone" || found.ppid !== system.selfPid)
|
|
13205
|
+
return false;
|
|
13206
|
+
if (!found.state.startsWith("Z"))
|
|
13207
|
+
return true;
|
|
13208
|
+
const result = system.waitNoHang(pid);
|
|
13209
|
+
if (result === pid) {
|
|
13210
|
+
reaped += 1;
|
|
13211
|
+
log7.info("child.reaped", { pid, waitedMs: Date.now() - startedAt });
|
|
13212
|
+
return false;
|
|
13213
|
+
}
|
|
13214
|
+
if (result === 0)
|
|
13215
|
+
return true;
|
|
13216
|
+
abandon(pid, "waitpid-failed");
|
|
13217
|
+
return false;
|
|
13218
|
+
};
|
|
13219
|
+
const schedule = (pid, reported, startedAt, delayMs, checks) => {
|
|
13220
|
+
const timer = setTimeout(() => {
|
|
13221
|
+
pending.delete(pid);
|
|
13222
|
+
let again;
|
|
13223
|
+
try {
|
|
13224
|
+
again = check(pid, reported, startedAt);
|
|
13225
|
+
} catch {
|
|
13226
|
+
again = true;
|
|
13227
|
+
}
|
|
13228
|
+
if (!again)
|
|
13229
|
+
return;
|
|
13230
|
+
if (checks + 1 >= maxChecks) {
|
|
13231
|
+
abandon(pid, "not-a-zombie");
|
|
13232
|
+
return;
|
|
13233
|
+
}
|
|
13234
|
+
schedule(pid, reported, startedAt, Math.min(delayMs * 2, maxCheckMs), checks + 1);
|
|
13235
|
+
}, delayMs);
|
|
13236
|
+
timer.unref?.();
|
|
13237
|
+
pending.set(pid, timer);
|
|
13238
|
+
};
|
|
13239
|
+
return {
|
|
13240
|
+
reap(pid, reported) {
|
|
13241
|
+
if (!Number.isSafeInteger(pid) || pid <= 1 || pid === system.selfPid)
|
|
13242
|
+
return;
|
|
13243
|
+
if (pending.has(pid) || reported())
|
|
13244
|
+
return;
|
|
13245
|
+
if (pending.size >= maxPending) {
|
|
13246
|
+
abandon(pid, "capacity");
|
|
13247
|
+
return;
|
|
13248
|
+
}
|
|
13249
|
+
schedule(pid, reported, Date.now(), graceMs, 0);
|
|
13250
|
+
},
|
|
13251
|
+
stats: () => ({ pending: pending.size, reaped, abandoned }),
|
|
13252
|
+
stop() {
|
|
13253
|
+
for (const timer of pending.values())
|
|
13254
|
+
clearTimeout(timer);
|
|
13255
|
+
pending.clear();
|
|
13256
|
+
}
|
|
13257
|
+
};
|
|
13258
|
+
}
|
|
13259
|
+
var WNOHANG = 1;
|
|
13260
|
+
function loadDarwinWaitpid(loadFfi = () => createRequire(import.meta.url)("bun:ffi")) {
|
|
13261
|
+
try {
|
|
13262
|
+
const { dlopen, FFIType } = loadFfi();
|
|
13263
|
+
const libSystem = dlopen("/usr/lib/libSystem.B.dylib", {
|
|
13264
|
+
waitpid: { args: [FFIType.i32, FFIType.ptr, FFIType.i32], returns: FFIType.i32 }
|
|
13265
|
+
});
|
|
13266
|
+
const status = new Int32Array(1);
|
|
13267
|
+
return (pid) => libSystem.symbols.waitpid(pid, status, WNOHANG);
|
|
13268
|
+
} catch {
|
|
13269
|
+
return;
|
|
13270
|
+
}
|
|
13271
|
+
}
|
|
13272
|
+
function darwinReaperSystem(loadFfi) {
|
|
13273
|
+
const waitNoHang = loadDarwinWaitpid(loadFfi);
|
|
13274
|
+
if (!waitNoHang)
|
|
13275
|
+
return;
|
|
13276
|
+
return {
|
|
13277
|
+
selfPid: process.pid,
|
|
13278
|
+
inspect(pid) {
|
|
13279
|
+
const result = bunRuntime()?.spawnSync(["/bin/ps", "-o", "ppid=,stat=", "-p", String(pid)], PROCESS_INSPECTION_OPTIONS);
|
|
13280
|
+
if (!result)
|
|
13281
|
+
return;
|
|
13282
|
+
const output = result.stdout.toString().trim();
|
|
13283
|
+
if (!result.success)
|
|
13284
|
+
return result.exitCode === 1 && output === "" ? "gone" : undefined;
|
|
13285
|
+
const match = /^(\d+)\s+(\S+)$/.exec(output);
|
|
13286
|
+
return match ? { ppid: Number(match[1]), state: match[2] } : undefined;
|
|
13287
|
+
},
|
|
13288
|
+
waitNoHang
|
|
13289
|
+
};
|
|
13290
|
+
}
|
|
13291
|
+
var defaultReaper;
|
|
13292
|
+
function createDarwinLostExitReaper(loadFfi) {
|
|
13293
|
+
const system = darwinReaperSystem(loadFfi);
|
|
13294
|
+
if (!system)
|
|
13295
|
+
log7.warn("child.reap-unavailable");
|
|
13296
|
+
return system ? createLostExitReaper({ system }) : null;
|
|
13297
|
+
}
|
|
13298
|
+
function sharedReaper() {
|
|
13299
|
+
if (defaultReaper === undefined) {
|
|
13300
|
+
defaultReaper = createDarwinLostExitReaper();
|
|
13301
|
+
}
|
|
13302
|
+
return defaultReaper ?? undefined;
|
|
13303
|
+
}
|
|
13304
|
+
function reapAfterLostExit(pid, reported) {
|
|
13305
|
+
if (process.platform !== "darwin" || pid === undefined || !bunRuntime())
|
|
13306
|
+
return;
|
|
13307
|
+
sharedReaper()?.reap(pid, reported);
|
|
13308
|
+
}
|
|
13309
|
+
|
|
13310
|
+
// ../protocol/src/node/command-capture.ts
|
|
13311
|
+
class CommandFailedError extends Error {
|
|
13312
|
+
stdout;
|
|
13313
|
+
stdoutBytes;
|
|
13314
|
+
stderr;
|
|
13315
|
+
timedOut;
|
|
13316
|
+
outputCloseTimedOut;
|
|
13317
|
+
executableMissing;
|
|
13318
|
+
aborted;
|
|
13319
|
+
outputLimitExceeded;
|
|
13320
|
+
exitCode;
|
|
13321
|
+
signal;
|
|
13322
|
+
constructor(message, details = {}) {
|
|
13323
|
+
super(message);
|
|
13324
|
+
this.name = "CommandFailedError";
|
|
13325
|
+
this.stdout = details.stdout ?? "";
|
|
13326
|
+
this.stdoutBytes = details.stdoutBytes ?? Buffer.alloc(0);
|
|
13327
|
+
this.stderr = details.stderr ?? "";
|
|
13328
|
+
this.timedOut = details.timedOut ?? false;
|
|
13329
|
+
this.outputCloseTimedOut = details.outputCloseTimedOut ?? false;
|
|
13330
|
+
this.executableMissing = details.executableMissing ?? false;
|
|
13331
|
+
this.aborted = details.aborted ?? false;
|
|
13332
|
+
this.outputLimitExceeded = details.outputLimitExceeded ?? false;
|
|
13333
|
+
this.exitCode = details.exitCode ?? null;
|
|
13334
|
+
this.signal = details.signal ?? null;
|
|
13335
|
+
}
|
|
13336
|
+
toJSON() {
|
|
13337
|
+
return { ...formatLogError(this), ...classifyCommandFailure(this) };
|
|
13338
|
+
}
|
|
13339
|
+
[inspect.custom]() {
|
|
13340
|
+
const { name, reason, exitCode, signal, stack } = this.toJSON();
|
|
13341
|
+
const frames = stack?.length ? ` | ${stack.join(" | ")}` : "";
|
|
13342
|
+
return `${name} reason=${reason} exitCode=${exitCode} signal=${signal} outputOmitted=true${frames}`;
|
|
13343
|
+
}
|
|
13344
|
+
}
|
|
13345
|
+
function redactCommandValues(value, redactValues) {
|
|
13346
|
+
const secrets = Array.from(new Set((redactValues ?? []).filter((secret) => typeof secret === "string" && secret.length > 0))).sort((left, right) => right.length - left.length);
|
|
13347
|
+
return secrets.reduce((redacted, secret) => redacted.split(secret).join("[REDACTED]"), value);
|
|
13348
|
+
}
|
|
13349
|
+
var COMMAND_ABORTED_MESSAGE = "Command aborted";
|
|
13350
|
+
var OUTPUT_LIMIT_MESSAGE = "maxBuffer length exceeded";
|
|
13351
|
+
function commandFailureOutcome(error) {
|
|
13352
|
+
const details = error ?? {};
|
|
13353
|
+
const message = typeof details.message === "string" ? details.message : "";
|
|
13354
|
+
return {
|
|
13355
|
+
timedOut: details.killed === true,
|
|
13356
|
+
executableMissing: details.code === "ENOENT",
|
|
13357
|
+
aborted: message === COMMAND_ABORTED_MESSAGE,
|
|
13358
|
+
outputLimitExceeded: details.outputLimitExceeded === true,
|
|
13359
|
+
exitCode: typeof details.code === "number" ? details.code : null,
|
|
13360
|
+
signal: details.signal ?? null
|
|
13361
|
+
};
|
|
13362
|
+
}
|
|
13363
|
+
var commandInvocations = new Map;
|
|
13364
|
+
var commandCaptureMetrics;
|
|
13365
|
+
var commandObservers = new Map;
|
|
13366
|
+
function nonInteractiveGitEnv(env) {
|
|
13367
|
+
const merged = { ...env ?? process.env };
|
|
13368
|
+
merged.GIT_TERMINAL_PROMPT ??= "0";
|
|
13369
|
+
if (process.platform !== "win32") {
|
|
13370
|
+
merged.SSH_ASKPASS ??= "/usr/bin/false";
|
|
13371
|
+
merged.SSH_ASKPASS_REQUIRE ??= "force";
|
|
13372
|
+
}
|
|
13373
|
+
return merged;
|
|
13374
|
+
}
|
|
13375
|
+
var MAX_COMMAND_OUTPUT_BYTES = 50 * 1024 * 1024;
|
|
13376
|
+
var COMMAND_KILL_GRACE_MS = 100;
|
|
13377
|
+
var COMMAND_OUTPUT_CHECK_MS = 100;
|
|
13378
|
+
var COMMAND_GROUP_POLL_MS = 5;
|
|
13379
|
+
var COMMAND_GROUP_POLL_MAX_MS = 200;
|
|
13380
|
+
function openCaptureFile() {
|
|
13381
|
+
const filePath = path3.join(os.tmpdir(), `orkestrator-capture-${randomUUID2()}`);
|
|
13382
|
+
const fd = captureFs.openSync(filePath, fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_RDWR | fsConstants.O_APPEND, 384);
|
|
13383
|
+
try {
|
|
13384
|
+
captureFs.unlinkSync(filePath);
|
|
13385
|
+
return fd;
|
|
13386
|
+
} catch (error) {
|
|
13387
|
+
captureFs.closeSync(fd);
|
|
13388
|
+
throw error;
|
|
13389
|
+
}
|
|
13390
|
+
}
|
|
13391
|
+
function readCaptureFile(fd, limit) {
|
|
13392
|
+
const size = Math.min(captureFs.fstatSync(fd).size, limit);
|
|
13393
|
+
const buffer = Buffer.allocUnsafe(size);
|
|
13394
|
+
let offset = 0;
|
|
13395
|
+
while (offset < size) {
|
|
13396
|
+
const bytesRead = captureFs.readSync(fd, buffer, offset, size - offset, offset);
|
|
13397
|
+
if (bytesRead === 0)
|
|
13398
|
+
break;
|
|
13399
|
+
offset += bytesRead;
|
|
13400
|
+
}
|
|
13401
|
+
return buffer.subarray(0, offset);
|
|
13402
|
+
}
|
|
13403
|
+
function spawnCaptured(command, args, options, stdoutFd, stderrFd) {
|
|
13404
|
+
const payload = options.stdin?.length ? Buffer.from(options.stdin) : undefined;
|
|
13405
|
+
const env = command === "git" ? nonInteractiveGitEnv(options.env) : options.env ?? process.env;
|
|
13406
|
+
const detached = process.platform !== "win32";
|
|
13407
|
+
const bun = bunRuntime();
|
|
13408
|
+
if (bun) {
|
|
13409
|
+
const child = bun.spawn([command, ...args], {
|
|
13410
|
+
cwd: options.cwd,
|
|
13411
|
+
env,
|
|
13412
|
+
detached,
|
|
13413
|
+
windowsHide: true,
|
|
13414
|
+
stdin: payload ?? "pipe",
|
|
13415
|
+
stdout: stdoutFd,
|
|
13416
|
+
stderr: stderrFd
|
|
13417
|
+
});
|
|
13418
|
+
if (!payload)
|
|
13419
|
+
closeStdin(child.stdin);
|
|
13420
|
+
const current = () => ({ code: child.exitCode, signal: child.signalCode });
|
|
13421
|
+
return {
|
|
13422
|
+
pid: child.pid,
|
|
13423
|
+
exited: child.exited.then(current),
|
|
13424
|
+
current,
|
|
13425
|
+
kill: (signal) => child.kill(signal)
|
|
13426
|
+
};
|
|
13427
|
+
}
|
|
13428
|
+
const child = spawn(command, args, {
|
|
13429
|
+
cwd: options.cwd,
|
|
13430
|
+
env,
|
|
13431
|
+
detached,
|
|
13432
|
+
windowsHide: true,
|
|
13433
|
+
stdio: [payload ? "pipe" : "ignore", stdoutFd, stderrFd]
|
|
13434
|
+
});
|
|
13435
|
+
if (payload) {
|
|
13436
|
+
child.stdin?.on("error", () => {
|
|
13437
|
+
return;
|
|
13438
|
+
});
|
|
13439
|
+
child.stdin?.end(payload);
|
|
13440
|
+
}
|
|
13441
|
+
return {
|
|
13442
|
+
pid: child.pid,
|
|
13443
|
+
exited: new Promise((resolve, reject) => {
|
|
13444
|
+
child.once("exit", (code, signal) => resolve({ code, signal }));
|
|
13445
|
+
child.once("error", reject);
|
|
13446
|
+
}),
|
|
13447
|
+
current: () => ({ code: child.exitCode, signal: child.signalCode }),
|
|
13448
|
+
kill: (signal) => {
|
|
13449
|
+
child.kill(signal);
|
|
13450
|
+
}
|
|
13451
|
+
};
|
|
13452
|
+
}
|
|
13453
|
+
function closeStdin(stdin) {
|
|
13454
|
+
try {
|
|
13455
|
+
Promise.resolve(stdin.end()).catch(() => {
|
|
13456
|
+
return;
|
|
13457
|
+
});
|
|
13458
|
+
} catch {}
|
|
13459
|
+
}
|
|
13460
|
+
function exitReported(child) {
|
|
13461
|
+
const { code, signal } = child.current();
|
|
13462
|
+
return code !== null || signal !== null;
|
|
13463
|
+
}
|
|
13464
|
+
function signalCommand(child, signal) {
|
|
13465
|
+
if (child.pid === undefined)
|
|
13466
|
+
return;
|
|
13467
|
+
try {
|
|
13468
|
+
if (process.platform !== "win32") {
|
|
13469
|
+
process.kill(-child.pid, signal);
|
|
13470
|
+
} else {
|
|
13471
|
+
child.kill(signal);
|
|
13472
|
+
}
|
|
13473
|
+
} catch {}
|
|
13474
|
+
}
|
|
13475
|
+
function commandGroupAlive(child) {
|
|
13476
|
+
if (process.platform === "win32" || child.pid === undefined)
|
|
13477
|
+
return false;
|
|
13478
|
+
try {
|
|
13479
|
+
process.kill(-child.pid, 0);
|
|
13480
|
+
} catch (error) {
|
|
13481
|
+
if (error.code === "ESRCH")
|
|
13482
|
+
return false;
|
|
13483
|
+
}
|
|
13484
|
+
return groupHasLiveMember(child.pid);
|
|
13485
|
+
}
|
|
13486
|
+
function executeCommandBytes(command, args, options, timeoutMs, outputLimit, stderrLimit) {
|
|
13487
|
+
return new Promise((resolve, reject) => {
|
|
13488
|
+
if (options.signal?.aborted) {
|
|
13489
|
+
reject(Object.assign(new Error(COMMAND_ABORTED_MESSAGE), { killed: true }));
|
|
13490
|
+
return;
|
|
13491
|
+
}
|
|
13492
|
+
const captureFds = [];
|
|
13493
|
+
const releaseCaptureFds = () => {
|
|
13494
|
+
for (const fd of captureFds.splice(0)) {
|
|
13495
|
+
try {
|
|
13496
|
+
captureFs.closeSync(fd);
|
|
13497
|
+
} catch {}
|
|
13498
|
+
}
|
|
13499
|
+
};
|
|
13500
|
+
try {
|
|
13501
|
+
captureFds.push(openCaptureFile());
|
|
13502
|
+
captureFds.push(openCaptureFile());
|
|
13503
|
+
} catch (error) {
|
|
13504
|
+
releaseCaptureFds();
|
|
13505
|
+
const code = error.code ?? "unknown";
|
|
13506
|
+
reject(new Error(`Could not open a command output file in the temporary directory: ${code}`));
|
|
13507
|
+
return;
|
|
13508
|
+
}
|
|
13509
|
+
const [stdoutFd, stderrFd] = captureFds;
|
|
13510
|
+
let child;
|
|
13511
|
+
try {
|
|
13512
|
+
child = spawnCaptured(command, args, options, stdoutFd, stderrFd);
|
|
13513
|
+
} catch (error) {
|
|
13514
|
+
releaseCaptureFds();
|
|
13515
|
+
reject(error);
|
|
13516
|
+
return;
|
|
13517
|
+
}
|
|
13518
|
+
let settled = false;
|
|
13519
|
+
let timedOut = false;
|
|
13520
|
+
let timeoutTimer;
|
|
13521
|
+
let groupTimer;
|
|
13522
|
+
let limitTimer;
|
|
13523
|
+
let stopExitWatch = () => {};
|
|
13524
|
+
let commandExit;
|
|
13525
|
+
let pendingFailure;
|
|
13526
|
+
const finishCapture = () => {
|
|
13527
|
+
settled = true;
|
|
13528
|
+
clearTimeout(timeoutTimer);
|
|
13529
|
+
clearTimeout(groupTimer);
|
|
13530
|
+
clearInterval(limitTimer);
|
|
13531
|
+
stopExitWatch();
|
|
13532
|
+
options.signal?.removeEventListener("abort", abort);
|
|
13533
|
+
if (!exitReported(child))
|
|
13534
|
+
reapAfterLostExit(child.pid, () => exitReported(child));
|
|
13535
|
+
try {
|
|
13536
|
+
return {
|
|
13537
|
+
stdout: readCaptureFile(stdoutFd, outputLimit),
|
|
13538
|
+
stderr: readCaptureFile(stderrFd, stderrLimit)
|
|
13539
|
+
};
|
|
13540
|
+
} catch (error) {
|
|
13541
|
+
reject(error);
|
|
13542
|
+
return;
|
|
13543
|
+
} finally {
|
|
13544
|
+
releaseCaptureFds();
|
|
13545
|
+
}
|
|
13546
|
+
};
|
|
13547
|
+
const rejectFailure = (error) => {
|
|
13548
|
+
const output = finishCapture();
|
|
13549
|
+
if (output)
|
|
13550
|
+
reject(Object.assign(error, { ...output, killed: timedOut }));
|
|
13551
|
+
};
|
|
13552
|
+
const awaitTermination = (delayMs) => {
|
|
13553
|
+
clearTimeout(groupTimer);
|
|
13554
|
+
if (settled)
|
|
13555
|
+
return;
|
|
13556
|
+
if ((commandExit || exitReported(child)) && !commandGroupAlive(child)) {
|
|
13557
|
+
rejectFailure(pendingFailure);
|
|
13558
|
+
return;
|
|
13559
|
+
}
|
|
13560
|
+
groupTimer = setTimeout(awaitTermination, delayMs, Math.min(delayMs * 2, COMMAND_GROUP_POLL_MAX_MS));
|
|
13561
|
+
};
|
|
13562
|
+
const fail = (error) => {
|
|
13563
|
+
if (settled || pendingFailure)
|
|
13564
|
+
return;
|
|
13565
|
+
if (options.waitForTermination && child.pid !== undefined) {
|
|
13566
|
+
pendingFailure = error;
|
|
13567
|
+
signalCommand(child, "SIGKILL");
|
|
13568
|
+
clearTimeout(timeoutTimer);
|
|
13569
|
+
clearInterval(limitTimer);
|
|
13570
|
+
awaitTermination(COMMAND_GROUP_POLL_MS);
|
|
13571
|
+
} else
|
|
13572
|
+
rejectFailure(error);
|
|
13573
|
+
};
|
|
13574
|
+
const abort = () => {
|
|
13575
|
+
timedOut = true;
|
|
13576
|
+
signalCommand(child, "SIGKILL");
|
|
13577
|
+
fail(new Error(COMMAND_ABORTED_MESSAGE));
|
|
13578
|
+
};
|
|
13579
|
+
options.signal?.addEventListener("abort", abort, { once: true });
|
|
13580
|
+
const checkOutputLimit = () => {
|
|
13581
|
+
const stream = captureFs.fstatSync(stdoutFd).size > outputLimit ? "stdout" : captureFs.fstatSync(stderrFd).size > stderrLimit ? "stderr" : undefined;
|
|
13582
|
+
if (stream === undefined)
|
|
13583
|
+
return false;
|
|
13584
|
+
signalCommand(child, "SIGKILL");
|
|
13585
|
+
fail(Object.assign(new Error(`${stream} ${OUTPUT_LIMIT_MESSAGE}`), {
|
|
13586
|
+
outputLimitExceeded: true
|
|
13587
|
+
}));
|
|
13588
|
+
return true;
|
|
13589
|
+
};
|
|
13590
|
+
const failIfOverLimit = () => {
|
|
13591
|
+
try {
|
|
13592
|
+
return checkOutputLimit();
|
|
13593
|
+
} catch (error) {
|
|
13594
|
+
signalCommand(child, "SIGKILL");
|
|
13595
|
+
fail(error instanceof Error ? error : new Error(String(error)));
|
|
13596
|
+
return true;
|
|
13597
|
+
}
|
|
13598
|
+
};
|
|
13599
|
+
limitTimer = setInterval(() => {
|
|
13600
|
+
if (!settled && !timedOut && !pendingFailure)
|
|
13601
|
+
failIfOverLimit();
|
|
13602
|
+
}, COMMAND_OUTPUT_CHECK_MS);
|
|
13603
|
+
const settleOnExit = () => {
|
|
13604
|
+
if (settled || timedOut || pendingFailure || failIfOverLimit())
|
|
13605
|
+
return;
|
|
13606
|
+
if (commandExit?.code !== 0 || commandExit.signal !== null) {
|
|
13607
|
+
fail(Object.assign(new Error(`Command failed: ${[command, ...args].join(" ")}`), {
|
|
13608
|
+
code: commandExit?.code,
|
|
13609
|
+
signal: commandExit?.signal
|
|
13610
|
+
}));
|
|
13611
|
+
return;
|
|
13612
|
+
}
|
|
13613
|
+
const output = finishCapture();
|
|
13614
|
+
if (output)
|
|
13615
|
+
resolve(output);
|
|
13616
|
+
};
|
|
13617
|
+
const awaitGroupExit = (delayMs) => {
|
|
13618
|
+
if (settled || timedOut || pendingFailure)
|
|
13619
|
+
return;
|
|
13620
|
+
if (commandGroupAlive(child)) {
|
|
13621
|
+
groupTimer = setTimeout(awaitGroupExit, delayMs, Math.min(delayMs * 2, COMMAND_GROUP_POLL_MAX_MS));
|
|
13622
|
+
return;
|
|
13623
|
+
}
|
|
13624
|
+
settleOnExit();
|
|
13625
|
+
};
|
|
13626
|
+
const onCommandExit = (exit) => {
|
|
13627
|
+
if (commandExit)
|
|
13628
|
+
return;
|
|
13629
|
+
commandExit = exit;
|
|
13630
|
+
stopExitWatch();
|
|
13631
|
+
if (pendingFailure)
|
|
13632
|
+
awaitTermination(COMMAND_GROUP_POLL_MS);
|
|
13633
|
+
else if (options.waitForDescendants)
|
|
13634
|
+
awaitGroupExit(COMMAND_GROUP_POLL_MS);
|
|
13635
|
+
else
|
|
13636
|
+
settleOnExit();
|
|
13637
|
+
};
|
|
13638
|
+
child.exited.then(onCommandExit, (error) => fail(error instanceof Error ? error : new Error(String(error))));
|
|
13639
|
+
stopExitWatch = watchForLostExit(child.pid, (exit) => {
|
|
13640
|
+
if (!settled)
|
|
13641
|
+
onCommandExit(exit);
|
|
13642
|
+
});
|
|
13643
|
+
if (timeoutMs > 0) {
|
|
13644
|
+
timeoutTimer = setTimeout(() => {
|
|
13645
|
+
timedOut = true;
|
|
13646
|
+
signalCommand(child, "SIGTERM");
|
|
13647
|
+
timeoutTimer = setTimeout(() => {
|
|
13648
|
+
signalCommand(child, "SIGKILL");
|
|
13649
|
+
fail(Object.assign(new Error(`Command timed out after ${timeoutMs} ms`), {
|
|
13650
|
+
code: child.current().code,
|
|
13651
|
+
signal: child.current().signal
|
|
13652
|
+
}));
|
|
13653
|
+
}, COMMAND_KILL_GRACE_MS);
|
|
13654
|
+
}, timeoutMs);
|
|
13655
|
+
}
|
|
13656
|
+
});
|
|
13657
|
+
}
|
|
13658
|
+
async function runCommandBytes(command, args = [], options = {}) {
|
|
13659
|
+
const timeoutMs = options.timeoutMs ?? 60000;
|
|
13660
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > 2147483647) {
|
|
13661
|
+
throw new RangeError("timeoutMs must be an integer between 0 and 2147483647");
|
|
13662
|
+
}
|
|
13663
|
+
const outputLimit = options.maxOutputBytes ?? MAX_COMMAND_OUTPUT_BYTES;
|
|
13664
|
+
if (!Number.isSafeInteger(outputLimit) || outputLimit <= 0) {
|
|
13665
|
+
throw new RangeError("maxOutputBytes must be a positive integer");
|
|
13666
|
+
}
|
|
13667
|
+
const stderrLimit = options.maxStderrBytes ?? outputLimit;
|
|
13668
|
+
if (!Number.isSafeInteger(stderrLimit) || stderrLimit <= 0) {
|
|
13669
|
+
throw new RangeError("maxStderrBytes must be a positive integer");
|
|
13670
|
+
}
|
|
13671
|
+
if (commandInvocations.size < 64 || commandInvocations.has(command)) {
|
|
13672
|
+
commandInvocations.set(command, (commandInvocations.get(command) ?? 0) + 1);
|
|
13673
|
+
}
|
|
13674
|
+
for (const observer of commandObservers.get(command) ?? [])
|
|
13675
|
+
observer(args);
|
|
13676
|
+
commandCaptureMetrics?.started(command, args);
|
|
13677
|
+
try {
|
|
13678
|
+
const { stdout, stderr } = await executeCommandBytes(command, args, options, timeoutMs, outputLimit, stderrLimit);
|
|
13679
|
+
commandCaptureMetrics?.capturedBytes(stdout.length);
|
|
13680
|
+
return {
|
|
13681
|
+
stdout: Buffer.isBuffer(stdout) ? stdout : Buffer.from(stdout),
|
|
13682
|
+
stderr: Buffer.isBuffer(stderr) ? stderr : Buffer.from(stderr)
|
|
13683
|
+
};
|
|
13684
|
+
} catch (error) {
|
|
13685
|
+
const outcome = commandFailureOutcome(error);
|
|
13686
|
+
const redacting = options.redactValues?.some((value) => typeof value === "string" && value.length > 0);
|
|
13687
|
+
if (error && typeof error === "object" && "stdout" in error && "stderr" in error) {
|
|
13688
|
+
const withOutput = error;
|
|
13689
|
+
const stderr = withOutput.stderr?.toString() ?? "";
|
|
13690
|
+
const stdout = withOutput.stdout?.toString() ?? "";
|
|
13691
|
+
const message = (stderr || stdout || withOutput.message || "Command failed").trim();
|
|
13692
|
+
throw new CommandFailedError(redactCommandValues(message, options.redactValues), {
|
|
13693
|
+
...outcome,
|
|
13694
|
+
stdout: redactCommandValues(stdout, options.redactValues),
|
|
13695
|
+
stderr: redactCommandValues(stderr, options.redactValues),
|
|
13696
|
+
...!redacting && Buffer.isBuffer(withOutput.stdout) ? { stdoutBytes: withOutput.stdout } : {}
|
|
13697
|
+
});
|
|
13698
|
+
}
|
|
13699
|
+
if (redacting) {
|
|
13700
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
13701
|
+
throw new CommandFailedError(redactCommandValues(message || "Command failed", options.redactValues), outcome);
|
|
13702
|
+
}
|
|
13703
|
+
if (outcome.timedOut || outcome.executableMissing) {
|
|
13704
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
13705
|
+
throw new CommandFailedError(message || "Command failed", outcome);
|
|
13706
|
+
}
|
|
13707
|
+
throw error;
|
|
13708
|
+
}
|
|
13709
|
+
}
|
|
13710
|
+
async function runCommand(command, args = [], options = {}) {
|
|
13711
|
+
const { stdout, stderr } = await runCommandBytes(command, args, options);
|
|
13712
|
+
return {
|
|
13713
|
+
stdout: redactCommandValues(stdout.toString(), options.redactValues),
|
|
13714
|
+
stderr: redactCommandValues(stderr.toString(), options.redactValues)
|
|
13715
|
+
};
|
|
13716
|
+
}
|
|
13717
|
+
|
|
13718
|
+
// ../protocol/src/node/workspace-change-probe.ts
|
|
12594
13719
|
var DEFAULT_MAX_UNTRACKED_FILE_BYTES = 2 * 1024 * 1024;
|
|
12595
13720
|
var DEFAULT_MAX_UNTRACKED_FILES = 5000;
|
|
12596
13721
|
var DEFAULT_SLOW_SNAPSHOT_MS = 500;
|
|
@@ -12604,31 +13729,20 @@ var temporaryObjectDirectories = new Set;
|
|
|
12604
13729
|
process.once("exit", () => {
|
|
12605
13730
|
for (const directory of temporaryObjectDirectories) {
|
|
12606
13731
|
try {
|
|
12607
|
-
|
|
13732
|
+
rmSync2(directory, { recursive: true, force: true });
|
|
12608
13733
|
} catch {}
|
|
12609
13734
|
}
|
|
12610
13735
|
});
|
|
12611
|
-
var runGit = (args, options) =>
|
|
12612
|
-
const
|
|
12613
|
-
|
|
12614
|
-
|
|
12615
|
-
|
|
12616
|
-
|
|
12617
|
-
|
|
12618
|
-
let stdout = "";
|
|
12619
|
-
let stdoutBytes = 0;
|
|
12620
|
-
child.stdout.setEncoding("utf8");
|
|
12621
|
-
child.stdout.on("data", (chunk) => {
|
|
12622
|
-
stdoutBytes += chunk.length;
|
|
12623
|
-
if (stdoutBytes <= GIT_MAX_BUFFER)
|
|
12624
|
-
stdout += chunk;
|
|
13736
|
+
var runGit = async (args, options) => {
|
|
13737
|
+
const { stdout } = await runCommand("git", args, {
|
|
13738
|
+
cwd: options.cwd,
|
|
13739
|
+
env: { ...process.env, ...options.env, GIT_OPTIONAL_LOCKS: "0" },
|
|
13740
|
+
timeoutMs: GIT_TIMEOUT_MS,
|
|
13741
|
+
maxOutputBytes: GIT_MAX_BUFFER,
|
|
13742
|
+
...options.stdin === undefined ? {} : { stdin: options.stdin }
|
|
12625
13743
|
});
|
|
12626
|
-
|
|
12627
|
-
|
|
12628
|
-
child.on("close", (code) => code === 0 ? resolvePromise({ stdout }) : reject(new Error(`git exited with ${code}`)));
|
|
12629
|
-
child.stdin.on("error", () => {});
|
|
12630
|
-
child.stdin.end(options.stdin);
|
|
12631
|
-
});
|
|
13744
|
+
return { stdout };
|
|
13745
|
+
};
|
|
12632
13746
|
|
|
12633
13747
|
class WorkspaceChangeProbe {
|
|
12634
13748
|
git;
|
|
@@ -12872,8 +13986,8 @@ class WorkspaceChangeProbe {
|
|
|
12872
13986
|
return;
|
|
12873
13987
|
return {
|
|
12874
13988
|
root,
|
|
12875
|
-
indexPath:
|
|
12876
|
-
objectsPath:
|
|
13989
|
+
indexPath: isAbsolute3(index) ? index : resolve3(cwd, index),
|
|
13990
|
+
objectsPath: isAbsolute3(objects) ? objects : resolve3(cwd, objects)
|
|
12877
13991
|
};
|
|
12878
13992
|
}).catch(() => {
|
|
12879
13993
|
return;
|
|
@@ -12916,8 +14030,8 @@ class WorkspaceChangeProbe {
|
|
|
12916
14030
|
return;
|
|
12917
14031
|
const { root, indexPath } = repo.location;
|
|
12918
14032
|
const started = this.now();
|
|
12919
|
-
const tempIndex =
|
|
12920
|
-
const objectDirectory = await mkdtemp2(
|
|
14033
|
+
const tempIndex = join8(this.tempDir, `orkestrator-probe-${randomUUID3()}.index`);
|
|
14034
|
+
const objectDirectory = await mkdtemp2(join8(this.tempDir, "orkestrator-probe-objects-"));
|
|
12921
14035
|
temporaryObjectDirectories.add(objectDirectory);
|
|
12922
14036
|
let retained = false;
|
|
12923
14037
|
try {
|
|
@@ -12934,7 +14048,7 @@ class WorkspaceChangeProbe {
|
|
|
12934
14048
|
const included = [];
|
|
12935
14049
|
const skipped = new Map;
|
|
12936
14050
|
for (const path of untracked) {
|
|
12937
|
-
const stats = await lstat(
|
|
14051
|
+
const stats = await lstat(join8(root, path)).catch(() => {
|
|
12938
14052
|
return;
|
|
12939
14053
|
});
|
|
12940
14054
|
if (!stats)
|
|
@@ -13080,20 +14194,20 @@ function parseNumstatZ(output) {
|
|
|
13080
14194
|
}
|
|
13081
14195
|
|
|
13082
14196
|
// ../../bridges/claude-bridge/src/services/command-changes.ts
|
|
13083
|
-
import { join as
|
|
14197
|
+
import { join as join11 } from "node:path";
|
|
13084
14198
|
|
|
13085
14199
|
// ../../bridges/claude-bridge/src/services/change-evidence.ts
|
|
13086
14200
|
import { createHash as createHash8 } from "node:crypto";
|
|
13087
14201
|
import {
|
|
13088
|
-
closeSync,
|
|
14202
|
+
closeSync as closeSync3,
|
|
13089
14203
|
existsSync as existsSync2,
|
|
13090
14204
|
mkdirSync,
|
|
13091
|
-
openSync,
|
|
13092
|
-
readFileSync as
|
|
13093
|
-
rmSync as
|
|
14205
|
+
openSync as openSync3,
|
|
14206
|
+
readFileSync as readFileSync5,
|
|
14207
|
+
rmSync as rmSync3,
|
|
13094
14208
|
writeSync
|
|
13095
14209
|
} from "node:fs";
|
|
13096
|
-
import { join as
|
|
14210
|
+
import { join as join10 } from "node:path";
|
|
13097
14211
|
|
|
13098
14212
|
// ../protocol/src/field-validation.ts
|
|
13099
14213
|
function isPlainRecord(value) {
|
|
@@ -13496,10 +14610,10 @@ function workspaceObservationReportIssues(value) {
|
|
|
13496
14610
|
}
|
|
13497
14611
|
|
|
13498
14612
|
// ../protocol/src/node/change-tracking/evidence-spool.ts
|
|
13499
|
-
import { createHash as createHash7, randomUUID as
|
|
13500
|
-
import { readdirSync, readFileSync as
|
|
14613
|
+
import { createHash as createHash7, randomUUID as randomUUID4 } from "node:crypto";
|
|
14614
|
+
import { readdirSync as readdirSync2, readFileSync as readFileSync4 } from "node:fs";
|
|
13501
14615
|
import { appendFile as appendFile2, mkdir as mkdir4, rename as rename4, rm as rm5, writeFile as writeFile4 } from "node:fs/promises";
|
|
13502
|
-
import { join as
|
|
14616
|
+
import { join as join9 } from "node:path";
|
|
13503
14617
|
var DEFAULT_EVIDENCE_SPOOL_LIMITS = {
|
|
13504
14618
|
maxEntries: 2048,
|
|
13505
14619
|
maxEntryBytes: 256 * 1024,
|
|
@@ -13542,7 +14656,7 @@ class ChangeEvidenceSpool {
|
|
|
13542
14656
|
restoring = false;
|
|
13543
14657
|
constructor(options = {}) {
|
|
13544
14658
|
this.limits = { ...DEFAULT_EVIDENCE_SPOOL_LIMITS, ...options.limits };
|
|
13545
|
-
this.runtimeEpoch = options.runtimeEpoch ??
|
|
14659
|
+
this.runtimeEpoch = options.runtimeEpoch ?? randomUUID4();
|
|
13546
14660
|
this.directory = options.directory;
|
|
13547
14661
|
if (this.directory) {
|
|
13548
14662
|
this.restoring = true;
|
|
@@ -13645,7 +14759,7 @@ class ChangeEvidenceSpool {
|
|
|
13645
14759
|
return;
|
|
13646
14760
|
if (this.entries.length >= this.limits.maxEntries - 1)
|
|
13647
14761
|
return;
|
|
13648
|
-
const gapId =
|
|
14762
|
+
const gapId = randomUUID4();
|
|
13649
14763
|
const coverage = this.droppedUnknown ? {
|
|
13650
14764
|
kind: "unknown-range",
|
|
13651
14765
|
bindingId: this.gapBindingId || "unknown",
|
|
@@ -13762,7 +14876,7 @@ class ChangeEvidenceSpool {
|
|
|
13762
14876
|
const lines = this.pendingLines.splice(0).join("");
|
|
13763
14877
|
this.enqueueIo(async () => {
|
|
13764
14878
|
await mkdir4(directory, { recursive: true, mode: 448 });
|
|
13765
|
-
await appendFile2(
|
|
14879
|
+
await appendFile2(join9(directory, ENTRIES_FILE), lines, { mode: 384 });
|
|
13766
14880
|
});
|
|
13767
14881
|
}
|
|
13768
14882
|
persistBody(id, bytes) {
|
|
@@ -13770,9 +14884,9 @@ class ChangeEvidenceSpool {
|
|
|
13770
14884
|
if (!directory || this.restoring)
|
|
13771
14885
|
return;
|
|
13772
14886
|
this.enqueueIo(async () => {
|
|
13773
|
-
const bodies =
|
|
14887
|
+
const bodies = join9(directory, BODY_DIRECTORY);
|
|
13774
14888
|
await mkdir4(bodies, { recursive: true, mode: 448 });
|
|
13775
|
-
await writeFile4(
|
|
14889
|
+
await writeFile4(join9(bodies, bodyFileName(id)), bytes, { mode: 384, flag: "wx" }).catch((error) => {
|
|
13776
14890
|
if (error.code !== "EEXIST")
|
|
13777
14891
|
throw error;
|
|
13778
14892
|
});
|
|
@@ -13782,7 +14896,7 @@ class ChangeEvidenceSpool {
|
|
|
13782
14896
|
const directory = this.directory;
|
|
13783
14897
|
if (!directory)
|
|
13784
14898
|
return;
|
|
13785
|
-
this.enqueueIo(() => rm5(
|
|
14899
|
+
this.enqueueIo(() => rm5(join9(directory, BODY_DIRECTORY, bodyFileName(id)), { force: true }));
|
|
13786
14900
|
}
|
|
13787
14901
|
compactPersisted() {
|
|
13788
14902
|
const directory = this.directory;
|
|
@@ -13793,7 +14907,7 @@ class ChangeEvidenceSpool {
|
|
|
13793
14907
|
`);
|
|
13794
14908
|
this.enqueueIo(async () => {
|
|
13795
14909
|
await mkdir4(directory, { recursive: true, mode: 448 });
|
|
13796
|
-
const file =
|
|
14910
|
+
const file = join9(directory, ENTRIES_FILE);
|
|
13797
14911
|
const temp = `${file}.${process.pid}.tmp`;
|
|
13798
14912
|
await writeFile4(temp, body ? `${body}
|
|
13799
14913
|
` : "", { mode: 384 });
|
|
@@ -13805,10 +14919,10 @@ class ChangeEvidenceSpool {
|
|
|
13805
14919
|
await this.io;
|
|
13806
14920
|
}
|
|
13807
14921
|
restore(directory) {
|
|
13808
|
-
const bodyDirectory =
|
|
14922
|
+
const bodyDirectory = join9(directory, BODY_DIRECTORY);
|
|
13809
14923
|
try {
|
|
13810
|
-
for (const name of
|
|
13811
|
-
const bytes = new Uint8Array(
|
|
14924
|
+
for (const name of readdirSync2(bodyDirectory)) {
|
|
14925
|
+
const bytes = new Uint8Array(readFileSync4(join9(bodyDirectory, name)));
|
|
13812
14926
|
const id = evidenceBodyId(bytes);
|
|
13813
14927
|
if (bodyFileName(id) !== name)
|
|
13814
14928
|
continue;
|
|
@@ -13820,7 +14934,7 @@ class ChangeEvidenceSpool {
|
|
|
13820
14934
|
} catch {}
|
|
13821
14935
|
let text = "";
|
|
13822
14936
|
try {
|
|
13823
|
-
text =
|
|
14937
|
+
text = readFileSync4(join9(directory, ENTRIES_FILE), "utf8");
|
|
13824
14938
|
} catch {
|
|
13825
14939
|
return;
|
|
13826
14940
|
}
|
|
@@ -14201,14 +15315,14 @@ function record(value) {
|
|
|
14201
15315
|
function text(value) {
|
|
14202
15316
|
return typeof value === "string" ? value : undefined;
|
|
14203
15317
|
}
|
|
14204
|
-
function
|
|
15318
|
+
function path4(value) {
|
|
14205
15319
|
return typeof value === "string" && value.length > 0 ? value : undefined;
|
|
14206
15320
|
}
|
|
14207
15321
|
function claudeProposalEvidence(toolName, input) {
|
|
14208
15322
|
const fields = record(input);
|
|
14209
15323
|
switch (toolName) {
|
|
14210
15324
|
case "Edit": {
|
|
14211
|
-
const filePath =
|
|
15325
|
+
const filePath = path4(fields.file_path);
|
|
14212
15326
|
if (!filePath)
|
|
14213
15327
|
return [];
|
|
14214
15328
|
return [
|
|
@@ -14226,7 +15340,7 @@ function claudeProposalEvidence(toolName, input) {
|
|
|
14226
15340
|
];
|
|
14227
15341
|
}
|
|
14228
15342
|
case "MultiEdit": {
|
|
14229
|
-
const filePath =
|
|
15343
|
+
const filePath = path4(fields.file_path);
|
|
14230
15344
|
if (!filePath || !Array.isArray(fields.edits))
|
|
14231
15345
|
return [];
|
|
14232
15346
|
return fields.edits.map((edit, index) => {
|
|
@@ -14245,7 +15359,7 @@ function claudeProposalEvidence(toolName, input) {
|
|
|
14245
15359
|
});
|
|
14246
15360
|
}
|
|
14247
15361
|
case "Write": {
|
|
14248
|
-
const filePath =
|
|
15362
|
+
const filePath = path4(fields.file_path);
|
|
14249
15363
|
if (!filePath)
|
|
14250
15364
|
return [];
|
|
14251
15365
|
return [
|
|
@@ -14263,7 +15377,7 @@ function claudeProposalEvidence(toolName, input) {
|
|
|
14263
15377
|
];
|
|
14264
15378
|
}
|
|
14265
15379
|
case "NotebookEdit": {
|
|
14266
|
-
const filePath =
|
|
15380
|
+
const filePath = path4(fields.notebook_path);
|
|
14267
15381
|
if (!filePath)
|
|
14268
15382
|
return [];
|
|
14269
15383
|
const deleting = fields.edit_mode === "delete";
|
|
@@ -14332,20 +15446,20 @@ function createChangeEvidence(options) {
|
|
|
14332
15446
|
};
|
|
14333
15447
|
}
|
|
14334
15448
|
function claimSpoolDirectory(root = claudeChangeEvidenceDir(), scope = process.env.CWD || process.cwd()) {
|
|
14335
|
-
const directory =
|
|
14336
|
-
const owner =
|
|
15449
|
+
const directory = join10(root, createHash8("sha256").update(scope).digest("hex").slice(0, 32));
|
|
15450
|
+
const owner = join10(directory, "owner.pid");
|
|
14337
15451
|
try {
|
|
14338
15452
|
mkdirSync(directory, { recursive: true, mode: 448 });
|
|
14339
15453
|
for (let attempt = 0;attempt < 2; attempt++) {
|
|
14340
15454
|
try {
|
|
14341
|
-
const fd =
|
|
15455
|
+
const fd = openSync3(owner, "wx", 384);
|
|
14342
15456
|
writeSync(fd, ownerFileContents());
|
|
14343
|
-
|
|
15457
|
+
closeSync3(fd);
|
|
14344
15458
|
return directory;
|
|
14345
15459
|
} catch (error) {
|
|
14346
15460
|
if (error.code !== "EEXIST")
|
|
14347
15461
|
return;
|
|
14348
|
-
const holder = parseOwnerFile(
|
|
15462
|
+
const holder = parseOwnerFile(readFileSync5(owner, "utf8"));
|
|
14349
15463
|
if (holder) {
|
|
14350
15464
|
const state = recordedOwnerState(holder, { slowPath: true });
|
|
14351
15465
|
if (state === "current")
|
|
@@ -14353,7 +15467,7 @@ function claimSpoolDirectory(root = claudeChangeEvidenceDir(), scope = process.e
|
|
|
14353
15467
|
if (state !== "dead")
|
|
14354
15468
|
return;
|
|
14355
15469
|
}
|
|
14356
|
-
|
|
15470
|
+
rmSync3(owner, { force: true });
|
|
14357
15471
|
}
|
|
14358
15472
|
}
|
|
14359
15473
|
} catch {}
|
|
@@ -14531,7 +15645,7 @@ function commandChangeJournal(sdkSessionId) {
|
|
|
14531
15645
|
if (journal) {
|
|
14532
15646
|
journals.delete(sdkSessionId);
|
|
14533
15647
|
} else {
|
|
14534
|
-
journal = new CommandChangeJournal(
|
|
15648
|
+
journal = new CommandChangeJournal(join11(claudeCommandChangesDir(), `${sdkSessionId}.jsonl`));
|
|
14535
15649
|
}
|
|
14536
15650
|
journals.set(sdkSessionId, journal);
|
|
14537
15651
|
while (journals.size > MAX_CACHED_JOURNALS) {
|
|
@@ -15298,17 +16412,17 @@ class ClaudeAttachmentError extends Error {
|
|
|
15298
16412
|
var BRIDGE_ATTACHMENT_ROOT_ENV = "ORKESTRATOR_BRIDGE_ATTACHMENT_ROOT";
|
|
15299
16413
|
function configuredAttachmentRoot(env = process.env) {
|
|
15300
16414
|
const value = env[BRIDGE_ATTACHMENT_ROOT_ENV]?.trim();
|
|
15301
|
-
return value &&
|
|
16415
|
+
return value && isAbsolute4(value) ? resolve4(value) : undefined;
|
|
15302
16416
|
}
|
|
15303
16417
|
function attachmentContainmentRoot(filePath, cwd, extraRoot = configuredAttachmentRoot()) {
|
|
15304
|
-
if (extraRoot &&
|
|
16418
|
+
if (extraRoot && isAbsolute4(filePath) && isPathWithin2(extraRoot, resolve4(filePath))) {
|
|
15305
16419
|
return extraRoot;
|
|
15306
16420
|
}
|
|
15307
|
-
return
|
|
16421
|
+
return resolve4(cwd);
|
|
15308
16422
|
}
|
|
15309
16423
|
function isPathWithin2(rootPath, targetPath) {
|
|
15310
16424
|
const childPath = relative(rootPath, targetPath);
|
|
15311
|
-
return childPath === "" || childPath !== ".." && !childPath.startsWith(`..${
|
|
16425
|
+
return childPath === "" || childPath !== ".." && !childPath.startsWith(`..${sep2}`) && !isAbsolute4(childPath);
|
|
15312
16426
|
}
|
|
15313
16427
|
function attachmentErrorForFsFailure(error) {
|
|
15314
16428
|
const code = error?.code;
|
|
@@ -15323,8 +16437,8 @@ function attachmentErrorForFsFailure(error) {
|
|
|
15323
16437
|
async function assertNoSymlinkComponents(lexicalRoot, targetPath) {
|
|
15324
16438
|
const childPath = relative(lexicalRoot, targetPath);
|
|
15325
16439
|
let currentPath = lexicalRoot;
|
|
15326
|
-
for (const segment of childPath.split(
|
|
15327
|
-
currentPath =
|
|
16440
|
+
for (const segment of childPath.split(sep2).filter(Boolean)) {
|
|
16441
|
+
currentPath = join12(currentPath, segment);
|
|
15328
16442
|
const stats = await lstat2(currentPath).catch((error) => {
|
|
15329
16443
|
throw attachmentErrorForFsFailure(error);
|
|
15330
16444
|
});
|
|
@@ -15352,7 +16466,7 @@ async function assertOpenedWorkspaceFile(targetPath, canonicalRoot, openedStats)
|
|
|
15352
16466
|
}
|
|
15353
16467
|
async function readWorkspaceImageAttachment(filePath, cwd, afterSymlinkValidation, afterCanonicalValidation, afterInitialValidation) {
|
|
15354
16468
|
const lexicalRoot = attachmentContainmentRoot(filePath, cwd);
|
|
15355
|
-
const targetPath =
|
|
16469
|
+
const targetPath = isAbsolute4(filePath) ? resolve4(filePath) : resolve4(lexicalRoot, filePath);
|
|
15356
16470
|
if (!isPathWithin2(lexicalRoot, targetPath)) {
|
|
15357
16471
|
throw new ClaudeAttachmentError("attachment_outside_workspace", "Image attachment must be contained in the current workspace.");
|
|
15358
16472
|
}
|
|
@@ -15368,8 +16482,8 @@ async function readWorkspaceImageAttachment(filePath, cwd, afterSymlinkValidatio
|
|
|
15368
16482
|
throw new ClaudeAttachmentError("attachment_outside_workspace", "Image attachment must be contained in the current workspace.");
|
|
15369
16483
|
}
|
|
15370
16484
|
await afterCanonicalValidation?.(targetPath);
|
|
15371
|
-
const noFollow =
|
|
15372
|
-
const handle = await open2(targetPath,
|
|
16485
|
+
const noFollow = constants3.O_NOFOLLOW ?? 0;
|
|
16486
|
+
const handle = await open2(targetPath, constants3.O_RDONLY | noFollow).catch((error) => {
|
|
15373
16487
|
throw attachmentErrorForFsFailure(error);
|
|
15374
16488
|
});
|
|
15375
16489
|
try {
|
|
@@ -16382,7 +17496,7 @@ function reconcileClaudeUsage(terminal, streamed) {
|
|
|
16382
17496
|
}
|
|
16383
17497
|
|
|
16384
17498
|
// ../../bridges/claude-bridge/src/services/session-manager-prompt-turn-lifecycle.ts
|
|
16385
|
-
var
|
|
17499
|
+
var log8 = createLogger("bridge.claude");
|
|
16386
17500
|
function diagnosticErrorClass(error) {
|
|
16387
17501
|
try {
|
|
16388
17502
|
if (!(error instanceof Error))
|
|
@@ -16451,7 +17565,7 @@ async function reconcilePlanModeFromStatus(turn, reported) {
|
|
|
16451
17565
|
try {
|
|
16452
17566
|
await applySessionPlanMode(session, false);
|
|
16453
17567
|
} catch (error) {
|
|
16454
|
-
|
|
17568
|
+
log8.warn("plan-mode.record-failed", { sessionId, errorClass: diagnosticErrorClass(error) });
|
|
16455
17569
|
}
|
|
16456
17570
|
}
|
|
16457
17571
|
function setCompletionBlockedByBackgroundTasks(turn, blocked) {
|
|
@@ -16696,7 +17810,7 @@ function createTurnState(session, sessionId, init) {
|
|
|
16696
17810
|
}
|
|
16697
17811
|
|
|
16698
17812
|
// ../../bridges/claude-bridge/src/services/session-manager-prompt-admission.ts
|
|
16699
|
-
var
|
|
17813
|
+
var log9 = createLogger("bridge.claude");
|
|
16700
17814
|
var STREAM_EVENT_COALESCE_MS = 100;
|
|
16701
17815
|
function admitPrompt(sessionId, options) {
|
|
16702
17816
|
const session = sessions.get(sessionId);
|
|
@@ -16831,7 +17945,7 @@ async function readTranscriptForPrompt(session) {
|
|
|
16831
17945
|
try {
|
|
16832
17946
|
return await readPersistedSessionMessagesOnce(session);
|
|
16833
17947
|
} catch (error) {
|
|
16834
|
-
|
|
17948
|
+
log9.warn("transcript.hydrate-failed", { error: formatLogError(error, { stack: false }) });
|
|
16835
17949
|
return TRANSCRIPT_READ_FAILED;
|
|
16836
17950
|
}
|
|
16837
17951
|
}
|
|
@@ -16918,7 +18032,7 @@ import { query as query2 } from "@anthropic-ai/claude-agent-sdk";
|
|
|
16918
18032
|
|
|
16919
18033
|
// ../../bridges/claude-bridge/src/services/mcp-config.ts
|
|
16920
18034
|
import { createHash as createHash9 } from "node:crypto";
|
|
16921
|
-
import { join as
|
|
18035
|
+
import { join as join13 } from "node:path";
|
|
16922
18036
|
|
|
16923
18037
|
// ../protocol/src/agent-mail.ts
|
|
16924
18038
|
var AGENT_MAIL_MAX_BODY_BYTES = 32 * 1024;
|
|
@@ -16986,7 +18100,7 @@ var ORKESTRATOR_ARTIFACT_MCP_SERVER_NAME = "orkestrator-artifacts";
|
|
|
16986
18100
|
var ORKESTRATOR_ARTIFACT_MCP_PATH = "/artifact-mcp";
|
|
16987
18101
|
|
|
16988
18102
|
// ../../bridges/claude-bridge/src/services/mcp-config.ts
|
|
16989
|
-
var
|
|
18103
|
+
var log10 = createLogger("bridge.claude");
|
|
16990
18104
|
var AGENT_MCP_SERVER_NAME = "orkestrator";
|
|
16991
18105
|
var AGENT_MCP_URL_ENV = "ORKESTRATOR_AGENT_MCP_URL";
|
|
16992
18106
|
var AGENT_MCP_TOKEN_ENV = "ORKESTRATOR_AGENT_MCP_TOKEN";
|
|
@@ -17033,7 +18147,7 @@ async function loadGlobalMcpServers() {
|
|
|
17033
18147
|
return servers ?? {};
|
|
17034
18148
|
}
|
|
17035
18149
|
async function loadProjectMcpServers(cwd) {
|
|
17036
|
-
const servers = await readJsonSliceCached(
|
|
18150
|
+
const servers = await readJsonSliceCached(join13(cwd, ".mcp.json"), "mcpServers", (config) => config?.mcpServers);
|
|
17037
18151
|
return servers ?? {};
|
|
17038
18152
|
}
|
|
17039
18153
|
async function loadProjectOverridesFromGlobal2(cwd) {
|
|
@@ -17071,7 +18185,7 @@ function toSdkServers(configs) {
|
|
|
17071
18185
|
if (sdkConfig) {
|
|
17072
18186
|
servers[name] = sdkConfig;
|
|
17073
18187
|
} else {
|
|
17074
|
-
|
|
18188
|
+
log10.warn("mcp.config-ignored");
|
|
17075
18189
|
}
|
|
17076
18190
|
}
|
|
17077
18191
|
return servers;
|
|
@@ -17153,7 +18267,7 @@ async function loadScopedMcpServers(cwd, scope) {
|
|
|
17153
18267
|
const [global2, projectGlobal, projectLocal] = await Promise.all([
|
|
17154
18268
|
readJsonSliceCachedWithDigest(path, "mcpServers", (config) => config?.mcpServers),
|
|
17155
18269
|
scope === "all" ? readJsonSliceCachedWithDigest(path, `projects:${cwd}:mcpServers`, (config) => config?.projects?.[cwd]?.mcpServers) : null,
|
|
17156
|
-
scope === "all" ? readJsonSliceCachedWithDigest(
|
|
18270
|
+
scope === "all" ? readJsonSliceCachedWithDigest(join13(cwd, ".mcp.json"), "mcpServers", (config) => config?.mcpServers) : null
|
|
17157
18271
|
]);
|
|
17158
18272
|
const configs = {
|
|
17159
18273
|
...global2.value,
|
|
@@ -17234,11 +18348,11 @@ async function getMcpRuntimeConfig(cwd, env = process.env, connection, sources =
|
|
|
17234
18348
|
}
|
|
17235
18349
|
|
|
17236
18350
|
// ../../bridges/claude-bridge/src/services/session-manager-commands.ts
|
|
17237
|
-
import { randomUUID as
|
|
18351
|
+
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
17238
18352
|
|
|
17239
18353
|
// ../../bridges/claude-bridge/src/services/claude-model-catalog.ts
|
|
17240
|
-
import { homedir as
|
|
17241
|
-
import { join as
|
|
18354
|
+
import { homedir as homedir3 } from "node:os";
|
|
18355
|
+
import { join as join14 } from "node:path";
|
|
17242
18356
|
import { stat as stat5 } from "node:fs/promises";
|
|
17243
18357
|
|
|
17244
18358
|
// ../../bridges/claude-bridge/src/services/live-claude-control.ts
|
|
@@ -17436,7 +18550,7 @@ function claudeReadiness() {
|
|
|
17436
18550
|
}
|
|
17437
18551
|
|
|
17438
18552
|
// ../../bridges/claude-bridge/src/services/claude-model-catalog.ts
|
|
17439
|
-
var
|
|
18553
|
+
var log11 = createLogger("bridge.claude");
|
|
17440
18554
|
var CLAUDE_MODEL_CACHE_TTL_MS = 60 * 60000;
|
|
17441
18555
|
var CLAUDE_MODEL_PROBE_TIMEOUT_MS = 25000;
|
|
17442
18556
|
var remembered;
|
|
@@ -17464,15 +18578,15 @@ function catalogModels(models) {
|
|
|
17464
18578
|
}));
|
|
17465
18579
|
}
|
|
17466
18580
|
async function claudeCliIdentity() {
|
|
17467
|
-
const configDir = process.env.CLAUDE_CONFIG_DIR?.trim() ||
|
|
18581
|
+
const configDir = process.env.CLAUDE_CONFIG_DIR?.trim() || join14(homedir3(), ".claude");
|
|
17468
18582
|
const executable = process.env.CLAUDE_CLI_PATH?.trim();
|
|
17469
18583
|
const resolved = executable ? Bun.which(executable, { PATH: process.env.PATH }) || executable : undefined;
|
|
17470
18584
|
const cwd = process.env.CWD || process.cwd();
|
|
17471
18585
|
const paths = [
|
|
17472
18586
|
resolved,
|
|
17473
|
-
|
|
17474
|
-
|
|
17475
|
-
|
|
18587
|
+
join14(configDir, "settings.json"),
|
|
18588
|
+
join14(cwd, ".claude/settings.json"),
|
|
18589
|
+
join14(cwd, ".claude/settings.local.json")
|
|
17476
18590
|
];
|
|
17477
18591
|
const files = await Promise.all(paths.map(async (path) => {
|
|
17478
18592
|
const file = path ? await stat5(path).catch(() => {
|
|
@@ -17577,7 +18691,7 @@ async function probeModels(at) {
|
|
|
17577
18691
|
await rememberModels(models, account, at);
|
|
17578
18692
|
return { source: "sdk", models: catalogModels(models) };
|
|
17579
18693
|
} catch (error) {
|
|
17580
|
-
|
|
18694
|
+
log11.warn("models.fetch-failed", { error: formatLogError(error) });
|
|
17581
18695
|
return fallbackCatalog();
|
|
17582
18696
|
} finally {
|
|
17583
18697
|
clearTimeout(timer);
|
|
@@ -17919,7 +19033,7 @@ function idleSteerPromptReply(prompt, agentLabel) {
|
|
|
17919
19033
|
|
|
17920
19034
|
// ../../bridges/claude-bridge/src/services/claude-terminal-commands.ts
|
|
17921
19035
|
import { mkdir as mkdir5, readFile as readFile6, rename as rename5, writeFile as writeFile5 } from "node:fs/promises";
|
|
17922
|
-
import { join as
|
|
19036
|
+
import { join as join15 } from "node:path";
|
|
17923
19037
|
var FILE_NAME = "terminal-slash-commands.json";
|
|
17924
19038
|
var MAX_VERSIONS = 4;
|
|
17925
19039
|
var MAX_NAMES = 512;
|
|
@@ -17930,7 +19044,7 @@ var dirty = false;
|
|
|
17930
19044
|
var entries = [];
|
|
17931
19045
|
var writes = Promise.resolve();
|
|
17932
19046
|
function filePath() {
|
|
17933
|
-
return
|
|
19047
|
+
return join15(claudeOrkestratorDir(), FILE_NAME);
|
|
17934
19048
|
}
|
|
17935
19049
|
function validVersion(value) {
|
|
17936
19050
|
return typeof value === "string" && value.length > 0 && value.length <= MAX_VERSION_LENGTH;
|
|
@@ -18483,7 +19597,7 @@ async function gracefulInterruptClaudeSession(sessionId) {
|
|
|
18483
19597
|
}
|
|
18484
19598
|
|
|
18485
19599
|
// ../../bridges/claude-bridge/src/services/session-manager-commands.ts
|
|
18486
|
-
var CATALOGUE_GENERATION =
|
|
19600
|
+
var CATALOGUE_GENERATION = randomUUID5();
|
|
18487
19601
|
var COMMAND_PROBE_TIMEOUT_MS = 30000;
|
|
18488
19602
|
var MAX_LOCAL_COMMAND_OUTPUT_BYTES = 64 * 1024;
|
|
18489
19603
|
var MAX_MESSAGE_BYTES = 512;
|
|
@@ -19377,7 +20491,7 @@ function claudeArtifactServerTools(servers) {
|
|
|
19377
20491
|
|
|
19378
20492
|
// ../protocol/src/node/repository-instructions.ts
|
|
19379
20493
|
import { open as open3, realpath as realpath3 } from "node:fs/promises";
|
|
19380
|
-
import { join as
|
|
20494
|
+
import { join as join16, relative as relative2, isAbsolute as isAbsolute5 } from "node:path";
|
|
19381
20495
|
|
|
19382
20496
|
// ../protocol/src/rich-content-policy.ts
|
|
19383
20497
|
var KIB = 1024;
|
|
@@ -19576,11 +20690,11 @@ function repositoryInstructionsBlock(path, content, truncated) {
|
|
|
19576
20690
|
// ../protocol/src/node/repository-instructions.ts
|
|
19577
20691
|
var MAX_REPOSITORY_INSTRUCTIONS_BYTES = 256 * 1024;
|
|
19578
20692
|
async function readRepositoryInstructions(cwd, maxBytes = MAX_REPOSITORY_INSTRUCTIONS_BYTES) {
|
|
19579
|
-
const path =
|
|
20693
|
+
const path = join16(cwd, REPOSITORY_INSTRUCTIONS_FILE);
|
|
19580
20694
|
try {
|
|
19581
20695
|
const [root, target] = await Promise.all([realpath3(cwd), realpath3(path)]);
|
|
19582
20696
|
const inside = relative2(root, target);
|
|
19583
|
-
if (!inside || inside.startsWith("..") ||
|
|
20697
|
+
if (!inside || inside.startsWith("..") || isAbsolute5(inside))
|
|
19584
20698
|
return;
|
|
19585
20699
|
const handle = await open3(target, "r");
|
|
19586
20700
|
try {
|
|
@@ -19877,14 +20991,14 @@ function isValidMcpFormContent(schema, content) {
|
|
|
19877
20991
|
}
|
|
19878
20992
|
|
|
19879
20993
|
// ../../bridges/claude-bridge/src/services/session-manager-interactions.ts
|
|
19880
|
-
var
|
|
20994
|
+
var log12 = createLogger("bridge.claude");
|
|
19881
20995
|
function answerQuestion(requestId, answers) {
|
|
19882
20996
|
const question = pendingQuestions.get(requestId);
|
|
19883
20997
|
if (!question) {
|
|
19884
20998
|
debugLog("[session-manager] Question not found for requestId:", requestId);
|
|
19885
20999
|
return false;
|
|
19886
21000
|
}
|
|
19887
|
-
|
|
21001
|
+
log12.info("question.answering", { requestId, answerCount: Object.keys(answers).length });
|
|
19888
21002
|
const resolver = questionResolvers.get(requestId);
|
|
19889
21003
|
if (resolver) {
|
|
19890
21004
|
debugLog("[session-manager] Resolving promise for question:", requestId);
|
|
@@ -19936,7 +21050,7 @@ function respondToPlanApproval(requestId, approved, feedback) {
|
|
|
19936
21050
|
debugLog("[session-manager] Refusing incomplete plan approval", { requestId });
|
|
19937
21051
|
return false;
|
|
19938
21052
|
}
|
|
19939
|
-
|
|
21053
|
+
log12.info("plan-approval.responding", {
|
|
19940
21054
|
requestId,
|
|
19941
21055
|
approved,
|
|
19942
21056
|
hasFeedback: typeof feedback === "string" && feedback.length > 0
|
|
@@ -21185,7 +22299,7 @@ function classifyUsageLimitError(text) {
|
|
|
21185
22299
|
var USAGE_LIMIT_ERROR_CODE = "usage-limit";
|
|
21186
22300
|
|
|
21187
22301
|
// ../../bridges/claude-bridge/src/services/session-manager-prompt-handlers/result.ts
|
|
21188
|
-
var
|
|
22302
|
+
var log13 = createLogger("bridge.claude");
|
|
21189
22303
|
function claudeStartupFailureMessage(reason) {
|
|
21190
22304
|
switch (reason) {
|
|
21191
22305
|
case "org_pin_api_key_conflict":
|
|
@@ -21358,7 +22472,7 @@ async function handleResultMessage(turn, message) {
|
|
|
21358
22472
|
debugLog("[session-manager] Query stopped by the user", { sessionId });
|
|
21359
22473
|
finishTurnInputIfSettled(turn);
|
|
21360
22474
|
} else {
|
|
21361
|
-
|
|
22475
|
+
log13.error("query.failed", { subtype: resultMsg.subtype, sessionId, isError: resultIsError });
|
|
21362
22476
|
const startupFailure = resultMsg.startup_failure_reason ? claudeStartupFailureMessage(resultMsg.startup_failure_reason) : undefined;
|
|
21363
22477
|
const usageLimit = resultMsg.subtype === "success" && classifyUsageLimitError(resultMsg.result) ? resultMsg.result.trim().slice(0, MAX_USAGE_LIMIT_ERROR_CHARS) : undefined;
|
|
21364
22478
|
const resultError = startupFailure || resultMsg.errors?.filter(Boolean).join(`
|
|
@@ -21788,7 +22902,7 @@ async function handleSystemMessage(turn, message) {
|
|
|
21788
22902
|
}
|
|
21789
22903
|
|
|
21790
22904
|
// ../../bridges/claude-bridge/src/services/session-manager-prompt-handlers/user.ts
|
|
21791
|
-
var
|
|
22905
|
+
var log14 = createLogger("bridge.claude");
|
|
21792
22906
|
function handleUserMessage(turn, message) {
|
|
21793
22907
|
const { session, sessionId, stream } = turn;
|
|
21794
22908
|
const { toolTracker, taskRegistry, activeTaskIds } = stream;
|
|
@@ -21838,7 +22952,7 @@ function handleUserMessage(turn, message) {
|
|
|
21838
22952
|
if (turn.planApprovedThisTurn) {
|
|
21839
22953
|
for (const tool of toolTracker.getTools()) {
|
|
21840
22954
|
if (tool.toolName === "ExitPlanMode" && tool.toolState === "failure" && tool.toolUseId) {
|
|
21841
|
-
|
|
22955
|
+
log14.warn("plan-exit.failure-overridden", { sessionId, toolUseId: tool.toolUseId });
|
|
21842
22956
|
toolTracker.updateToolResult(tool.toolUseId, {
|
|
21843
22957
|
state: "success",
|
|
21844
22958
|
output: "Plan approved by the user. Proceeding with implementation.",
|
|
@@ -21910,7 +23024,7 @@ async function handleTurnMessage(turn, message) {
|
|
|
21910
23024
|
}
|
|
21911
23025
|
|
|
21912
23026
|
// ../../bridges/claude-bridge/src/services/session-manager-prompt-can-use-tool.ts
|
|
21913
|
-
var
|
|
23027
|
+
var log15 = createLogger("bridge.claude");
|
|
21914
23028
|
function boundedPlan(content) {
|
|
21915
23029
|
if (typeof content !== "string" || content.trim().length === 0)
|
|
21916
23030
|
return {};
|
|
@@ -21969,7 +23083,7 @@ async function askUserQuestion(turn, input, permissionContext) {
|
|
|
21969
23083
|
});
|
|
21970
23084
|
try {
|
|
21971
23085
|
const answers = await Promise.race([answerPromise, timeoutPromise]);
|
|
21972
|
-
|
|
23086
|
+
log15.info("question.answers-received", { questionId, answerCount: Object.keys(answers).length });
|
|
21973
23087
|
return {
|
|
21974
23088
|
behavior: "allow",
|
|
21975
23089
|
updatedInput: {
|
|
@@ -21978,7 +23092,7 @@ async function askUserQuestion(turn, input, permissionContext) {
|
|
|
21978
23092
|
}
|
|
21979
23093
|
};
|
|
21980
23094
|
} catch (error) {
|
|
21981
|
-
|
|
23095
|
+
log15.warn("question.wait-failed", { error: formatLogError(error) });
|
|
21982
23096
|
const message = error instanceof Error ? error.message : "Question was cancelled";
|
|
21983
23097
|
if (pendingQuestions.has(questionId)) {
|
|
21984
23098
|
eventEmitter.emit({
|
|
@@ -22059,7 +23173,7 @@ async function requestPlanApproval(turn, input, permissionContext) {
|
|
|
22059
23173
|
});
|
|
22060
23174
|
try {
|
|
22061
23175
|
const response = await Promise.race([approvalPromise, timeoutPromise]);
|
|
22062
|
-
|
|
23176
|
+
log15.info("plan-approval.result", {
|
|
22063
23177
|
approvalId,
|
|
22064
23178
|
approved: response.approved,
|
|
22065
23179
|
hasFeedback: typeof response.feedback === "string" && response.feedback.length > 0
|
|
@@ -22108,7 +23222,7 @@ Please revise the plan based on this feedback.` : `I've reviewed the plan and I
|
|
|
22108
23222
|
};
|
|
22109
23223
|
}
|
|
22110
23224
|
} catch (error) {
|
|
22111
|
-
|
|
23225
|
+
log15.warn("plan-approval.wait-failed", { error: formatLogError(error) });
|
|
22112
23226
|
const errorMessage = error instanceof Error ? error.message : "Plan approval was cancelled";
|
|
22113
23227
|
if (pendingPlanApprovals.has(approvalId)) {
|
|
22114
23228
|
eventEmitter.emit({
|
|
@@ -22198,7 +23312,7 @@ function createClaudeRuntimeTurn(turn) {
|
|
|
22198
23312
|
}
|
|
22199
23313
|
|
|
22200
23314
|
// ../../bridges/claude-bridge/src/services/session-manager-prompt-launch.ts
|
|
22201
|
-
var
|
|
23315
|
+
var log16 = createLogger("bridge.claude");
|
|
22202
23316
|
async function consumeClaudeRuntime(runtime, frames, markEnded) {
|
|
22203
23317
|
let failure;
|
|
22204
23318
|
try {
|
|
@@ -22275,7 +23389,7 @@ function releaseOrphanedForeground(runtime, error) {
|
|
|
22275
23389
|
eventEmitter.emit({ type: "session.idle", sessionId, data: { success: true } });
|
|
22276
23390
|
return;
|
|
22277
23391
|
}
|
|
22278
|
-
|
|
23392
|
+
log16.error("runtime.ended-under-resumed-turn", { sessionId });
|
|
22279
23393
|
session.status = "error";
|
|
22280
23394
|
session.error = error instanceof Error ? error.message : String(error);
|
|
22281
23395
|
session.errorCode = undefined;
|
|
@@ -22440,7 +23554,7 @@ async function runTurnOnRuntime(turn, plan, testHooks) {
|
|
|
22440
23554
|
}
|
|
22441
23555
|
|
|
22442
23556
|
// ../../bridges/claude-bridge/src/services/session-manager-prompt-settle.ts
|
|
22443
|
-
var
|
|
23557
|
+
var log17 = createLogger("bridge.claude");
|
|
22444
23558
|
function settleTurnEnd(turn) {
|
|
22445
23559
|
const { session, sessionId, options, structuredRequestId, abortController, stream, diagnostics } = turn;
|
|
22446
23560
|
diagnostics?.streamSettled("resolved");
|
|
@@ -22562,7 +23676,7 @@ function settleFailedTurn(turn, error) {
|
|
|
22562
23676
|
recordInterruptedStructuredOutputIfCurrent(turn);
|
|
22563
23677
|
return;
|
|
22564
23678
|
}
|
|
22565
|
-
|
|
23679
|
+
log17.error("prompt.failed", { errorClass: diagnosticErrorClass(error) });
|
|
22566
23680
|
if (session.abortController === abortController) {
|
|
22567
23681
|
const killedBy = killedClaudeProcessSignal(error);
|
|
22568
23682
|
const failure = killedBy ? claudeProcessKilledMessage(killedBy) : error instanceof Error ? error.message : String(error);
|
|
@@ -22672,7 +23786,7 @@ function finalizeTurn(turn) {
|
|
|
22672
23786
|
}
|
|
22673
23787
|
|
|
22674
23788
|
// ../../bridges/claude-bridge/src/services/session-manager-prompt.ts
|
|
22675
|
-
var
|
|
23789
|
+
var log18 = createLogger("bridge.claude");
|
|
22676
23790
|
function turnWriterLiveness(turn) {
|
|
22677
23791
|
const tasks = Object.values(turn.session.backgroundTasks ?? {});
|
|
22678
23792
|
if (tasks.some((task) => LIVE_BACKGROUND_TASK_STATUSES.has(task.status)))
|
|
@@ -22715,7 +23829,7 @@ async function sendPrompt(sessionId, prompt, options, testHooks) {
|
|
|
22715
23829
|
try {
|
|
22716
23830
|
await sendPrompt(sessionId, followUp.prompt, followUp.options);
|
|
22717
23831
|
} catch (repromptError) {
|
|
22718
|
-
|
|
23832
|
+
log18.error(followUp.failureEvent, { error: formatLogError(repromptError) });
|
|
22719
23833
|
return Promise.reject(repromptError);
|
|
22720
23834
|
}
|
|
22721
23835
|
} catch (error) {
|
|
@@ -22727,7 +23841,7 @@ async function sendPrompt(sessionId, prompt, options, testHooks) {
|
|
|
22727
23841
|
}
|
|
22728
23842
|
}
|
|
22729
23843
|
// ../../bridges/claude-bridge/src/services/session-manager-close.ts
|
|
22730
|
-
var
|
|
23844
|
+
var log19 = createLogger("bridge.claude");
|
|
22731
23845
|
var CLOSE_CONFIRMATION_BUDGET_MS = 1e4;
|
|
22732
23846
|
|
|
22733
23847
|
class SessionCloseNotConfirmedError extends Error {
|
|
@@ -22790,7 +23904,7 @@ async function closeQueryControls(controls, deadline) {
|
|
|
22790
23904
|
if (await settlesBy(Promise.resolve(control.close()), deadline))
|
|
22791
23905
|
return;
|
|
22792
23906
|
} catch (error) {
|
|
22793
|
-
|
|
23907
|
+
log19.error("query.close-failed", {
|
|
22794
23908
|
errorClass: error instanceof Error ? error.name : typeof error
|
|
22795
23909
|
});
|
|
22796
23910
|
}
|
|
@@ -22810,18 +23924,18 @@ async function settlesBy(work, deadline) {
|
|
|
22810
23924
|
}
|
|
22811
23925
|
}
|
|
22812
23926
|
// ../../bridges/claude-bridge/src/routes/config.ts
|
|
22813
|
-
var
|
|
23927
|
+
var log20 = createLogger("bridge.claude");
|
|
22814
23928
|
var config2 = new Hono2;
|
|
22815
23929
|
config2.get("/models", async (c) => {
|
|
22816
23930
|
if (c.req.query("forceRefresh") === "true")
|
|
22817
23931
|
invalidateClaudeModelCatalog();
|
|
22818
23932
|
const startedAt = Date.now();
|
|
22819
|
-
|
|
23933
|
+
log20.debug("models.requested");
|
|
22820
23934
|
const [{ models, source }, versions] = await Promise.all([
|
|
22821
23935
|
getAvailableModelCatalog(),
|
|
22822
23936
|
getClaudeRuntimeVersions()
|
|
22823
23937
|
]);
|
|
22824
|
-
|
|
23938
|
+
log20.debug("models.responded", { count: models.length, durationMs: Date.now() - startedAt });
|
|
22825
23939
|
const response = {
|
|
22826
23940
|
models,
|
|
22827
23941
|
source,
|
|
@@ -22898,7 +24012,7 @@ function humanPromptObservation(messages, tasks) {
|
|
|
22898
24012
|
}
|
|
22899
24013
|
|
|
22900
24014
|
// ../../bridges/claude-bridge/src/routes/session.ts
|
|
22901
|
-
import { randomUUID as
|
|
24015
|
+
import { randomUUID as randomUUID6 } from "node:crypto";
|
|
22902
24016
|
|
|
22903
24017
|
// ../../node_modules/.bun/hono@4.13.13/node_modules/hono/dist/middleware/body-limit/index.js
|
|
22904
24018
|
var ERROR_MESSAGE = "Payload Too Large";
|
|
@@ -22996,10 +24110,13 @@ function sessionRuntimeHealthBody(session) {
|
|
|
22996
24110
|
mcpConfigReporting: MCP_CONFIG_REPORTING_VERSION,
|
|
22997
24111
|
...session?.mcpConfigRevision ? { mcpConfig: structuredClone(session.mcpConfigRevision) } : {}
|
|
22998
24112
|
};
|
|
22999
|
-
if (!session
|
|
24113
|
+
if (!session)
|
|
23000
24114
|
return { ...emptyRuntimeHealth(), ...mcpConfig };
|
|
24115
|
+
const state = openClaudeRuntime(session) ? "attached" : "detached";
|
|
24116
|
+
if (!session.health)
|
|
24117
|
+
return { ...emptyRuntimeHealth(), summary: { state }, ...mcpConfig };
|
|
23001
24118
|
const { drift, notices } = session.health.snapshot();
|
|
23002
|
-
return { summary: drift ? { drift } : {}, notices, ...mcpConfig };
|
|
24119
|
+
return { summary: { state, ...drift ? { drift } : {} }, notices, ...mcpConfig };
|
|
23003
24120
|
}
|
|
23004
24121
|
|
|
23005
24122
|
// ../protocol/src/node/transcript-window.ts
|
|
@@ -23814,7 +24931,7 @@ function bridgeTranscriptPageRouteBody(source, query) {
|
|
|
23814
24931
|
}
|
|
23815
24932
|
|
|
23816
24933
|
// ../../bridges/claude-bridge/src/routes/session-transcript.ts
|
|
23817
|
-
var
|
|
24934
|
+
var log21 = createLogger("bridge.claude");
|
|
23818
24935
|
function claudeTranscriptSource(id, generation) {
|
|
23819
24936
|
const sessionData = peekSession(id);
|
|
23820
24937
|
if (!sessionData)
|
|
@@ -23867,7 +24984,7 @@ function registerSessionTranscriptRoutes(app, generation, materialize) {
|
|
|
23867
24984
|
const response = c.json(bridgeTranscriptRouteBody(read.source, query3(c)));
|
|
23868
24985
|
if (read.needsHydration) {
|
|
23869
24986
|
hydratePersistedSessionMessages(id).catch((error) => {
|
|
23870
|
-
|
|
24987
|
+
log21.warn("transcript.background-hydrate-failed", {
|
|
23871
24988
|
error: formatLogError(error, { stack: false })
|
|
23872
24989
|
});
|
|
23873
24990
|
});
|
|
@@ -23879,9 +24996,9 @@ function registerSessionTranscriptRoutes(app, generation, materialize) {
|
|
|
23879
24996
|
}
|
|
23880
24997
|
|
|
23881
24998
|
// ../../bridges/claude-bridge/src/routes/session.ts
|
|
23882
|
-
var
|
|
24999
|
+
var log22 = createLogger("bridge.claude");
|
|
23883
25000
|
var session = new Hono2;
|
|
23884
|
-
var TRANSCRIPT_GENERATION =
|
|
25001
|
+
var TRANSCRIPT_GENERATION = randomUUID6();
|
|
23885
25002
|
var MAX_QUESTION_ANSWER_REQUEST_BYTES = AGENT_INTERACTION_LIMITS.maxSerializedPayloadBytes + 1024;
|
|
23886
25003
|
var MAX_CLAUDE_TRANSCRIPT_RESPONSE_BYTES = 16 * 1024 * 1024;
|
|
23887
25004
|
function boundClaudeTranscriptResponse(messages, tailMessages) {
|
|
@@ -23959,7 +25076,7 @@ session.post("/create", async (c) => {
|
|
|
23959
25076
|
const clientSessionKey = body.clientSessionKey;
|
|
23960
25077
|
const policy = effectiveExecutionPolicy(isNativeAgentExecutionPolicy(body.policy) ? body.policy : undefined);
|
|
23961
25078
|
const newSession = policy ? await createOrRecoverSession(title, clientSessionKey, policy) : await createOrRecoverSession(title, clientSessionKey);
|
|
23962
|
-
|
|
25079
|
+
log22.info("session.created", { sessionId: newSession.id });
|
|
23963
25080
|
const response = {
|
|
23964
25081
|
sessionId: newSession.id,
|
|
23965
25082
|
title: newSession.title
|
|
@@ -23967,10 +25084,10 @@ session.post("/create", async (c) => {
|
|
|
23967
25084
|
return c.json(response, 201);
|
|
23968
25085
|
} catch (error) {
|
|
23969
25086
|
if (error instanceof PolicyWideningRefusedError) {
|
|
23970
|
-
|
|
25087
|
+
log22.warn("session.policy-widening-refused", { widened: error.widened.join(",") });
|
|
23971
25088
|
return c.json(error.refusal(), 403);
|
|
23972
25089
|
}
|
|
23973
|
-
|
|
25090
|
+
log22.error("session.create-failed", { error: formatLogError(error) });
|
|
23974
25091
|
return c.json({ error: error instanceof Error ? error.message : "Failed to create session" }, 500);
|
|
23975
25092
|
}
|
|
23976
25093
|
});
|
|
@@ -23978,7 +25095,7 @@ session.get("/list", async (c) => {
|
|
|
23978
25095
|
try {
|
|
23979
25096
|
await reconcilePersistedSessions();
|
|
23980
25097
|
} catch (error) {
|
|
23981
|
-
|
|
25098
|
+
log22.warn("sessions.reconcile-failed", { error: formatLogError(error) });
|
|
23982
25099
|
}
|
|
23983
25100
|
const sessions = listSessions();
|
|
23984
25101
|
const response = {
|
|
@@ -23997,7 +25114,7 @@ async function resolveSession(id, failureMessage) {
|
|
|
23997
25114
|
try {
|
|
23998
25115
|
return { ok: true, session: getSession(id) ?? await ensurePersistedSession(id) };
|
|
23999
25116
|
} catch (error) {
|
|
24000
|
-
|
|
25117
|
+
log22.error("session.resolve-failed", { action: failureMessage, error: formatLogError(error) });
|
|
24001
25118
|
return {
|
|
24002
25119
|
ok: false,
|
|
24003
25120
|
body: { error: errorMessage(error, failureMessage) },
|
|
@@ -24018,7 +25135,7 @@ session.get("/:id", async (c) => {
|
|
|
24018
25135
|
try {
|
|
24019
25136
|
await hydratePersistedSessionMessages(id);
|
|
24020
25137
|
} catch (error) {
|
|
24021
|
-
|
|
25138
|
+
log22.error("session.task-state-hydrate-failed", { error: formatLogError(error) });
|
|
24022
25139
|
return c.json({ error: errorMessage(error, "Failed to hydrate session task state") }, sessionErrorStatus(error));
|
|
24023
25140
|
}
|
|
24024
25141
|
}
|
|
@@ -24070,7 +25187,7 @@ session.get("/:id/usage", async (c) => {
|
|
|
24070
25187
|
const contextUsage = await refreshClaudeContextUsage(resolved.session);
|
|
24071
25188
|
return c.json({ contextUsage });
|
|
24072
25189
|
} catch (error) {
|
|
24073
|
-
|
|
25190
|
+
log22.warn("context-usage.read-failed", { error: formatLogError(error, { stack: false }) });
|
|
24074
25191
|
return c.json({ error: "Context usage is temporarily unavailable" }, 503);
|
|
24075
25192
|
}
|
|
24076
25193
|
});
|
|
@@ -24120,7 +25237,7 @@ session.post("/:id/config", async (c) => {
|
|
|
24120
25237
|
const refusePolicyWidening = () => {
|
|
24121
25238
|
const widened = nextPolicy ? executionPolicyWidenings(sessionData.executionPolicy, nextPolicy) : [];
|
|
24122
25239
|
if (widened.length > 0) {
|
|
24123
|
-
|
|
25240
|
+
log22.warn("session.policy-widening-refused", {
|
|
24124
25241
|
sessionId: sessionData.id,
|
|
24125
25242
|
widened: widened.join(",")
|
|
24126
25243
|
});
|
|
@@ -24161,7 +25278,7 @@ session.get("/:id/commands", async (c) => {
|
|
|
24161
25278
|
try {
|
|
24162
25279
|
return c.json(await readClaudeCommandCatalogue(c.req.param("id")));
|
|
24163
25280
|
} catch (error) {
|
|
24164
|
-
|
|
25281
|
+
log22.warn("commands.read-failed", { error: formatLogError(error, { stack: false }) });
|
|
24165
25282
|
return c.json({ error: errorMessage(error, "Claude command discovery failed") }, 503);
|
|
24166
25283
|
}
|
|
24167
25284
|
});
|
|
@@ -24406,7 +25523,7 @@ session.post("/:id/prompt", async (c) => {
|
|
|
24406
25523
|
rejectStarted?.(sessionOperationError("conflict", "Prompt stopped before launch"));
|
|
24407
25524
|
}, (error) => {
|
|
24408
25525
|
rejectStarted?.(error);
|
|
24409
|
-
|
|
25526
|
+
log22.error("prompt.processing-failed", { error: formatLogError(error) });
|
|
24410
25527
|
});
|
|
24411
25528
|
return { started, completion };
|
|
24412
25529
|
});
|
|
@@ -24420,7 +25537,7 @@ session.post("/:id/prompt", async (c) => {
|
|
|
24420
25537
|
duplicate: true
|
|
24421
25538
|
});
|
|
24422
25539
|
}
|
|
24423
|
-
|
|
25540
|
+
log22.debug("prompt.accepted", { sessionId: id });
|
|
24424
25541
|
return c.json({
|
|
24425
25542
|
status: "processing",
|
|
24426
25543
|
requestId,
|
|
@@ -24433,7 +25550,7 @@ session.post("/:id/prompt", async (c) => {
|
|
|
24433
25550
|
if (sessionData.rewindInProgress === true) {
|
|
24434
25551
|
return c.json({ error: "Session is restoring files from a checkpoint" }, 409);
|
|
24435
25552
|
}
|
|
24436
|
-
|
|
25553
|
+
log22.info("prompt.received", {
|
|
24437
25554
|
sessionId: id,
|
|
24438
25555
|
promptLength: prompt.length,
|
|
24439
25556
|
model,
|
|
@@ -24461,16 +25578,16 @@ session.post("/:id/prompt", async (c) => {
|
|
|
24461
25578
|
...workflowResultTurn ? { workflowResultTurn } : {},
|
|
24462
25579
|
...providerPrompt !== undefined ? { providerPrompt } : {}
|
|
24463
25580
|
}).catch((error) => {
|
|
24464
|
-
|
|
25581
|
+
log22.error("prompt.processing-failed", { error: formatLogError(error) });
|
|
24465
25582
|
});
|
|
24466
|
-
|
|
25583
|
+
log22.debug("prompt.accepted", { sessionId: id });
|
|
24467
25584
|
return c.json({
|
|
24468
25585
|
status: "processing",
|
|
24469
25586
|
requestId,
|
|
24470
25587
|
turnStartedAt: sessionData.turnStartedAt
|
|
24471
25588
|
}, 202);
|
|
24472
25589
|
} catch (error) {
|
|
24473
|
-
|
|
25590
|
+
log22.error("prompt.send-failed", { error: formatLogError(error) });
|
|
24474
25591
|
return c.json({ error: errorMessage(error, "Failed to send prompt") }, sessionErrorStatus(error));
|
|
24475
25592
|
}
|
|
24476
25593
|
});
|
|
@@ -24514,7 +25631,7 @@ session.delete("/:id", async (c) => {
|
|
|
24514
25631
|
}
|
|
24515
25632
|
return c.json({ error: "Session not found" }, 404);
|
|
24516
25633
|
} catch (error) {
|
|
24517
|
-
|
|
25634
|
+
log22.error("session.delete-failed", { error: formatLogError(error) });
|
|
24518
25635
|
return c.json({ error: errorMessage(error, "Failed to delete session") }, sessionErrorStatus(error));
|
|
24519
25636
|
}
|
|
24520
25637
|
});
|
|
@@ -24529,7 +25646,7 @@ session.post("/:id/rename", async (c) => {
|
|
|
24529
25646
|
const renamed = await renameSessionDurably(id, title);
|
|
24530
25647
|
return renamed ? c.json({ status: "renamed", title }) : c.json({ error: "Session not found" }, 404);
|
|
24531
25648
|
} catch (error) {
|
|
24532
|
-
|
|
25649
|
+
log22.error("session.rename-failed", { error: formatLogError(error) });
|
|
24533
25650
|
return c.json({ error: errorMessage(error, "Failed to rename session") }, sessionErrorStatus(error));
|
|
24534
25651
|
}
|
|
24535
25652
|
});
|
|
@@ -24558,7 +25675,7 @@ session.post("/:id/fork", async (c) => {
|
|
|
24558
25675
|
title: forked.title
|
|
24559
25676
|
}, 201);
|
|
24560
25677
|
} catch (error) {
|
|
24561
|
-
|
|
25678
|
+
log22.error("session.fork-failed", { error: formatLogError(error) });
|
|
24562
25679
|
return c.json({ error: errorMessage(error, "Failed to fork session") }, sessionErrorStatus(error));
|
|
24563
25680
|
}
|
|
24564
25681
|
});
|
|
@@ -24590,7 +25707,7 @@ session.post("/:id/compact", compactBodyLimit, async (c) => {
|
|
|
24590
25707
|
}
|
|
24591
25708
|
const { instructions } = parsed;
|
|
24592
25709
|
sendPrompt(id, instructions ? `/compact ${instructions}` : "/compact").catch((error) => {
|
|
24593
|
-
|
|
25710
|
+
log22.error("session.compact-failed", { error: formatLogError(error) });
|
|
24594
25711
|
});
|
|
24595
25712
|
return c.json(instructions ? { status: "processing", instructions: "applied" } : { status: "processing" }, 202);
|
|
24596
25713
|
});
|
|
@@ -24608,7 +25725,7 @@ session.post("/:id/rewind", async (c) => {
|
|
|
24608
25725
|
const result = await rewindSessionFiles(id, messageId, dryRun);
|
|
24609
25726
|
return c.json({ status: dryRun ? "previewed" : "rewound", result });
|
|
24610
25727
|
} catch (error) {
|
|
24611
|
-
|
|
25728
|
+
log22.error("session.rewind-failed", { error: formatLogError(error) });
|
|
24612
25729
|
return c.json({ error: errorMessage(error, "Failed to rewind session files") }, sessionErrorStatus(error));
|
|
24613
25730
|
}
|
|
24614
25731
|
});
|
|
@@ -24619,7 +25736,7 @@ session.post("/:id/tasks/:taskId/stop", async (c) => {
|
|
|
24619
25736
|
return c.json({ status: "stopped" });
|
|
24620
25737
|
return c.json({ error: stopped.message }, stopped.reason === "no_control_channel" ? 409 : 404);
|
|
24621
25738
|
} catch (error) {
|
|
24622
|
-
|
|
25739
|
+
log22.error("task.stop-route-failed", { error: formatLogError(error) });
|
|
24623
25740
|
return c.json({ error: errorMessage(error, "Failed to stop background task") }, sessionErrorStatus(error));
|
|
24624
25741
|
}
|
|
24625
25742
|
});
|
|
@@ -24690,7 +25807,7 @@ session.post("/:id/questions/:questionId/answer", questionAnswerBodyLimit, async
|
|
|
24690
25807
|
const pendingQuestions = getPendingQuestions(sessionId);
|
|
24691
25808
|
const pendingQuestion = pendingQuestions.find((q) => q.id === questionId);
|
|
24692
25809
|
if (!pendingQuestion) {
|
|
24693
|
-
|
|
25810
|
+
log22.info("question.stale", { questionId });
|
|
24694
25811
|
return c.json(stalePrompt("Question is no longer pending"), STALE_PROMPT_STATUS);
|
|
24695
25812
|
}
|
|
24696
25813
|
if (!isBoundedClaudeQuestionAnswers(answersArray, pendingQuestion.questions.length)) {
|
|
@@ -24701,7 +25818,7 @@ session.post("/:id/questions/:questionId/answer", questionAnswerBodyLimit, async
|
|
|
24701
25818
|
const questionAnswers = answersArray[index] || [];
|
|
24702
25819
|
answersRecord[q.question] = serializeClaudeQuestionAnswer(questionAnswers, q.multiSelect === true);
|
|
24703
25820
|
});
|
|
24704
|
-
|
|
25821
|
+
log22.debug("question.answers-prepared", {
|
|
24705
25822
|
questionId,
|
|
24706
25823
|
questionCount: pendingQuestion.questions.length,
|
|
24707
25824
|
answerCount: answersArray.reduce((count, answers) => count + answers.length, 0)
|
|
@@ -24713,7 +25830,7 @@ session.post("/:id/questions/:questionId/answer", questionAnswerBodyLimit, async
|
|
|
24713
25830
|
return c.json(stalePrompt("Question is no longer pending"), STALE_PROMPT_STATUS);
|
|
24714
25831
|
}
|
|
24715
25832
|
} catch (error) {
|
|
24716
|
-
|
|
25833
|
+
log22.error("question.answer-failed", { error: formatLogError(error) });
|
|
24717
25834
|
return c.json({ error: error instanceof Error ? error.message : "Failed to answer question" }, 500);
|
|
24718
25835
|
}
|
|
24719
25836
|
});
|
|
@@ -24753,7 +25870,7 @@ session.post("/:id/plan-approvals/:approvalId/respond", planApprovalBodyLimit, a
|
|
|
24753
25870
|
if (approved && (typeof pendingApproval.plan !== "string" || pendingApproval.plan.trim().length === 0 || pendingApproval.planTruncated === true)) {
|
|
24754
25871
|
return c.json({ error: "A complete plan is required before approval", status: "rejected" }, 409);
|
|
24755
25872
|
}
|
|
24756
|
-
|
|
25873
|
+
log22.info("plan-approval.response-received", {
|
|
24757
25874
|
sessionId,
|
|
24758
25875
|
approvalId,
|
|
24759
25876
|
approved,
|
|
@@ -24766,7 +25883,7 @@ session.post("/:id/plan-approvals/:approvalId/respond", planApprovalBodyLimit, a
|
|
|
24766
25883
|
return c.json(stalePrompt("Plan approval is no longer pending"), STALE_PROMPT_STATUS);
|
|
24767
25884
|
}
|
|
24768
25885
|
} catch (error) {
|
|
24769
|
-
|
|
25886
|
+
log22.error("plan-approval.response-failed", { error: formatLogError(error) });
|
|
24770
25887
|
return c.json({ error: error instanceof Error ? error.message : "Failed to respond to plan approval" }, 500);
|
|
24771
25888
|
}
|
|
24772
25889
|
});
|
|
@@ -25165,7 +26282,7 @@ class EventRing {
|
|
|
25165
26282
|
}
|
|
25166
26283
|
|
|
25167
26284
|
// ../../bridges/claude-bridge/src/routes/events.ts
|
|
25168
|
-
var
|
|
26285
|
+
var log23 = createLogger("bridge.claude");
|
|
25169
26286
|
var serializedEvents = new WeakMap;
|
|
25170
26287
|
function serializeEvent(event) {
|
|
25171
26288
|
let serialized = serializedEvents.get(event);
|
|
@@ -25371,10 +26488,10 @@ function createEventsRouter(limits = {}) {
|
|
|
25371
26488
|
events.get("/subscribe", (c) => {
|
|
25372
26489
|
const origin = c.req.header("origin");
|
|
25373
26490
|
const userAgent = c.req.header("user-agent");
|
|
25374
|
-
|
|
26491
|
+
log23.debug("sse.subscribe-requested", { origin, userAgent });
|
|
25375
26492
|
return streamSSE(c, async (stream) => {
|
|
25376
26493
|
const connectedAt = new Date().toISOString();
|
|
25377
|
-
|
|
26494
|
+
log23.debug("sse.opened", { connectedAt });
|
|
25378
26495
|
let isOpen = true;
|
|
25379
26496
|
let resolveConnectionClosed;
|
|
25380
26497
|
const connectionClosed = new Promise((resolve) => {
|
|
@@ -25385,7 +26502,7 @@ function createEventsRouter(limits = {}) {
|
|
|
25385
26502
|
resolveRequestAborted = resolve;
|
|
25386
26503
|
});
|
|
25387
26504
|
const onRequestAbort = () => {
|
|
25388
|
-
|
|
26505
|
+
log23.debug("sse.aborted");
|
|
25389
26506
|
isOpen = false;
|
|
25390
26507
|
resolveRequestAborted();
|
|
25391
26508
|
};
|
|
@@ -25399,7 +26516,7 @@ function createEventsRouter(limits = {}) {
|
|
|
25399
26516
|
if (!isOpen)
|
|
25400
26517
|
return;
|
|
25401
26518
|
isOpen = false;
|
|
25402
|
-
|
|
26519
|
+
log23.info("sse.closed", { reason });
|
|
25403
26520
|
resolveConnectionClosed();
|
|
25404
26521
|
};
|
|
25405
26522
|
const writeFrame = createBoundedSseWriter(async (frame) => {
|
|
@@ -25450,7 +26567,7 @@ function createEventsRouter(limits = {}) {
|
|
|
25450
26567
|
}
|
|
25451
26568
|
writeFrame(frame).catch((error) => {
|
|
25452
26569
|
if (!c.req.raw.signal.aborted) {
|
|
25453
|
-
|
|
26570
|
+
log23.warn("sse.write-failed", { error: formatLogError(error) });
|
|
25454
26571
|
closeConnection("write failed");
|
|
25455
26572
|
}
|
|
25456
26573
|
});
|
|
@@ -25512,7 +26629,7 @@ function createEventsRouter(limits = {}) {
|
|
|
25512
26629
|
data: JSON.stringify({ timestamp: new Date().toISOString() })
|
|
25513
26630
|
}).catch((error) => {
|
|
25514
26631
|
if (!c.req.raw.signal.aborted) {
|
|
25515
|
-
|
|
26632
|
+
log23.warn("sse.keepalive-failed", { error: formatLogError(error, { stack: false }) });
|
|
25516
26633
|
closeConnection("keepalive failed");
|
|
25517
26634
|
}
|
|
25518
26635
|
});
|
|
@@ -25520,10 +26637,10 @@ function createEventsRouter(limits = {}) {
|
|
|
25520
26637
|
await Promise.race([connectionClosed, requestAborted]);
|
|
25521
26638
|
} catch (error) {
|
|
25522
26639
|
if (!c.req.raw.signal.aborted) {
|
|
25523
|
-
|
|
26640
|
+
log23.warn("sse.handshake-failed", { error: formatLogError(error) });
|
|
25524
26641
|
}
|
|
25525
26642
|
} finally {
|
|
25526
|
-
|
|
26643
|
+
log23.debug("sse.cleanup");
|
|
25527
26644
|
isOpen = false;
|
|
25528
26645
|
c.req.raw.signal.removeEventListener("abort", onRequestAbort);
|
|
25529
26646
|
if (keepaliveInterval)
|
|
@@ -25539,7 +26656,7 @@ var events = createEventsRouter();
|
|
|
25539
26656
|
var events_default = events;
|
|
25540
26657
|
|
|
25541
26658
|
// ../../bridges/claude-bridge/src/routes/mcp.ts
|
|
25542
|
-
var
|
|
26659
|
+
var log24 = createLogger("bridge.claude");
|
|
25543
26660
|
var mcp = new Hono2;
|
|
25544
26661
|
mcp.get("/servers", async (c) => {
|
|
25545
26662
|
try {
|
|
@@ -25550,14 +26667,14 @@ mcp.get("/servers", async (c) => {
|
|
|
25550
26667
|
cwd
|
|
25551
26668
|
});
|
|
25552
26669
|
} catch (error) {
|
|
25553
|
-
|
|
26670
|
+
log24.error("mcp.read-failed", { error: formatLogError(error) });
|
|
25554
26671
|
return c.json({ error: error instanceof Error ? error.message : "Failed to get MCP servers" }, 500);
|
|
25555
26672
|
}
|
|
25556
26673
|
});
|
|
25557
26674
|
var mcp_default = mcp;
|
|
25558
26675
|
|
|
25559
26676
|
// ../../bridges/claude-bridge/src/routes/plugins.ts
|
|
25560
|
-
var
|
|
26677
|
+
var log25 = createLogger("bridge.claude");
|
|
25561
26678
|
var plugins = new Hono2;
|
|
25562
26679
|
plugins.get("/", async (c) => {
|
|
25563
26680
|
try {
|
|
@@ -25568,7 +26685,7 @@ plugins.get("/", async (c) => {
|
|
|
25568
26685
|
cwd
|
|
25569
26686
|
});
|
|
25570
26687
|
} catch (error) {
|
|
25571
|
-
|
|
26688
|
+
log25.error("plugins.read-failed", { error: formatLogError(error) });
|
|
25572
26689
|
return c.json({ error: error instanceof Error ? error.message : "Failed to get plugins" }, 500);
|
|
25573
26690
|
}
|
|
25574
26691
|
});
|
|
@@ -25761,9 +26878,9 @@ function installFatalRejectionGuard(options) {
|
|
|
25761
26878
|
}
|
|
25762
26879
|
|
|
25763
26880
|
// ../protocol/src/node/process-failure-log.ts
|
|
25764
|
-
var
|
|
26881
|
+
var log26 = createLogger("process");
|
|
25765
26882
|
function logUnhandledRejection(reason) {
|
|
25766
|
-
|
|
26883
|
+
log26.throttled("error", "rejection.unhandled", {
|
|
25767
26884
|
error: reason,
|
|
25768
26885
|
fields: () => ({ error: formatLogError(reason, { message: false }) })
|
|
25769
26886
|
});
|
|
@@ -25774,7 +26891,7 @@ var X_ALREADY_SENT = "x-hono-already-sent";
|
|
|
25774
26891
|
|
|
25775
26892
|
// ../../node_modules/.bun/@hono+node-server@2.1.5+c539cad7f494f5c9/node_modules/@hono/node-server/dist/index.mjs
|
|
25776
26893
|
import { STATUS_CODES, ServerResponse, createServer } from "node:http";
|
|
25777
|
-
import { Http2ServerRequest, constants as
|
|
26894
|
+
import { Http2ServerRequest, constants as constants4 } from "node:http2";
|
|
25778
26895
|
import { Readable } from "node:stream";
|
|
25779
26896
|
|
|
25780
26897
|
// ../../node_modules/.bun/hono@4.13.13/node_modules/hono/dist/helper/websocket/index.js
|
|
@@ -26693,7 +27810,7 @@ var drainIncoming = (incoming) => {
|
|
|
26693
27810
|
incomingWithDrainState[incomingDraining] = true;
|
|
26694
27811
|
if (incoming instanceof Http2ServerRequest) {
|
|
26695
27812
|
try {
|
|
26696
|
-
incoming.stream?.close?.(
|
|
27813
|
+
incoming.stream?.close?.(constants4.NGHTTP2_NO_ERROR);
|
|
26697
27814
|
} catch {}
|
|
26698
27815
|
return;
|
|
26699
27816
|
}
|
|
@@ -27254,36 +28371,221 @@ var serve = (options, listeningListener) => {
|
|
|
27254
28371
|
};
|
|
27255
28372
|
|
|
27256
28373
|
// ../protocol/src/node/bridge-credential.ts
|
|
27257
|
-
import { createHash as
|
|
27258
|
-
import { createRequire } from "node:module";
|
|
28374
|
+
import { createHash as createHash14, randomBytes as randomBytes3, timingSafeEqual } from "node:crypto";
|
|
28375
|
+
import { createRequire as createRequire2 } from "node:module";
|
|
28376
|
+
|
|
28377
|
+
// ../protocol/src/node/bridge-authority.ts
|
|
28378
|
+
import {
|
|
28379
|
+
createHash as createHash13,
|
|
28380
|
+
createPrivateKey,
|
|
28381
|
+
createPublicKey,
|
|
28382
|
+
generateKeyPairSync,
|
|
28383
|
+
randomBytes as randomBytes2,
|
|
28384
|
+
sign,
|
|
28385
|
+
verify
|
|
28386
|
+
} from "node:crypto";
|
|
28387
|
+
var BRIDGE_AUTHORITY_HEADER = "x-orkestrator-authority";
|
|
28388
|
+
var BRIDGE_AUTHORITY_REFUSED_CODE = "authority-signature-required";
|
|
28389
|
+
var BRIDGE_AUTHORITY_WINDOW_MS = 5 * 60000;
|
|
28390
|
+
var BRIDGE_AUTHORITY_MAX_NONCES = 8192;
|
|
28391
|
+
var BRIDGE_AUTHORITY_MAX_BODY_BYTES = 64 * 1024 * 1024;
|
|
28392
|
+
var SCHEME = "orkestrator-bridge-authority-v1";
|
|
28393
|
+
var KEY_PATTERN = /^[A-Za-z0-9_-]{40,200}$/;
|
|
28394
|
+
var HEADER_PATTERN = /^v1 t=(\d{1,16}) n=([A-Za-z0-9_-]{22}) s=([A-Za-z0-9_-]{86})$/;
|
|
28395
|
+
var READ_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
|
|
28396
|
+
var UNSIGNED_ROUTES = [
|
|
28397
|
+
/^\/session\/[^/]+\/close$/,
|
|
28398
|
+
/^\/sessions\/activity$/,
|
|
28399
|
+
/^\/debug\/log-policy$/
|
|
28400
|
+
];
|
|
28401
|
+
function bridgeAuthorityKeyEnv(tokenEnv) {
|
|
28402
|
+
return `${tokenEnv}_AUTHORITY_KEY`;
|
|
28403
|
+
}
|
|
28404
|
+
function isBridgeAuthorityKey(value) {
|
|
28405
|
+
return typeof value === "string" && KEY_PATTERN.test(value);
|
|
28406
|
+
}
|
|
28407
|
+
function publicKeyFrom(encoded) {
|
|
28408
|
+
if (!isBridgeAuthorityKey(encoded))
|
|
28409
|
+
return null;
|
|
28410
|
+
try {
|
|
28411
|
+
const key = createPublicKey({
|
|
28412
|
+
key: Buffer.from(encoded, "base64url"),
|
|
28413
|
+
format: "der",
|
|
28414
|
+
type: "spki"
|
|
28415
|
+
});
|
|
28416
|
+
return key.asymmetricKeyType === "ed25519" ? key : null;
|
|
28417
|
+
} catch {
|
|
28418
|
+
return null;
|
|
28419
|
+
}
|
|
28420
|
+
}
|
|
28421
|
+
function bridgeAuthorityTarget(url) {
|
|
28422
|
+
const parsed = new URL(url, "http://bridge.invalid");
|
|
28423
|
+
return `${parsed.pathname}${parsed.search}`;
|
|
28424
|
+
}
|
|
28425
|
+
function bridgeRequestNeedsAuthority(method, target) {
|
|
28426
|
+
if (READ_METHODS.has(method.toUpperCase()))
|
|
28427
|
+
return false;
|
|
28428
|
+
const pathname = bridgeAuthorityTarget(target).split("?", 1)[0];
|
|
28429
|
+
return !UNSIGNED_ROUTES.some((pattern) => pattern.test(pathname));
|
|
28430
|
+
}
|
|
28431
|
+
function bodyDigest(body) {
|
|
28432
|
+
return createHash13("sha256").update(body ?? "").digest("hex");
|
|
28433
|
+
}
|
|
28434
|
+
function signedMessage(method, target, issuedAt, nonce, digest) {
|
|
28435
|
+
return Buffer.from([SCHEME, method.toUpperCase(), target, String(issuedAt), nonce, digest].join(`
|
|
28436
|
+
`));
|
|
28437
|
+
}
|
|
28438
|
+
var UNENFORCED = {
|
|
28439
|
+
enforced: false,
|
|
28440
|
+
requires: () => false,
|
|
28441
|
+
check: () => ({ ok: true })
|
|
28442
|
+
};
|
|
28443
|
+
function bridgeAuthorityFromPublicKey(publicKey, options = {}) {
|
|
28444
|
+
if (publicKey === undefined)
|
|
28445
|
+
return UNENFORCED;
|
|
28446
|
+
const key = publicKeyFrom(publicKey);
|
|
28447
|
+
const now = options.now ?? Date.now;
|
|
28448
|
+
const maxNonces = options.maxNonces ?? BRIDGE_AUTHORITY_MAX_NONCES;
|
|
28449
|
+
const seen = new Map;
|
|
28450
|
+
let floor = -Infinity;
|
|
28451
|
+
const remember = (nonce, issuedAt, current) => {
|
|
28452
|
+
for (const [oldNonce, oldIssuedAt] of seen) {
|
|
28453
|
+
if (seen.size < maxNonces && oldIssuedAt >= current - BRIDGE_AUTHORITY_WINDOW_MS)
|
|
28454
|
+
break;
|
|
28455
|
+
seen.delete(oldNonce);
|
|
28456
|
+
floor = Math.max(floor, oldIssuedAt);
|
|
28457
|
+
}
|
|
28458
|
+
seen.set(nonce, issuedAt);
|
|
28459
|
+
};
|
|
28460
|
+
return {
|
|
28461
|
+
enforced: true,
|
|
28462
|
+
requires: bridgeRequestNeedsAuthority,
|
|
28463
|
+
check(request) {
|
|
28464
|
+
if (!request.header)
|
|
28465
|
+
return { ok: false, reason: "missing" };
|
|
28466
|
+
const match = HEADER_PATTERN.exec(request.header.trim());
|
|
28467
|
+
if (!match)
|
|
28468
|
+
return { ok: false, reason: "malformed" };
|
|
28469
|
+
const issuedAt = Number(match[1]);
|
|
28470
|
+
const nonce = match[2];
|
|
28471
|
+
const current = now();
|
|
28472
|
+
if (Math.abs(current - issuedAt) > BRIDGE_AUTHORITY_WINDOW_MS || issuedAt <= floor) {
|
|
28473
|
+
return { ok: false, reason: "stale" };
|
|
28474
|
+
}
|
|
28475
|
+
if (!key)
|
|
28476
|
+
return { ok: false, reason: "invalid" };
|
|
28477
|
+
const valid = verify(null, signedMessage(request.method, bridgeAuthorityTarget(request.url), issuedAt, nonce, bodyDigest(request.body)), key, Buffer.from(match[3], "base64url"));
|
|
28478
|
+
if (!valid)
|
|
28479
|
+
return { ok: false, reason: "invalid" };
|
|
28480
|
+
if (seen.has(nonce))
|
|
28481
|
+
return { ok: false, reason: "replayed" };
|
|
28482
|
+
remember(nonce, issuedAt, current);
|
|
28483
|
+
return { ok: true };
|
|
28484
|
+
}
|
|
28485
|
+
};
|
|
28486
|
+
}
|
|
28487
|
+
function loadBridgeAuthority(tokenEnv, options = {}) {
|
|
28488
|
+
const env = options.env ?? process.env;
|
|
28489
|
+
const name = bridgeAuthorityKeyEnv(tokenEnv);
|
|
28490
|
+
const value = env[name]?.trim();
|
|
28491
|
+
delete env[name];
|
|
28492
|
+
return bridgeAuthorityFromPublicKey(value || undefined, { now: options.now });
|
|
28493
|
+
}
|
|
28494
|
+
function refusal(reason) {
|
|
28495
|
+
return {
|
|
28496
|
+
status: 403,
|
|
28497
|
+
body: {
|
|
28498
|
+
error: "This request changes an agent's authority and needs the backend's signature",
|
|
28499
|
+
code: BRIDGE_AUTHORITY_REFUSED_CODE,
|
|
28500
|
+
reason
|
|
28501
|
+
}
|
|
28502
|
+
};
|
|
28503
|
+
}
|
|
28504
|
+
var TOO_LARGE = {
|
|
28505
|
+
status: 413,
|
|
28506
|
+
body: { error: "Request body is too large" }
|
|
28507
|
+
};
|
|
28508
|
+
var admittedBodies = new WeakMap;
|
|
28509
|
+
async function readBounded(request, maxBodyBytes) {
|
|
28510
|
+
const declared = Number(request.headers.get("content-length") ?? NaN);
|
|
28511
|
+
if (Number.isFinite(declared) && declared > maxBodyBytes)
|
|
28512
|
+
return null;
|
|
28513
|
+
if (!request.body)
|
|
28514
|
+
return new Uint8Array;
|
|
28515
|
+
const reader = request.body.getReader();
|
|
28516
|
+
const chunks = [];
|
|
28517
|
+
let total = 0;
|
|
28518
|
+
for (;; ) {
|
|
28519
|
+
const { done, value } = await reader.read();
|
|
28520
|
+
if (done)
|
|
28521
|
+
break;
|
|
28522
|
+
total += value.byteLength;
|
|
28523
|
+
if (total > maxBodyBytes) {
|
|
28524
|
+
await reader.cancel().catch(() => {
|
|
28525
|
+
return;
|
|
28526
|
+
});
|
|
28527
|
+
return null;
|
|
28528
|
+
}
|
|
28529
|
+
chunks.push(value);
|
|
28530
|
+
}
|
|
28531
|
+
return Buffer.concat(chunks);
|
|
28532
|
+
}
|
|
28533
|
+
async function admitFetchBridgeRequest(authority, original, maxBodyBytes = BRIDGE_AUTHORITY_MAX_BODY_BYTES) {
|
|
28534
|
+
if (!authority.requires(original.method, original.url))
|
|
28535
|
+
return {};
|
|
28536
|
+
const header = original.headers.get(BRIDGE_AUTHORITY_HEADER);
|
|
28537
|
+
if (!header)
|
|
28538
|
+
return { refusal: refusal("missing") };
|
|
28539
|
+
const body = await readBounded(original, maxBodyBytes);
|
|
28540
|
+
if (!body)
|
|
28541
|
+
return { refusal: TOO_LARGE };
|
|
28542
|
+
const result = authority.check({ method: original.method, url: original.url, header, body });
|
|
28543
|
+
if (!result.ok)
|
|
28544
|
+
return { refusal: refusal(result.reason) };
|
|
28545
|
+
const headers = new Headers(original.headers);
|
|
28546
|
+
headers.set("content-length", String(body.byteLength));
|
|
28547
|
+
headers.delete("transfer-encoding");
|
|
28548
|
+
return {
|
|
28549
|
+
request: new Request(original.url, {
|
|
28550
|
+
method: original.method,
|
|
28551
|
+
headers,
|
|
28552
|
+
body: body.byteLength > 0 ? new Uint8Array(body) : undefined,
|
|
28553
|
+
signal: original.signal
|
|
28554
|
+
})
|
|
28555
|
+
};
|
|
28556
|
+
}
|
|
28557
|
+
|
|
28558
|
+
// ../protocol/src/node/bridge-credential.ts
|
|
27259
28559
|
var BRIDGE_TOKEN_PREFIX = "okb_";
|
|
27260
28560
|
var PR_SET_DUMPABLE = 4;
|
|
27261
28561
|
var VERIFIER_PATTERN = /^[0-9a-f]{64}$/;
|
|
27262
|
-
var
|
|
28562
|
+
var log27 = createLogger("bridge.lifecycle");
|
|
27263
28563
|
function mintBridgeToken() {
|
|
27264
|
-
return `${BRIDGE_TOKEN_PREFIX}${
|
|
28564
|
+
return `${BRIDGE_TOKEN_PREFIX}${randomBytes3(32).toString("base64url")}`;
|
|
27265
28565
|
}
|
|
27266
28566
|
function bridgeTokenVerifier(token) {
|
|
27267
|
-
return
|
|
28567
|
+
return createHash14("sha256").update(token).digest("hex");
|
|
27268
28568
|
}
|
|
27269
28569
|
function bridgeTokenVerifierEnv(tokenEnv) {
|
|
27270
28570
|
return `${tokenEnv}_SHA256`;
|
|
27271
28571
|
}
|
|
27272
|
-
function credentialFromVerifier(verifier, plainToken) {
|
|
28572
|
+
function credentialFromVerifier(verifier, plainToken, authority = UNENFORCED_AUTHORITY) {
|
|
27273
28573
|
const expected = Buffer.from(verifier, "hex");
|
|
27274
28574
|
return {
|
|
27275
28575
|
plainToken,
|
|
28576
|
+
authority,
|
|
27276
28577
|
matches(candidate) {
|
|
27277
28578
|
if (!candidate)
|
|
27278
28579
|
return false;
|
|
27279
|
-
return timingSafeEqual(expected,
|
|
28580
|
+
return timingSafeEqual(expected, createHash14("sha256").update(candidate).digest());
|
|
27280
28581
|
}
|
|
27281
28582
|
};
|
|
27282
28583
|
}
|
|
27283
|
-
|
|
27284
|
-
|
|
28584
|
+
var UNENFORCED_AUTHORITY = loadBridgeAuthority("", { env: {} });
|
|
28585
|
+
function bridgeCredentialFromToken(token, authority = UNENFORCED_AUTHORITY) {
|
|
28586
|
+
return credentialFromVerifier(bridgeTokenVerifier(token), token, authority);
|
|
27285
28587
|
}
|
|
27286
|
-
function markProcessNonDumpable(loadFfi = () =>
|
|
28588
|
+
function markProcessNonDumpable(loadFfi = () => createRequire2(import.meta.url)("bun:ffi")) {
|
|
27287
28589
|
if (process.platform !== "linux" || !process.versions.bun)
|
|
27288
28590
|
return false;
|
|
27289
28591
|
try {
|
|
@@ -27300,9 +28602,9 @@ function markProcessNonDumpable(loadFfi = () => createRequire(import.meta.url)("
|
|
|
27300
28602
|
} finally {
|
|
27301
28603
|
libc.close();
|
|
27302
28604
|
}
|
|
27303
|
-
|
|
28605
|
+
log27.warn("credential.not-hardened", { reason: "prctl-refused" });
|
|
27304
28606
|
} catch {
|
|
27305
|
-
|
|
28607
|
+
log27.warn("credential.not-hardened", { reason: "ffi-unavailable" });
|
|
27306
28608
|
}
|
|
27307
28609
|
return false;
|
|
27308
28610
|
}
|
|
@@ -27313,19 +28615,20 @@ function loadBridgeCredential(tokenEnv, options = {}) {
|
|
|
27313
28615
|
const token = env[tokenEnv]?.trim();
|
|
27314
28616
|
delete env[verifierEnv];
|
|
27315
28617
|
delete env[tokenEnv];
|
|
28618
|
+
const authority = loadBridgeAuthority(tokenEnv, { env });
|
|
27316
28619
|
if (verifier) {
|
|
27317
28620
|
(options.harden ?? markProcessNonDumpable)();
|
|
27318
|
-
return VERIFIER_PATTERN.test(verifier) ? credentialFromVerifier(verifier, undefined) : bridgeCredentialFromToken(mintBridgeToken());
|
|
28621
|
+
return VERIFIER_PATTERN.test(verifier) ? credentialFromVerifier(verifier, undefined, authority) : bridgeCredentialFromToken(mintBridgeToken(), authority);
|
|
27319
28622
|
}
|
|
27320
|
-
return bridgeCredentialFromToken(token || mintBridgeToken());
|
|
28623
|
+
return bridgeCredentialFromToken(token || mintBridgeToken(), authority);
|
|
27321
28624
|
}
|
|
27322
28625
|
|
|
27323
28626
|
// ../../bridges/claude-bridge/src/index.ts
|
|
27324
|
-
var
|
|
28627
|
+
var log28 = createLogger("bridge.claude");
|
|
27325
28628
|
configureBridgeLogger();
|
|
27326
28629
|
var app = new Hono2;
|
|
27327
28630
|
app.onError((error, c) => {
|
|
27328
|
-
|
|
28631
|
+
log28.error("http.request-failed", {
|
|
27329
28632
|
method: c.req.method,
|
|
27330
28633
|
path: c.req.path,
|
|
27331
28634
|
error: formatLogError(error)
|
|
@@ -27392,6 +28695,12 @@ app.use("*", async (c, next) => {
|
|
|
27392
28695
|
if (!tokenMatches(dedicatedHeaderToken) && !tokenMatches(headerToken) && !tokenMatches(eventToken)) {
|
|
27393
28696
|
return c.json({ error: "Unauthorized" }, 401);
|
|
27394
28697
|
}
|
|
28698
|
+
const admission = await admitFetchBridgeRequest(bridgeCredential.authority, c.req.raw);
|
|
28699
|
+
if ("refusal" in admission) {
|
|
28700
|
+
return c.json(admission.refusal.body, admission.refusal.status);
|
|
28701
|
+
}
|
|
28702
|
+
if (admission.request)
|
|
28703
|
+
c.req.raw = admission.request;
|
|
27395
28704
|
}
|
|
27396
28705
|
await next();
|
|
27397
28706
|
});
|
|
@@ -27448,7 +28757,7 @@ if (parentPid !== null) {
|
|
|
27448
28757
|
startParentWatchdog({
|
|
27449
28758
|
parentPid,
|
|
27450
28759
|
onParentExit: () => {
|
|
27451
|
-
|
|
28760
|
+
log28.warn("parent.gone", { parentPid });
|
|
27452
28761
|
process.exit(0);
|
|
27453
28762
|
}
|
|
27454
28763
|
});
|
|
@@ -27459,13 +28768,13 @@ function startBridgeServer(env = process.env, start = serve) {
|
|
|
27459
28768
|
}
|
|
27460
28769
|
const port = parseInt(env.PORT || "4097", 10);
|
|
27461
28770
|
const hostname = env.HOSTNAME || "0.0.0.0";
|
|
27462
|
-
|
|
28771
|
+
log28.debug("server.starting", { hostname, port });
|
|
27463
28772
|
const server = start({
|
|
27464
28773
|
fetch: app.fetch,
|
|
27465
28774
|
port,
|
|
27466
28775
|
hostname
|
|
27467
28776
|
});
|
|
27468
|
-
|
|
28777
|
+
log28.info("server.listening", { hostname, port });
|
|
27469
28778
|
return server;
|
|
27470
28779
|
}
|
|
27471
28780
|
var __testing = {
|