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.
@@ -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/node/bridge-diagnostics.ts
2
74
  import { createHash } from "node:crypto";
3
75
 
@@ -44,7 +116,7 @@ var MAX_FRAME_CHARS = 240;
44
116
  var MAX_RAW_FRAME_CHARS = 1024;
45
117
  var MAX_CAUSE_DEPTH = 2;
46
118
  var TRUNCATED_MARKER = "...[truncated]";
47
- var NAME_PATTERN = /^[A-Za-z_$][\w$.-]{0,63}$/;
119
+ var NAME_PATTERN2 = /^[A-Za-z_$][\w$.-]{0,63}$/;
48
120
  var CODE_PATTERN = /^[\w.:-]{1,64}$/;
49
121
  var SYSCALL_PATTERN = /^[\w./ -]{1,128}$/;
50
122
  var COMMAND_OUTPUT_FIELDS = ["stdout", "stderr", "cmd", "spawnargs"];
@@ -122,7 +194,7 @@ function describe(error, includeStack, includeMessage, depth) {
122
194
  if (!(error instanceof Error) && typeof rawMessage !== "string") {
123
195
  return { name: "NonError", message: "[object]" };
124
196
  }
125
- const name = matching(read(error, "name"), NAME_PATTERN) ?? "Error";
197
+ const name = matching(read(error, "name"), NAME_PATTERN2) ?? "Error";
126
198
  const message = typeof rawMessage === "string" ? rawMessage : undefined;
127
199
  const commandFailure = isCommandFailure(error, name, message);
128
200
  const stackHoldsMessage = message !== undefined && String(read(error, "stack") ?? "").includes(message);
@@ -177,7 +249,7 @@ function logErrorKind(error) {
177
249
  const safeCode = finite(code) ?? matching(code, CODE_PATTERN);
178
250
  if (safeCode !== undefined)
179
251
  return String(safeCode);
180
- return matching(read(error, "name"), NAME_PATTERN) ?? "Error";
252
+ return matching(read(error, "name"), NAME_PATTERN2) ?? "Error";
181
253
  }
182
254
 
183
255
  // ../protocol/src/log-vocabulary/define.ts
@@ -598,6 +670,7 @@ var DESKTOP_LOG_AREAS = defineLogAreas({
598
670
  events: {
599
671
  "attention-failed": "A dialog could not ask for the user's attention.",
600
672
  closed: "A native dialog closed.",
673
+ "hidden-cancelled": "A hidden profile cancelled a dialog without opening native UI.",
601
674
  "open-failed": "A dialog could not open; it was answered as cancelled.",
602
675
  opening: "A native dialog is opening.",
603
676
  "preview-beforeunload-ignored": "A browser preview's beforeunload handler was ignored.",
@@ -683,6 +756,7 @@ var ENVIRONMENT_LOG_AREAS = defineLogAreas({
683
756
  "orphan-session.reaped": "A native session no tab references was torn down.",
684
757
  "handoff-sweep.failed": "Sweeping transferred transcripts no tab references failed.",
685
758
  "delete.terminals-survived": "Terminal process trees outlived termination, so the deletion stops.",
759
+ "delete.step-deadline": "A deletion step that runs child processes passed its deadline; they are stopped and the deletion fails once they have.",
686
760
  "delete.artifacts-left": "Graph run artifact directories were not removed.",
687
761
  "delete.worktrees-kept": "Graph runs kept branch worktrees.",
688
762
  "delete.step-failed": "One best-effort part of deleting an environment failed; `step` says which, and the rest goes on.",
@@ -717,6 +791,7 @@ var GATEWAY_LOG_AREAS = defineLogAreas({
717
791
  "host.refused": "A request named a host this gateway does not answer to. Logged once per name, up to a limit.",
718
792
  "port.fallback": "The preferred port was taken, so a nearby one is used.",
719
793
  "port.fallback-distant": "The preferred port and those nearby were taken, so another is used.",
794
+ "request-auth.fallback": "A desktop request-auth hook failed closed. Phase only; no request or error content.",
720
795
  "request.failed": "A gateway request failed. Throttled: repeats are counted, not written.",
721
796
  "websocket.upgrade-failed": "A WebSocket upgrade failed.",
722
797
  "events.client-dropped": "An event-stream client buffered too much and was dropped; it reconnects and refetches.",
@@ -775,6 +850,11 @@ var LOCAL_SERVER_LOG_AREAS = defineLogAreas({
775
850
  requested: "boolean"
776
851
  }
777
852
  },
853
+ "bridge.orphans-reaped": {
854
+ 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.",
855
+ essential: true,
856
+ fields: { key: "label", pid: "number", result: "label" }
857
+ },
778
858
  "reaper.tmux-list-failed": "Orphaned claude-tmux sessions could not be listed.",
779
859
  "reaper.tmux-kill-failed": "An orphaned tmux session could not be killed.",
780
860
  "reaper.tmux-reaped": "Orphaned claude-tmux sessions of a deleted environment were killed.",
@@ -825,6 +905,8 @@ var LOGGING_LOG_AREAS = defineLogAreas({
825
905
  },
826
906
  "essential.write-failed": "Writing the essential log failed. Its entries are counted, and a marker reports them at the next write that works.",
827
907
  "policy.changed": "The logging settings changed: saving, retention and levels, with no content.",
908
+ "policy.detail-expired": "Raised log detail reached its expiry, so the backend set its raised levels back to info. Saving is unchanged.",
909
+ "policy.expiry-failed": "Checking or applying the log detail expiry failed; the next check, a minute later, tries again.",
828
910
  "policy.bridge-predates-route": "A running bridge has no logging settings route; it applies them at its next start.",
829
911
  "policy.push-failed": "A running bridge did not take the logging settings after retries; its next start resends them.",
830
912
  "prune.failed": "Removing expired log files failed; the next sweep retries.",
@@ -832,6 +914,23 @@ var LOGGING_LOG_AREAS = defineLogAreas({
832
914
  "unknown-area": "Code outside the type checker asked for an area that is not listed.",
833
915
  ...THROTTLE_LOG_EVENTS
834
916
  }
917
+ },
918
+ "renderer-errors": {
919
+ description: "Renderer failures a desktop window reported from its error ring: class, boundary, surface, count and fingerprint, never a message or stack.",
920
+ events: {
921
+ "error.recorded": {
922
+ description: "A renderer reported `count` new occurrences of one failure since its last report.",
923
+ essential: true,
924
+ fields: {
925
+ errorClass: "label",
926
+ boundary: "label",
927
+ route: "label",
928
+ fingerprint: "label",
929
+ count: "number"
930
+ }
931
+ },
932
+ "report.rate-limited": "Renderer error entries arrived faster than the backend records them, so `dropped` were counted and not written."
933
+ }
835
934
  }
836
935
  });
837
936
 
@@ -889,6 +988,8 @@ var NATIVE_AGENT_LOG_AREAS = defineLogAreas({
889
988
  "usage-limit.notice-failed": "A usage-limit stop's outcome could not be read for its notice.",
890
989
  "usage-limit.resend-failed": "Resending after a usage limit failed. An unknown send stays in the journal.",
891
990
  "title.strategy-failed": "A session title strategy failed, so the next is tried. Content-free: the error can quote the prompt.",
991
+ "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.",
992
+ "steer.capability-cleared": "A projection cleared `actions.steer` because its bridge did not qualify. Identifiers and turn status only.",
892
993
  ...THROTTLE_LOG_EVENTS
893
994
  }
894
995
  },
@@ -989,6 +1090,9 @@ var RUNTIME_LOG_AREAS = defineLogAreas({
989
1090
  essential: true,
990
1091
  fields: { origin: "label", ...ESSENTIAL_ERROR_FIELDS }
991
1092
  },
1093
+ "child.reaped": "A macOS child whose exit Bun lost was reaped after its command settled, so it no longer waits as a zombie.",
1094
+ "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.",
1095
+ "child.reap-unavailable": "waitpid could not be loaded, so children whose exit Bun lost stay zombies until this process exits.",
992
1096
  ...THROTTLE_LOG_EVENTS
993
1097
  }
994
1098
  }
@@ -1395,6 +1499,13 @@ var COORDINATOR_LOG_AREAS = defineLogAreas({
1395
1499
  "store.workflows-cleared": "The workflow store was full, so a batch of its oldest finished records was removed.",
1396
1500
  "store.workflows-in-use": "The workflow store was full and every record was still in use, so new work was refused.",
1397
1501
  "remote-worker.settle-failed": "A remote worker could not be settled.",
1502
+ "node-release.failed": "Work on a node that was forgotten or handed over could not be closed; the sweep's registry check retries.",
1503
+ "node-release.reconcile-failed": "The sweep could not check records against the node registry; the next sweep retries.",
1504
+ "node-release.unregistered": "Records named a node the registry no longer holds, so their work was closed here.",
1505
+ "node-release.notice-failed": "The notice for work closed on a released node could not be sent; it stays owed and the sweep retries.",
1506
+ "node-release.no-coordinator": "Work closed on a released node belonged to a coordinator that no longer exists, so nobody was told.",
1507
+ "node-offline.notice-failed": "The notice that a node has been unreachable for a day could not be sent; the next failed read retries.",
1508
+ "node-offline.check-failed": "Whether a long-unreachable node's coordinators were told could not be checked; the next read retries.",
1398
1509
  "checkout.merge-followed": "After an environment's PR merged, the project checkout was fast-forwarded, or `outcome` says why not.",
1399
1510
  "checkout.merge-follow-failed": "Fast-forwarding the project checkout failed, after an environment's PR merged or before mail woke the main coordinator.",
1400
1511
  "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`).",
@@ -1491,6 +1602,7 @@ var DOCKER_LOG_AREAS = defineLogAreas({
1491
1602
  events: {
1492
1603
  "portable-inputs.relay-missing": "Docker is rootless and the image predates the staged-input relay, so the container cannot read them until rebuilt.",
1493
1604
  "git-mirror.mount-unavailable": "A new container gets no project Git mirror, so its clone goes to the remote.",
1605
+ "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.",
1494
1606
  "git-mirror.refreshed": "A project's Git mirror was built or updated.",
1495
1607
  "git-mirror.seeded": "A project's Git mirror was built from its host checkout and only what the remote added to it.",
1496
1608
  "git-mirror.seed-skipped": "A project's host checkout could not seed its Git mirror, so the build downloads everything.",
@@ -1576,7 +1688,11 @@ var DOCKER_LOG_AREAS = defineLogAreas({
1576
1688
  "network.list-failed": "Docker networks could not be listed.",
1577
1689
  "network.inspect-failed": "A Docker network could not be inspected.",
1578
1690
  "stale-containers.removing": "Stale probe containers are being removed.",
1579
- "stale-networks.removing": "Stale probe networks are being removed."
1691
+ "stale-networks.removing": "Stale probe networks are being removed.",
1692
+ "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).",
1693
+ "peers.subnets-loaded": "The Docker subnets the agent tools server admits were reloaded.",
1694
+ "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.",
1695
+ "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."
1580
1696
  }
1581
1697
  }
1582
1698
  });
@@ -1667,6 +1783,7 @@ var NODES_LOG_AREAS = defineLogAreas({
1667
1783
  "verification.record-failed": "A node verification could not be recorded.",
1668
1784
  "profile.record-failed": "A node profile could not be recorded.",
1669
1785
  "detach.unconfirmed": "A forgotten node has not confirmed the detach yet.",
1786
+ "grant.revocation-listener-failed": "A connection could not be told its client grant was removed; the grant is still gone.",
1670
1787
  "handover.recovery-pending": "Command handover recovery is still pending.",
1671
1788
  "ticket-sync.work-record-failed": "A remote build started but its ticket work location could not be saved.",
1672
1789
  "ticket-sync.failed": "A Kanban sync with a node failed; it is retried.",
@@ -1719,7 +1836,9 @@ var HOST_LOG_AREAS = defineLogAreas({
1719
1836
  "tool.missing": "A host tool was not found.",
1720
1837
  "maintenance.listener-failed": "A host maintenance listener threw; the others still run.",
1721
1838
  "suspend.reconcile-failed": "Reconciling due work after a host suspension failed.",
1722
- "load.sample-failed": "Sampling machine load failed; the next sample retries."
1839
+ "load.sample-failed": "Sampling machine load failed; the next sample retries.",
1840
+ "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.",
1841
+ ...THROTTLE_LOG_EVENTS
1723
1842
  }
1724
1843
  }
1725
1844
  });
@@ -3316,34 +3435,201 @@ function createBridgeDiagnostics(bridge, state, metrics) {
3316
3435
  var bufferedFlushes = new Set;
3317
3436
 
3318
3437
  // ../protocol/src/node/bridge-credential.ts
3319
- import { createHash as createHash2, randomBytes, timingSafeEqual } from "node:crypto";
3438
+ import { createHash as createHash3, randomBytes as randomBytes2, timingSafeEqual } from "node:crypto";
3320
3439
  import { createRequire } from "node:module";
3440
+
3441
+ // ../protocol/src/node/bridge-authority.ts
3442
+ import {
3443
+ createHash as createHash2,
3444
+ createPrivateKey,
3445
+ createPublicKey,
3446
+ generateKeyPairSync,
3447
+ randomBytes,
3448
+ sign,
3449
+ verify
3450
+ } from "node:crypto";
3451
+ var BRIDGE_AUTHORITY_HEADER = "x-orkestrator-authority";
3452
+ var BRIDGE_AUTHORITY_REFUSED_CODE = "authority-signature-required";
3453
+ var BRIDGE_AUTHORITY_WINDOW_MS = 5 * 60000;
3454
+ var BRIDGE_AUTHORITY_MAX_NONCES = 8192;
3455
+ var BRIDGE_AUTHORITY_MAX_BODY_BYTES = 64 * 1024 * 1024;
3456
+ var SCHEME = "orkestrator-bridge-authority-v1";
3457
+ var KEY_PATTERN = /^[A-Za-z0-9_-]{40,200}$/;
3458
+ var HEADER_PATTERN = /^v1 t=(\d{1,16}) n=([A-Za-z0-9_-]{22}) s=([A-Za-z0-9_-]{86})$/;
3459
+ var READ_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
3460
+ var UNSIGNED_ROUTES = [
3461
+ /^\/session\/[^/]+\/close$/,
3462
+ /^\/sessions\/activity$/,
3463
+ /^\/debug\/log-policy$/
3464
+ ];
3465
+ function bridgeAuthorityKeyEnv(tokenEnv) {
3466
+ return `${tokenEnv}_AUTHORITY_KEY`;
3467
+ }
3468
+ function isBridgeAuthorityKey(value) {
3469
+ return typeof value === "string" && KEY_PATTERN.test(value);
3470
+ }
3471
+ function publicKeyFrom(encoded) {
3472
+ if (!isBridgeAuthorityKey(encoded))
3473
+ return null;
3474
+ try {
3475
+ const key = createPublicKey({
3476
+ key: Buffer.from(encoded, "base64url"),
3477
+ format: "der",
3478
+ type: "spki"
3479
+ });
3480
+ return key.asymmetricKeyType === "ed25519" ? key : null;
3481
+ } catch {
3482
+ return null;
3483
+ }
3484
+ }
3485
+ function bridgeAuthorityTarget(url) {
3486
+ const parsed = new URL(url, "http://bridge.invalid");
3487
+ return `${parsed.pathname}${parsed.search}`;
3488
+ }
3489
+ function bridgeRequestNeedsAuthority(method, target) {
3490
+ if (READ_METHODS.has(method.toUpperCase()))
3491
+ return false;
3492
+ const pathname = bridgeAuthorityTarget(target).split("?", 1)[0];
3493
+ return !UNSIGNED_ROUTES.some((pattern) => pattern.test(pathname));
3494
+ }
3495
+ function bodyDigest(body) {
3496
+ return createHash2("sha256").update(body ?? "").digest("hex");
3497
+ }
3498
+ function signedMessage(method, target, issuedAt, nonce, digest) {
3499
+ return Buffer.from([SCHEME, method.toUpperCase(), target, String(issuedAt), nonce, digest].join(`
3500
+ `));
3501
+ }
3502
+ var UNENFORCED = {
3503
+ enforced: false,
3504
+ requires: () => false,
3505
+ check: () => ({ ok: true })
3506
+ };
3507
+ function bridgeAuthorityFromPublicKey(publicKey, options = {}) {
3508
+ if (publicKey === undefined)
3509
+ return UNENFORCED;
3510
+ const key = publicKeyFrom(publicKey);
3511
+ const now = options.now ?? Date.now;
3512
+ const maxNonces = options.maxNonces ?? BRIDGE_AUTHORITY_MAX_NONCES;
3513
+ const seen = new Map;
3514
+ let floor = -Infinity;
3515
+ const remember = (nonce, issuedAt, current) => {
3516
+ for (const [oldNonce, oldIssuedAt] of seen) {
3517
+ if (seen.size < maxNonces && oldIssuedAt >= current - BRIDGE_AUTHORITY_WINDOW_MS)
3518
+ break;
3519
+ seen.delete(oldNonce);
3520
+ floor = Math.max(floor, oldIssuedAt);
3521
+ }
3522
+ seen.set(nonce, issuedAt);
3523
+ };
3524
+ return {
3525
+ enforced: true,
3526
+ requires: bridgeRequestNeedsAuthority,
3527
+ check(request) {
3528
+ if (!request.header)
3529
+ return { ok: false, reason: "missing" };
3530
+ const match = HEADER_PATTERN.exec(request.header.trim());
3531
+ if (!match)
3532
+ return { ok: false, reason: "malformed" };
3533
+ const issuedAt = Number(match[1]);
3534
+ const nonce = match[2];
3535
+ const current = now();
3536
+ if (Math.abs(current - issuedAt) > BRIDGE_AUTHORITY_WINDOW_MS || issuedAt <= floor) {
3537
+ return { ok: false, reason: "stale" };
3538
+ }
3539
+ if (!key)
3540
+ return { ok: false, reason: "invalid" };
3541
+ const valid = verify(null, signedMessage(request.method, bridgeAuthorityTarget(request.url), issuedAt, nonce, bodyDigest(request.body)), key, Buffer.from(match[3], "base64url"));
3542
+ if (!valid)
3543
+ return { ok: false, reason: "invalid" };
3544
+ if (seen.has(nonce))
3545
+ return { ok: false, reason: "replayed" };
3546
+ remember(nonce, issuedAt, current);
3547
+ return { ok: true };
3548
+ }
3549
+ };
3550
+ }
3551
+ function loadBridgeAuthority(tokenEnv, options = {}) {
3552
+ const env = options.env ?? process.env;
3553
+ const name = bridgeAuthorityKeyEnv(tokenEnv);
3554
+ const value = env[name]?.trim();
3555
+ delete env[name];
3556
+ return bridgeAuthorityFromPublicKey(value || undefined, { now: options.now });
3557
+ }
3558
+ function refusal(reason) {
3559
+ return {
3560
+ status: 403,
3561
+ body: {
3562
+ error: "This request changes an agent's authority and needs the backend's signature",
3563
+ code: BRIDGE_AUTHORITY_REFUSED_CODE,
3564
+ reason
3565
+ }
3566
+ };
3567
+ }
3568
+ var TOO_LARGE = {
3569
+ status: 413,
3570
+ body: { error: "Request body is too large" }
3571
+ };
3572
+ var admittedBodies = new WeakMap;
3573
+ async function admitNodeBridgeRequest(authority, request, maxBodyBytes) {
3574
+ const method = request.method ?? "GET";
3575
+ const url = request.url ?? "/";
3576
+ if (!authority.requires(method, url))
3577
+ return null;
3578
+ const header = request.headers[BRIDGE_AUTHORITY_HEADER];
3579
+ const value = Array.isArray(header) ? header[0] : header;
3580
+ if (!value)
3581
+ return refusal("missing");
3582
+ const chunks = [];
3583
+ let total = 0;
3584
+ for await (const chunk of request) {
3585
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
3586
+ total += buffer.length;
3587
+ if (total > maxBodyBytes)
3588
+ return TOO_LARGE;
3589
+ chunks.push(buffer);
3590
+ }
3591
+ const body = Buffer.concat(chunks);
3592
+ const result = authority.check({ method, url, header: value, body });
3593
+ if (!result.ok)
3594
+ return refusal(result.reason);
3595
+ admittedBodies.set(request, body);
3596
+ return null;
3597
+ }
3598
+ function takeAdmittedBody(request) {
3599
+ const body = admittedBodies.get(request);
3600
+ admittedBodies.delete(request);
3601
+ return body;
3602
+ }
3603
+
3604
+ // ../protocol/src/node/bridge-credential.ts
3321
3605
  var BRIDGE_TOKEN_PREFIX = "okb_";
3322
3606
  var PR_SET_DUMPABLE = 4;
3323
3607
  var VERIFIER_PATTERN = /^[0-9a-f]{64}$/;
3324
3608
  var log3 = createLogger("bridge.lifecycle");
3325
3609
  function mintBridgeToken() {
3326
- return `${BRIDGE_TOKEN_PREFIX}${randomBytes(32).toString("base64url")}`;
3610
+ return `${BRIDGE_TOKEN_PREFIX}${randomBytes2(32).toString("base64url")}`;
3327
3611
  }
3328
3612
  function bridgeTokenVerifier(token) {
3329
- return createHash2("sha256").update(token).digest("hex");
3613
+ return createHash3("sha256").update(token).digest("hex");
3330
3614
  }
3331
3615
  function bridgeTokenVerifierEnv(tokenEnv) {
3332
3616
  return `${tokenEnv}_SHA256`;
3333
3617
  }
3334
- function credentialFromVerifier(verifier, plainToken) {
3618
+ function credentialFromVerifier(verifier, plainToken, authority = UNENFORCED_AUTHORITY) {
3335
3619
  const expected = Buffer.from(verifier, "hex");
3336
3620
  return {
3337
3621
  plainToken,
3622
+ authority,
3338
3623
  matches(candidate) {
3339
3624
  if (!candidate)
3340
3625
  return false;
3341
- return timingSafeEqual(expected, createHash2("sha256").update(candidate).digest());
3626
+ return timingSafeEqual(expected, createHash3("sha256").update(candidate).digest());
3342
3627
  }
3343
3628
  };
3344
3629
  }
3345
- function bridgeCredentialFromToken(token) {
3346
- return credentialFromVerifier(bridgeTokenVerifier(token), token);
3630
+ var UNENFORCED_AUTHORITY = loadBridgeAuthority("", { env: {} });
3631
+ function bridgeCredentialFromToken(token, authority = UNENFORCED_AUTHORITY) {
3632
+ return credentialFromVerifier(bridgeTokenVerifier(token), token, authority);
3347
3633
  }
3348
3634
  function markProcessNonDumpable(loadFfi = () => createRequire(import.meta.url)("bun:ffi")) {
3349
3635
  if (process.platform !== "linux" || !process.versions.bun)
@@ -3375,16 +3661,17 @@ function loadBridgeCredential(tokenEnv, options = {}) {
3375
3661
  const token = env[tokenEnv]?.trim();
3376
3662
  delete env[verifierEnv];
3377
3663
  delete env[tokenEnv];
3664
+ const authority = loadBridgeAuthority(tokenEnv, { env });
3378
3665
  if (verifier) {
3379
3666
  (options.harden ?? markProcessNonDumpable)();
3380
- return VERIFIER_PATTERN.test(verifier) ? credentialFromVerifier(verifier, undefined) : bridgeCredentialFromToken(mintBridgeToken());
3667
+ return VERIFIER_PATTERN.test(verifier) ? credentialFromVerifier(verifier, undefined, authority) : bridgeCredentialFromToken(mintBridgeToken(), authority);
3381
3668
  }
3382
- return bridgeCredentialFromToken(token || mintBridgeToken());
3669
+ return bridgeCredentialFromToken(token || mintBridgeToken(), authority);
3383
3670
  }
3384
3671
 
3385
3672
  // ../../bridges/acp-bridge/src/acp-context.ts
3386
3673
  import { spawn as spawn2 } from "node:child_process";
3387
- import { createHmac, randomBytes as randomBytes3, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
3674
+ import { createHmac, randomBytes as randomBytes4, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
3388
3675
  import { resolve as resolve3 } from "node:path";
3389
3676
 
3390
3677
  // ../protocol/src/capacity-retry.ts
@@ -12206,10 +12493,10 @@ async function acpReadiness(provider, authMethodEnv, env = process.env) {
12206
12493
 
12207
12494
  // ../../bridges/acp-bridge/src/acp-client-methods.ts
12208
12495
  import { spawn } from "node:child_process";
12209
- import { constants } from "node:fs";
12496
+ import { constants as constants2 } from "node:fs";
12210
12497
  import { lstat, open as open2, realpath } from "node:fs/promises";
12211
12498
  import { dirname, isAbsolute, join as join2, relative, resolve, sep } from "node:path";
12212
- import { randomBytes as randomBytes2 } from "node:crypto";
12499
+ import { randomBytes as randomBytes3 } from "node:crypto";
12213
12500
 
12214
12501
  // ../protocol/src/coordinator-web-research.ts
12215
12502
  var DEFAULT_COORDINATOR_RESEARCH_MCP_SERVERS = Object.freeze([{ name: "context7", url: "https://mcp.context7.com/mcp" }]);
@@ -12576,7 +12863,7 @@ class AcpClientMethods {
12576
12863
  }
12577
12864
  async readTextFile(request) {
12578
12865
  const target = await secureExistingFile(request.path, this.workspaceRoot);
12579
- const handle = await open2(target.path, constants.O_RDONLY | constants.O_NOFOLLOW);
12866
+ const handle = await open2(target.path, constants2.O_RDONLY | constants2.O_NOFOLLOW);
12580
12867
  try {
12581
12868
  const stats = await handle.stat();
12582
12869
  assertSameFile(stats, target.stats);
@@ -12599,7 +12886,7 @@ class AcpClientMethods {
12599
12886
  throw new Error("ACP file write exceeds the 2 MiB limit");
12600
12887
  }
12601
12888
  const target = await secureWritableFile(request.path, this.workspaceRoot);
12602
- const handle = await open2(target.path, constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW, 384);
12889
+ const handle = await open2(target.path, constants2.O_WRONLY | constants2.O_CREAT | constants2.O_TRUNC | constants2.O_NOFOLLOW, 384);
12603
12890
  try {
12604
12891
  const stats = await handle.stat();
12605
12892
  if (!stats.isFile())
@@ -12625,7 +12912,7 @@ class AcpClientMethods {
12625
12912
  }
12626
12913
  const cwd = await secureTerminalCwd(request.cwd, this.workspaceRoot);
12627
12914
  const outputLimit = Math.min(MAX_TERMINAL_OUTPUT_BYTES, Number.isSafeInteger(request.outputByteLimit) && (request.outputByteLimit ?? 0) > 0 ? request.outputByteLimit : DEFAULT_TERMINAL_OUTPUT_BYTES);
12628
- const terminalId = randomBytes2(16).toString("hex");
12915
+ const terminalId = randomBytes3(16).toString("hex");
12629
12916
  const child = this.spawnTerminalImpl(request.command, request.args ?? [], {
12630
12917
  cwd,
12631
12918
  env: withoutBridgeControlEnvironment({
@@ -12914,7 +13201,7 @@ function isString(value) {
12914
13201
  }
12915
13202
 
12916
13203
  // ../../bridges/acp-bridge/src/acp-readonly-profile.ts
12917
- import { mkdtempSync as mkdtempSync2, writeFileSync, rmSync } from "node:fs";
13204
+ import { mkdtempSync as mkdtempSync2, writeFileSync, rmSync as rmSync2 } from "node:fs";
12918
13205
  import { tmpdir as tmpdir2 } from "node:os";
12919
13206
  import { join as join3 } from "node:path";
12920
13207
  var GROK_READ_ONLY_PROFILE = `---
@@ -12931,7 +13218,7 @@ disallowedTools:
12931
13218
  `;
12932
13219
  function createReadOnlyProfile() {
12933
13220
  const directory = mkdtempSync2(join3(tmpdir2(), "orkestrator-grok-profile-"));
12934
- const dispose = () => rmSync(directory, { recursive: true, force: true });
13221
+ const dispose = () => rmSync2(directory, { recursive: true, force: true });
12935
13222
  try {
12936
13223
  const path = join3(directory, "read-only.md");
12937
13224
  writeFileSync(path, GROK_READ_ONLY_PROFILE, { mode: 384 });
@@ -13023,7 +13310,7 @@ function grokQuestionTimeoutFromEnv(env) {
13023
13310
  }
13024
13311
 
13025
13312
  // ../../bridges/acp-bridge/src/acp-mcp-inventory.ts
13026
- import { createHash as createHash3 } from "node:crypto";
13313
+ import { createHash as createHash4 } from "node:crypto";
13027
13314
  import { readFile, stat } from "node:fs/promises";
13028
13315
  import { homedir as homedir2 } from "node:os";
13029
13316
  import { join as join4, resolve as resolve2 } from "node:path";
@@ -13114,7 +13401,7 @@ function grokMcpConfigFiles(options = { cwd: process.cwd() }) {
13114
13401
  }
13115
13402
  async function fileDigest(file) {
13116
13403
  try {
13117
- return `sha256:${createHash3("sha256").update(await readFile(file)).digest("base64url")}`;
13404
+ return `sha256:${createHash4("sha256").update(await readFile(file)).digest("base64url")}`;
13118
13405
  } catch {
13119
13406
  return "absent";
13120
13407
  }
@@ -13122,7 +13409,7 @@ async function fileDigest(file) {
13122
13409
  async function grokMcpConfigFingerprint(files) {
13123
13410
  const [user, project] = await Promise.all([fileDigest(files.user), fileDigest(files.project)]);
13124
13411
  return {
13125
- fingerprint: createHash3("sha256").update(`user=${user}\x00project=${project}`).digest("base64url"),
13412
+ fingerprint: createHash4("sha256").update(`user=${user}\x00project=${project}`).digest("base64url"),
13126
13413
  sources: { user, project }
13127
13414
  };
13128
13415
  }
@@ -13190,7 +13477,7 @@ var hostname = process.env.HOSTNAME?.trim() || "127.0.0.1";
13190
13477
  var workingDirectory = resolve3(process.env.CWD?.trim() || process.cwd());
13191
13478
  var bridgeCredential = loadBridgeCredential("ACP_BRIDGE_TOKEN");
13192
13479
  var authToken = bridgeCredential.plainToken ?? "";
13193
- var externalSessionKey = randomBytes3(32);
13480
+ var externalSessionKey = randomBytes4(32);
13194
13481
  var executable = providerConfig.executable;
13195
13482
  var stateDirectory = process.env.ACP_STATE_DIR?.trim();
13196
13483
  var stateFile = stateDirectory ? resolve3(stateDirectory, "state.json") : null;
@@ -14507,7 +14794,7 @@ function encodedStringBytes(value, previous) {
14507
14794
  // ../../bridges/acp-bridge/src/acp-persist-writer.ts
14508
14795
  import { promises as fs2 } from "node:fs";
14509
14796
  import { dirname as dirname2 } from "node:path";
14510
- import { randomBytes as randomBytes4 } from "node:crypto";
14797
+ import { randomBytes as randomBytes5 } from "node:crypto";
14511
14798
 
14512
14799
  // ../protocol/src/node/transcript-window.ts
14513
14800
  import { Buffer as Buffer4 } from "node:buffer";
@@ -14811,16 +15098,16 @@ async function writePersistedState() {
14811
15098
  throw new Error("ACP persisted state exceeds its byte limit");
14812
15099
  }
14813
15100
  await fs2.mkdir(dirname2(file), { recursive: true, mode: 448 });
14814
- const temporary = `${file}.${process.pid}.${randomBytes4(6).toString("hex")}.tmp`;
15101
+ const temporary = `${file}.${process.pid}.${randomBytes5(6).toString("hex")}.tmp`;
14815
15102
  await fs2.writeFile(temporary, payload, { mode: 384 });
14816
15103
  await fs2.rename(temporary, file);
14817
15104
  }
14818
15105
 
14819
15106
  // ../../bridges/acp-bridge/src/acp-rows.ts
14820
- import { randomBytes as randomBytes5 } from "node:crypto";
15107
+ import { randomBytes as randomBytes6 } from "node:crypto";
14821
15108
 
14822
15109
  // ../protocol/src/node/revised-rows.ts
14823
- import { createHash as createHash4 } from "node:crypto";
15110
+ import { createHash as createHash5 } from "node:crypto";
14824
15111
  var RECENTLY_REVISED_ROWS_MAX = 128;
14825
15112
 
14826
15113
  class RecentlyRevisedRows {
@@ -14858,7 +15145,7 @@ class RecentlyRevisedRows {
14858
15145
  function revisedRowsReconciliationToken(overflowVersion, omitted) {
14859
15146
  if (overflowVersion === 0 && omitted.length === 0)
14860
15147
  return;
14861
- const digest = createHash4("sha256").update(String(overflowVersion));
15148
+ const digest = createHash5("sha256").update(String(overflowVersion));
14862
15149
  for (const row of omitted)
14863
15150
  digest.update(JSON.stringify(row) ?? "null");
14864
15151
  return digest.digest("hex");
@@ -14907,7 +15194,7 @@ function currentAssistantMessage(state) {
14907
15194
  if (!message || message.role !== "assistant" || rowIsFull(message) || state.status !== "running" && state.historyReplay !== "hydrate") {
14908
15195
  const modelId = boundedModelId(state.sessionConfig.composer.selectedModelId);
14909
15196
  message = {
14910
- id: randomBytes5(12).toString("hex"),
15197
+ id: randomBytes6(12).toString("hex"),
14911
15198
  role: "assistant",
14912
15199
  content: "",
14913
15200
  parts: [],
@@ -16742,7 +17029,7 @@ var DEFAULT_WORKFLOW_RESULT_TOOLS_SETTINGS = {
16742
17029
  };
16743
17030
 
16744
17031
  // ../../bridges/acp-bridge/src/acp-session.ts
16745
- import { randomBytes as randomBytes8 } from "node:crypto";
17032
+ import { randomBytes as randomBytes9 } from "node:crypto";
16746
17033
  import { resolve as resolve7 } from "node:path";
16747
17034
 
16748
17035
  // ../../bridges/acp-bridge/src/session-config.ts
@@ -17970,18 +18257,18 @@ async function readJournal(path, maxEntries) {
17970
18257
  }
17971
18258
 
17972
18259
  // ../../bridges/acp-bridge/src/grok-interjection.ts
17973
- import { createHash as createHash5, randomBytes as randomBytes6 } from "node:crypto";
18260
+ import { createHash as createHash6, randomBytes as randomBytes7 } from "node:crypto";
17974
18261
  var GROK_INTERJECT_METHOD = "_x.ai/interject";
17975
18262
  var GROK_INTERJECTION_NOTIFICATION = "_x.ai/session/interjection";
17976
18263
  var MAX_GROK_INTERJECTION_JOURNAL = 256;
17977
18264
  var MAX_GROK_INTERJECTION_ID_BYTES = 512;
17978
18265
  var MAX_GROK_INTERJECTION_TEXT_BYTES = 64 * 1024;
17979
- var grokBridgeGeneration = randomBytes6(12).toString("base64url");
18266
+ var grokBridgeGeneration = randomBytes7(12).toString("base64url");
17980
18267
  function grokRunId(promptSequence) {
17981
18268
  return `grok:${grokBridgeGeneration}:${promptSequence}`;
17982
18269
  }
17983
18270
  function grokInterjectionDigest(text) {
17984
- return createHash5("sha256").update(text).digest("hex");
18271
+ return createHash6("sha256").update(text).digest("hex");
17985
18272
  }
17986
18273
  function parseGrokInterjectResult(value) {
17987
18274
  if (!isObject6(value) || value.status !== "queued")
@@ -18073,7 +18360,7 @@ function applyGrokInterjectionBroadcast(journal, acpSessionId, method, params, n
18073
18360
  return broadcast;
18074
18361
  }
18075
18362
  async function probeGrokInterjectionExtension(requester) {
18076
- const probeId = `orkestrator-qualification-${randomBytes6(12).toString("base64url")}`;
18363
+ const probeId = `orkestrator-qualification-${randomBytes7(12).toString("base64url")}`;
18077
18364
  try {
18078
18365
  await requestGrokInterjection(requester, {
18079
18366
  sessionId: probeId,
@@ -18109,7 +18396,7 @@ function isObject6(value) {
18109
18396
  }
18110
18397
 
18111
18398
  // ../../bridges/acp-bridge/src/acp-commands.ts
18112
- import { randomBytes as randomBytes7 } from "node:crypto";
18399
+ import { randomBytes as randomBytes8 } from "node:crypto";
18113
18400
 
18114
18401
  // ../protocol/src/agent-command-catalogue.ts
18115
18402
  var NATIVE_AGENT_COMMAND_CATALOGUE_VERSION = 1;
@@ -18240,7 +18527,7 @@ function commandUnavailableResponse(message) {
18240
18527
  }
18241
18528
 
18242
18529
  // ../../bridges/acp-bridge/src/acp-commands.ts
18243
- var COMMAND_CATALOGUE_GENERATION = `${provider}:${randomBytes7(8).toString("hex")}`;
18530
+ var COMMAND_CATALOGUE_GENERATION = `${provider}:${randomBytes8(8).toString("hex")}`;
18244
18531
  var COMMAND_ROWS_BYTE_BUDGET = COMMAND_CATALOGUE_LIMITS.maxWireBytes - 16 * 1024;
18245
18532
  var PROVIDER_LABEL = `${provider.charAt(0).toUpperCase()}${provider.slice(1)}`;
18246
18533
  function commandId(name) {
@@ -19243,16 +19530,854 @@ class InteractionDeadline {
19243
19530
  }
19244
19531
 
19245
19532
  // ../../bridges/acp-bridge/src/acp-command-changes.ts
19246
- import { createHash as createHash7 } from "node:crypto";
19533
+ import { createHash as createHash8 } from "node:crypto";
19247
19534
  import { resolve as resolve6 } from "node:path";
19248
19535
 
19249
19536
  // ../protocol/src/node/workspace-change-probe.ts
19250
- import { execFile, spawn as spawn3 } from "node:child_process";
19251
- import { randomUUID } from "node:crypto";
19252
- import { rmSync as rmSync2 } from "node:fs";
19537
+ import { randomUUID as randomUUID2 } from "node:crypto";
19538
+ import { rmSync as rmSync3 } from "node:fs";
19253
19539
  import { copyFile, lstat as lstat2, mkdtemp, rm as rm2 } from "node:fs/promises";
19254
19540
  import { tmpdir as tmpdir3 } from "node:os";
19255
19541
  import { delimiter, isAbsolute as isAbsolute3, join as join6, resolve as resolve4 } from "node:path";
19542
+
19543
+ // ../protocol/src/node/command-capture.ts
19544
+ import { spawn as spawn3 } from "node:child_process";
19545
+ import { randomUUID } from "node:crypto";
19546
+ import { constants as fsConstants } from "node:fs";
19547
+ import * as captureFs from "node:fs";
19548
+ import os from "node:os";
19549
+ import path2 from "node:path";
19550
+ import { inspect } from "node:util";
19551
+
19552
+ // ../protocol/src/node/command-failure-reason.ts
19553
+ var MAX_MATCHED_CHARS = 16 * 1024;
19554
+ var SIGNAL_PATTERN = /^SIG[A-Z0-9]{1,16}$/;
19555
+ var TOOL_RULES = {
19556
+ git: [
19557
+ ["branch-exists", /a branch named .* already exists/i],
19558
+ ["ref-conflict", /exists; cannot create|cannot lock ref .* is at .* but expected/i],
19559
+ ["lock-held", /could not lock config file [^\n]*: File exists/i],
19560
+ ["lock-held", /(?:unable to create '[^\n]*\.lock'|cannot lock ref)[^\n]*: File exists/i],
19561
+ ["lock-held", /another git process/i],
19562
+ ["worktree-conflict", /already (?:checked out|used by worktree)|used by worktree at/i],
19563
+ ["invalid-ref", /not a valid (?:branch name|object name)|bad (?:revision|object)/i],
19564
+ ["invalid-ref", /unknown revision|ambiguous argument|invalid reference/i],
19565
+ ["branch-not-found", /no branch named|refname .* not found|branch '.*' not found/i],
19566
+ ["branch-not-found", /did not match any file\(s\) known to git/i],
19567
+ ["dubious-ownership", /detected dubious ownership/i],
19568
+ ["no-remote", /does not appear to be a git repository|no such remote/i],
19569
+ ["no-remote", /repository (?:.* )?not found/i],
19570
+ ["not-a-repository", /not a git repository/i],
19571
+ ["remote-ref-missing", /could(?:n't| not) find remote ref|not our ref/i],
19572
+ ["merge-conflict", /\bCONFLICT \(|merge conflict|could not apply|unmerged files/i],
19573
+ ["dirty-worktree", /local changes .* would be overwritten|commit your changes or stash/i],
19574
+ ["nothing-to-commit", /nothing to commit|no changes added to commit/i],
19575
+ ["push-rejected", /\[(?:remote )?rejected\]|non-fast-forward/i],
19576
+ ["identity-unknown", /please tell me who you are|unable to auto-detect email/i],
19577
+ [
19578
+ "worktree-has-changes",
19579
+ /^fatal: [^\n]*['"] contains modified or untracked files(?:, use --force to delete it)?\.?\s*$/im
19580
+ ],
19581
+ ["not-a-worktree", /^fatal: [^\n]*['"] is not a working tree\.?\s*$/im],
19582
+ ["branch-not-merged", /^(?:error|fatal): [^\n]*['"] is not fully merged\.?\s*$/im]
19583
+ ],
19584
+ gh: [
19585
+ ["pull-request-exists", /a pull request for branch .* already exists/i],
19586
+ ["no-pull-request", /no (?:pull requests? (?:found|match)|open pull requests?\b)/i],
19587
+ ["rate-limited", /rate limit|http 429/i],
19588
+ ["forbidden", /http 403|resource not accessible/i],
19589
+ ["resource-not-found", /http 404|could not resolve to a/i],
19590
+ ["server-error", /http 5\d\d/i]
19591
+ ],
19592
+ docker: [
19593
+ ["daemon-unavailable", /cannot connect to the docker daemon|error during connect/i],
19594
+ [
19595
+ "daemon-unavailable",
19596
+ /is the docker daemon running|docker desktop is (?:not running|unable)/i
19597
+ ],
19598
+ ["container-not-found", /no such container/i],
19599
+ ["container-not-running", /container .* is (?:not running|paused|restarting)/i],
19600
+ ["container-name-conflict", /name .* is already in use/i],
19601
+ ["image-not-found", /no such image|pull access denied|manifest .* not found/i],
19602
+ ["image-not-found", /manifest unknown|repository does not exist/i],
19603
+ ["removal-in-progress", /removal of container .* is already in progress/i],
19604
+ [
19605
+ "image-in-use",
19606
+ /image is (?:being used|referenced)|unable to (?:remove|delete) .*must be forced/i
19607
+ ],
19608
+ ["volume-in-use", /volume is in use/i],
19609
+ ["volume-not-found", /no such volume/i],
19610
+ ["network-in-use", /has active endpoints/i],
19611
+ ["network-not-found", /network .* not found/i]
19612
+ ],
19613
+ tmux: [
19614
+ ["session-exists", /duplicate session/i],
19615
+ [
19616
+ "server-not-running",
19617
+ /no server running|failed to connect to server|no sessions|server exited|lost server/i
19618
+ ],
19619
+ [
19620
+ "server-not-running",
19621
+ /error connecting to \/[^\n]* \((?:No such file or directory|Connection refused)\)/i
19622
+ ],
19623
+ ["session-not-found", /can't find (?:session|window|pane)|session not found/i]
19624
+ ]
19625
+ };
19626
+ var ALL_TOOLS = Object.keys(TOOL_RULES);
19627
+ var SHARED_RULES = [
19628
+ ["disk-full", /no space left|enospc|disk quota exceeded/i],
19629
+ ["auth-failed", /authentication (?:failed|required)|could not read (?:username|password)/i],
19630
+ ["auth-failed", /terminal prompts disabled|invalid username or password|bad credentials/i],
19631
+ ["auth-failed", /permission denied \(|permission to \S+ denied|host key verification failed/i],
19632
+ ["auth-failed", /gh auth login|not logged in|unauthorized|http 401|returned error: 40[13]/i],
19633
+ ["network-failed", /could not resolve host|connection (?:timed out|refused|reset)/i],
19634
+ ["network-failed", /network is unreachable|no route to host|temporary failure in name/i],
19635
+ ["network-failed", /early eof|failed to connect|remote end hung up/i],
19636
+ ["network-failed", /unable to access ['"]?https?:\/\//i],
19637
+ ["network-failed", /tls handshake|i\/o timeout/i],
19638
+ [
19639
+ "network-failed",
19640
+ /error connecting to (?:https?:\/\/)?[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?(?::\d+)?(?:[\s/:]|$)/i
19641
+ ],
19642
+ ["port-in-use", /port is already allocated|address already in use/i],
19643
+ ["permission-denied", /permission denied|operation not permitted|read-only file system/i],
19644
+ ["command-not-found", /command not found/i],
19645
+ ["path-not-found", /no such file or directory/i],
19646
+ ["invalid-usage", /^usage: |unknown (?:option|flag|command|shorthand flag)|invalid option/im]
19647
+ ];
19648
+ var TOOL_EXIT_CODES = {
19649
+ git: { 129: "invalid-usage" },
19650
+ gh: { 2: "aborted", 4: "auth-failed" },
19651
+ docker: { 125: "daemon-error" },
19652
+ tmux: {}
19653
+ };
19654
+ var SHARED_EXIT_CODES = {
19655
+ 124: "timed-out",
19656
+ 126: "not-executable",
19657
+ 127: "command-not-found",
19658
+ 137: "killed",
19659
+ 143: "killed"
19660
+ };
19661
+ function read2(target, key) {
19662
+ return target[key];
19663
+ }
19664
+ function boundedForMatching(text) {
19665
+ if (text.length <= MAX_MATCHED_CHARS)
19666
+ return text;
19667
+ const half = MAX_MATCHED_CHARS / 2;
19668
+ return `${text.slice(0, half)}
19669
+ ${text.slice(-half)}`;
19670
+ }
19671
+ function failureText(error) {
19672
+ const stderr = read2(error, "stderr");
19673
+ if (Buffer.isBuffer(stderr) && stderr.length > 0) {
19674
+ return boundedForMatching(stderr.subarray(-MAX_MATCHED_CHARS).toString());
19675
+ }
19676
+ if (typeof stderr === "string" && stderr.length > 0)
19677
+ return boundedForMatching(stderr);
19678
+ const message = read2(error, "message");
19679
+ if (typeof message !== "string")
19680
+ return "";
19681
+ return message.startsWith("Command failed") ? "" : boundedForMatching(message);
19682
+ }
19683
+ function isRawSpawnEnoent(error) {
19684
+ const syscall = read2(error, "syscall");
19685
+ return read2(error, "code") === "ENOENT" && typeof syscall === "string" && /^(?:spawn(?:Sync)?(?:\s|$)|posix_spawnp?$)/.test(syscall);
19686
+ }
19687
+ function classifiedReason(error, exitCode, signal, options) {
19688
+ if (read2(error, "aborted") === true)
19689
+ return "aborted";
19690
+ if (read2(error, "outputLimitExceeded") === true)
19691
+ return "output-too-large";
19692
+ if (read2(error, "timedOut") === true)
19693
+ return "timed-out";
19694
+ if (read2(error, "executableMissing") === true || isRawSpawnEnoent(error)) {
19695
+ return "executable-missing";
19696
+ }
19697
+ const named = exitCode === null ? undefined : options.exitCodes?.[exitCode];
19698
+ if (named)
19699
+ return named;
19700
+ if (signal)
19701
+ return "killed";
19702
+ const text = failureText(error);
19703
+ for (const tool of options.tools ?? ALL_TOOLS) {
19704
+ for (const [reason, pattern] of TOOL_RULES[tool]) {
19705
+ if (pattern.test(text))
19706
+ return reason;
19707
+ }
19708
+ }
19709
+ for (const [reason, pattern] of SHARED_RULES) {
19710
+ if (pattern.test(text))
19711
+ return reason;
19712
+ }
19713
+ if (exitCode !== null) {
19714
+ for (const tool of options.tools ?? []) {
19715
+ const reason = TOOL_EXIT_CODES[tool][exitCode];
19716
+ if (reason)
19717
+ return reason;
19718
+ }
19719
+ const reason = SHARED_EXIT_CODES[exitCode];
19720
+ if (reason)
19721
+ return reason;
19722
+ }
19723
+ return "unclassified";
19724
+ }
19725
+ function numericExitCode(error) {
19726
+ for (const key of ["exitCode", "code"]) {
19727
+ const value = read2(error, key);
19728
+ if (typeof value === "number" && Number.isFinite(value))
19729
+ return value;
19730
+ }
19731
+ return null;
19732
+ }
19733
+ function classifyCommandFailure(error, options = {}) {
19734
+ if (typeof error !== "object" || error === null) {
19735
+ return { reason: "unclassified", exitCode: null, signal: null };
19736
+ }
19737
+ try {
19738
+ const exitCode = numericExitCode(error);
19739
+ const rawSignal = read2(error, "signal");
19740
+ const signal = typeof rawSignal === "string" && SIGNAL_PATTERN.test(rawSignal) ? rawSignal : null;
19741
+ return { reason: classifiedReason(error, exitCode, signal, options), exitCode, signal };
19742
+ } catch {
19743
+ return { reason: "unclassified", exitCode: null, signal: null };
19744
+ }
19745
+ }
19746
+
19747
+ // ../protocol/src/node/lost-exit-reaper.ts
19748
+ import { createRequire as createRequire2 } from "node:module";
19749
+
19750
+ // ../protocol/src/node/shell-process-state.ts
19751
+ import { spawnSync } from "node:child_process";
19752
+ import { readdirSync, readFileSync as readFileSync2 } from "node:fs";
19753
+ import { constants as osConstants } from "node:os";
19754
+ var PROCESS_INSPECTION_OPTIONS = {
19755
+ timeout: 100,
19756
+ killSignal: "SIGKILL",
19757
+ maxBuffer: 1024 * 1024
19758
+ };
19759
+ function bunRuntime() {
19760
+ return globalThis.Bun;
19761
+ }
19762
+ function decodeWaitStatus(status) {
19763
+ const signalNumber = status & 127;
19764
+ if (signalNumber === 0)
19765
+ return { code: status >> 8 & 255, signal: null };
19766
+ const name = Object.entries(osConstants.signals).find(([, value]) => value === signalNumber)?.[0];
19767
+ return { code: null, signal: name ?? "SIGKILL" };
19768
+ }
19769
+ function readZombieExit(pid) {
19770
+ try {
19771
+ const result = bunRuntime()?.spawnSync(["/bin/ps", "-o", "stat=,xstat=", "-p", String(pid)], PROCESS_INSPECTION_OPTIONS);
19772
+ if (!result?.success)
19773
+ return;
19774
+ const { stdout } = result;
19775
+ const match = /^Z\S*\s+([0-9a-f]+)\s*$/i.exec(stdout.toString().trim());
19776
+ return match ? decodeWaitStatus(Number.parseInt(match[1], 16)) : undefined;
19777
+ } catch {
19778
+ return;
19779
+ }
19780
+ }
19781
+ var EXIT_WATCH_MS = 1000;
19782
+ var EXIT_WATCH_MAX_MS = 16000;
19783
+ function watchForLostExit(pid, onExit) {
19784
+ if (process.platform !== "darwin" || pid === undefined || !bunRuntime())
19785
+ return () => {
19786
+ return;
19787
+ };
19788
+ let timer;
19789
+ const watch = (delayMs) => {
19790
+ timer = setTimeout(() => {
19791
+ const exit = readZombieExit(pid);
19792
+ if (exit)
19793
+ onExit(exit);
19794
+ else
19795
+ watch(Math.min(delayMs * 2, EXIT_WATCH_MAX_MS));
19796
+ }, delayMs);
19797
+ };
19798
+ watch(EXIT_WATCH_MS);
19799
+ return () => clearTimeout(timer);
19800
+ }
19801
+ function isLiveMember(state, groupId, pgid) {
19802
+ return Number(groupId) === pgid && state !== undefined && !/^[ZX]/.test(state);
19803
+ }
19804
+ function linuxGroupHasLiveMember(pgid) {
19805
+ for (const entry of readdirSync("/proc")) {
19806
+ if (!/^\d+$/.test(entry))
19807
+ continue;
19808
+ let stat;
19809
+ try {
19810
+ stat = readFileSync2(`/proc/${entry}/stat`, "latin1");
19811
+ } catch {
19812
+ continue;
19813
+ }
19814
+ const [state, , groupId] = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
19815
+ if (isLiveMember(state, groupId, pgid))
19816
+ return true;
19817
+ }
19818
+ return false;
19819
+ }
19820
+ function psGroupHasLiveMember(pgid) {
19821
+ const argv = ["-A", "-o", "pgid=,stat="];
19822
+ const bun = bunRuntime();
19823
+ const result = bun ? bun.spawnSync(["/bin/ps", ...argv], PROCESS_INSPECTION_OPTIONS) : spawnSync("/bin/ps", argv, PROCESS_INSPECTION_OPTIONS);
19824
+ const succeeded = "success" in result ? result.success : result.status === 0 && !result.error;
19825
+ if (!succeeded)
19826
+ return true;
19827
+ return result.stdout.toString().split(`
19828
+ `).some((line) => {
19829
+ const [groupId, state] = line.trim().split(/\s+/);
19830
+ return isLiveMember(state, groupId, pgid);
19831
+ });
19832
+ }
19833
+ function groupHasLiveMember(pgid) {
19834
+ try {
19835
+ return process.platform === "linux" ? linuxGroupHasLiveMember(pgid) : psGroupHasLiveMember(pgid);
19836
+ } catch {
19837
+ return true;
19838
+ }
19839
+ }
19840
+
19841
+ // ../protocol/src/node/lost-exit-reaper.ts
19842
+ var log7 = createLogger("process");
19843
+ var REAP_GRACE_MS = 2000;
19844
+ var REAP_MAX_CHECK_MS = 30000;
19845
+ var REAP_MAX_CHECKS = 12;
19846
+ var REAP_MAX_PENDING = 256;
19847
+ function createLostExitReaper(options) {
19848
+ const { system } = options;
19849
+ const graceMs = options.graceMs ?? REAP_GRACE_MS;
19850
+ const maxCheckMs = options.maxCheckMs ?? REAP_MAX_CHECK_MS;
19851
+ const maxChecks = options.maxChecks ?? REAP_MAX_CHECKS;
19852
+ const maxPending = options.maxPending ?? REAP_MAX_PENDING;
19853
+ const pending = new Map;
19854
+ let reaped = 0;
19855
+ let abandoned = 0;
19856
+ const abandon = (pid, reason) => {
19857
+ abandoned += 1;
19858
+ log7.warn("child.reap-abandoned", { pid, reason });
19859
+ };
19860
+ const check = (pid, reported, startedAt) => {
19861
+ if (reported())
19862
+ return false;
19863
+ const found = system.inspect(pid);
19864
+ if (found === undefined)
19865
+ return true;
19866
+ if (found === "gone" || found.ppid !== system.selfPid)
19867
+ return false;
19868
+ if (!found.state.startsWith("Z"))
19869
+ return true;
19870
+ const result = system.waitNoHang(pid);
19871
+ if (result === pid) {
19872
+ reaped += 1;
19873
+ log7.info("child.reaped", { pid, waitedMs: Date.now() - startedAt });
19874
+ return false;
19875
+ }
19876
+ if (result === 0)
19877
+ return true;
19878
+ abandon(pid, "waitpid-failed");
19879
+ return false;
19880
+ };
19881
+ const schedule = (pid, reported, startedAt, delayMs, checks) => {
19882
+ const timer = setTimeout(() => {
19883
+ pending.delete(pid);
19884
+ let again;
19885
+ try {
19886
+ again = check(pid, reported, startedAt);
19887
+ } catch {
19888
+ again = true;
19889
+ }
19890
+ if (!again)
19891
+ return;
19892
+ if (checks + 1 >= maxChecks) {
19893
+ abandon(pid, "not-a-zombie");
19894
+ return;
19895
+ }
19896
+ schedule(pid, reported, startedAt, Math.min(delayMs * 2, maxCheckMs), checks + 1);
19897
+ }, delayMs);
19898
+ timer.unref?.();
19899
+ pending.set(pid, timer);
19900
+ };
19901
+ return {
19902
+ reap(pid, reported) {
19903
+ if (!Number.isSafeInteger(pid) || pid <= 1 || pid === system.selfPid)
19904
+ return;
19905
+ if (pending.has(pid) || reported())
19906
+ return;
19907
+ if (pending.size >= maxPending) {
19908
+ abandon(pid, "capacity");
19909
+ return;
19910
+ }
19911
+ schedule(pid, reported, Date.now(), graceMs, 0);
19912
+ },
19913
+ stats: () => ({ pending: pending.size, reaped, abandoned }),
19914
+ stop() {
19915
+ for (const timer of pending.values())
19916
+ clearTimeout(timer);
19917
+ pending.clear();
19918
+ }
19919
+ };
19920
+ }
19921
+ var WNOHANG = 1;
19922
+ function loadDarwinWaitpid(loadFfi = () => createRequire2(import.meta.url)("bun:ffi")) {
19923
+ try {
19924
+ const { dlopen, FFIType } = loadFfi();
19925
+ const libSystem = dlopen("/usr/lib/libSystem.B.dylib", {
19926
+ waitpid: { args: [FFIType.i32, FFIType.ptr, FFIType.i32], returns: FFIType.i32 }
19927
+ });
19928
+ const status = new Int32Array(1);
19929
+ return (pid) => libSystem.symbols.waitpid(pid, status, WNOHANG);
19930
+ } catch {
19931
+ return;
19932
+ }
19933
+ }
19934
+ function darwinReaperSystem(loadFfi) {
19935
+ const waitNoHang = loadDarwinWaitpid(loadFfi);
19936
+ if (!waitNoHang)
19937
+ return;
19938
+ return {
19939
+ selfPid: process.pid,
19940
+ inspect(pid) {
19941
+ const result = bunRuntime()?.spawnSync(["/bin/ps", "-o", "ppid=,stat=", "-p", String(pid)], PROCESS_INSPECTION_OPTIONS);
19942
+ if (!result)
19943
+ return;
19944
+ const output = result.stdout.toString().trim();
19945
+ if (!result.success)
19946
+ return result.exitCode === 1 && output === "" ? "gone" : undefined;
19947
+ const match = /^(\d+)\s+(\S+)$/.exec(output);
19948
+ return match ? { ppid: Number(match[1]), state: match[2] } : undefined;
19949
+ },
19950
+ waitNoHang
19951
+ };
19952
+ }
19953
+ var defaultReaper;
19954
+ function createDarwinLostExitReaper(loadFfi) {
19955
+ const system = darwinReaperSystem(loadFfi);
19956
+ if (!system)
19957
+ log7.warn("child.reap-unavailable");
19958
+ return system ? createLostExitReaper({ system }) : null;
19959
+ }
19960
+ function sharedReaper() {
19961
+ if (defaultReaper === undefined) {
19962
+ defaultReaper = createDarwinLostExitReaper();
19963
+ }
19964
+ return defaultReaper ?? undefined;
19965
+ }
19966
+ function reapAfterLostExit(pid, reported) {
19967
+ if (process.platform !== "darwin" || pid === undefined || !bunRuntime())
19968
+ return;
19969
+ sharedReaper()?.reap(pid, reported);
19970
+ }
19971
+
19972
+ // ../protocol/src/node/command-capture.ts
19973
+ class CommandFailedError extends Error {
19974
+ stdout;
19975
+ stdoutBytes;
19976
+ stderr;
19977
+ timedOut;
19978
+ outputCloseTimedOut;
19979
+ executableMissing;
19980
+ aborted;
19981
+ outputLimitExceeded;
19982
+ exitCode;
19983
+ signal;
19984
+ constructor(message, details = {}) {
19985
+ super(message);
19986
+ this.name = "CommandFailedError";
19987
+ this.stdout = details.stdout ?? "";
19988
+ this.stdoutBytes = details.stdoutBytes ?? Buffer.alloc(0);
19989
+ this.stderr = details.stderr ?? "";
19990
+ this.timedOut = details.timedOut ?? false;
19991
+ this.outputCloseTimedOut = details.outputCloseTimedOut ?? false;
19992
+ this.executableMissing = details.executableMissing ?? false;
19993
+ this.aborted = details.aborted ?? false;
19994
+ this.outputLimitExceeded = details.outputLimitExceeded ?? false;
19995
+ this.exitCode = details.exitCode ?? null;
19996
+ this.signal = details.signal ?? null;
19997
+ }
19998
+ toJSON() {
19999
+ return { ...formatLogError(this), ...classifyCommandFailure(this) };
20000
+ }
20001
+ [inspect.custom]() {
20002
+ const { name, reason, exitCode, signal, stack } = this.toJSON();
20003
+ const frames = stack?.length ? ` | ${stack.join(" | ")}` : "";
20004
+ return `${name} reason=${reason} exitCode=${exitCode} signal=${signal} outputOmitted=true${frames}`;
20005
+ }
20006
+ }
20007
+ function redactCommandValues(value, redactValues) {
20008
+ const secrets = Array.from(new Set((redactValues ?? []).filter((secret) => typeof secret === "string" && secret.length > 0))).sort((left, right) => right.length - left.length);
20009
+ return secrets.reduce((redacted, secret) => redacted.split(secret).join("[REDACTED]"), value);
20010
+ }
20011
+ var COMMAND_ABORTED_MESSAGE = "Command aborted";
20012
+ var OUTPUT_LIMIT_MESSAGE = "maxBuffer length exceeded";
20013
+ function commandFailureOutcome(error) {
20014
+ const details = error ?? {};
20015
+ const message = typeof details.message === "string" ? details.message : "";
20016
+ return {
20017
+ timedOut: details.killed === true,
20018
+ executableMissing: details.code === "ENOENT",
20019
+ aborted: message === COMMAND_ABORTED_MESSAGE,
20020
+ outputLimitExceeded: details.outputLimitExceeded === true,
20021
+ exitCode: typeof details.code === "number" ? details.code : null,
20022
+ signal: details.signal ?? null
20023
+ };
20024
+ }
20025
+ var commandInvocations = new Map;
20026
+ var commandCaptureMetrics;
20027
+ var commandObservers = new Map;
20028
+ function nonInteractiveGitEnv(env) {
20029
+ const merged = { ...env ?? process.env };
20030
+ merged.GIT_TERMINAL_PROMPT ??= "0";
20031
+ if (process.platform !== "win32") {
20032
+ merged.SSH_ASKPASS ??= "/usr/bin/false";
20033
+ merged.SSH_ASKPASS_REQUIRE ??= "force";
20034
+ }
20035
+ return merged;
20036
+ }
20037
+ var MAX_COMMAND_OUTPUT_BYTES = 50 * 1024 * 1024;
20038
+ var COMMAND_KILL_GRACE_MS = 100;
20039
+ var COMMAND_OUTPUT_CHECK_MS = 100;
20040
+ var COMMAND_GROUP_POLL_MS = 5;
20041
+ var COMMAND_GROUP_POLL_MAX_MS = 200;
20042
+ function openCaptureFile() {
20043
+ const filePath = path2.join(os.tmpdir(), `orkestrator-capture-${randomUUID()}`);
20044
+ const fd = captureFs.openSync(filePath, fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_RDWR | fsConstants.O_APPEND, 384);
20045
+ try {
20046
+ captureFs.unlinkSync(filePath);
20047
+ return fd;
20048
+ } catch (error) {
20049
+ captureFs.closeSync(fd);
20050
+ throw error;
20051
+ }
20052
+ }
20053
+ function readCaptureFile(fd, limit) {
20054
+ const size = Math.min(captureFs.fstatSync(fd).size, limit);
20055
+ const buffer = Buffer.allocUnsafe(size);
20056
+ let offset = 0;
20057
+ while (offset < size) {
20058
+ const bytesRead = captureFs.readSync(fd, buffer, offset, size - offset, offset);
20059
+ if (bytesRead === 0)
20060
+ break;
20061
+ offset += bytesRead;
20062
+ }
20063
+ return buffer.subarray(0, offset);
20064
+ }
20065
+ function spawnCaptured(command, args, options, stdoutFd, stderrFd) {
20066
+ const payload = options.stdin?.length ? Buffer.from(options.stdin) : undefined;
20067
+ const env = command === "git" ? nonInteractiveGitEnv(options.env) : options.env ?? process.env;
20068
+ const detached = process.platform !== "win32";
20069
+ const bun = bunRuntime();
20070
+ if (bun) {
20071
+ const child = bun.spawn([command, ...args], {
20072
+ cwd: options.cwd,
20073
+ env,
20074
+ detached,
20075
+ windowsHide: true,
20076
+ stdin: payload ?? "pipe",
20077
+ stdout: stdoutFd,
20078
+ stderr: stderrFd
20079
+ });
20080
+ if (!payload)
20081
+ closeStdin(child.stdin);
20082
+ const current = () => ({ code: child.exitCode, signal: child.signalCode });
20083
+ return {
20084
+ pid: child.pid,
20085
+ exited: child.exited.then(current),
20086
+ current,
20087
+ kill: (signal) => child.kill(signal)
20088
+ };
20089
+ }
20090
+ const child = spawn3(command, args, {
20091
+ cwd: options.cwd,
20092
+ env,
20093
+ detached,
20094
+ windowsHide: true,
20095
+ stdio: [payload ? "pipe" : "ignore", stdoutFd, stderrFd]
20096
+ });
20097
+ if (payload) {
20098
+ child.stdin?.on("error", () => {
20099
+ return;
20100
+ });
20101
+ child.stdin?.end(payload);
20102
+ }
20103
+ return {
20104
+ pid: child.pid,
20105
+ exited: new Promise((resolve, reject) => {
20106
+ child.once("exit", (code, signal) => resolve({ code, signal }));
20107
+ child.once("error", reject);
20108
+ }),
20109
+ current: () => ({ code: child.exitCode, signal: child.signalCode }),
20110
+ kill: (signal) => {
20111
+ child.kill(signal);
20112
+ }
20113
+ };
20114
+ }
20115
+ function closeStdin(stdin) {
20116
+ try {
20117
+ Promise.resolve(stdin.end()).catch(() => {
20118
+ return;
20119
+ });
20120
+ } catch {}
20121
+ }
20122
+ function exitReported(child) {
20123
+ const { code, signal } = child.current();
20124
+ return code !== null || signal !== null;
20125
+ }
20126
+ function signalCommand(child, signal) {
20127
+ if (child.pid === undefined)
20128
+ return;
20129
+ try {
20130
+ if (process.platform !== "win32") {
20131
+ process.kill(-child.pid, signal);
20132
+ } else {
20133
+ child.kill(signal);
20134
+ }
20135
+ } catch {}
20136
+ }
20137
+ function commandGroupAlive(child) {
20138
+ if (process.platform === "win32" || child.pid === undefined)
20139
+ return false;
20140
+ try {
20141
+ process.kill(-child.pid, 0);
20142
+ } catch (error) {
20143
+ if (error.code === "ESRCH")
20144
+ return false;
20145
+ }
20146
+ return groupHasLiveMember(child.pid);
20147
+ }
20148
+ function executeCommandBytes(command, args, options, timeoutMs, outputLimit, stderrLimit) {
20149
+ return new Promise((resolve, reject) => {
20150
+ if (options.signal?.aborted) {
20151
+ reject(Object.assign(new Error(COMMAND_ABORTED_MESSAGE), { killed: true }));
20152
+ return;
20153
+ }
20154
+ const captureFds = [];
20155
+ const releaseCaptureFds = () => {
20156
+ for (const fd of captureFds.splice(0)) {
20157
+ try {
20158
+ captureFs.closeSync(fd);
20159
+ } catch {}
20160
+ }
20161
+ };
20162
+ try {
20163
+ captureFds.push(openCaptureFile());
20164
+ captureFds.push(openCaptureFile());
20165
+ } catch (error) {
20166
+ releaseCaptureFds();
20167
+ const code = error.code ?? "unknown";
20168
+ reject(new Error(`Could not open a command output file in the temporary directory: ${code}`));
20169
+ return;
20170
+ }
20171
+ const [stdoutFd, stderrFd] = captureFds;
20172
+ let child;
20173
+ try {
20174
+ child = spawnCaptured(command, args, options, stdoutFd, stderrFd);
20175
+ } catch (error) {
20176
+ releaseCaptureFds();
20177
+ reject(error);
20178
+ return;
20179
+ }
20180
+ let settled = false;
20181
+ let timedOut = false;
20182
+ let timeoutTimer;
20183
+ let groupTimer;
20184
+ let limitTimer;
20185
+ let stopExitWatch = () => {};
20186
+ let commandExit;
20187
+ let pendingFailure;
20188
+ const finishCapture = () => {
20189
+ settled = true;
20190
+ clearTimeout(timeoutTimer);
20191
+ clearTimeout(groupTimer);
20192
+ clearInterval(limitTimer);
20193
+ stopExitWatch();
20194
+ options.signal?.removeEventListener("abort", abort);
20195
+ if (!exitReported(child))
20196
+ reapAfterLostExit(child.pid, () => exitReported(child));
20197
+ try {
20198
+ return {
20199
+ stdout: readCaptureFile(stdoutFd, outputLimit),
20200
+ stderr: readCaptureFile(stderrFd, stderrLimit)
20201
+ };
20202
+ } catch (error) {
20203
+ reject(error);
20204
+ return;
20205
+ } finally {
20206
+ releaseCaptureFds();
20207
+ }
20208
+ };
20209
+ const rejectFailure = (error) => {
20210
+ const output = finishCapture();
20211
+ if (output)
20212
+ reject(Object.assign(error, { ...output, killed: timedOut }));
20213
+ };
20214
+ const awaitTermination = (delayMs) => {
20215
+ clearTimeout(groupTimer);
20216
+ if (settled)
20217
+ return;
20218
+ if ((commandExit || exitReported(child)) && !commandGroupAlive(child)) {
20219
+ rejectFailure(pendingFailure);
20220
+ return;
20221
+ }
20222
+ groupTimer = setTimeout(awaitTermination, delayMs, Math.min(delayMs * 2, COMMAND_GROUP_POLL_MAX_MS));
20223
+ };
20224
+ const fail = (error) => {
20225
+ if (settled || pendingFailure)
20226
+ return;
20227
+ if (options.waitForTermination && child.pid !== undefined) {
20228
+ pendingFailure = error;
20229
+ signalCommand(child, "SIGKILL");
20230
+ clearTimeout(timeoutTimer);
20231
+ clearInterval(limitTimer);
20232
+ awaitTermination(COMMAND_GROUP_POLL_MS);
20233
+ } else
20234
+ rejectFailure(error);
20235
+ };
20236
+ const abort = () => {
20237
+ timedOut = true;
20238
+ signalCommand(child, "SIGKILL");
20239
+ fail(new Error(COMMAND_ABORTED_MESSAGE));
20240
+ };
20241
+ options.signal?.addEventListener("abort", abort, { once: true });
20242
+ const checkOutputLimit = () => {
20243
+ const stream = captureFs.fstatSync(stdoutFd).size > outputLimit ? "stdout" : captureFs.fstatSync(stderrFd).size > stderrLimit ? "stderr" : undefined;
20244
+ if (stream === undefined)
20245
+ return false;
20246
+ signalCommand(child, "SIGKILL");
20247
+ fail(Object.assign(new Error(`${stream} ${OUTPUT_LIMIT_MESSAGE}`), {
20248
+ outputLimitExceeded: true
20249
+ }));
20250
+ return true;
20251
+ };
20252
+ const failIfOverLimit = () => {
20253
+ try {
20254
+ return checkOutputLimit();
20255
+ } catch (error) {
20256
+ signalCommand(child, "SIGKILL");
20257
+ fail(error instanceof Error ? error : new Error(String(error)));
20258
+ return true;
20259
+ }
20260
+ };
20261
+ limitTimer = setInterval(() => {
20262
+ if (!settled && !timedOut && !pendingFailure)
20263
+ failIfOverLimit();
20264
+ }, COMMAND_OUTPUT_CHECK_MS);
20265
+ const settleOnExit = () => {
20266
+ if (settled || timedOut || pendingFailure || failIfOverLimit())
20267
+ return;
20268
+ if (commandExit?.code !== 0 || commandExit.signal !== null) {
20269
+ fail(Object.assign(new Error(`Command failed: ${[command, ...args].join(" ")}`), {
20270
+ code: commandExit?.code,
20271
+ signal: commandExit?.signal
20272
+ }));
20273
+ return;
20274
+ }
20275
+ const output = finishCapture();
20276
+ if (output)
20277
+ resolve(output);
20278
+ };
20279
+ const awaitGroupExit = (delayMs) => {
20280
+ if (settled || timedOut || pendingFailure)
20281
+ return;
20282
+ if (commandGroupAlive(child)) {
20283
+ groupTimer = setTimeout(awaitGroupExit, delayMs, Math.min(delayMs * 2, COMMAND_GROUP_POLL_MAX_MS));
20284
+ return;
20285
+ }
20286
+ settleOnExit();
20287
+ };
20288
+ const onCommandExit = (exit) => {
20289
+ if (commandExit)
20290
+ return;
20291
+ commandExit = exit;
20292
+ stopExitWatch();
20293
+ if (pendingFailure)
20294
+ awaitTermination(COMMAND_GROUP_POLL_MS);
20295
+ else if (options.waitForDescendants)
20296
+ awaitGroupExit(COMMAND_GROUP_POLL_MS);
20297
+ else
20298
+ settleOnExit();
20299
+ };
20300
+ child.exited.then(onCommandExit, (error) => fail(error instanceof Error ? error : new Error(String(error))));
20301
+ stopExitWatch = watchForLostExit(child.pid, (exit) => {
20302
+ if (!settled)
20303
+ onCommandExit(exit);
20304
+ });
20305
+ if (timeoutMs > 0) {
20306
+ timeoutTimer = setTimeout(() => {
20307
+ timedOut = true;
20308
+ signalCommand(child, "SIGTERM");
20309
+ timeoutTimer = setTimeout(() => {
20310
+ signalCommand(child, "SIGKILL");
20311
+ fail(Object.assign(new Error(`Command timed out after ${timeoutMs} ms`), {
20312
+ code: child.current().code,
20313
+ signal: child.current().signal
20314
+ }));
20315
+ }, COMMAND_KILL_GRACE_MS);
20316
+ }, timeoutMs);
20317
+ }
20318
+ });
20319
+ }
20320
+ async function runCommandBytes(command, args = [], options = {}) {
20321
+ const timeoutMs = options.timeoutMs ?? 60000;
20322
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > 2147483647) {
20323
+ throw new RangeError("timeoutMs must be an integer between 0 and 2147483647");
20324
+ }
20325
+ const outputLimit = options.maxOutputBytes ?? MAX_COMMAND_OUTPUT_BYTES;
20326
+ if (!Number.isSafeInteger(outputLimit) || outputLimit <= 0) {
20327
+ throw new RangeError("maxOutputBytes must be a positive integer");
20328
+ }
20329
+ const stderrLimit = options.maxStderrBytes ?? outputLimit;
20330
+ if (!Number.isSafeInteger(stderrLimit) || stderrLimit <= 0) {
20331
+ throw new RangeError("maxStderrBytes must be a positive integer");
20332
+ }
20333
+ if (commandInvocations.size < 64 || commandInvocations.has(command)) {
20334
+ commandInvocations.set(command, (commandInvocations.get(command) ?? 0) + 1);
20335
+ }
20336
+ for (const observer of commandObservers.get(command) ?? [])
20337
+ observer(args);
20338
+ commandCaptureMetrics?.started(command, args);
20339
+ try {
20340
+ const { stdout, stderr } = await executeCommandBytes(command, args, options, timeoutMs, outputLimit, stderrLimit);
20341
+ commandCaptureMetrics?.capturedBytes(stdout.length);
20342
+ return {
20343
+ stdout: Buffer.isBuffer(stdout) ? stdout : Buffer.from(stdout),
20344
+ stderr: Buffer.isBuffer(stderr) ? stderr : Buffer.from(stderr)
20345
+ };
20346
+ } catch (error) {
20347
+ const outcome = commandFailureOutcome(error);
20348
+ const redacting = options.redactValues?.some((value) => typeof value === "string" && value.length > 0);
20349
+ if (error && typeof error === "object" && "stdout" in error && "stderr" in error) {
20350
+ const withOutput = error;
20351
+ const stderr = withOutput.stderr?.toString() ?? "";
20352
+ const stdout = withOutput.stdout?.toString() ?? "";
20353
+ const message = (stderr || stdout || withOutput.message || "Command failed").trim();
20354
+ throw new CommandFailedError(redactCommandValues(message, options.redactValues), {
20355
+ ...outcome,
20356
+ stdout: redactCommandValues(stdout, options.redactValues),
20357
+ stderr: redactCommandValues(stderr, options.redactValues),
20358
+ ...!redacting && Buffer.isBuffer(withOutput.stdout) ? { stdoutBytes: withOutput.stdout } : {}
20359
+ });
20360
+ }
20361
+ if (redacting) {
20362
+ const message = error instanceof Error ? error.message : String(error);
20363
+ throw new CommandFailedError(redactCommandValues(message || "Command failed", options.redactValues), outcome);
20364
+ }
20365
+ if (outcome.timedOut || outcome.executableMissing) {
20366
+ const message = error instanceof Error ? error.message : String(error);
20367
+ throw new CommandFailedError(message || "Command failed", outcome);
20368
+ }
20369
+ throw error;
20370
+ }
20371
+ }
20372
+ async function runCommand(command, args = [], options = {}) {
20373
+ const { stdout, stderr } = await runCommandBytes(command, args, options);
20374
+ return {
20375
+ stdout: redactCommandValues(stdout.toString(), options.redactValues),
20376
+ stderr: redactCommandValues(stderr.toString(), options.redactValues)
20377
+ };
20378
+ }
20379
+
20380
+ // ../protocol/src/node/workspace-change-probe.ts
19256
20381
  var DEFAULT_MAX_UNTRACKED_FILE_BYTES = 2 * 1024 * 1024;
19257
20382
  var DEFAULT_MAX_UNTRACKED_FILES = 5000;
19258
20383
  var DEFAULT_SLOW_SNAPSHOT_MS = 500;
@@ -19266,31 +20391,20 @@ var temporaryObjectDirectories = new Set;
19266
20391
  process.once("exit", () => {
19267
20392
  for (const directory of temporaryObjectDirectories) {
19268
20393
  try {
19269
- rmSync2(directory, { recursive: true, force: true });
20394
+ rmSync3(directory, { recursive: true, force: true });
19270
20395
  } catch {}
19271
20396
  }
19272
20397
  });
19273
- var runGit = (args, options) => new Promise((resolvePromise, reject) => {
19274
- const env = { ...process.env, ...options.env, GIT_OPTIONAL_LOCKS: "0" };
19275
- if (options.stdin === undefined) {
19276
- execFile("git", args, { cwd: options.cwd, env, timeout: GIT_TIMEOUT_MS, maxBuffer: GIT_MAX_BUFFER }, (error, stdout) => error ? reject(error) : resolvePromise({ stdout: String(stdout) }));
19277
- return;
19278
- }
19279
- const child = spawn3("git", args, { cwd: options.cwd, env, timeout: GIT_TIMEOUT_MS });
19280
- let stdout = "";
19281
- let stdoutBytes = 0;
19282
- child.stdout.setEncoding("utf8");
19283
- child.stdout.on("data", (chunk) => {
19284
- stdoutBytes += chunk.length;
19285
- if (stdoutBytes <= GIT_MAX_BUFFER)
19286
- stdout += chunk;
20398
+ var runGit = async (args, options) => {
20399
+ const { stdout } = await runCommand("git", args, {
20400
+ cwd: options.cwd,
20401
+ env: { ...process.env, ...options.env, GIT_OPTIONAL_LOCKS: "0" },
20402
+ timeoutMs: GIT_TIMEOUT_MS,
20403
+ maxOutputBytes: GIT_MAX_BUFFER,
20404
+ ...options.stdin === undefined ? {} : { stdin: options.stdin }
19287
20405
  });
19288
- child.stderr.resume();
19289
- child.on("error", reject);
19290
- child.on("close", (code) => code === 0 ? resolvePromise({ stdout }) : reject(new Error(`git exited with ${code}`)));
19291
- child.stdin.on("error", () => {});
19292
- child.stdin.end(options.stdin);
19293
- });
20406
+ return { stdout };
20407
+ };
19294
20408
 
19295
20409
  class WorkspaceChangeProbe {
19296
20410
  git;
@@ -19578,7 +20692,7 @@ class WorkspaceChangeProbe {
19578
20692
  return;
19579
20693
  const { root, indexPath } = repo.location;
19580
20694
  const started = this.now();
19581
- const tempIndex = join6(this.tempDir, `orkestrator-probe-${randomUUID()}.index`);
20695
+ const tempIndex = join6(this.tempDir, `orkestrator-probe-${randomUUID2()}.index`);
19582
20696
  const objectDirectory = await mkdtemp(join6(this.tempDir, "orkestrator-probe-objects-"));
19583
20697
  temporaryObjectDirectories.add(objectDirectory);
19584
20698
  let retained = false;
@@ -19841,7 +20955,7 @@ function acpToolKind(source, runtime) {
19841
20955
  }
19842
20956
 
19843
20957
  // ../../bridges/acp-bridge/src/change-evidence.ts
19844
- import { randomUUID as randomUUID3 } from "node:crypto";
20958
+ import { randomUUID as randomUUID4 } from "node:crypto";
19845
20959
  import { resolve as resolve5 } from "node:path";
19846
20960
 
19847
20961
  // ../protocol/src/field-validation.ts
@@ -20245,8 +21359,8 @@ function workspaceObservationReportIssues(value) {
20245
21359
  }
20246
21360
 
20247
21361
  // ../protocol/src/node/change-tracking/evidence-spool.ts
20248
- import { createHash as createHash6, randomUUID as randomUUID2 } from "node:crypto";
20249
- import { readdirSync, readFileSync as readFileSync2 } from "node:fs";
21362
+ import { createHash as createHash7, randomUUID as randomUUID3 } from "node:crypto";
21363
+ import { readdirSync as readdirSync2, readFileSync as readFileSync3 } from "node:fs";
20250
21364
  import { appendFile as appendFile2, mkdir as mkdir2, rename as rename2, rm as rm3, writeFile as writeFile2 } from "node:fs/promises";
20251
21365
  import { join as join7 } from "node:path";
20252
21366
  var DEFAULT_EVIDENCE_SPOOL_LIMITS = {
@@ -20261,10 +21375,10 @@ var DEFAULT_EVIDENCE_SPOOL_LIMITS = {
20261
21375
  var ENTRIES_FILE = "entries.jsonl";
20262
21376
  var BODY_DIRECTORY = "bodies";
20263
21377
  function evidenceBodyId(bytes) {
20264
- return `sha256:${createHash6("sha256").update(bytes).digest("hex")}`;
21378
+ return `sha256:${createHash7("sha256").update(bytes).digest("hex")}`;
20265
21379
  }
20266
21380
  function stableEvidenceId(...parts) {
20267
- const hash = createHash6("sha256");
21381
+ const hash = createHash7("sha256");
20268
21382
  for (const part of parts)
20269
21383
  hash.update(`${part ?? ""}\x00`);
20270
21384
  return hash.digest("hex").slice(0, 40);
@@ -20291,7 +21405,7 @@ class ChangeEvidenceSpool {
20291
21405
  restoring = false;
20292
21406
  constructor(options = {}) {
20293
21407
  this.limits = { ...DEFAULT_EVIDENCE_SPOOL_LIMITS, ...options.limits };
20294
- this.runtimeEpoch = options.runtimeEpoch ?? randomUUID2();
21408
+ this.runtimeEpoch = options.runtimeEpoch ?? randomUUID3();
20295
21409
  this.directory = options.directory;
20296
21410
  if (this.directory) {
20297
21411
  this.restoring = true;
@@ -20394,7 +21508,7 @@ class ChangeEvidenceSpool {
20394
21508
  return;
20395
21509
  if (this.entries.length >= this.limits.maxEntries - 1)
20396
21510
  return;
20397
- const gapId = randomUUID2();
21511
+ const gapId = randomUUID3();
20398
21512
  const coverage = this.droppedUnknown ? {
20399
21513
  kind: "unknown-range",
20400
21514
  bindingId: this.gapBindingId || "unknown",
@@ -20556,8 +21670,8 @@ class ChangeEvidenceSpool {
20556
21670
  restore(directory) {
20557
21671
  const bodyDirectory = join7(directory, BODY_DIRECTORY);
20558
21672
  try {
20559
- for (const name of readdirSync(bodyDirectory)) {
20560
- const bytes = new Uint8Array(readFileSync2(join7(bodyDirectory, name)));
21673
+ for (const name of readdirSync2(bodyDirectory)) {
21674
+ const bytes = new Uint8Array(readFileSync3(join7(bodyDirectory, name)));
20561
21675
  const id = evidenceBodyId(bytes);
20562
21676
  if (bodyFileName(id) !== name)
20563
21677
  continue;
@@ -20569,7 +21683,7 @@ class ChangeEvidenceSpool {
20569
21683
  } catch {}
20570
21684
  let text = "";
20571
21685
  try {
20572
- text = readFileSync2(join7(directory, ENTRIES_FILE), "utf8");
21686
+ text = readFileSync3(join7(directory, ENTRIES_FILE), "utf8");
20573
21687
  } catch {
20574
21688
  return;
20575
21689
  }
@@ -20907,7 +22021,7 @@ function canonicalEvidence(evidence) {
20907
22021
  }
20908
22022
 
20909
22023
  // ../../bridges/acp-bridge/src/change-evidence.ts
20910
- var log7 = createLogger("bridge.acp");
22024
+ var log8 = createLogger("bridge.acp");
20911
22025
  var MAX_DIFF_BLOCKS_PER_CALL = 100;
20912
22026
  var MAX_HELD_DIFF_BYTES = 32 * 1024 * 1024;
20913
22027
  var MAX_SEEN_CALL_IDS = 8192;
@@ -21031,7 +22145,7 @@ function recordFor(state, part) {
21031
22145
  evidence.pendingApprovals.delete(part.toolUseId);
21032
22146
  record = {
21033
22147
  callId: part.toolUseId,
21034
- ...isReusedCallId(state, evidence, part) ? { attemptId: `reuse:${turnId ?? randomUUID3()}` } : {},
22148
+ ...isReusedCallId(state, evidence, part) ? { attemptId: `reuse:${turnId ?? randomUUID4()}` } : {},
21035
22149
  ...turnId ? { turnId } : {},
21036
22150
  awaitingApproval: approval === "awaiting",
21037
22151
  approved: false,
@@ -21206,7 +22320,7 @@ function recordAcpToolEvidence(state, part, update) {
21206
22320
  if (isTerminal(phase))
21207
22321
  settleRecord(state, part, record);
21208
22322
  } catch (error) {
21209
- log7.warn("evidence.record-failed", {
22323
+ log8.warn("evidence.record-failed", {
21210
22324
  errorClass: error instanceof Error ? error.name : "unknown"
21211
22325
  });
21212
22326
  }
@@ -21250,13 +22364,13 @@ function recordAcpShellObservation(state, toolUseId, observation) {
21250
22364
  ...observation.unavailableReason ? { unavailableReason: observation.unavailableReason } : {}
21251
22365
  });
21252
22366
  } catch (error) {
21253
- log7.warn("evidence.shell-record-failed", {
22367
+ log8.warn("evidence.shell-record-failed", {
21254
22368
  errorClass: error instanceof Error ? error.name : "unknown"
21255
22369
  });
21256
22370
  }
21257
22371
  }
21258
22372
  function beginAcpTurnEvidence(state, requestId) {
21259
- const turnId = requestId || `turn:${randomUUID3()}`;
22373
+ const turnId = requestId || `turn:${randomUUID4()}`;
21260
22374
  evidenceFor(state).turn = { turnId, backgroundLaunched: false };
21261
22375
  changeEvidenceRecorder().turn({ conversationId: state.id, turnId }, "running", "may-write");
21262
22376
  }
@@ -21282,14 +22396,14 @@ function endAcpTurnEvidence(state, outcome) {
21282
22396
  const writers = state.activeSubagentToolIds.size > 0 || turn.backgroundLaunched ? "may-write" : "quiescent";
21283
22397
  changeEvidenceRecorder().turn({ conversationId: state.id, turnId: turn.turnId }, outcome, writers);
21284
22398
  } catch (error) {
21285
- log7.warn("evidence.turn-record-failed", {
22399
+ log8.warn("evidence.turn-record-failed", {
21286
22400
  errorClass: error instanceof Error ? error.name : "unknown"
21287
22401
  });
21288
22402
  }
21289
22403
  }
21290
22404
 
21291
22405
  // ../../bridges/acp-bridge/src/acp-command-changes.ts
21292
- var log8 = createLogger("bridge.acp");
22406
+ var log9 = createLogger("bridge.acp");
21293
22407
  var MAX_WINDOWS_PER_SESSION = 256;
21294
22408
  var MAX_CACHED_JOURNALS = MAX_RESUMABLE_SESSIONS;
21295
22409
  var probe;
@@ -21403,7 +22517,7 @@ function closeWindow(active, state, toolUseId, role) {
21403
22517
  recordAcpShellObservation(state, toolUseId, observation);
21404
22518
  recordCommandChange(state, toolUseId, legacyCommandChange(observation));
21405
22519
  }).catch((error) => {
21406
- log8.warn("command-change.record-failed", {
22520
+ log9.warn("command-change.record-failed", {
21407
22521
  errorClass: error instanceof Error ? error.name : "unknown"
21408
22522
  });
21409
22523
  });
@@ -21462,7 +22576,7 @@ async function applyJournaledCommandChanges(state) {
21462
22576
  function journalFor(acpSessionId) {
21463
22577
  if (!journalDirectory || !acpSessionId)
21464
22578
  return;
21465
- const name = createHash7("sha256").update(acpSessionId).digest("hex").slice(0, 40);
22579
+ const name = createHash8("sha256").update(acpSessionId).digest("hex").slice(0, 40);
21466
22580
  const path = resolve6(journalDirectory, `${name}.jsonl`);
21467
22581
  let journal = journals.get(path);
21468
22582
  if (journal) {
@@ -21620,7 +22734,7 @@ async function resumeSessionReserved(acpSessionId, signal, patch, policy, agentM
21620
22734
  throw new HttpError(410, `${provider} cannot reload persisted ACP sessions`);
21621
22735
  }
21622
22736
  state = {
21623
- id: randomBytes8(16).toString("hex"),
22737
+ id: randomBytes9(16).toString("hex"),
21624
22738
  acpSessionId,
21625
22739
  status: "idle",
21626
22740
  messages: [],
@@ -21777,7 +22891,7 @@ async function createSessionReserved(clientSessionKey, signal, spawnOptions = {}
21777
22891
  if (!isObject3(created) || typeof created.sessionId !== "string") {
21778
22892
  throw new Error(`${provider} returned an invalid ACP session`);
21779
22893
  }
21780
- const id = randomBytes8(16).toString("hex");
22894
+ const id = randomBytes9(16).toString("hex");
21781
22895
  const sessionConfig = normalizeAcpSessionConfig(provider, created);
21782
22896
  rememberCatalog(sessionConfig.composer);
21783
22897
  const state = newSessionState(id, clientSessionKey, created.sessionId, child, sessionConfig, spawnOptions);
@@ -21846,7 +22960,7 @@ function newSessionState(id, clientSessionKey, acpSessionId, child, sessionConfi
21846
22960
  };
21847
22961
  }
21848
22962
  async function createDeferredSession(clientSessionKey, spawnOptions) {
21849
- const id = randomBytes8(16).toString("hex");
22963
+ const id = randomBytes9(16).toString("hex");
21850
22964
  const empty = normalizeAcpSessionConfig(provider, {});
21851
22965
  const sessionConfig = withRequestedSelection({ ...empty, composer: { ...empty.composer, models: catalogCache?.models ?? [] } }, composerPatchFromSpawn(spawnOptions));
21852
22966
  const state = newSessionState(id, clientSessionKey, "", null, sessionConfig, spawnOptions);
@@ -22558,7 +23672,7 @@ function parkPermission(state, child, requestId, params) {
22558
23672
  }
22559
23673
  ];
22560
23674
  }).slice(0, 20) : [];
22561
- const id = randomBytes8(12).toString("hex");
23675
+ const id = randomBytes9(12).toString("hex");
22562
23676
  const requestedAt = Date.now();
22563
23677
  const promptSequence = state.promptSequence;
22564
23678
  const toolCallId = isObject3(params.toolCall) ? params.toolCall.toolCallId : undefined;
@@ -22615,7 +23729,7 @@ function permissionTitle(params) {
22615
23729
  return title.slice(0, 500);
22616
23730
  }
22617
23731
  function appendNonTextContent(state, update, role) {
22618
- const messageId = randomBytes8(12).toString("hex");
23732
+ const messageId = randomBytes9(12).toString("hex");
22619
23733
  const parts = contentBlockParts(update.content, messageId, 0);
22620
23734
  if (parts.length === 0)
22621
23735
  return;
@@ -22755,7 +23869,7 @@ function applySessionUpdate(state, params) {
22755
23869
  if (!message) {
22756
23870
  const modelId = role === "assistant" ? boundedModelId(state.sessionConfig.composer.selectedModelId) : undefined;
22757
23871
  message = {
22758
- id: randomBytes8(12).toString("hex"),
23872
+ id: randomBytes9(12).toString("hex"),
22759
23873
  role,
22760
23874
  content: "",
22761
23875
  parts: [],
@@ -23182,7 +24296,7 @@ function setPromptJournal(state, entry) {
23182
24296
  state.promptJournal.set(entry.requestId, entry);
23183
24297
  }
23184
24298
  // ../../bridges/acp-bridge/src/acp-prompt.ts
23185
- import { randomBytes as randomBytes9 } from "node:crypto";
24299
+ import { randomBytes as randomBytes10 } from "node:crypto";
23186
24300
 
23187
24301
  // ../../bridges/acp-bridge/src/structured-prompt-marker.ts
23188
24302
  var STRUCTURED_PROMPT_INSTRUCTION_PREFIX = "End your turn with exactly one JSON value";
@@ -23259,7 +24373,7 @@ function openRetryCard(state, text) {
23259
24373
  type: "retry",
23260
24374
  content: text,
23261
24375
  toolState: "pending",
23262
- sourcePartId: randomBytes9(12).toString("hex"),
24376
+ sourcePartId: randomBytes10(12).toString("hex"),
23263
24377
  sourceMessageId: message.id,
23264
24378
  createdAt: new Date().toISOString()
23265
24379
  };
@@ -23450,6 +24564,7 @@ function effectiveLogLevel(detail, area) {
23450
24564
  return detail.level;
23451
24565
  }
23452
24566
  }
24567
+ var LOG_DETAIL_EXPIRY_MS = 24 * 60 * 60 * 1000;
23453
24568
  function logDetailEnablesBridgeDiagnostics(detail) {
23454
24569
  return LEVEL_DETAIL[effectiveLogLevel(detail, BRIDGE_DIAGNOSTICS_LOG_AREA)] >= LEVEL_DETAIL.debug;
23455
24570
  }
@@ -23725,7 +24840,7 @@ function humanPromptObservation(messages, tasks) {
23725
24840
  }
23726
24841
 
23727
24842
  // ../../bridges/acp-bridge/src/acp-http.ts
23728
- import { randomBytes as randomBytes10 } from "node:crypto";
24843
+ import { randomBytes as randomBytes11 } from "node:crypto";
23729
24844
  import { pathToFileURL } from "node:url";
23730
24845
  import { gzip } from "node:zlib";
23731
24846
 
@@ -23906,7 +25021,7 @@ var STRUCTURED_OUTPUT_FAILURE_CODES = new Set([
23906
25021
  ]);
23907
25022
 
23908
25023
  // ../../bridges/acp-bridge/src/prompt-attachments.ts
23909
- import { constants as constants2 } from "node:fs";
25024
+ import { constants as constants3 } from "node:fs";
23910
25025
  import { lstat as lstat3, open as open4, realpath as realpath3 } from "node:fs/promises";
23911
25026
  import { isAbsolute as isAbsolute4, join as join8, relative as relative3, resolve as resolve8, sep as sep2 } from "node:path";
23912
25027
 
@@ -24071,8 +25186,8 @@ async function readWorkspaceImage(filePath, workspaceRoot) {
24071
25186
  if (!isPathWithin(canonicalRoot, canonicalTarget)) {
24072
25187
  throw new PromptAttachmentError("attachment_outside_workspace", "Image attachment must be contained in the current workspace");
24073
25188
  }
24074
- const noFollow = constants2.O_NOFOLLOW ?? 0;
24075
- const handle = await open4(targetPath, constants2.O_RDONLY | noFollow).catch((error) => {
25189
+ const noFollow = constants3.O_NOFOLLOW ?? 0;
25190
+ const handle = await open4(targetPath, constants3.O_RDONLY | noFollow).catch((error) => {
24076
25191
  throw attachmentErrorForFsFailure(error);
24077
25192
  });
24078
25193
  try {
@@ -24164,7 +25279,7 @@ var DEFAULT_MCP_MANAGEMENT_ROLLOUT = Object.freeze({
24164
25279
 
24165
25280
  // ../protocol/src/node/bridge-transcript-summary.ts
24166
25281
  import { Buffer as Buffer5 } from "node:buffer";
24167
- import { createHash as createHash8 } from "node:crypto";
25282
+ import { createHash as createHash9 } from "node:crypto";
24168
25283
 
24169
25284
  // ../protocol/src/node/progressive-transcript.ts
24170
25285
  var BRIDGE_TRANSCRIPT_MAX_MESSAGES = 100;
@@ -24330,7 +25445,7 @@ function digestPayload(payload) {
24330
25445
  const serialized = JSON.stringify(payload);
24331
25446
  return {
24332
25447
  bytes: Buffer5.byteLength(serialized),
24333
- digest: createHash8("sha256").update(serialized).digest("base64url").slice(0, 32)
25448
+ digest: createHash9("sha256").update(serialized).digest("base64url").slice(0, 32)
24334
25449
  };
24335
25450
  }
24336
25451
  function topLevelKey(part, index) {
@@ -25043,8 +26158,8 @@ function holdParkedRequest(state, family, id, held) {
25043
26158
  }
25044
26159
 
25045
26160
  // ../../bridges/acp-bridge/src/acp-http.ts
25046
- var TRANSCRIPT_GENERATION = randomBytes10(16).toString("hex");
25047
- var log9 = createLogger("bridge.acp");
26161
+ var TRANSCRIPT_GENERATION = randomBytes11(16).toString("hex");
26162
+ var log10 = createLogger("bridge.acp");
25048
26163
 
25049
26164
  class CommandUnavailableError extends Error {
25050
26165
  }
@@ -25055,6 +26170,9 @@ async function route(request, response, clientSignal) {
25055
26170
  }
25056
26171
  if (!authenticated(request))
25057
26172
  return json(response, 401, { error: "Unauthorized" });
26173
+ const refused = await admitNodeBridgeRequest(bridgeCredential.authority, request, MAX_BODY_BYTES);
26174
+ if (refused)
26175
+ return json(response, refused.status, refused.body);
25058
26176
  if (url.pathname === "/global/auth-check" && request.method === "GET") {
25059
26177
  return json(response, 200, { ok: true });
25060
26178
  }
@@ -25098,7 +26216,7 @@ async function route(request, response, clientSignal) {
25098
26216
  } catch (error) {
25099
26217
  if (error instanceof HttpError || error instanceof CredentialError)
25100
26218
  throw error;
25101
- log9.warn("http.route-failed", {
26219
+ log10.warn("http.route-failed", {
25102
26220
  method: request.method,
25103
26221
  error: formatLogError(error, { message: false })
25104
26222
  });
@@ -25491,7 +26609,7 @@ async function route(request, response, clientSignal) {
25491
26609
  }
25492
26610
  throw error;
25493
26611
  }
25494
- const userMessageId = randomBytes10(12).toString("hex");
26612
+ const userMessageId = randomBytes11(12).toString("hex");
25495
26613
  const userVisiblePrompt = selectedCommand ? displayPrompt || prompt : prompt;
25496
26614
  state.messages.push({
25497
26615
  id: userMessageId,
@@ -25775,13 +26893,18 @@ function storeAgentMcp(state, value) {
25775
26893
  }
25776
26894
  async function readJson(request) {
25777
26895
  const chunks = [];
25778
- let bytes = 0;
25779
- for await (const chunk of request) {
25780
- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
25781
- bytes += buffer.length;
25782
- if (bytes > MAX_BODY_BYTES)
25783
- throw new HttpError(413, "Request body is too large");
25784
- chunks.push(buffer);
26896
+ const admitted = takeAdmittedBody(request);
26897
+ if (admitted) {
26898
+ chunks.push(admitted);
26899
+ } else {
26900
+ let bytes = 0;
26901
+ for await (const chunk of request) {
26902
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
26903
+ bytes += buffer.length;
26904
+ if (bytes > MAX_BODY_BYTES)
26905
+ throw new HttpError(413, "Request body is too large");
26906
+ chunks.push(buffer);
26907
+ }
25785
26908
  }
25786
26909
  let parsed;
25787
26910
  try {
@@ -25988,9 +27111,9 @@ function installFatalRejectionGuard(options) {
25988
27111
  }
25989
27112
 
25990
27113
  // ../protocol/src/node/process-failure-log.ts
25991
- var log10 = createLogger("process");
27114
+ var log11 = createLogger("process");
25992
27115
  function logUnhandledRejection(reason) {
25993
- log10.throttled("error", "rejection.unhandled", {
27116
+ log11.throttled("error", "rejection.unhandled", {
25994
27117
  error: reason,
25995
27118
  fields: () => ({ error: formatLogError(reason, { message: false }) })
25996
27119
  });
@@ -26023,7 +27146,7 @@ function watchClientDisconnect(request, response, onDisconnect) {
26023
27146
  }
26024
27147
 
26025
27148
  // ../../bridges/acp-bridge/src/acp-server.ts
26026
- var log11 = createLogger("bridge.acp");
27149
+ var log12 = createLogger("bridge.acp");
26027
27150
  configureBridgeLogger();
26028
27151
  await restorePersistedState();
26029
27152
  var server = createServer((request, response) => {
@@ -26038,13 +27161,13 @@ var server = createServer((request, response) => {
26038
27161
  return;
26039
27162
  }
26040
27163
  if (error instanceof PolicyWideningRefusedError) {
26041
- log11.warn("session.policy-widening-refused", { widened: error.widened.join(",") });
27164
+ log12.warn("session.policy-widening-refused", { widened: error.widened.join(",") });
26042
27165
  json(response, 403, error.refusal());
26043
27166
  return;
26044
27167
  }
26045
27168
  const status = error instanceof HttpError ? error.status : 500;
26046
27169
  if (status === 500 && !controller.signal.aborted) {
26047
- log11.warn("http.route-failed", {
27170
+ log12.warn("http.route-failed", {
26048
27171
  method: request.method,
26049
27172
  error: formatLogError(error, { message: false })
26050
27173
  });
@@ -26052,7 +27175,7 @@ var server = createServer((request, response) => {
26052
27175
  json(response, status, { error: error instanceof Error ? error.message : String(error) });
26053
27176
  }).finally(stopWatchingClient);
26054
27177
  });
26055
- server.listen(port, hostname, () => log11.info("server.listening", { provider, hostname, port }));
27178
+ server.listen(port, hostname, () => log12.info("server.listening", { provider, hostname, port }));
26056
27179
  var shutdownPromise = null;
26057
27180
  function shutdown() {
26058
27181
  if (shutdownPromise)