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/agent-platforms.ts
2
74
  var AGENT_PLATFORMS = Object.freeze([
3
75
  "claude",
@@ -1394,6 +1466,7 @@ var DESKTOP_LOG_AREAS = defineLogAreas({
1394
1466
  events: {
1395
1467
  "attention-failed": "A dialog could not ask for the user's attention.",
1396
1468
  closed: "A native dialog closed.",
1469
+ "hidden-cancelled": "A hidden profile cancelled a dialog without opening native UI.",
1397
1470
  "open-failed": "A dialog could not open; it was answered as cancelled.",
1398
1471
  opening: "A native dialog is opening.",
1399
1472
  "preview-beforeunload-ignored": "A browser preview's beforeunload handler was ignored.",
@@ -1479,6 +1552,7 @@ var ENVIRONMENT_LOG_AREAS = defineLogAreas({
1479
1552
  "orphan-session.reaped": "A native session no tab references was torn down.",
1480
1553
  "handoff-sweep.failed": "Sweeping transferred transcripts no tab references failed.",
1481
1554
  "delete.terminals-survived": "Terminal process trees outlived termination, so the deletion stops.",
1555
+ "delete.step-deadline": "A deletion step that runs child processes passed its deadline; they are stopped and the deletion fails once they have.",
1482
1556
  "delete.artifacts-left": "Graph run artifact directories were not removed.",
1483
1557
  "delete.worktrees-kept": "Graph runs kept branch worktrees.",
1484
1558
  "delete.step-failed": "One best-effort part of deleting an environment failed; `step` says which, and the rest goes on.",
@@ -1513,6 +1587,7 @@ var GATEWAY_LOG_AREAS = defineLogAreas({
1513
1587
  "host.refused": "A request named a host this gateway does not answer to. Logged once per name, up to a limit.",
1514
1588
  "port.fallback": "The preferred port was taken, so a nearby one is used.",
1515
1589
  "port.fallback-distant": "The preferred port and those nearby were taken, so another is used.",
1590
+ "request-auth.fallback": "A desktop request-auth hook failed closed. Phase only; no request or error content.",
1516
1591
  "request.failed": "A gateway request failed. Throttled: repeats are counted, not written.",
1517
1592
  "websocket.upgrade-failed": "A WebSocket upgrade failed.",
1518
1593
  "events.client-dropped": "An event-stream client buffered too much and was dropped; it reconnects and refetches.",
@@ -1571,6 +1646,11 @@ var LOCAL_SERVER_LOG_AREAS = defineLogAreas({
1571
1646
  requested: "boolean"
1572
1647
  }
1573
1648
  },
1649
+ "bridge.orphans-reaped": {
1650
+ 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.",
1651
+ essential: true,
1652
+ fields: { key: "label", pid: "number", result: "label" }
1653
+ },
1574
1654
  "reaper.tmux-list-failed": "Orphaned claude-tmux sessions could not be listed.",
1575
1655
  "reaper.tmux-kill-failed": "An orphaned tmux session could not be killed.",
1576
1656
  "reaper.tmux-reaped": "Orphaned claude-tmux sessions of a deleted environment were killed.",
@@ -1621,6 +1701,8 @@ var LOGGING_LOG_AREAS = defineLogAreas({
1621
1701
  },
1622
1702
  "essential.write-failed": "Writing the essential log failed. Its entries are counted, and a marker reports them at the next write that works.",
1623
1703
  "policy.changed": "The logging settings changed: saving, retention and levels, with no content.",
1704
+ "policy.detail-expired": "Raised log detail reached its expiry, so the backend set its raised levels back to info. Saving is unchanged.",
1705
+ "policy.expiry-failed": "Checking or applying the log detail expiry failed; the next check, a minute later, tries again.",
1624
1706
  "policy.bridge-predates-route": "A running bridge has no logging settings route; it applies them at its next start.",
1625
1707
  "policy.push-failed": "A running bridge did not take the logging settings after retries; its next start resends them.",
1626
1708
  "prune.failed": "Removing expired log files failed; the next sweep retries.",
@@ -1628,6 +1710,23 @@ var LOGGING_LOG_AREAS = defineLogAreas({
1628
1710
  "unknown-area": "Code outside the type checker asked for an area that is not listed.",
1629
1711
  ...THROTTLE_LOG_EVENTS
1630
1712
  }
1713
+ },
1714
+ "renderer-errors": {
1715
+ description: "Renderer failures a desktop window reported from its error ring: class, boundary, surface, count and fingerprint, never a message or stack.",
1716
+ events: {
1717
+ "error.recorded": {
1718
+ description: "A renderer reported `count` new occurrences of one failure since its last report.",
1719
+ essential: true,
1720
+ fields: {
1721
+ errorClass: "label",
1722
+ boundary: "label",
1723
+ route: "label",
1724
+ fingerprint: "label",
1725
+ count: "number"
1726
+ }
1727
+ },
1728
+ "report.rate-limited": "Renderer error entries arrived faster than the backend records them, so `dropped` were counted and not written."
1729
+ }
1631
1730
  }
1632
1731
  });
1633
1732
 
@@ -1685,6 +1784,8 @@ var NATIVE_AGENT_LOG_AREAS = defineLogAreas({
1685
1784
  "usage-limit.notice-failed": "A usage-limit stop's outcome could not be read for its notice.",
1686
1785
  "usage-limit.resend-failed": "Resending after a usage limit failed. An unknown send stays in the journal.",
1687
1786
  "title.strategy-failed": "A session title strategy failed, so the next is tried. Content-free: the error can quote the prompt.",
1787
+ "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.",
1788
+ "steer.capability-cleared": "A projection cleared `actions.steer` because its bridge did not qualify. Identifiers and turn status only.",
1688
1789
  ...THROTTLE_LOG_EVENTS
1689
1790
  }
1690
1791
  },
@@ -1785,6 +1886,9 @@ var RUNTIME_LOG_AREAS = defineLogAreas({
1785
1886
  essential: true,
1786
1887
  fields: { origin: "label", ...ESSENTIAL_ERROR_FIELDS }
1787
1888
  },
1889
+ "child.reaped": "A macOS child whose exit Bun lost was reaped after its command settled, so it no longer waits as a zombie.",
1890
+ "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.",
1891
+ "child.reap-unavailable": "waitpid could not be loaded, so children whose exit Bun lost stay zombies until this process exits.",
1788
1892
  ...THROTTLE_LOG_EVENTS
1789
1893
  }
1790
1894
  }
@@ -2191,6 +2295,13 @@ var COORDINATOR_LOG_AREAS = defineLogAreas({
2191
2295
  "store.workflows-cleared": "The workflow store was full, so a batch of its oldest finished records was removed.",
2192
2296
  "store.workflows-in-use": "The workflow store was full and every record was still in use, so new work was refused.",
2193
2297
  "remote-worker.settle-failed": "A remote worker could not be settled.",
2298
+ "node-release.failed": "Work on a node that was forgotten or handed over could not be closed; the sweep's registry check retries.",
2299
+ "node-release.reconcile-failed": "The sweep could not check records against the node registry; the next sweep retries.",
2300
+ "node-release.unregistered": "Records named a node the registry no longer holds, so their work was closed here.",
2301
+ "node-release.notice-failed": "The notice for work closed on a released node could not be sent; it stays owed and the sweep retries.",
2302
+ "node-release.no-coordinator": "Work closed on a released node belonged to a coordinator that no longer exists, so nobody was told.",
2303
+ "node-offline.notice-failed": "The notice that a node has been unreachable for a day could not be sent; the next failed read retries.",
2304
+ "node-offline.check-failed": "Whether a long-unreachable node's coordinators were told could not be checked; the next read retries.",
2194
2305
  "checkout.merge-followed": "After an environment's PR merged, the project checkout was fast-forwarded, or `outcome` says why not.",
2195
2306
  "checkout.merge-follow-failed": "Fast-forwarding the project checkout failed, after an environment's PR merged or before mail woke the main coordinator.",
2196
2307
  "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`).",
@@ -2287,6 +2398,7 @@ var DOCKER_LOG_AREAS = defineLogAreas({
2287
2398
  events: {
2288
2399
  "portable-inputs.relay-missing": "Docker is rootless and the image predates the staged-input relay, so the container cannot read them until rebuilt.",
2289
2400
  "git-mirror.mount-unavailable": "A new container gets no project Git mirror, so its clone goes to the remote.",
2401
+ "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.",
2290
2402
  "git-mirror.refreshed": "A project's Git mirror was built or updated.",
2291
2403
  "git-mirror.seeded": "A project's Git mirror was built from its host checkout and only what the remote added to it.",
2292
2404
  "git-mirror.seed-skipped": "A project's host checkout could not seed its Git mirror, so the build downloads everything.",
@@ -2372,7 +2484,11 @@ var DOCKER_LOG_AREAS = defineLogAreas({
2372
2484
  "network.list-failed": "Docker networks could not be listed.",
2373
2485
  "network.inspect-failed": "A Docker network could not be inspected.",
2374
2486
  "stale-containers.removing": "Stale probe containers are being removed.",
2375
- "stale-networks.removing": "Stale probe networks are being removed."
2487
+ "stale-networks.removing": "Stale probe networks are being removed.",
2488
+ "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).",
2489
+ "peers.subnets-loaded": "The Docker subnets the agent tools server admits were reloaded.",
2490
+ "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.",
2491
+ "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."
2376
2492
  }
2377
2493
  }
2378
2494
  });
@@ -2463,6 +2579,7 @@ var NODES_LOG_AREAS = defineLogAreas({
2463
2579
  "verification.record-failed": "A node verification could not be recorded.",
2464
2580
  "profile.record-failed": "A node profile could not be recorded.",
2465
2581
  "detach.unconfirmed": "A forgotten node has not confirmed the detach yet.",
2582
+ "grant.revocation-listener-failed": "A connection could not be told its client grant was removed; the grant is still gone.",
2466
2583
  "handover.recovery-pending": "Command handover recovery is still pending.",
2467
2584
  "ticket-sync.work-record-failed": "A remote build started but its ticket work location could not be saved.",
2468
2585
  "ticket-sync.failed": "A Kanban sync with a node failed; it is retried.",
@@ -2515,7 +2632,9 @@ var HOST_LOG_AREAS = defineLogAreas({
2515
2632
  "tool.missing": "A host tool was not found.",
2516
2633
  "maintenance.listener-failed": "A host maintenance listener threw; the others still run.",
2517
2634
  "suspend.reconcile-failed": "Reconciling due work after a host suspension failed.",
2518
- "load.sample-failed": "Sampling machine load failed; the next sample retries."
2635
+ "load.sample-failed": "Sampling machine load failed; the next sample retries.",
2636
+ "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.",
2637
+ ...THROTTLE_LOG_EVENTS
2519
2638
  }
2520
2639
  }
2521
2640
  });
@@ -3092,7 +3211,7 @@ var MAX_FRAME_CHARS = 240;
3092
3211
  var MAX_RAW_FRAME_CHARS = 1024;
3093
3212
  var MAX_CAUSE_DEPTH = 2;
3094
3213
  var TRUNCATED_MARKER = "...[truncated]";
3095
- var NAME_PATTERN = /^[A-Za-z_$][\w$.-]{0,63}$/;
3214
+ var NAME_PATTERN2 = /^[A-Za-z_$][\w$.-]{0,63}$/;
3096
3215
  var CODE_PATTERN = /^[\w.:-]{1,64}$/;
3097
3216
  var SYSCALL_PATTERN = /^[\w./ -]{1,128}$/;
3098
3217
  var COMMAND_OUTPUT_FIELDS = ["stdout", "stderr", "cmd", "spawnargs"];
@@ -3170,7 +3289,7 @@ function describe(error, includeStack, includeMessage, depth) {
3170
3289
  if (!(error instanceof Error) && typeof rawMessage !== "string") {
3171
3290
  return { name: "NonError", message: "[object]" };
3172
3291
  }
3173
- const name = matching(read(error, "name"), NAME_PATTERN) ?? "Error";
3292
+ const name = matching(read(error, "name"), NAME_PATTERN2) ?? "Error";
3174
3293
  const message = typeof rawMessage === "string" ? rawMessage : undefined;
3175
3294
  const commandFailure = isCommandFailure(error, name, message);
3176
3295
  const stackHoldsMessage = message !== undefined && String(read(error, "stack") ?? "").includes(message);
@@ -3225,7 +3344,7 @@ function logErrorKind(error) {
3225
3344
  const safeCode = finite(code) ?? matching(code, CODE_PATTERN);
3226
3345
  if (safeCode !== undefined)
3227
3346
  return String(safeCode);
3228
- return matching(read(error, "name"), NAME_PATTERN) ?? "Error";
3347
+ return matching(read(error, "name"), NAME_PATTERN2) ?? "Error";
3229
3348
  }
3230
3349
 
3231
3350
  // ../protocol/src/log-essential-labels.ts
@@ -3838,6 +3957,7 @@ function effectiveLogLevel(detail, area) {
3838
3957
  return detail.level;
3839
3958
  }
3840
3959
  }
3960
+ var LOG_DETAIL_EXPIRY_MS = 24 * 60 * 60 * 1000;
3841
3961
  function logDetailEnablesBridgeDiagnostics(detail) {
3842
3962
  return LEVEL_DETAIL[effectiveLogLevel(detail, BRIDGE_DIAGNOSTICS_LOG_AREA)] >= LEVEL_DETAIL.debug;
3843
3963
  }
@@ -3851,34 +3971,219 @@ function parseBridgeLogPolicy(value) {
3851
3971
  }
3852
3972
 
3853
3973
  // ../protocol/src/node/bridge-credential.ts
3854
- import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
3974
+ import { createHash as createHash2, randomBytes as randomBytes2, timingSafeEqual } from "node:crypto";
3855
3975
  import { createRequire } from "node:module";
3976
+
3977
+ // ../protocol/src/node/bridge-authority.ts
3978
+ import {
3979
+ createHash,
3980
+ createPrivateKey,
3981
+ createPublicKey,
3982
+ generateKeyPairSync,
3983
+ randomBytes,
3984
+ sign,
3985
+ verify
3986
+ } from "node:crypto";
3987
+ var BRIDGE_AUTHORITY_HEADER = "x-orkestrator-authority";
3988
+ var BRIDGE_AUTHORITY_REFUSED_CODE = "authority-signature-required";
3989
+ var BRIDGE_AUTHORITY_WINDOW_MS = 5 * 60000;
3990
+ var BRIDGE_AUTHORITY_MAX_NONCES = 8192;
3991
+ var BRIDGE_AUTHORITY_MAX_BODY_BYTES = 64 * 1024 * 1024;
3992
+ var SCHEME = "orkestrator-bridge-authority-v1";
3993
+ var KEY_PATTERN = /^[A-Za-z0-9_-]{40,200}$/;
3994
+ var HEADER_PATTERN = /^v1 t=(\d{1,16}) n=([A-Za-z0-9_-]{22}) s=([A-Za-z0-9_-]{86})$/;
3995
+ var READ_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
3996
+ var UNSIGNED_ROUTES = [
3997
+ /^\/session\/[^/]+\/close$/,
3998
+ /^\/sessions\/activity$/,
3999
+ /^\/debug\/log-policy$/
4000
+ ];
4001
+ function bridgeAuthorityKeyEnv(tokenEnv) {
4002
+ return `${tokenEnv}_AUTHORITY_KEY`;
4003
+ }
4004
+ function isBridgeAuthorityKey(value) {
4005
+ return typeof value === "string" && KEY_PATTERN.test(value);
4006
+ }
4007
+ function publicKeyFrom(encoded) {
4008
+ if (!isBridgeAuthorityKey(encoded))
4009
+ return null;
4010
+ try {
4011
+ const key = createPublicKey({
4012
+ key: Buffer.from(encoded, "base64url"),
4013
+ format: "der",
4014
+ type: "spki"
4015
+ });
4016
+ return key.asymmetricKeyType === "ed25519" ? key : null;
4017
+ } catch {
4018
+ return null;
4019
+ }
4020
+ }
4021
+ function bridgeAuthorityTarget(url) {
4022
+ const parsed = new URL(url, "http://bridge.invalid");
4023
+ return `${parsed.pathname}${parsed.search}`;
4024
+ }
4025
+ function bridgeRequestNeedsAuthority(method, target) {
4026
+ if (READ_METHODS.has(method.toUpperCase()))
4027
+ return false;
4028
+ const pathname = bridgeAuthorityTarget(target).split("?", 1)[0];
4029
+ return !UNSIGNED_ROUTES.some((pattern) => pattern.test(pathname));
4030
+ }
4031
+ function bodyDigest(body) {
4032
+ return createHash("sha256").update(body ?? "").digest("hex");
4033
+ }
4034
+ function signedMessage(method, target, issuedAt, nonce, digest) {
4035
+ return Buffer.from([SCHEME, method.toUpperCase(), target, String(issuedAt), nonce, digest].join(`
4036
+ `));
4037
+ }
4038
+ var UNENFORCED = {
4039
+ enforced: false,
4040
+ requires: () => false,
4041
+ check: () => ({ ok: true })
4042
+ };
4043
+ function bridgeAuthorityFromPublicKey(publicKey, options = {}) {
4044
+ if (publicKey === undefined)
4045
+ return UNENFORCED;
4046
+ const key = publicKeyFrom(publicKey);
4047
+ const now = options.now ?? Date.now;
4048
+ const maxNonces = options.maxNonces ?? BRIDGE_AUTHORITY_MAX_NONCES;
4049
+ const seen = new Map;
4050
+ let floor = -Infinity;
4051
+ const remember = (nonce, issuedAt, current) => {
4052
+ for (const [oldNonce, oldIssuedAt] of seen) {
4053
+ if (seen.size < maxNonces && oldIssuedAt >= current - BRIDGE_AUTHORITY_WINDOW_MS)
4054
+ break;
4055
+ seen.delete(oldNonce);
4056
+ floor = Math.max(floor, oldIssuedAt);
4057
+ }
4058
+ seen.set(nonce, issuedAt);
4059
+ };
4060
+ return {
4061
+ enforced: true,
4062
+ requires: bridgeRequestNeedsAuthority,
4063
+ check(request) {
4064
+ if (!request.header)
4065
+ return { ok: false, reason: "missing" };
4066
+ const match = HEADER_PATTERN.exec(request.header.trim());
4067
+ if (!match)
4068
+ return { ok: false, reason: "malformed" };
4069
+ const issuedAt = Number(match[1]);
4070
+ const nonce = match[2];
4071
+ const current = now();
4072
+ if (Math.abs(current - issuedAt) > BRIDGE_AUTHORITY_WINDOW_MS || issuedAt <= floor) {
4073
+ return { ok: false, reason: "stale" };
4074
+ }
4075
+ if (!key)
4076
+ return { ok: false, reason: "invalid" };
4077
+ const valid = verify(null, signedMessage(request.method, bridgeAuthorityTarget(request.url), issuedAt, nonce, bodyDigest(request.body)), key, Buffer.from(match[3], "base64url"));
4078
+ if (!valid)
4079
+ return { ok: false, reason: "invalid" };
4080
+ if (seen.has(nonce))
4081
+ return { ok: false, reason: "replayed" };
4082
+ remember(nonce, issuedAt, current);
4083
+ return { ok: true };
4084
+ }
4085
+ };
4086
+ }
4087
+ function loadBridgeAuthority(tokenEnv, options = {}) {
4088
+ const env = options.env ?? process.env;
4089
+ const name = bridgeAuthorityKeyEnv(tokenEnv);
4090
+ const value = env[name]?.trim();
4091
+ delete env[name];
4092
+ return bridgeAuthorityFromPublicKey(value || undefined, { now: options.now });
4093
+ }
4094
+ function refusal(reason) {
4095
+ return {
4096
+ status: 403,
4097
+ body: {
4098
+ error: "This request changes an agent's authority and needs the backend's signature",
4099
+ code: BRIDGE_AUTHORITY_REFUSED_CODE,
4100
+ reason
4101
+ }
4102
+ };
4103
+ }
4104
+ var TOO_LARGE = {
4105
+ status: 413,
4106
+ body: { error: "Request body is too large" }
4107
+ };
4108
+ var admittedBodies = new WeakMap;
4109
+ async function readBounded(request, maxBodyBytes) {
4110
+ const declared = Number(request.headers.get("content-length") ?? NaN);
4111
+ if (Number.isFinite(declared) && declared > maxBodyBytes)
4112
+ return null;
4113
+ if (!request.body)
4114
+ return new Uint8Array;
4115
+ const reader = request.body.getReader();
4116
+ const chunks = [];
4117
+ let total = 0;
4118
+ for (;; ) {
4119
+ const { done, value } = await reader.read();
4120
+ if (done)
4121
+ break;
4122
+ total += value.byteLength;
4123
+ if (total > maxBodyBytes) {
4124
+ await reader.cancel().catch(() => {
4125
+ return;
4126
+ });
4127
+ return null;
4128
+ }
4129
+ chunks.push(value);
4130
+ }
4131
+ return Buffer.concat(chunks);
4132
+ }
4133
+ async function admitFetchBridgeRequest(authority, original, maxBodyBytes = BRIDGE_AUTHORITY_MAX_BODY_BYTES) {
4134
+ if (!authority.requires(original.method, original.url))
4135
+ return {};
4136
+ const header = original.headers.get(BRIDGE_AUTHORITY_HEADER);
4137
+ if (!header)
4138
+ return { refusal: refusal("missing") };
4139
+ const body = await readBounded(original, maxBodyBytes);
4140
+ if (!body)
4141
+ return { refusal: TOO_LARGE };
4142
+ const result = authority.check({ method: original.method, url: original.url, header, body });
4143
+ if (!result.ok)
4144
+ return { refusal: refusal(result.reason) };
4145
+ const headers = new Headers(original.headers);
4146
+ headers.set("content-length", String(body.byteLength));
4147
+ headers.delete("transfer-encoding");
4148
+ return {
4149
+ request: new Request(original.url, {
4150
+ method: original.method,
4151
+ headers,
4152
+ body: body.byteLength > 0 ? new Uint8Array(body) : undefined,
4153
+ signal: original.signal
4154
+ })
4155
+ };
4156
+ }
4157
+
4158
+ // ../protocol/src/node/bridge-credential.ts
3856
4159
  var BRIDGE_TOKEN_PREFIX = "okb_";
3857
4160
  var PR_SET_DUMPABLE = 4;
3858
4161
  var VERIFIER_PATTERN = /^[0-9a-f]{64}$/;
3859
4162
  var log = createLogger("bridge.lifecycle");
3860
4163
  function mintBridgeToken() {
3861
- return `${BRIDGE_TOKEN_PREFIX}${randomBytes(32).toString("base64url")}`;
4164
+ return `${BRIDGE_TOKEN_PREFIX}${randomBytes2(32).toString("base64url")}`;
3862
4165
  }
3863
4166
  function bridgeTokenVerifier(token) {
3864
- return createHash("sha256").update(token).digest("hex");
4167
+ return createHash2("sha256").update(token).digest("hex");
3865
4168
  }
3866
4169
  function bridgeTokenVerifierEnv(tokenEnv) {
3867
4170
  return `${tokenEnv}_SHA256`;
3868
4171
  }
3869
- function credentialFromVerifier(verifier, plainToken) {
4172
+ function credentialFromVerifier(verifier, plainToken, authority = UNENFORCED_AUTHORITY) {
3870
4173
  const expected = Buffer.from(verifier, "hex");
3871
4174
  return {
3872
4175
  plainToken,
4176
+ authority,
3873
4177
  matches(candidate) {
3874
4178
  if (!candidate)
3875
4179
  return false;
3876
- return timingSafeEqual(expected, createHash("sha256").update(candidate).digest());
4180
+ return timingSafeEqual(expected, createHash2("sha256").update(candidate).digest());
3877
4181
  }
3878
4182
  };
3879
4183
  }
3880
- function bridgeCredentialFromToken(token) {
3881
- return credentialFromVerifier(bridgeTokenVerifier(token), token);
4184
+ var UNENFORCED_AUTHORITY = loadBridgeAuthority("", { env: {} });
4185
+ function bridgeCredentialFromToken(token, authority = UNENFORCED_AUTHORITY) {
4186
+ return credentialFromVerifier(bridgeTokenVerifier(token), token, authority);
3882
4187
  }
3883
4188
  function markProcessNonDumpable(loadFfi = () => createRequire(import.meta.url)("bun:ffi")) {
3884
4189
  if (process.platform !== "linux" || !process.versions.bun)
@@ -3910,11 +4215,12 @@ function loadBridgeCredential(tokenEnv, options = {}) {
3910
4215
  const token = env[tokenEnv]?.trim();
3911
4216
  delete env[verifierEnv];
3912
4217
  delete env[tokenEnv];
4218
+ const authority = loadBridgeAuthority(tokenEnv, { env });
3913
4219
  if (verifier) {
3914
4220
  (options.harden ?? markProcessNonDumpable)();
3915
- return VERIFIER_PATTERN.test(verifier) ? credentialFromVerifier(verifier, undefined) : bridgeCredentialFromToken(mintBridgeToken());
4221
+ return VERIFIER_PATTERN.test(verifier) ? credentialFromVerifier(verifier, undefined, authority) : bridgeCredentialFromToken(mintBridgeToken(), authority);
3916
4222
  }
3917
- return bridgeCredentialFromToken(token || mintBridgeToken());
4223
+ return bridgeCredentialFromToken(token || mintBridgeToken(), authority);
3918
4224
  }
3919
4225
 
3920
4226
  // ../protocol/src/node/logger-environment.ts
@@ -3993,7 +4299,7 @@ function applyLogDetail(detail, env = process.env) {
3993
4299
  }
3994
4300
 
3995
4301
  // ../protocol/src/node/bridge-diagnostics.ts
3996
- import { createHash as createHash2 } from "node:crypto";
4302
+ import { createHash as createHash3 } from "node:crypto";
3997
4303
 
3998
4304
  // ../protocol/src/event-loop-stall-monitor.ts
3999
4305
  var log2 = createLogger("event-loop");
@@ -4092,7 +4398,7 @@ function sameSet(a, b) {
4092
4398
  function identity(value) {
4093
4399
  if (typeof value !== "string" || !value || value.length > MAX_ID_LENGTH)
4094
4400
  return;
4095
- return createHash2("sha256").update(value).digest("hex").slice(0, 16);
4401
+ return createHash3("sha256").update(value).digest("hex").slice(0, 16);
4096
4402
  }
4097
4403
  function readBridgeDebugFlag(value) {
4098
4404
  return value?.trim() === "1";
@@ -4546,7 +4852,7 @@ var X_ALREADY_SENT = "x-hono-already-sent";
4546
4852
 
4547
4853
  // ../../node_modules/.bun/@hono+node-server@2.1.5+c539cad7f494f5c9/node_modules/@hono/node-server/dist/index.mjs
4548
4854
  import { STATUS_CODES, ServerResponse, createServer } from "node:http";
4549
- import { Http2ServerRequest, constants } from "node:http2";
4855
+ import { Http2ServerRequest, constants as constants2 } from "node:http2";
4550
4856
  import { Readable } from "node:stream";
4551
4857
 
4552
4858
  // ../../node_modules/.bun/hono@4.13.13/node_modules/hono/dist/helper/websocket/index.js
@@ -5465,7 +5771,7 @@ var drainIncoming = (incoming) => {
5465
5771
  incomingWithDrainState[incomingDraining] = true;
5466
5772
  if (incoming instanceof Http2ServerRequest) {
5467
5773
  try {
5468
- incoming.stream?.close?.(constants.NGHTTP2_NO_ERROR);
5774
+ incoming.stream?.close?.(constants2.NGHTTP2_NO_ERROR);
5469
5775
  } catch {}
5470
5776
  return;
5471
5777
  }
@@ -7960,12 +8266,850 @@ function structuredOutputFailure(provider, code, message, options = {}) {
7960
8266
  }
7961
8267
 
7962
8268
  // ../protocol/src/node/workspace-change-probe.ts
7963
- import { execFile, spawn } from "node:child_process";
7964
- import { randomUUID } from "node:crypto";
7965
- import { rmSync } from "node:fs";
8269
+ import { randomUUID as randomUUID2 } from "node:crypto";
8270
+ import { rmSync as rmSync2 } from "node:fs";
7966
8271
  import { copyFile, lstat, mkdtemp, rm } from "node:fs/promises";
7967
8272
  import { tmpdir } from "node:os";
7968
8273
  import { delimiter, isAbsolute, join, resolve } from "node:path";
8274
+
8275
+ // ../protocol/src/node/command-capture.ts
8276
+ import { spawn } from "node:child_process";
8277
+ import { randomUUID } from "node:crypto";
8278
+ import { constants as fsConstants } from "node:fs";
8279
+ import * as captureFs from "node:fs";
8280
+ import os from "node:os";
8281
+ import path from "node:path";
8282
+ import { inspect } from "node:util";
8283
+
8284
+ // ../protocol/src/node/command-failure-reason.ts
8285
+ var MAX_MATCHED_CHARS = 16 * 1024;
8286
+ var SIGNAL_PATTERN = /^SIG[A-Z0-9]{1,16}$/;
8287
+ var TOOL_RULES = {
8288
+ git: [
8289
+ ["branch-exists", /a branch named .* already exists/i],
8290
+ ["ref-conflict", /exists; cannot create|cannot lock ref .* is at .* but expected/i],
8291
+ ["lock-held", /could not lock config file [^\n]*: File exists/i],
8292
+ ["lock-held", /(?:unable to create '[^\n]*\.lock'|cannot lock ref)[^\n]*: File exists/i],
8293
+ ["lock-held", /another git process/i],
8294
+ ["worktree-conflict", /already (?:checked out|used by worktree)|used by worktree at/i],
8295
+ ["invalid-ref", /not a valid (?:branch name|object name)|bad (?:revision|object)/i],
8296
+ ["invalid-ref", /unknown revision|ambiguous argument|invalid reference/i],
8297
+ ["branch-not-found", /no branch named|refname .* not found|branch '.*' not found/i],
8298
+ ["branch-not-found", /did not match any file\(s\) known to git/i],
8299
+ ["dubious-ownership", /detected dubious ownership/i],
8300
+ ["no-remote", /does not appear to be a git repository|no such remote/i],
8301
+ ["no-remote", /repository (?:.* )?not found/i],
8302
+ ["not-a-repository", /not a git repository/i],
8303
+ ["remote-ref-missing", /could(?:n't| not) find remote ref|not our ref/i],
8304
+ ["merge-conflict", /\bCONFLICT \(|merge conflict|could not apply|unmerged files/i],
8305
+ ["dirty-worktree", /local changes .* would be overwritten|commit your changes or stash/i],
8306
+ ["nothing-to-commit", /nothing to commit|no changes added to commit/i],
8307
+ ["push-rejected", /\[(?:remote )?rejected\]|non-fast-forward/i],
8308
+ ["identity-unknown", /please tell me who you are|unable to auto-detect email/i],
8309
+ [
8310
+ "worktree-has-changes",
8311
+ /^fatal: [^\n]*['"] contains modified or untracked files(?:, use --force to delete it)?\.?\s*$/im
8312
+ ],
8313
+ ["not-a-worktree", /^fatal: [^\n]*['"] is not a working tree\.?\s*$/im],
8314
+ ["branch-not-merged", /^(?:error|fatal): [^\n]*['"] is not fully merged\.?\s*$/im]
8315
+ ],
8316
+ gh: [
8317
+ ["pull-request-exists", /a pull request for branch .* already exists/i],
8318
+ ["no-pull-request", /no (?:pull requests? (?:found|match)|open pull requests?\b)/i],
8319
+ ["rate-limited", /rate limit|http 429/i],
8320
+ ["forbidden", /http 403|resource not accessible/i],
8321
+ ["resource-not-found", /http 404|could not resolve to a/i],
8322
+ ["server-error", /http 5\d\d/i]
8323
+ ],
8324
+ docker: [
8325
+ ["daemon-unavailable", /cannot connect to the docker daemon|error during connect/i],
8326
+ [
8327
+ "daemon-unavailable",
8328
+ /is the docker daemon running|docker desktop is (?:not running|unable)/i
8329
+ ],
8330
+ ["container-not-found", /no such container/i],
8331
+ ["container-not-running", /container .* is (?:not running|paused|restarting)/i],
8332
+ ["container-name-conflict", /name .* is already in use/i],
8333
+ ["image-not-found", /no such image|pull access denied|manifest .* not found/i],
8334
+ ["image-not-found", /manifest unknown|repository does not exist/i],
8335
+ ["removal-in-progress", /removal of container .* is already in progress/i],
8336
+ [
8337
+ "image-in-use",
8338
+ /image is (?:being used|referenced)|unable to (?:remove|delete) .*must be forced/i
8339
+ ],
8340
+ ["volume-in-use", /volume is in use/i],
8341
+ ["volume-not-found", /no such volume/i],
8342
+ ["network-in-use", /has active endpoints/i],
8343
+ ["network-not-found", /network .* not found/i]
8344
+ ],
8345
+ tmux: [
8346
+ ["session-exists", /duplicate session/i],
8347
+ [
8348
+ "server-not-running",
8349
+ /no server running|failed to connect to server|no sessions|server exited|lost server/i
8350
+ ],
8351
+ [
8352
+ "server-not-running",
8353
+ /error connecting to \/[^\n]* \((?:No such file or directory|Connection refused)\)/i
8354
+ ],
8355
+ ["session-not-found", /can't find (?:session|window|pane)|session not found/i]
8356
+ ]
8357
+ };
8358
+ var ALL_TOOLS = Object.keys(TOOL_RULES);
8359
+ var SHARED_RULES = [
8360
+ ["disk-full", /no space left|enospc|disk quota exceeded/i],
8361
+ ["auth-failed", /authentication (?:failed|required)|could not read (?:username|password)/i],
8362
+ ["auth-failed", /terminal prompts disabled|invalid username or password|bad credentials/i],
8363
+ ["auth-failed", /permission denied \(|permission to \S+ denied|host key verification failed/i],
8364
+ ["auth-failed", /gh auth login|not logged in|unauthorized|http 401|returned error: 40[13]/i],
8365
+ ["network-failed", /could not resolve host|connection (?:timed out|refused|reset)/i],
8366
+ ["network-failed", /network is unreachable|no route to host|temporary failure in name/i],
8367
+ ["network-failed", /early eof|failed to connect|remote end hung up/i],
8368
+ ["network-failed", /unable to access ['"]?https?:\/\//i],
8369
+ ["network-failed", /tls handshake|i\/o timeout/i],
8370
+ [
8371
+ "network-failed",
8372
+ /error connecting to (?:https?:\/\/)?[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?(?::\d+)?(?:[\s/:]|$)/i
8373
+ ],
8374
+ ["port-in-use", /port is already allocated|address already in use/i],
8375
+ ["permission-denied", /permission denied|operation not permitted|read-only file system/i],
8376
+ ["command-not-found", /command not found/i],
8377
+ ["path-not-found", /no such file or directory/i],
8378
+ ["invalid-usage", /^usage: |unknown (?:option|flag|command|shorthand flag)|invalid option/im]
8379
+ ];
8380
+ var TOOL_EXIT_CODES = {
8381
+ git: { 129: "invalid-usage" },
8382
+ gh: { 2: "aborted", 4: "auth-failed" },
8383
+ docker: { 125: "daemon-error" },
8384
+ tmux: {}
8385
+ };
8386
+ var SHARED_EXIT_CODES = {
8387
+ 124: "timed-out",
8388
+ 126: "not-executable",
8389
+ 127: "command-not-found",
8390
+ 137: "killed",
8391
+ 143: "killed"
8392
+ };
8393
+ function read2(target, key) {
8394
+ return target[key];
8395
+ }
8396
+ function boundedForMatching(text) {
8397
+ if (text.length <= MAX_MATCHED_CHARS)
8398
+ return text;
8399
+ const half = MAX_MATCHED_CHARS / 2;
8400
+ return `${text.slice(0, half)}
8401
+ ${text.slice(-half)}`;
8402
+ }
8403
+ function failureText(error) {
8404
+ const stderr = read2(error, "stderr");
8405
+ if (Buffer.isBuffer(stderr) && stderr.length > 0) {
8406
+ return boundedForMatching(stderr.subarray(-MAX_MATCHED_CHARS).toString());
8407
+ }
8408
+ if (typeof stderr === "string" && stderr.length > 0)
8409
+ return boundedForMatching(stderr);
8410
+ const message = read2(error, "message");
8411
+ if (typeof message !== "string")
8412
+ return "";
8413
+ return message.startsWith("Command failed") ? "" : boundedForMatching(message);
8414
+ }
8415
+ function isRawSpawnEnoent(error) {
8416
+ const syscall = read2(error, "syscall");
8417
+ return read2(error, "code") === "ENOENT" && typeof syscall === "string" && /^(?:spawn(?:Sync)?(?:\s|$)|posix_spawnp?$)/.test(syscall);
8418
+ }
8419
+ function classifiedReason(error, exitCode, signal, options) {
8420
+ if (read2(error, "aborted") === true)
8421
+ return "aborted";
8422
+ if (read2(error, "outputLimitExceeded") === true)
8423
+ return "output-too-large";
8424
+ if (read2(error, "timedOut") === true)
8425
+ return "timed-out";
8426
+ if (read2(error, "executableMissing") === true || isRawSpawnEnoent(error)) {
8427
+ return "executable-missing";
8428
+ }
8429
+ const named = exitCode === null ? undefined : options.exitCodes?.[exitCode];
8430
+ if (named)
8431
+ return named;
8432
+ if (signal)
8433
+ return "killed";
8434
+ const text = failureText(error);
8435
+ for (const tool of options.tools ?? ALL_TOOLS) {
8436
+ for (const [reason, pattern] of TOOL_RULES[tool]) {
8437
+ if (pattern.test(text))
8438
+ return reason;
8439
+ }
8440
+ }
8441
+ for (const [reason, pattern] of SHARED_RULES) {
8442
+ if (pattern.test(text))
8443
+ return reason;
8444
+ }
8445
+ if (exitCode !== null) {
8446
+ for (const tool of options.tools ?? []) {
8447
+ const reason = TOOL_EXIT_CODES[tool][exitCode];
8448
+ if (reason)
8449
+ return reason;
8450
+ }
8451
+ const reason = SHARED_EXIT_CODES[exitCode];
8452
+ if (reason)
8453
+ return reason;
8454
+ }
8455
+ return "unclassified";
8456
+ }
8457
+ function numericExitCode(error) {
8458
+ for (const key of ["exitCode", "code"]) {
8459
+ const value = read2(error, key);
8460
+ if (typeof value === "number" && Number.isFinite(value))
8461
+ return value;
8462
+ }
8463
+ return null;
8464
+ }
8465
+ function classifyCommandFailure(error, options = {}) {
8466
+ if (typeof error !== "object" || error === null) {
8467
+ return { reason: "unclassified", exitCode: null, signal: null };
8468
+ }
8469
+ try {
8470
+ const exitCode = numericExitCode(error);
8471
+ const rawSignal = read2(error, "signal");
8472
+ const signal = typeof rawSignal === "string" && SIGNAL_PATTERN.test(rawSignal) ? rawSignal : null;
8473
+ return { reason: classifiedReason(error, exitCode, signal, options), exitCode, signal };
8474
+ } catch {
8475
+ return { reason: "unclassified", exitCode: null, signal: null };
8476
+ }
8477
+ }
8478
+
8479
+ // ../protocol/src/node/lost-exit-reaper.ts
8480
+ import { createRequire as createRequire2 } from "node:module";
8481
+
8482
+ // ../protocol/src/node/shell-process-state.ts
8483
+ import { spawnSync } from "node:child_process";
8484
+ import { readdirSync, readFileSync } from "node:fs";
8485
+ import { constants as osConstants } from "node:os";
8486
+ var PROCESS_INSPECTION_OPTIONS = {
8487
+ timeout: 100,
8488
+ killSignal: "SIGKILL",
8489
+ maxBuffer: 1024 * 1024
8490
+ };
8491
+ function bunRuntime() {
8492
+ return globalThis.Bun;
8493
+ }
8494
+ function decodeWaitStatus(status) {
8495
+ const signalNumber = status & 127;
8496
+ if (signalNumber === 0)
8497
+ return { code: status >> 8 & 255, signal: null };
8498
+ const name = Object.entries(osConstants.signals).find(([, value]) => value === signalNumber)?.[0];
8499
+ return { code: null, signal: name ?? "SIGKILL" };
8500
+ }
8501
+ function readZombieExit(pid) {
8502
+ try {
8503
+ const result = bunRuntime()?.spawnSync(["/bin/ps", "-o", "stat=,xstat=", "-p", String(pid)], PROCESS_INSPECTION_OPTIONS);
8504
+ if (!result?.success)
8505
+ return;
8506
+ const { stdout } = result;
8507
+ const match = /^Z\S*\s+([0-9a-f]+)\s*$/i.exec(stdout.toString().trim());
8508
+ return match ? decodeWaitStatus(Number.parseInt(match[1], 16)) : undefined;
8509
+ } catch {
8510
+ return;
8511
+ }
8512
+ }
8513
+ var EXIT_WATCH_MS = 1000;
8514
+ var EXIT_WATCH_MAX_MS = 16000;
8515
+ function watchForLostExit(pid, onExit) {
8516
+ if (process.platform !== "darwin" || pid === undefined || !bunRuntime())
8517
+ return () => {
8518
+ return;
8519
+ };
8520
+ let timer;
8521
+ const watch = (delayMs) => {
8522
+ timer = setTimeout(() => {
8523
+ const exit = readZombieExit(pid);
8524
+ if (exit)
8525
+ onExit(exit);
8526
+ else
8527
+ watch(Math.min(delayMs * 2, EXIT_WATCH_MAX_MS));
8528
+ }, delayMs);
8529
+ };
8530
+ watch(EXIT_WATCH_MS);
8531
+ return () => clearTimeout(timer);
8532
+ }
8533
+ function isLiveMember(state, groupId, pgid) {
8534
+ return Number(groupId) === pgid && state !== undefined && !/^[ZX]/.test(state);
8535
+ }
8536
+ function linuxGroupHasLiveMember(pgid) {
8537
+ for (const entry of readdirSync("/proc")) {
8538
+ if (!/^\d+$/.test(entry))
8539
+ continue;
8540
+ let stat;
8541
+ try {
8542
+ stat = readFileSync(`/proc/${entry}/stat`, "latin1");
8543
+ } catch {
8544
+ continue;
8545
+ }
8546
+ const [state, , groupId] = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
8547
+ if (isLiveMember(state, groupId, pgid))
8548
+ return true;
8549
+ }
8550
+ return false;
8551
+ }
8552
+ function psGroupHasLiveMember(pgid) {
8553
+ const argv = ["-A", "-o", "pgid=,stat="];
8554
+ const bun = bunRuntime();
8555
+ const result = bun ? bun.spawnSync(["/bin/ps", ...argv], PROCESS_INSPECTION_OPTIONS) : spawnSync("/bin/ps", argv, PROCESS_INSPECTION_OPTIONS);
8556
+ const succeeded = "success" in result ? result.success : result.status === 0 && !result.error;
8557
+ if (!succeeded)
8558
+ return true;
8559
+ return result.stdout.toString().split(`
8560
+ `).some((line) => {
8561
+ const [groupId, state] = line.trim().split(/\s+/);
8562
+ return isLiveMember(state, groupId, pgid);
8563
+ });
8564
+ }
8565
+ function groupHasLiveMember(pgid) {
8566
+ try {
8567
+ return process.platform === "linux" ? linuxGroupHasLiveMember(pgid) : psGroupHasLiveMember(pgid);
8568
+ } catch {
8569
+ return true;
8570
+ }
8571
+ }
8572
+
8573
+ // ../protocol/src/node/lost-exit-reaper.ts
8574
+ var log4 = createLogger("process");
8575
+ var REAP_GRACE_MS = 2000;
8576
+ var REAP_MAX_CHECK_MS = 30000;
8577
+ var REAP_MAX_CHECKS = 12;
8578
+ var REAP_MAX_PENDING = 256;
8579
+ function createLostExitReaper(options) {
8580
+ const { system } = options;
8581
+ const graceMs = options.graceMs ?? REAP_GRACE_MS;
8582
+ const maxCheckMs = options.maxCheckMs ?? REAP_MAX_CHECK_MS;
8583
+ const maxChecks = options.maxChecks ?? REAP_MAX_CHECKS;
8584
+ const maxPending = options.maxPending ?? REAP_MAX_PENDING;
8585
+ const pending = new Map;
8586
+ let reaped = 0;
8587
+ let abandoned = 0;
8588
+ const abandon = (pid, reason) => {
8589
+ abandoned += 1;
8590
+ log4.warn("child.reap-abandoned", { pid, reason });
8591
+ };
8592
+ const check = (pid, reported, startedAt) => {
8593
+ if (reported())
8594
+ return false;
8595
+ const found = system.inspect(pid);
8596
+ if (found === undefined)
8597
+ return true;
8598
+ if (found === "gone" || found.ppid !== system.selfPid)
8599
+ return false;
8600
+ if (!found.state.startsWith("Z"))
8601
+ return true;
8602
+ const result = system.waitNoHang(pid);
8603
+ if (result === pid) {
8604
+ reaped += 1;
8605
+ log4.info("child.reaped", { pid, waitedMs: Date.now() - startedAt });
8606
+ return false;
8607
+ }
8608
+ if (result === 0)
8609
+ return true;
8610
+ abandon(pid, "waitpid-failed");
8611
+ return false;
8612
+ };
8613
+ const schedule = (pid, reported, startedAt, delayMs, checks) => {
8614
+ const timer = setTimeout(() => {
8615
+ pending.delete(pid);
8616
+ let again;
8617
+ try {
8618
+ again = check(pid, reported, startedAt);
8619
+ } catch {
8620
+ again = true;
8621
+ }
8622
+ if (!again)
8623
+ return;
8624
+ if (checks + 1 >= maxChecks) {
8625
+ abandon(pid, "not-a-zombie");
8626
+ return;
8627
+ }
8628
+ schedule(pid, reported, startedAt, Math.min(delayMs * 2, maxCheckMs), checks + 1);
8629
+ }, delayMs);
8630
+ timer.unref?.();
8631
+ pending.set(pid, timer);
8632
+ };
8633
+ return {
8634
+ reap(pid, reported) {
8635
+ if (!Number.isSafeInteger(pid) || pid <= 1 || pid === system.selfPid)
8636
+ return;
8637
+ if (pending.has(pid) || reported())
8638
+ return;
8639
+ if (pending.size >= maxPending) {
8640
+ abandon(pid, "capacity");
8641
+ return;
8642
+ }
8643
+ schedule(pid, reported, Date.now(), graceMs, 0);
8644
+ },
8645
+ stats: () => ({ pending: pending.size, reaped, abandoned }),
8646
+ stop() {
8647
+ for (const timer of pending.values())
8648
+ clearTimeout(timer);
8649
+ pending.clear();
8650
+ }
8651
+ };
8652
+ }
8653
+ var WNOHANG = 1;
8654
+ function loadDarwinWaitpid(loadFfi = () => createRequire2(import.meta.url)("bun:ffi")) {
8655
+ try {
8656
+ const { dlopen, FFIType } = loadFfi();
8657
+ const libSystem = dlopen("/usr/lib/libSystem.B.dylib", {
8658
+ waitpid: { args: [FFIType.i32, FFIType.ptr, FFIType.i32], returns: FFIType.i32 }
8659
+ });
8660
+ const status = new Int32Array(1);
8661
+ return (pid) => libSystem.symbols.waitpid(pid, status, WNOHANG);
8662
+ } catch {
8663
+ return;
8664
+ }
8665
+ }
8666
+ function darwinReaperSystem(loadFfi) {
8667
+ const waitNoHang = loadDarwinWaitpid(loadFfi);
8668
+ if (!waitNoHang)
8669
+ return;
8670
+ return {
8671
+ selfPid: process.pid,
8672
+ inspect(pid) {
8673
+ const result = bunRuntime()?.spawnSync(["/bin/ps", "-o", "ppid=,stat=", "-p", String(pid)], PROCESS_INSPECTION_OPTIONS);
8674
+ if (!result)
8675
+ return;
8676
+ const output = result.stdout.toString().trim();
8677
+ if (!result.success)
8678
+ return result.exitCode === 1 && output === "" ? "gone" : undefined;
8679
+ const match = /^(\d+)\s+(\S+)$/.exec(output);
8680
+ return match ? { ppid: Number(match[1]), state: match[2] } : undefined;
8681
+ },
8682
+ waitNoHang
8683
+ };
8684
+ }
8685
+ var defaultReaper;
8686
+ function createDarwinLostExitReaper(loadFfi) {
8687
+ const system = darwinReaperSystem(loadFfi);
8688
+ if (!system)
8689
+ log4.warn("child.reap-unavailable");
8690
+ return system ? createLostExitReaper({ system }) : null;
8691
+ }
8692
+ function sharedReaper() {
8693
+ if (defaultReaper === undefined) {
8694
+ defaultReaper = createDarwinLostExitReaper();
8695
+ }
8696
+ return defaultReaper ?? undefined;
8697
+ }
8698
+ function reapAfterLostExit(pid, reported) {
8699
+ if (process.platform !== "darwin" || pid === undefined || !bunRuntime())
8700
+ return;
8701
+ sharedReaper()?.reap(pid, reported);
8702
+ }
8703
+
8704
+ // ../protocol/src/node/command-capture.ts
8705
+ class CommandFailedError extends Error {
8706
+ stdout;
8707
+ stdoutBytes;
8708
+ stderr;
8709
+ timedOut;
8710
+ outputCloseTimedOut;
8711
+ executableMissing;
8712
+ aborted;
8713
+ outputLimitExceeded;
8714
+ exitCode;
8715
+ signal;
8716
+ constructor(message, details = {}) {
8717
+ super(message);
8718
+ this.name = "CommandFailedError";
8719
+ this.stdout = details.stdout ?? "";
8720
+ this.stdoutBytes = details.stdoutBytes ?? Buffer.alloc(0);
8721
+ this.stderr = details.stderr ?? "";
8722
+ this.timedOut = details.timedOut ?? false;
8723
+ this.outputCloseTimedOut = details.outputCloseTimedOut ?? false;
8724
+ this.executableMissing = details.executableMissing ?? false;
8725
+ this.aborted = details.aborted ?? false;
8726
+ this.outputLimitExceeded = details.outputLimitExceeded ?? false;
8727
+ this.exitCode = details.exitCode ?? null;
8728
+ this.signal = details.signal ?? null;
8729
+ }
8730
+ toJSON() {
8731
+ return { ...formatLogError(this), ...classifyCommandFailure(this) };
8732
+ }
8733
+ [inspect.custom]() {
8734
+ const { name, reason, exitCode, signal, stack } = this.toJSON();
8735
+ const frames = stack?.length ? ` | ${stack.join(" | ")}` : "";
8736
+ return `${name} reason=${reason} exitCode=${exitCode} signal=${signal} outputOmitted=true${frames}`;
8737
+ }
8738
+ }
8739
+ function redactCommandValues(value, redactValues) {
8740
+ const secrets = Array.from(new Set((redactValues ?? []).filter((secret) => typeof secret === "string" && secret.length > 0))).sort((left, right) => right.length - left.length);
8741
+ return secrets.reduce((redacted, secret) => redacted.split(secret).join("[REDACTED]"), value);
8742
+ }
8743
+ var COMMAND_ABORTED_MESSAGE = "Command aborted";
8744
+ var OUTPUT_LIMIT_MESSAGE = "maxBuffer length exceeded";
8745
+ function commandFailureOutcome(error) {
8746
+ const details = error ?? {};
8747
+ const message = typeof details.message === "string" ? details.message : "";
8748
+ return {
8749
+ timedOut: details.killed === true,
8750
+ executableMissing: details.code === "ENOENT",
8751
+ aborted: message === COMMAND_ABORTED_MESSAGE,
8752
+ outputLimitExceeded: details.outputLimitExceeded === true,
8753
+ exitCode: typeof details.code === "number" ? details.code : null,
8754
+ signal: details.signal ?? null
8755
+ };
8756
+ }
8757
+ var commandInvocations = new Map;
8758
+ var commandCaptureMetrics;
8759
+ var commandObservers = new Map;
8760
+ function nonInteractiveGitEnv(env) {
8761
+ const merged = { ...env ?? process.env };
8762
+ merged.GIT_TERMINAL_PROMPT ??= "0";
8763
+ if (process.platform !== "win32") {
8764
+ merged.SSH_ASKPASS ??= "/usr/bin/false";
8765
+ merged.SSH_ASKPASS_REQUIRE ??= "force";
8766
+ }
8767
+ return merged;
8768
+ }
8769
+ var MAX_COMMAND_OUTPUT_BYTES = 50 * 1024 * 1024;
8770
+ var COMMAND_KILL_GRACE_MS = 100;
8771
+ var COMMAND_OUTPUT_CHECK_MS = 100;
8772
+ var COMMAND_GROUP_POLL_MS = 5;
8773
+ var COMMAND_GROUP_POLL_MAX_MS = 200;
8774
+ function openCaptureFile() {
8775
+ const filePath = path.join(os.tmpdir(), `orkestrator-capture-${randomUUID()}`);
8776
+ const fd = captureFs.openSync(filePath, fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_RDWR | fsConstants.O_APPEND, 384);
8777
+ try {
8778
+ captureFs.unlinkSync(filePath);
8779
+ return fd;
8780
+ } catch (error) {
8781
+ captureFs.closeSync(fd);
8782
+ throw error;
8783
+ }
8784
+ }
8785
+ function readCaptureFile(fd, limit) {
8786
+ const size = Math.min(captureFs.fstatSync(fd).size, limit);
8787
+ const buffer = Buffer.allocUnsafe(size);
8788
+ let offset = 0;
8789
+ while (offset < size) {
8790
+ const bytesRead = captureFs.readSync(fd, buffer, offset, size - offset, offset);
8791
+ if (bytesRead === 0)
8792
+ break;
8793
+ offset += bytesRead;
8794
+ }
8795
+ return buffer.subarray(0, offset);
8796
+ }
8797
+ function spawnCaptured(command, args, options, stdoutFd, stderrFd) {
8798
+ const payload = options.stdin?.length ? Buffer.from(options.stdin) : undefined;
8799
+ const env = command === "git" ? nonInteractiveGitEnv(options.env) : options.env ?? process.env;
8800
+ const detached = process.platform !== "win32";
8801
+ const bun = bunRuntime();
8802
+ if (bun) {
8803
+ const child = bun.spawn([command, ...args], {
8804
+ cwd: options.cwd,
8805
+ env,
8806
+ detached,
8807
+ windowsHide: true,
8808
+ stdin: payload ?? "pipe",
8809
+ stdout: stdoutFd,
8810
+ stderr: stderrFd
8811
+ });
8812
+ if (!payload)
8813
+ closeStdin(child.stdin);
8814
+ const current = () => ({ code: child.exitCode, signal: child.signalCode });
8815
+ return {
8816
+ pid: child.pid,
8817
+ exited: child.exited.then(current),
8818
+ current,
8819
+ kill: (signal) => child.kill(signal)
8820
+ };
8821
+ }
8822
+ const child = spawn(command, args, {
8823
+ cwd: options.cwd,
8824
+ env,
8825
+ detached,
8826
+ windowsHide: true,
8827
+ stdio: [payload ? "pipe" : "ignore", stdoutFd, stderrFd]
8828
+ });
8829
+ if (payload) {
8830
+ child.stdin?.on("error", () => {
8831
+ return;
8832
+ });
8833
+ child.stdin?.end(payload);
8834
+ }
8835
+ return {
8836
+ pid: child.pid,
8837
+ exited: new Promise((resolve, reject) => {
8838
+ child.once("exit", (code, signal) => resolve({ code, signal }));
8839
+ child.once("error", reject);
8840
+ }),
8841
+ current: () => ({ code: child.exitCode, signal: child.signalCode }),
8842
+ kill: (signal) => {
8843
+ child.kill(signal);
8844
+ }
8845
+ };
8846
+ }
8847
+ function closeStdin(stdin) {
8848
+ try {
8849
+ Promise.resolve(stdin.end()).catch(() => {
8850
+ return;
8851
+ });
8852
+ } catch {}
8853
+ }
8854
+ function exitReported(child) {
8855
+ const { code, signal } = child.current();
8856
+ return code !== null || signal !== null;
8857
+ }
8858
+ function signalCommand(child, signal) {
8859
+ if (child.pid === undefined)
8860
+ return;
8861
+ try {
8862
+ if (process.platform !== "win32") {
8863
+ process.kill(-child.pid, signal);
8864
+ } else {
8865
+ child.kill(signal);
8866
+ }
8867
+ } catch {}
8868
+ }
8869
+ function commandGroupAlive(child) {
8870
+ if (process.platform === "win32" || child.pid === undefined)
8871
+ return false;
8872
+ try {
8873
+ process.kill(-child.pid, 0);
8874
+ } catch (error) {
8875
+ if (error.code === "ESRCH")
8876
+ return false;
8877
+ }
8878
+ return groupHasLiveMember(child.pid);
8879
+ }
8880
+ function executeCommandBytes(command, args, options, timeoutMs, outputLimit, stderrLimit) {
8881
+ return new Promise((resolve, reject) => {
8882
+ if (options.signal?.aborted) {
8883
+ reject(Object.assign(new Error(COMMAND_ABORTED_MESSAGE), { killed: true }));
8884
+ return;
8885
+ }
8886
+ const captureFds = [];
8887
+ const releaseCaptureFds = () => {
8888
+ for (const fd of captureFds.splice(0)) {
8889
+ try {
8890
+ captureFs.closeSync(fd);
8891
+ } catch {}
8892
+ }
8893
+ };
8894
+ try {
8895
+ captureFds.push(openCaptureFile());
8896
+ captureFds.push(openCaptureFile());
8897
+ } catch (error) {
8898
+ releaseCaptureFds();
8899
+ const code = error.code ?? "unknown";
8900
+ reject(new Error(`Could not open a command output file in the temporary directory: ${code}`));
8901
+ return;
8902
+ }
8903
+ const [stdoutFd, stderrFd] = captureFds;
8904
+ let child;
8905
+ try {
8906
+ child = spawnCaptured(command, args, options, stdoutFd, stderrFd);
8907
+ } catch (error) {
8908
+ releaseCaptureFds();
8909
+ reject(error);
8910
+ return;
8911
+ }
8912
+ let settled = false;
8913
+ let timedOut = false;
8914
+ let timeoutTimer;
8915
+ let groupTimer;
8916
+ let limitTimer;
8917
+ let stopExitWatch = () => {};
8918
+ let commandExit;
8919
+ let pendingFailure;
8920
+ const finishCapture = () => {
8921
+ settled = true;
8922
+ clearTimeout(timeoutTimer);
8923
+ clearTimeout(groupTimer);
8924
+ clearInterval(limitTimer);
8925
+ stopExitWatch();
8926
+ options.signal?.removeEventListener("abort", abort);
8927
+ if (!exitReported(child))
8928
+ reapAfterLostExit(child.pid, () => exitReported(child));
8929
+ try {
8930
+ return {
8931
+ stdout: readCaptureFile(stdoutFd, outputLimit),
8932
+ stderr: readCaptureFile(stderrFd, stderrLimit)
8933
+ };
8934
+ } catch (error) {
8935
+ reject(error);
8936
+ return;
8937
+ } finally {
8938
+ releaseCaptureFds();
8939
+ }
8940
+ };
8941
+ const rejectFailure = (error) => {
8942
+ const output = finishCapture();
8943
+ if (output)
8944
+ reject(Object.assign(error, { ...output, killed: timedOut }));
8945
+ };
8946
+ const awaitTermination = (delayMs) => {
8947
+ clearTimeout(groupTimer);
8948
+ if (settled)
8949
+ return;
8950
+ if ((commandExit || exitReported(child)) && !commandGroupAlive(child)) {
8951
+ rejectFailure(pendingFailure);
8952
+ return;
8953
+ }
8954
+ groupTimer = setTimeout(awaitTermination, delayMs, Math.min(delayMs * 2, COMMAND_GROUP_POLL_MAX_MS));
8955
+ };
8956
+ const fail = (error) => {
8957
+ if (settled || pendingFailure)
8958
+ return;
8959
+ if (options.waitForTermination && child.pid !== undefined) {
8960
+ pendingFailure = error;
8961
+ signalCommand(child, "SIGKILL");
8962
+ clearTimeout(timeoutTimer);
8963
+ clearInterval(limitTimer);
8964
+ awaitTermination(COMMAND_GROUP_POLL_MS);
8965
+ } else
8966
+ rejectFailure(error);
8967
+ };
8968
+ const abort = () => {
8969
+ timedOut = true;
8970
+ signalCommand(child, "SIGKILL");
8971
+ fail(new Error(COMMAND_ABORTED_MESSAGE));
8972
+ };
8973
+ options.signal?.addEventListener("abort", abort, { once: true });
8974
+ const checkOutputLimit = () => {
8975
+ const stream = captureFs.fstatSync(stdoutFd).size > outputLimit ? "stdout" : captureFs.fstatSync(stderrFd).size > stderrLimit ? "stderr" : undefined;
8976
+ if (stream === undefined)
8977
+ return false;
8978
+ signalCommand(child, "SIGKILL");
8979
+ fail(Object.assign(new Error(`${stream} ${OUTPUT_LIMIT_MESSAGE}`), {
8980
+ outputLimitExceeded: true
8981
+ }));
8982
+ return true;
8983
+ };
8984
+ const failIfOverLimit = () => {
8985
+ try {
8986
+ return checkOutputLimit();
8987
+ } catch (error) {
8988
+ signalCommand(child, "SIGKILL");
8989
+ fail(error instanceof Error ? error : new Error(String(error)));
8990
+ return true;
8991
+ }
8992
+ };
8993
+ limitTimer = setInterval(() => {
8994
+ if (!settled && !timedOut && !pendingFailure)
8995
+ failIfOverLimit();
8996
+ }, COMMAND_OUTPUT_CHECK_MS);
8997
+ const settleOnExit = () => {
8998
+ if (settled || timedOut || pendingFailure || failIfOverLimit())
8999
+ return;
9000
+ if (commandExit?.code !== 0 || commandExit.signal !== null) {
9001
+ fail(Object.assign(new Error(`Command failed: ${[command, ...args].join(" ")}`), {
9002
+ code: commandExit?.code,
9003
+ signal: commandExit?.signal
9004
+ }));
9005
+ return;
9006
+ }
9007
+ const output = finishCapture();
9008
+ if (output)
9009
+ resolve(output);
9010
+ };
9011
+ const awaitGroupExit = (delayMs) => {
9012
+ if (settled || timedOut || pendingFailure)
9013
+ return;
9014
+ if (commandGroupAlive(child)) {
9015
+ groupTimer = setTimeout(awaitGroupExit, delayMs, Math.min(delayMs * 2, COMMAND_GROUP_POLL_MAX_MS));
9016
+ return;
9017
+ }
9018
+ settleOnExit();
9019
+ };
9020
+ const onCommandExit = (exit) => {
9021
+ if (commandExit)
9022
+ return;
9023
+ commandExit = exit;
9024
+ stopExitWatch();
9025
+ if (pendingFailure)
9026
+ awaitTermination(COMMAND_GROUP_POLL_MS);
9027
+ else if (options.waitForDescendants)
9028
+ awaitGroupExit(COMMAND_GROUP_POLL_MS);
9029
+ else
9030
+ settleOnExit();
9031
+ };
9032
+ child.exited.then(onCommandExit, (error) => fail(error instanceof Error ? error : new Error(String(error))));
9033
+ stopExitWatch = watchForLostExit(child.pid, (exit) => {
9034
+ if (!settled)
9035
+ onCommandExit(exit);
9036
+ });
9037
+ if (timeoutMs > 0) {
9038
+ timeoutTimer = setTimeout(() => {
9039
+ timedOut = true;
9040
+ signalCommand(child, "SIGTERM");
9041
+ timeoutTimer = setTimeout(() => {
9042
+ signalCommand(child, "SIGKILL");
9043
+ fail(Object.assign(new Error(`Command timed out after ${timeoutMs} ms`), {
9044
+ code: child.current().code,
9045
+ signal: child.current().signal
9046
+ }));
9047
+ }, COMMAND_KILL_GRACE_MS);
9048
+ }, timeoutMs);
9049
+ }
9050
+ });
9051
+ }
9052
+ async function runCommandBytes(command, args = [], options = {}) {
9053
+ const timeoutMs = options.timeoutMs ?? 60000;
9054
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > 2147483647) {
9055
+ throw new RangeError("timeoutMs must be an integer between 0 and 2147483647");
9056
+ }
9057
+ const outputLimit = options.maxOutputBytes ?? MAX_COMMAND_OUTPUT_BYTES;
9058
+ if (!Number.isSafeInteger(outputLimit) || outputLimit <= 0) {
9059
+ throw new RangeError("maxOutputBytes must be a positive integer");
9060
+ }
9061
+ const stderrLimit = options.maxStderrBytes ?? outputLimit;
9062
+ if (!Number.isSafeInteger(stderrLimit) || stderrLimit <= 0) {
9063
+ throw new RangeError("maxStderrBytes must be a positive integer");
9064
+ }
9065
+ if (commandInvocations.size < 64 || commandInvocations.has(command)) {
9066
+ commandInvocations.set(command, (commandInvocations.get(command) ?? 0) + 1);
9067
+ }
9068
+ for (const observer of commandObservers.get(command) ?? [])
9069
+ observer(args);
9070
+ commandCaptureMetrics?.started(command, args);
9071
+ try {
9072
+ const { stdout, stderr } = await executeCommandBytes(command, args, options, timeoutMs, outputLimit, stderrLimit);
9073
+ commandCaptureMetrics?.capturedBytes(stdout.length);
9074
+ return {
9075
+ stdout: Buffer.isBuffer(stdout) ? stdout : Buffer.from(stdout),
9076
+ stderr: Buffer.isBuffer(stderr) ? stderr : Buffer.from(stderr)
9077
+ };
9078
+ } catch (error) {
9079
+ const outcome = commandFailureOutcome(error);
9080
+ const redacting = options.redactValues?.some((value) => typeof value === "string" && value.length > 0);
9081
+ if (error && typeof error === "object" && "stdout" in error && "stderr" in error) {
9082
+ const withOutput = error;
9083
+ const stderr = withOutput.stderr?.toString() ?? "";
9084
+ const stdout = withOutput.stdout?.toString() ?? "";
9085
+ const message = (stderr || stdout || withOutput.message || "Command failed").trim();
9086
+ throw new CommandFailedError(redactCommandValues(message, options.redactValues), {
9087
+ ...outcome,
9088
+ stdout: redactCommandValues(stdout, options.redactValues),
9089
+ stderr: redactCommandValues(stderr, options.redactValues),
9090
+ ...!redacting && Buffer.isBuffer(withOutput.stdout) ? { stdoutBytes: withOutput.stdout } : {}
9091
+ });
9092
+ }
9093
+ if (redacting) {
9094
+ const message = error instanceof Error ? error.message : String(error);
9095
+ throw new CommandFailedError(redactCommandValues(message || "Command failed", options.redactValues), outcome);
9096
+ }
9097
+ if (outcome.timedOut || outcome.executableMissing) {
9098
+ const message = error instanceof Error ? error.message : String(error);
9099
+ throw new CommandFailedError(message || "Command failed", outcome);
9100
+ }
9101
+ throw error;
9102
+ }
9103
+ }
9104
+ async function runCommand(command, args = [], options = {}) {
9105
+ const { stdout, stderr } = await runCommandBytes(command, args, options);
9106
+ return {
9107
+ stdout: redactCommandValues(stdout.toString(), options.redactValues),
9108
+ stderr: redactCommandValues(stderr.toString(), options.redactValues)
9109
+ };
9110
+ }
9111
+
9112
+ // ../protocol/src/node/workspace-change-probe.ts
7969
9113
  var DEFAULT_MAX_UNTRACKED_FILE_BYTES = 2 * 1024 * 1024;
7970
9114
  var DEFAULT_MAX_UNTRACKED_FILES = 5000;
7971
9115
  var DEFAULT_SLOW_SNAPSHOT_MS = 500;
@@ -7979,31 +9123,20 @@ var temporaryObjectDirectories = new Set;
7979
9123
  process.once("exit", () => {
7980
9124
  for (const directory of temporaryObjectDirectories) {
7981
9125
  try {
7982
- rmSync(directory, { recursive: true, force: true });
9126
+ rmSync2(directory, { recursive: true, force: true });
7983
9127
  } catch {}
7984
9128
  }
7985
9129
  });
7986
- var runGit = (args, options) => new Promise((resolvePromise, reject) => {
7987
- const env = { ...process.env, ...options.env, GIT_OPTIONAL_LOCKS: "0" };
7988
- if (options.stdin === undefined) {
7989
- execFile("git", args, { cwd: options.cwd, env, timeout: GIT_TIMEOUT_MS, maxBuffer: GIT_MAX_BUFFER }, (error, stdout) => error ? reject(error) : resolvePromise({ stdout: String(stdout) }));
7990
- return;
7991
- }
7992
- const child = spawn("git", args, { cwd: options.cwd, env, timeout: GIT_TIMEOUT_MS });
7993
- let stdout = "";
7994
- let stdoutBytes = 0;
7995
- child.stdout.setEncoding("utf8");
7996
- child.stdout.on("data", (chunk) => {
7997
- stdoutBytes += chunk.length;
7998
- if (stdoutBytes <= GIT_MAX_BUFFER)
7999
- stdout += chunk;
9130
+ var runGit = async (args, options) => {
9131
+ const { stdout } = await runCommand("git", args, {
9132
+ cwd: options.cwd,
9133
+ env: { ...process.env, ...options.env, GIT_OPTIONAL_LOCKS: "0" },
9134
+ timeoutMs: GIT_TIMEOUT_MS,
9135
+ maxOutputBytes: GIT_MAX_BUFFER,
9136
+ ...options.stdin === undefined ? {} : { stdin: options.stdin }
8000
9137
  });
8001
- child.stderr.resume();
8002
- child.on("error", reject);
8003
- child.on("close", (code) => code === 0 ? resolvePromise({ stdout }) : reject(new Error(`git exited with ${code}`)));
8004
- child.stdin.on("error", () => {});
8005
- child.stdin.end(options.stdin);
8006
- });
9138
+ return { stdout };
9139
+ };
8007
9140
 
8008
9141
  class WorkspaceChangeProbe {
8009
9142
  git;
@@ -8291,7 +9424,7 @@ class WorkspaceChangeProbe {
8291
9424
  return;
8292
9425
  const { root, indexPath } = repo.location;
8293
9426
  const started = this.now();
8294
- const tempIndex = join(this.tempDir, `orkestrator-probe-${randomUUID()}.index`);
9427
+ const tempIndex = join(this.tempDir, `orkestrator-probe-${randomUUID2()}.index`);
8295
9428
  const objectDirectory = await mkdtemp(join(this.tempDir, "orkestrator-probe-objects-"));
8296
9429
  temporaryObjectDirectories.add(objectDirectory);
8297
9430
  let retained = false;
@@ -9062,10 +10195,10 @@ function registerSessionActivityBatchRoute(app, runtime) {
9062
10195
  }
9063
10196
 
9064
10197
  // ../../bridges/codex-bridge/src/transcript-routes.ts
9065
- import { randomUUID as randomUUID2 } from "node:crypto";
10198
+ import { randomUUID as randomUUID3 } from "node:crypto";
9066
10199
 
9067
10200
  // ../protocol/src/node/revised-rows.ts
9068
- import { createHash as createHash3 } from "node:crypto";
10201
+ import { createHash as createHash4 } from "node:crypto";
9069
10202
  var RECENTLY_REVISED_ROWS_MAX = 128;
9070
10203
 
9071
10204
  class RecentlyRevisedRows {
@@ -9103,7 +10236,7 @@ class RecentlyRevisedRows {
9103
10236
  function revisedRowsReconciliationToken(overflowVersion, omitted) {
9104
10237
  if (overflowVersion === 0 && omitted.length === 0)
9105
10238
  return;
9106
- const digest = createHash3("sha256").update(String(overflowVersion));
10239
+ const digest = createHash4("sha256").update(String(overflowVersion));
9107
10240
  for (const row of omitted)
9108
10241
  digest.update(JSON.stringify(row) ?? "null");
9109
10242
  return digest.digest("hex");
@@ -9111,7 +10244,7 @@ function revisedRowsReconciliationToken(overflowVersion, omitted) {
9111
10244
 
9112
10245
  // ../protocol/src/node/bridge-transcript-summary.ts
9113
10246
  import { Buffer as Buffer3 } from "node:buffer";
9114
- import { createHash as createHash4 } from "node:crypto";
10247
+ import { createHash as createHash5 } from "node:crypto";
9115
10248
 
9116
10249
  // ../protocol/src/node/progressive-transcript.ts
9117
10250
  var BRIDGE_TRANSCRIPT_MAX_MESSAGES = 100;
@@ -9277,7 +10410,7 @@ function digestPayload(payload) {
9277
10410
  const serialized = JSON.stringify(payload);
9278
10411
  return {
9279
10412
  bytes: Buffer3.byteLength(serialized),
9280
- digest: createHash4("sha256").update(serialized).digest("base64url").slice(0, 32)
10413
+ digest: createHash5("sha256").update(serialized).digest("base64url").slice(0, 32)
9281
10414
  };
9282
10415
  }
9283
10416
  function topLevelKey(part, index) {
@@ -9671,7 +10804,7 @@ function changeEvidenceAckRouteBody(spool, body) {
9671
10804
  }
9672
10805
 
9673
10806
  // ../../bridges/codex-bridge/src/transcript-routes.ts
9674
- var TRANSCRIPT_PROCESS = randomUUID2();
10807
+ var TRANSCRIPT_PROCESS = randomUUID3();
9675
10808
  function codexTranscriptSource(runtime, sessionId) {
9676
10809
  const status = runtime.getStatus(sessionId, false);
9677
10810
  const cached = runtime.getCachedMessages(sessionId);
@@ -9722,7 +10855,7 @@ function registerCodexChangeEvidenceRoutes(app, spool) {
9722
10855
  }
9723
10856
 
9724
10857
  // ../../bridges/codex-bridge/src/change-evidence.ts
9725
- import { createHash as createHash6 } from "node:crypto";
10858
+ import { createHash as createHash7 } from "node:crypto";
9726
10859
  import { existsSync as existsSync2 } from "node:fs";
9727
10860
  import { basename, join as join8 } from "node:path";
9728
10861
 
@@ -10129,8 +11262,8 @@ function workspaceObservationReportIssues(value) {
10129
11262
  }
10130
11263
 
10131
11264
  // ../protocol/src/node/change-tracking/evidence-spool.ts
10132
- import { createHash as createHash5, randomUUID as randomUUID3 } from "node:crypto";
10133
- import { readdirSync, readFileSync } from "node:fs";
11265
+ import { createHash as createHash6, randomUUID as randomUUID4 } from "node:crypto";
11266
+ import { readdirSync as readdirSync2, readFileSync as readFileSync2 } from "node:fs";
10134
11267
  import { appendFile, mkdir, rename, rm as rm2, writeFile } from "node:fs/promises";
10135
11268
  import { join as join3 } from "node:path";
10136
11269
  var DEFAULT_EVIDENCE_SPOOL_LIMITS = {
@@ -10145,10 +11278,10 @@ var DEFAULT_EVIDENCE_SPOOL_LIMITS = {
10145
11278
  var ENTRIES_FILE = "entries.jsonl";
10146
11279
  var BODY_DIRECTORY = "bodies";
10147
11280
  function evidenceBodyId(bytes) {
10148
- return `sha256:${createHash5("sha256").update(bytes).digest("hex")}`;
11281
+ return `sha256:${createHash6("sha256").update(bytes).digest("hex")}`;
10149
11282
  }
10150
11283
  function stableEvidenceId(...parts) {
10151
- const hash = createHash5("sha256");
11284
+ const hash = createHash6("sha256");
10152
11285
  for (const part of parts)
10153
11286
  hash.update(`${part ?? ""}\x00`);
10154
11287
  return hash.digest("hex").slice(0, 40);
@@ -10175,7 +11308,7 @@ class ChangeEvidenceSpool {
10175
11308
  restoring = false;
10176
11309
  constructor(options = {}) {
10177
11310
  this.limits = { ...DEFAULT_EVIDENCE_SPOOL_LIMITS, ...options.limits };
10178
- this.runtimeEpoch = options.runtimeEpoch ?? randomUUID3();
11311
+ this.runtimeEpoch = options.runtimeEpoch ?? randomUUID4();
10179
11312
  this.directory = options.directory;
10180
11313
  if (this.directory) {
10181
11314
  this.restoring = true;
@@ -10278,7 +11411,7 @@ class ChangeEvidenceSpool {
10278
11411
  return;
10279
11412
  if (this.entries.length >= this.limits.maxEntries - 1)
10280
11413
  return;
10281
- const gapId = randomUUID3();
11414
+ const gapId = randomUUID4();
10282
11415
  const coverage = this.droppedUnknown ? {
10283
11416
  kind: "unknown-range",
10284
11417
  bindingId: this.gapBindingId || "unknown",
@@ -10440,8 +11573,8 @@ class ChangeEvidenceSpool {
10440
11573
  restore(directory) {
10441
11574
  const bodyDirectory = join3(directory, BODY_DIRECTORY);
10442
11575
  try {
10443
- for (const name of readdirSync(bodyDirectory)) {
10444
- const bytes = new Uint8Array(readFileSync(join3(bodyDirectory, name)));
11576
+ for (const name of readdirSync2(bodyDirectory)) {
11577
+ const bytes = new Uint8Array(readFileSync2(join3(bodyDirectory, name)));
10445
11578
  const id = evidenceBodyId(bytes);
10446
11579
  if (bodyFileName(id) !== name)
10447
11580
  continue;
@@ -10453,7 +11586,7 @@ class ChangeEvidenceSpool {
10453
11586
  } catch {}
10454
11587
  let text = "";
10455
11588
  try {
10456
- text = readFileSync(join3(directory, ENTRIES_FILE), "utf8");
11589
+ text = readFileSync2(join3(directory, ENTRIES_FILE), "utf8");
10457
11590
  } catch {
10458
11591
  return;
10459
11592
  }
@@ -11355,34 +12488,34 @@ async function inheritCommandChanges(codexHome, parentThreadId, forkThreadId, me
11355
12488
  }
11356
12489
 
11357
12490
  // ../../bridges/codex-bridge/src/change-evidence-migration.ts
11358
- import { randomUUID as randomUUID4 } from "node:crypto";
12491
+ import { randomUUID as randomUUID5 } from "node:crypto";
11359
12492
  import {
11360
12493
  existsSync,
11361
12494
  mkdirSync,
11362
- readFileSync as readFileSync2,
11363
- readdirSync as readdirSync2,
12495
+ readFileSync as readFileSync3,
12496
+ readdirSync as readdirSync3,
11364
12497
  renameSync,
11365
- rmSync as rmSync2,
12498
+ rmSync as rmSync3,
11366
12499
  statSync,
11367
12500
  writeFileSync
11368
12501
  } from "node:fs";
11369
12502
  import { join as join7, resolve as resolve2 } from "node:path";
11370
12503
  import { isDeepStrictEqual } from "node:util";
11371
- function readBounded(path, limit) {
12504
+ function readBounded2(path, limit) {
11372
12505
  if (statSync(path).size > limit)
11373
12506
  throw new Error("Evidence migration exceeds storage capacity");
11374
- const bytes = readFileSync2(path);
12507
+ const bytes = readFileSync3(path);
11375
12508
  if (bytes.length > limit)
11376
12509
  throw new Error("Evidence migration exceeds storage capacity");
11377
12510
  return bytes;
11378
12511
  }
11379
12512
  function publishFile(path, contents) {
11380
- const temporary = `${path}.${randomUUID4()}.tmp`;
12513
+ const temporary = `${path}.${randomUUID5()}.tmp`;
11381
12514
  try {
11382
12515
  writeFileSync(temporary, contents, { mode: 384 });
11383
12516
  renameSync(temporary, path);
11384
12517
  } finally {
11385
- rmSync2(temporary, { force: true });
12518
+ rmSync3(temporary, { force: true });
11386
12519
  }
11387
12520
  }
11388
12521
  function migrateCodexChangeEvidence(legacy, shared) {
@@ -11397,7 +12530,7 @@ function migrateCodexChangeEvidence(legacy, shared) {
11397
12530
  const file = join7(directory, "entries.jsonl");
11398
12531
  if (!existsSync(file))
11399
12532
  continue;
11400
- for (const line of readBounded(file, DEFAULT_EVIDENCE_SPOOL_LIMITS.maxQueuedBytes).toString("utf8").split(`
12533
+ for (const line of readBounded2(file, DEFAULT_EVIDENCE_SPOOL_LIMITS.maxQueuedBytes).toString("utf8").split(`
11401
12534
  `)) {
11402
12535
  if (!line)
11403
12536
  continue;
@@ -11438,7 +12571,7 @@ function migrateCodexChangeEvidence(legacy, shared) {
11438
12571
  for (const id of bodyIds) {
11439
12572
  const name = id.replace(/[^A-Za-z0-9]/g, "_");
11440
12573
  const target = join7(shared, "bodies", name);
11441
- const bytes = readBounded(existsSync(target) ? target : join7(legacy, "bodies", name), DEFAULT_EVIDENCE_SPOOL_LIMITS.maxSingleBodyBytes);
12574
+ const bytes = readBounded2(existsSync(target) ? target : join7(legacy, "bodies", name), DEFAULT_EVIDENCE_SPOOL_LIMITS.maxSingleBodyBytes);
11442
12575
  if (evidenceBodyId(bytes) !== id)
11443
12576
  throw new Error("Evidence migration body integrity failed");
11444
12577
  bodyBytes += bytes.length;
@@ -11448,13 +12581,13 @@ function migrateCodexChangeEvidence(legacy, shared) {
11448
12581
  publishFile(target, bytes);
11449
12582
  }
11450
12583
  const retainedNames = new Set([...bodyIds].map((id) => id.replace(/[^A-Za-z0-9]/g, "_")));
11451
- for (const name of readdirSync2(join7(shared, "bodies"))) {
12584
+ for (const name of readdirSync3(join7(shared, "bodies"))) {
11452
12585
  if (/^sha256_[a-f0-9]{64}$/.test(name) && !retainedNames.has(name)) {
11453
- rmSync2(join7(shared, "bodies", name));
12586
+ rmSync3(join7(shared, "bodies", name));
11454
12587
  }
11455
12588
  }
11456
12589
  publishFile(join7(shared, "entries.jsonl"), contents);
11457
- rmSync2(legacyFile);
12590
+ rmSync3(legacyFile);
11458
12591
  }
11459
12592
 
11460
12593
  // ../../bridges/codex-bridge/src/change-evidence.ts
@@ -11693,7 +12826,7 @@ function suppliedMovePath(change) {
11693
12826
  return supplied?.kind === "update" ? supplied.movePath : change.move_path;
11694
12827
  }
11695
12828
  function codexChangeEvidenceDir(codexHome, cwd) {
11696
- const cwdHash = createHash6("sha256").update(cwd).digest("hex").slice(0, 16);
12829
+ const cwdHash = createHash7("sha256").update(cwd).digest("hex").slice(0, 16);
11697
12830
  return join8(codexBridgeStateDir(codexHome), "change-evidence", cwdHash);
11698
12831
  }
11699
12832
  function createCodexChangeEvidence(options) {
@@ -12362,13 +13495,13 @@ function humanPromptObservation(messages, tasks) {
12362
13495
  var USAGE_LIMIT_ERROR_CODE = "usage-limit";
12363
13496
 
12364
13497
  // ../../bridges/codex-bridge/src/sessions/typed-prompts.ts
12365
- import { createHash as createHash7, randomUUID as randomUUID5 } from "node:crypto";
13498
+ import { createHash as createHash8, randomUUID as randomUUID6 } from "node:crypto";
12366
13499
  import { mkdir as mkdir4, open, opendir, rename as rename3, rm as rm4, writeFile as writeFile3 } from "node:fs/promises";
12367
13500
  import { dirname as dirname2, join as join10 } from "node:path";
12368
13501
  var MAX_TYPED_PROMPT_CHARS = 32000;
12369
13502
  var MAX_RECORD_BYTES = 6 * MAX_TYPED_PROMPT_CHARS + 2048;
12370
13503
  function typedPromptDigest(sentText) {
12371
- return createHash7("sha256").update(sentText.trim()).digest("hex");
13504
+ return createHash8("sha256").update(sentText.trim()).digest("hex");
12372
13505
  }
12373
13506
  function typedPromptFor(record, sentText) {
12374
13507
  return record?.sent === typedPromptDigest(sentText) ? record.typed : undefined;
@@ -12406,7 +13539,7 @@ var writes = new Map;
12406
13539
  async function writeRecord(path, record) {
12407
13540
  const pending = (writes.get(path) ?? Promise.resolve()).then(async () => {
12408
13541
  await mkdir4(dirname2(path), { recursive: true, mode: 448 });
12409
- const temp = `${path}.${randomUUID5()}.tmp`;
13542
+ const temp = `${path}.${randomUUID6()}.tmp`;
12410
13543
  try {
12411
13544
  await writeFile3(temp, JSON.stringify(record), { mode: 384, flag: "wx" });
12412
13545
  await rename3(temp, path);
@@ -14588,7 +15721,7 @@ async function deriveTranscriptSubagentPartsForTurn({
14588
15721
  }
14589
15722
 
14590
15723
  // ../../bridges/codex-bridge/src/history/rollout.ts
14591
- import { createHash as createHash8 } from "node:crypto";
15724
+ import { createHash as createHash9 } from "node:crypto";
14592
15725
  import { readdir, stat as stat5 } from "node:fs/promises";
14593
15726
  import { homedir } from "node:os";
14594
15727
  import { basename as basename2, join as join11 } from "node:path";
@@ -16073,6 +17206,24 @@ function mcpToolCallParts(item) {
16073
17206
  }
16074
17207
  ];
16075
17208
  }
17209
+ function commandExecutionParts(item) {
17210
+ const output = capCommandOutput(item.aggregated_output);
17211
+ const failed = item.status === "failed";
17212
+ return [
17213
+ {
17214
+ type: "tool-invocation",
17215
+ toolUseId: item.id,
17216
+ content: item.command,
17217
+ toolName: "bash",
17218
+ toolArgs: { command: item.command },
17219
+ toolState: item.status === "failed" ? "failure" : item.status === "completed" ? "success" : "pending",
17220
+ toolTitle: item.command,
17221
+ toolOutput: failed ? undefined : output || undefined,
17222
+ toolError: failed ? output || "Command failed" : undefined,
17223
+ ...finishedDuration(item)
17224
+ }
17225
+ ];
17226
+ }
16076
17227
  async function itemToParts(item, cwd, fileChangeContext) {
16077
17228
  switch (item.type) {
16078
17229
  case "agent_message":
@@ -16095,24 +17246,8 @@ async function itemToParts(item, cwd, fileChangeContext) {
16095
17246
  return [{ type: "text", content: agentMessageDisplayText(item) }];
16096
17247
  case "reasoning":
16097
17248
  return hasVisibleText(item.text) ? [{ type: "thinking", content: item.text }] : [];
16098
- case "command_execution": {
16099
- const output = capCommandOutput(item.aggregated_output);
16100
- const failed = item.status === "failed";
16101
- return [
16102
- {
16103
- type: "tool-invocation",
16104
- toolUseId: item.id,
16105
- content: item.command,
16106
- toolName: "bash",
16107
- toolArgs: { command: item.command },
16108
- toolState: item.status === "failed" ? "failure" : item.status === "completed" ? "success" : "pending",
16109
- toolTitle: item.command,
16110
- toolOutput: failed ? undefined : output || undefined,
16111
- toolError: failed ? output || "Command failed" : undefined,
16112
- ...finishedDuration(item)
16113
- }
16114
- ];
16115
- }
17249
+ case "command_execution":
17250
+ return commandExecutionParts(item);
16116
17251
  case "file_change":
16117
17252
  return item.changes.map((change, index) => ({
16118
17253
  type: "tool-invocation",
@@ -16419,8 +17554,39 @@ function codeModeMcpCallPart(call, toolUseId) {
16419
17554
  })[0];
16420
17555
  }
16421
17556
 
17557
+ // ../../bridges/codex-bridge/src/history/code-mode-commands.ts
17558
+ var ROLLOUT_COMMAND_EXECUTION_ITEM_TYPE = "CommandExecution";
17559
+ var PLAIN_WORD = /^[A-Za-z0-9_@%+=:,./-]+$/;
17560
+ function joinCommandArguments(argv) {
17561
+ return argv.map((word) => word === "" ? "''" : PLAIN_WORD.test(word) ? word : `'${word.replaceAll("'", `'"'"'`)}'`).join(" ");
17562
+ }
17563
+ function isRecord8(value) {
17564
+ return !!value && typeof value === "object" && !Array.isArray(value);
17565
+ }
17566
+ function rolloutCommandExecutionParts(item) {
17567
+ if (!isRecord8(item) || item.type !== ROLLOUT_COMMAND_EXECUTION_ITEM_TYPE)
17568
+ return null;
17569
+ if (typeof item.id !== "string" || item.id.length === 0)
17570
+ return null;
17571
+ const command = Array.isArray(item.command) ? item.command.every((word) => typeof word === "string") ? joinCommandArguments(item.command) : undefined : typeof item.command === "string" ? item.command : undefined;
17572
+ if (command === undefined)
17573
+ return null;
17574
+ const { item: adapted } = adaptAppServerItem({
17575
+ id: item.id,
17576
+ type: "commandExecution",
17577
+ command,
17578
+ aggregatedOutput: item.aggregated_output,
17579
+ status: item.status,
17580
+ exitCode: item.exit_code,
17581
+ durationMs: rolloutDurationMs(item.duration) ?? null
17582
+ });
17583
+ return adapted?.type === "command_execution" ? commandExecutionParts(adapted) : null;
17584
+ }
17585
+
16422
17586
  // ../protocol/src/coordinator.ts
16423
17587
  var COORDINATOR_CODEX_USER_SKILLS_DIR_ENV = "ORKESTRATOR_COORDINATOR_CODEX_USER_SKILLS_DIR";
17588
+ var COORDINATOR_OTHER_ENVIRONMENTS_SETTING_LABEL = "Let the coordinator use environments it did not create";
17589
+ var COORDINATOR_ENVIRONMENT_ORIGIN_REFUSAL = `Not done: this coordinator did not create that environment, so it may not send it work. Do not retry. Use an environment this coordinator launched, or start a new one. If the user wants this coordinator to work in environments it did not create, tell them to turn on "${COORDINATOR_OTHER_ENVIRONMENTS_SETTING_LABEL}" in this project's settings, under Coordinator.`;
16424
17590
  var COORDINATOR_CONTROL_TOOL_NAMES = Object.freeze([
16425
17591
  "ack_message",
16426
17592
  "add_ticket_comment",
@@ -16890,7 +18056,7 @@ async function readSessionIndex(path) {
16890
18056
  }
16891
18057
 
16892
18058
  // ../../bridges/codex-bridge/src/history/rollout.ts
16893
- var log4 = createLogger("bridge.codex");
18059
+ var log5 = createLogger("bridge.codex");
16894
18060
  function getCodexHomeDir() {
16895
18061
  return process.env.CODEX_HOME || join11(homedir(), ".codex");
16896
18062
  }
@@ -17459,7 +18625,7 @@ async function hydrateMessagesFromPersistedSession(threadId, options = {}) {
17459
18625
  };
17460
18626
  }
17461
18627
  }
17462
- log4.warn("rollout.hydrate-failed", { threadId });
18628
+ log5.warn("rollout.hydrate-failed", { threadId });
17463
18629
  return {
17464
18630
  messages: [],
17465
18631
  title: meta.title,
@@ -17483,7 +18649,7 @@ var NON_TOOL_TURN_ITEM_TYPES = new Set([
17483
18649
  ]);
17484
18650
  var MAX_OPEN_CODE_MODE_CELLS = 256;
17485
18651
  function replayedRowId(threadId, scope, kind, ordinal) {
17486
- const digest = createHash8("sha256").update(`${threadId}\x00${scope}\x00${kind}\x00${ordinal}`).digest("hex");
18652
+ const digest = createHash9("sha256").update(`${threadId}\x00${scope}\x00${kind}\x00${ordinal}`).digest("hex");
17487
18653
  return `msg-r-${digest.slice(0, 32)}`;
17488
18654
  }
17489
18655
  async function forEachHistoryBatch(snapshot, visit) {
@@ -17547,6 +18713,7 @@ async function replayPersistedRollout(threadId, snapshot, meta, structuredTurns)
17547
18713
  const spawnPartSlots = new Map;
17548
18714
  const messages = [];
17549
18715
  const toolPartsByCallId = new Map;
18716
+ const turnCallIds = new Set;
17550
18717
  const transcriptCwd = asNonEmptyString2(meta.cwd) ?? getWorkingDirectory();
17551
18718
  let currentTurnId;
17552
18719
  let currentTurnModel;
@@ -17626,6 +18793,10 @@ async function replayPersistedRollout(threadId, snapshot, meta, structuredTurns)
17626
18793
  const { toolState: _inFlight, ...settled } = cell.message.parts[call.partIndex];
17627
18794
  cell.message.parts[call.partIndex] = outcome?.failed ? { ...settled, toolState: "failure" } : settled;
17628
18795
  }
18796
+ if (cell.sawCommandRecord && cell.sourceCalls.length === 0 && !cell.keepExecRow && !outcome?.refused) {
18797
+ toolPartsByCallId.delete(cell.callId);
18798
+ dropPart(cell.message, cell.execPartIndex);
18799
+ }
17629
18800
  };
17630
18801
  const settleOpenCells = () => {
17631
18802
  for (const cell of openCells.values())
@@ -17656,13 +18827,32 @@ async function replayPersistedRollout(threadId, snapshot, meta, structuredTurns)
17656
18827
  callees: codeModeMcpCallees(source),
17657
18828
  sourceCalls,
17658
18829
  sawMcpRecord: false,
18830
+ sawCommandRecord: false,
17659
18831
  keepExecRow: false
17660
18832
  });
17661
18833
  };
18834
+ const visitCommandRecord = (item) => {
18835
+ const open = [...openCells.values()];
18836
+ const parts = rolloutCommandExecutionParts(item);
18837
+ const id = asNonEmptyString2(item.id);
18838
+ const direct = id !== undefined && turnCallIds.has(id);
18839
+ if (!parts || direct || open.length !== 1) {
18840
+ for (const cell of open)
18841
+ cell.keepExecRow = true;
18842
+ return;
18843
+ }
18844
+ const cell = open[0];
18845
+ cell.sawCommandRecord = true;
18846
+ cell.message.parts.push(...parts);
18847
+ };
17662
18848
  const visitCompletedItem = (item, timestamp) => {
17663
18849
  if (!item || typeof item !== "object" || Array.isArray(item))
17664
18850
  return;
17665
18851
  const fields = item;
18852
+ if (fields.type === ROLLOUT_COMMAND_EXECUTION_ITEM_TYPE) {
18853
+ visitCommandRecord(fields);
18854
+ return;
18855
+ }
17666
18856
  if (fields.type !== ROLLOUT_MCP_TOOL_CALL_ITEM_TYPE) {
17667
18857
  if (typeof fields.type === "string" && !NON_TOOL_TURN_ITEM_TYPES.has(fields.type)) {
17668
18858
  for (const cell of openCells.values())
@@ -17777,6 +18967,7 @@ async function replayPersistedRollout(threadId, snapshot, meta, structuredTurns)
17777
18967
  if (recordTurnId && recordTurnId !== currentTurnId) {
17778
18968
  settleOpenCells();
17779
18969
  currentTurnId = recordTurnId;
18970
+ turnCallIds.clear();
17780
18971
  typedPromptConsumed = false;
17781
18972
  currentTurnModel = undefined;
17782
18973
  closeAssistantRow();
@@ -17824,6 +19015,11 @@ async function replayPersistedRollout(threadId, snapshot, meta, structuredTurns)
17824
19015
  }
17825
19016
  if (ROLLOUT_TOOL_CALL_TYPES.has(String(payload.type)))
17826
19017
  currentRowCalledTool = true;
19018
+ if (ROLLOUT_TOOL_CALL_TYPES.has(String(payload.type))) {
19019
+ const callId = asNonEmptyString2(payload.call_id);
19020
+ if (callId)
19021
+ turnCallIds.add(callId);
19022
+ }
17827
19023
  if (payload.type === "function_call" || payload.type === "custom_tool_call") {
17828
19024
  const assistantMessage = ensureAssistantMessage(timestamp);
17829
19025
  const callId = asNonEmptyString2(payload.call_id);
@@ -17948,7 +19144,7 @@ async function replayPersistedRollout(threadId, snapshot, meta, structuredTurns)
17948
19144
  }
17949
19145
 
17950
19146
  // ../../bridges/codex-bridge/src/messages/render-turn.ts
17951
- var log5 = createLogger("bridge.codex");
19147
+ var log6 = createLogger("bridge.codex");
17952
19148
  var TRUNCATION_NOTICE = `
17953
19149
  … output truncated`;
17954
19150
  var SUBAGENT_TRANSCRIPT_PROBE_INTERVAL_MS = 2000;
@@ -18369,7 +19565,7 @@ async function renderTurn(turn, options) {
18369
19565
  loadSnapshot = latestSnapshot;
18370
19566
  }
18371
19567
  } catch (error) {
18372
- log5.warn("subagent.activity-load-failed", { error: formatLogError(error) });
19568
+ log6.warn("subagent.activity-load-failed", { error: formatLogError(error) });
18373
19569
  }
18374
19570
  }
18375
19571
  const { items, itemsByKey, accumulatorsByKey, versionsByKey, itemKeys } = collectTurnItems(turn, options.segment);
@@ -18644,7 +19840,7 @@ function openModelResponseRow(context, state, turn, event, now) {
18644
19840
  });
18645
19841
  return true;
18646
19842
  }
18647
- function segmentNeedsRender(turn, segment, historical, now = Date.now()) {
19843
+ function segmentNeedsRender(turn, segment, historical, now = Date.now(), probeIntervalMs = SUBAGENT_TRANSCRIPT_PROBE_INTERVAL_MS) {
18648
19844
  if (turn.assistantSegmentVersion(segment.assistantMessageId) !== historical.renderedItemVersion) {
18649
19845
  return true;
18650
19846
  }
@@ -18656,15 +19852,36 @@ function segmentNeedsRender(turn, segment, historical, now = Date.now()) {
18656
19852
  return false;
18657
19853
  }
18658
19854
  const probedAt = historical.render.subagentProbedAt;
18659
- return probedAt === 0 || now - probedAt >= SUBAGENT_TRANSCRIPT_PROBE_INTERVAL_MS;
19855
+ return probedAt === 0 || now - probedAt >= probeIntervalMs;
19856
+ }
19857
+ function scheduleSubagentProbe(state, turn, intervalMs, onDue) {
19858
+ const waiting = !turn.isTerminal() && (state.render.subagentActivity && !state.render.subagentSettled || Array.from(state.historicalAssistantSegments.values()).some((row) => !row.retiring && awaitsSubagent(row)));
19859
+ if (!waiting) {
19860
+ cancelSubagentProbe(state);
19861
+ return;
19862
+ }
19863
+ if (state.subagentProbeTimer)
19864
+ return;
19865
+ state.subagentProbeTimer = setTimeout(() => {
19866
+ state.subagentProbeTimer = undefined;
19867
+ onDue();
19868
+ }, intervalMs);
19869
+ state.subagentProbeTimer.unref?.();
19870
+ }
19871
+ function cancelSubagentProbe(state) {
19872
+ if (!state.subagentProbeTimer)
19873
+ return;
19874
+ clearTimeout(state.subagentProbeTimer);
19875
+ state.subagentProbeTimer = undefined;
18660
19876
  }
18661
19877
  async function publishAssistantRows(context, state, turn, options) {
18662
19878
  const now = Date.now();
19879
+ const probeIntervalMs = options.subagentProbeIntervalMs ?? SUBAGENT_TRANSCRIPT_PROBE_INTERVAL_MS;
18663
19880
  trackChangedRows(context, state, turn, now);
18664
19881
  const due = [];
18665
19882
  for (const [id, historical] of state.historicalAssistantSegments) {
18666
19883
  const segment = turn.findAssistantSegment(id);
18667
- if (segment && segmentNeedsRender(turn, segment, historical, now)) {
19884
+ if (segment && segmentNeedsRender(turn, segment, historical, now, probeIntervalMs)) {
18668
19885
  due.push(id);
18669
19886
  } else if (historical.retiring) {
18670
19887
  releaseRow(state, turn, id, historical);
@@ -18689,7 +19906,7 @@ async function publishAssistantRows(context, state, turn, options) {
18689
19906
  cwd: options.cwd,
18690
19907
  state: renderState,
18691
19908
  segment,
18692
- subagentProbeIntervalMs: SUBAGENT_TRANSCRIPT_PROBE_INTERVAL_MS,
19909
+ subagentProbeIntervalMs: probeIntervalMs,
18693
19910
  ...startedHistorical && !renderState.subagentActivity ? { skipSubagentProbe: true } : {}
18694
19911
  });
18695
19912
  const isCurrent = id === turn.assistantMessageId;
@@ -18760,7 +19977,7 @@ async function publishAssistantRows(context, state, turn, options) {
18760
19977
  }
18761
19978
 
18762
19979
  // ../../bridges/codex-bridge/src/app-server-runtime-sessions.ts
18763
- import { createHash as createHash13, randomUUID as randomUUID8 } from "node:crypto";
19980
+ import { createHash as createHash14, randomUUID as randomUUID9 } from "node:crypto";
18764
19981
 
18765
19982
  // ../protocol/src/agent-mail.ts
18766
19983
  var AGENT_MAIL_MAX_BODY_BYTES = 32 * 1024;
@@ -19096,12 +20313,12 @@ var ORKESTRATOR_ARTIFACT_MCP_PATH = "/artifact-mcp";
19096
20313
 
19097
20314
  // ../../bridges/codex-bridge/src/engine/app-server-engine.ts
19098
20315
  import { open as open9 } from "node:fs/promises";
19099
- import { createHash as createHash12 } from "node:crypto";
20316
+ import { createHash as createHash13 } from "node:crypto";
19100
20317
  import { isAbsolute as isAbsolute9, join as join20 } from "node:path";
19101
20318
 
19102
20319
  // ../../bridges/codex-bridge/src/app-server/process-supervisor.ts
19103
- import { execFile as execFile3, spawn as spawn2 } from "node:child_process";
19104
- import { randomUUID as randomUUID6 } from "node:crypto";
20320
+ import { execFile as execFile2, spawn as spawn2 } from "node:child_process";
20321
+ import { randomUUID as randomUUID7 } from "node:crypto";
19105
20322
  import {
19106
20323
  link,
19107
20324
  mkdir as mkdir6,
@@ -19270,14 +20487,14 @@ var PREVIEW_LIMIT = 200;
19270
20487
  function preview(value) {
19271
20488
  return value.length > PREVIEW_LIMIT ? `${value.slice(0, PREVIEW_LIMIT)}…` : value;
19272
20489
  }
19273
- function isRecord8(value) {
20490
+ function isRecord9(value) {
19274
20491
  return !!value && typeof value === "object" && !Array.isArray(value);
19275
20492
  }
19276
20493
  function isValidId(value) {
19277
20494
  return typeof value === "string" || typeof value === "number" && Number.isFinite(value);
19278
20495
  }
19279
20496
  function parseErrorBody(value) {
19280
- if (!isRecord8(value))
20497
+ if (!isRecord9(value))
19281
20498
  return null;
19282
20499
  const code = typeof value.code === "number" ? value.code : null;
19283
20500
  if (code === null)
@@ -19289,7 +20506,7 @@ function parseErrorBody(value) {
19289
20506
  };
19290
20507
  }
19291
20508
  function classifyInbound(value) {
19292
- if (!isRecord8(value)) {
20509
+ if (!isRecord9(value)) {
19293
20510
  return {
19294
20511
  kind: "invalid",
19295
20512
  detail: "envelope is not an object",
@@ -19356,17 +20573,17 @@ function parseInboundLine(line) {
19356
20573
  return classifyInbound(parsed);
19357
20574
  }
19358
20575
  function extractThreadId(params) {
19359
- if (!isRecord8(params))
20576
+ if (!isRecord9(params))
19360
20577
  return null;
19361
20578
  if (typeof params.threadId === "string" && params.threadId.length > 0)
19362
20579
  return params.threadId;
19363
- if (isRecord8(params.thread) && typeof params.thread.id === "string")
20580
+ if (isRecord9(params.thread) && typeof params.thread.id === "string")
19364
20581
  return params.thread.id;
19365
20582
  return null;
19366
20583
  }
19367
20584
 
19368
20585
  // ../../bridges/codex-bridge/src/app-server/jsonl-rpc-client.ts
19369
- var log6 = createLogger("bridge.codex");
20586
+ var log7 = createLogger("bridge.codex");
19370
20587
  var DEFAULT_MAX_INBOUND_LINE_BYTES = 64 * 1024 * 1024;
19371
20588
  var DEFAULT_MAX_OUTBOUND_LINE_BYTES = 32 * 1024 * 1024;
19372
20589
  var DEFAULT_REQUEST_TIMEOUT_MS = 60000;
@@ -19478,7 +20695,7 @@ class JsonlRpcClient {
19478
20695
  try {
19479
20696
  this.options.recordInboundLine(line);
19480
20697
  } catch (error) {
19481
- log6.error("recorder.threw", { error: formatLogError(error) });
20698
+ log7.error("recorder.threw", { error: formatLogError(error) });
19482
20699
  }
19483
20700
  }
19484
20701
  const message = parseInboundLine(line);
@@ -19510,7 +20727,7 @@ class JsonlRpcClient {
19510
20727
  try {
19511
20728
  this.options.onServerRequest(message);
19512
20729
  } catch (error) {
19513
- log6.error("server-request.handoff-failed", { error: formatLogError(error) });
20730
+ log7.error("server-request.handoff-failed", { error: formatLogError(error) });
19514
20731
  }
19515
20732
  return;
19516
20733
  }
@@ -19519,7 +20736,7 @@ class JsonlRpcClient {
19519
20736
  try {
19520
20737
  this.options.onNotification(message, extractThreadId(message.params), Buffer.byteLength(line, "utf8"));
19521
20738
  } catch (error) {
19522
- log6.error("notification.enqueue-failed", { error: formatLogError(error) });
20739
+ log7.error("notification.enqueue-failed", { error: formatLogError(error) });
19523
20740
  }
19524
20741
  return;
19525
20742
  }
@@ -19701,7 +20918,7 @@ class SerialQueue {
19701
20918
  run(key, task, bytes = 0) {
19702
20919
  if (this.depth >= this.maxDepth || this.bytes + bytes > this.maxBytes) {
19703
20920
  const overflow = { depth: this.depth, bytes: this.bytes };
19704
- log6.error("queue.overflow", overflow);
20921
+ log7.error("queue.overflow", overflow);
19705
20922
  this.clear();
19706
20923
  this.onOverflow?.(overflow);
19707
20924
  return;
@@ -19781,16 +20998,16 @@ class SerialQueue {
19781
20998
  queue.waiters.splice(0, resolved);
19782
20999
  }
19783
21000
  reportTaskFailure(key, error) {
19784
- log6.error("queue.task-failed", { key, error: formatLogError(error) });
21001
+ log7.error("queue.task-failed", { key, error: formatLogError(error) });
19785
21002
  }
19786
21003
  }
19787
21004
 
19788
21005
  // ../../bridges/codex-bridge/src/app-server/notification-recorder.ts
19789
21006
  import { appendFile as appendFile4, mkdir as mkdir5 } from "node:fs/promises";
19790
21007
  import { join as join13 } from "node:path";
19791
- var log7 = createLogger("bridge.codex");
21008
+ var log8 = createLogger("bridge.codex");
19792
21009
  function recorderNotice(message) {
19793
- log7.warn("recorder.notice", { detail: message });
21010
+ log8.warn("recorder.notice", { detail: message });
19794
21011
  }
19795
21012
  var DEFAULT_MAX_RECORDING_BYTES = 64 * 1024 * 1024;
19796
21013
  var DEFAULT_FLUSH_INTERVAL_MS = 250;
@@ -19903,7 +21120,7 @@ class NotificationRecorder {
19903
21120
  } catch (error) {
19904
21121
  this.stats.writeErrors += 1;
19905
21122
  this.stats.linesDropped += pending.length;
19906
- log7.error("recorder.write-failed", { error: formatLogError(error, { stack: false }) });
21123
+ log8.error("recorder.write-failed", { error: formatLogError(error, { stack: false }) });
19907
21124
  }
19908
21125
  }
19909
21126
  async close() {
@@ -19936,10 +21153,10 @@ function createRecorderFromEnv(options) {
19936
21153
 
19937
21154
  // ../../bridges/codex-bridge/src/runtime-env.ts
19938
21155
  import { execFile as execFileCallback } from "node:child_process";
19939
- import { createHash as createHash9 } from "node:crypto";
21156
+ import { createHash as createHash10 } from "node:crypto";
19940
21157
  import { promisify } from "node:util";
19941
- var log8 = createLogger("bridge.codex");
19942
- var execFile2 = promisify(execFileCallback);
21158
+ var log9 = createLogger("bridge.codex");
21159
+ var execFile = promisify(execFileCallback);
19943
21160
  var RUNTIME_ENV_SCRIPT_ENV = "ORKESTRATOR_RUNTIME_ENV_SCRIPT";
19944
21161
  var DEFAULT_RUNTIME_ENV_SCRIPT = "/usr/local/bin/orkestrator-runtime-env.sh";
19945
21162
  var RUNTIME_ENV_CREDENTIAL_VARIABLES = new Set([
@@ -20001,7 +21218,7 @@ function applyRuntimeEnvironmentOutput(output) {
20001
21218
  }
20002
21219
  return updated;
20003
21220
  }
20004
- async function refreshRuntimeEnvironment(run = execFile2) {
21221
+ async function refreshRuntimeEnvironment(run = execFile) {
20005
21222
  try {
20006
21223
  const runtimeEnvScript = getRuntimeEnvironmentScriptPath();
20007
21224
  const { stdout } = await run("/bin/sh", [
@@ -20016,14 +21233,14 @@ async function refreshRuntimeEnvironment(run = execFile2) {
20016
21233
  });
20017
21234
  const updated = applyRuntimeEnvironmentOutput(stdout);
20018
21235
  if (updated.length > 0) {
20019
- log8.info("runtime-env.refreshed", { names: updated.join(", ") });
21236
+ log9.info("runtime-env.refreshed", { names: updated.join(", ") });
20020
21237
  }
20021
21238
  } catch (error) {
20022
- log8.warn("runtime-env.refresh-failed", { error: formatLogError(error) });
21239
+ log9.warn("runtime-env.refresh-failed", { error: formatLogError(error) });
20023
21240
  }
20024
21241
  }
20025
21242
  function fingerprintRuntimeEnvironment(env = process.env) {
20026
- const hash = createHash9("sha256");
21243
+ const hash = createHash10("sha256");
20027
21244
  for (const name of [...RUNTIME_ENV_VARIABLES].sort()) {
20028
21245
  hash.update(name);
20029
21246
  hash.update("\x00");
@@ -20039,7 +21256,7 @@ function runtimeEnvironmentSnapshot(env = process.env) {
20039
21256
  }
20040
21257
 
20041
21258
  // ../../bridges/codex-bridge/src/app-server/process-supervisor.ts
20042
- var log9 = createLogger("bridge.codex");
21259
+ var log10 = createLogger("bridge.codex");
20043
21260
 
20044
21261
  class AppServerOwnershipUnavailableError extends AppServerUnavailableError {
20045
21262
  ownershipContention = true;
@@ -20094,7 +21311,7 @@ class AppServerSupervisor {
20094
21311
  unknownNotifications = 0;
20095
21312
  unknownServerRequests = 0;
20096
21313
  drainPromise = null;
20097
- pidOwnerToken = randomUUID6();
21314
+ pidOwnerToken = randomUUID7();
20098
21315
  pidOwnershipHeld = false;
20099
21316
  constructor(options) {
20100
21317
  this.options = options;
@@ -20258,7 +21475,7 @@ class AppServerSupervisor {
20258
21475
  if (this.stopping)
20259
21476
  throw new AppServerUnavailableError("stopped");
20260
21477
  const environmentFingerprint = this.fingerprintEnvironment();
20261
- const instanceId = randomUUID6();
21478
+ const instanceId = randomUUID7();
20262
21479
  const instanceStartedAt = this.now();
20263
21480
  if (this.options.pidFileEnabled !== false && !this.pidOwnershipHeld) {
20264
21481
  const available = await this.acquirePidFileOwnership(instanceId);
@@ -20325,7 +21542,7 @@ class AppServerSupervisor {
20325
21542
  if (describedLines >= STDERR_METADATA_LINE_BUDGET)
20326
21543
  return;
20327
21544
  describedLines += 1;
20328
- log9.info("app-server.stderr", () => ({
21545
+ log10.info("app-server.stderr", () => ({
20329
21546
  generation: generationId,
20330
21547
  detail: describeChildStderrLine(line)
20331
21548
  }));
@@ -20349,7 +21566,7 @@ class AppServerSupervisor {
20349
21566
  stderrTail = "";
20350
21567
  if (suppressedLines === 0)
20351
21568
  return;
20352
- log9.info("app-server.stderr-suppressed", {
21569
+ log10.info("app-server.stderr-suppressed", {
20353
21570
  generation: generationId,
20354
21571
  lines: suppressedLines,
20355
21572
  payloadBytes: suppressedBytes
@@ -20359,7 +21576,7 @@ class AppServerSupervisor {
20359
21576
  };
20360
21577
  const recorder = (this.options.createRecorder ?? ((generation) => createRecorderFromEnv({ generation })))(generationId);
20361
21578
  if (recorder) {
20362
- log9.warn("app-server.recording", {
21579
+ log10.warn("app-server.recording", {
20363
21580
  generation: generationId,
20364
21581
  fileName: recorder.getStats().fileName
20365
21582
  });
@@ -20372,7 +21589,7 @@ class AppServerSupervisor {
20372
21589
  onServerRequest: (request) => this.options.onServerRequest(request, generationId),
20373
21590
  onProtocolViolation: (detail) => {
20374
21591
  this.unknownNotifications += 1;
20375
- log9.warn("app-server.protocol-violation", { generation: generationId, detail });
21592
+ log10.warn("app-server.protocol-violation", { generation: generationId, detail });
20376
21593
  },
20377
21594
  ...recorder ? { recordInboundLine: (line) => recorder.record(line) } : {}
20378
21595
  });
@@ -20450,7 +21667,7 @@ class AppServerSupervisor {
20450
21667
  return;
20451
21668
  const exited = this.current;
20452
21669
  this.current = null;
20453
- log9.warn("app-server.exited", {
21670
+ log10.warn("app-server.exited", {
20454
21671
  generation: generationId,
20455
21672
  code,
20456
21673
  signal,
@@ -20470,7 +21687,7 @@ class AppServerSupervisor {
20470
21687
  const reason = "notification queue overflowed";
20471
21688
  this.lastError = reason;
20472
21689
  this.restartNow(reason).catch((error) => {
20473
- log9.error("app-server.overflow-restart-failed", { error: formatLogError(error) });
21690
+ log10.error("app-server.overflow-restart-failed", { error: formatLogError(error) });
20474
21691
  });
20475
21692
  }
20476
21693
  async ensureEnvironmentIsCurrent(options) {
@@ -20723,7 +21940,7 @@ class AppServerSupervisor {
20723
21940
  if (outcome === "contended")
20724
21941
  return true;
20725
21942
  if (matches && pid !== null) {
20726
- log9.info("app-server.stale-reaped", { pid });
21943
+ log10.info("app-server.stale-reaped", { pid });
20727
21944
  (this.options.signalPidFileProcess ?? signalStaleProcessTree)(pid);
20728
21945
  }
20729
21946
  return true;
@@ -20836,7 +22053,7 @@ class AppServerSupervisor {
20836
22053
  }
20837
22054
  function runPs(args) {
20838
22055
  return new Promise((resolve, reject) => {
20839
- execFile3("/bin/ps", args, {
22056
+ execFile2("/bin/ps", args, {
20840
22057
  maxBuffer: 1024 * 1024,
20841
22058
  env: { ...runtimeEnvironmentSnapshot(), LC_ALL: "C", LANG: "C", TZ: process.env.TZ }
20842
22059
  }, (error, stdout) => {
@@ -21033,14 +22250,14 @@ function proposedPrefix(value) {
21033
22250
  }
21034
22251
  return [...value];
21035
22252
  }
21036
- function isRecord9(value) {
22253
+ function isRecord10(value) {
21037
22254
  return !!value && typeof value === "object" && !Array.isArray(value);
21038
22255
  }
21039
22256
  function str2(value) {
21040
22257
  return typeof value === "string" && value.length > 0 ? value : undefined;
21041
22258
  }
21042
22259
  function changeKind2(value) {
21043
- const type = isRecord9(value) ? value.type : value;
22260
+ const type = isRecord10(value) ? value.type : value;
21044
22261
  return type === "add" ? "add" : type === "delete" ? "delete" : "update";
21045
22262
  }
21046
22263
  function commandText(value) {
@@ -21055,23 +22272,23 @@ function commandText(value) {
21055
22272
  function commandActionsText(value) {
21056
22273
  if (!Array.isArray(value))
21057
22274
  return;
21058
- const commands = value.map((entry) => isRecord9(entry) ? str2(entry.command) : undefined).filter((entry) => entry !== undefined);
22275
+ const commands = value.map((entry) => isRecord10(entry) ? str2(entry.command) : undefined).filter((entry) => entry !== undefined);
21059
22276
  return commands.length > 0 ? [...new Set(commands)].join(`
21060
22277
  `) : undefined;
21061
22278
  }
21062
22279
  function describeApproval(options) {
21063
- const params = isRecord9(options.params) ? options.params : {};
22280
+ const params = isRecord10(options.params) ? options.params : {};
21064
22281
  const kind = options.method === "item/permissions/requestApproval" ? "permissions" : options.method === "item/fileChange/requestApproval" || options.method === "applyPatchApproval" ? "file-change" : "command";
21065
- const changes = isRecord9(params.fileChanges) ? Object.entries(params.fileChanges).map(([path, change]) => ({
22282
+ const changes = isRecord10(params.fileChanges) ? Object.entries(params.fileChanges).map(([path, change]) => ({
21066
22283
  path,
21067
- kind: changeKind2(isRecord9(change) ? change.type : undefined),
21068
- ...isRecord9(change) && change.move_path != null ? { movePath: typeof change.move_path === "string" ? change.move_path : "" } : {}
22284
+ kind: changeKind2(isRecord10(change) ? change.type : undefined),
22285
+ ...isRecord10(change) && change.move_path != null ? { movePath: typeof change.move_path === "string" ? change.move_path : "" } : {}
21069
22286
  })) : undefined;
21070
- const permissions = isRecord9(params.permissions) ? {
22287
+ const permissions = isRecord10(params.permissions) ? {
21071
22288
  network: params.permissions.network != null,
21072
22289
  fileSystem: params.permissions.fileSystem != null
21073
22290
  } : undefined;
21074
- const networkContext = isRecord9(params.networkApprovalContext) ? str2(params.networkApprovalContext.host) : undefined;
22291
+ const networkContext = isRecord10(params.networkApprovalContext) ? str2(params.networkApprovalContext.host) : undefined;
21075
22292
  const command = commandText(params.command) ?? commandActionsText(params.commandActions);
21076
22293
  const v2Command = options.method === "item/commandExecution/requestApproval" && (params.kind === undefined || params.kind === null || params.kind === "command");
21077
22294
  const exactCommand = v2Command && typeof params.command === "string" && params.command.length > 0;
@@ -21122,8 +22339,8 @@ function buildApprovalResponse(method, decision, rawParams) {
21122
22339
  };
21123
22340
  }
21124
22341
  case "item/permissions/requestApproval": {
21125
- const params = isRecord9(rawParams) ? rawParams : {};
21126
- const requested = isRecord9(params.permissions) ? params.permissions : {};
22342
+ const params = isRecord10(rawParams) ? rawParams : {};
22343
+ const requested = isRecord10(params.permissions) ? params.permissions : {};
21127
22344
  const granting = isGrantingApprovalDecision(decision);
21128
22345
  return {
21129
22346
  result: {
@@ -21400,7 +22617,7 @@ function buildInteractionResponse(request, answer) {
21400
22617
  }
21401
22618
 
21402
22619
  // ../../bridges/codex-bridge/src/app-server/server-request-router.ts
21403
- var log10 = createLogger("bridge.codex");
22620
+ var log11 = createLogger("bridge.codex");
21404
22621
  var DEFAULT_RESPONSE_TIMEOUT_MS = 1e4;
21405
22622
  var DEFAULT_APPROVAL_TIMEOUT_MS = AGENT_INTERACTION_DEFAULT_TIMEOUT_MS;
21406
22623
 
@@ -21560,7 +22777,7 @@ class ServerRequestRouter {
21560
22777
  record.timedOut = true;
21561
22778
  this.counts.timedOut += 1;
21562
22779
  if (this.sendStarted.has(key)) {
21563
- log10.error("server-request.flush-timeout", {
22780
+ log11.error("server-request.flush-timeout", {
21564
22781
  method: record.method,
21565
22782
  timeoutMs: this.responseTimeoutMs
21566
22783
  });
@@ -21664,7 +22881,7 @@ class ServerRequestRouter {
21664
22881
  accepted = this.options.presentApproval?.(approval) === true;
21665
22882
  } catch (error) {
21666
22883
  deadline.settle();
21667
- log10.error("approval.present-failed", { error: formatLogError(error) });
22884
+ log11.error("approval.present-failed", { error: formatLogError(error) });
21668
22885
  return false;
21669
22886
  }
21670
22887
  if (!accepted) {
@@ -21701,7 +22918,7 @@ class ServerRequestRouter {
21701
22918
  try {
21702
22919
  this.options.onApprovalResolved?.(parked.request, decision, resolution);
21703
22920
  } catch (error) {
21704
- log10.error("approval.resolved-callback-failed", { error: formatLogError(error) });
22921
+ log11.error("approval.resolved-callback-failed", { error: formatLogError(error) });
21705
22922
  }
21706
22923
  if (options.skipSend) {
21707
22924
  this.pending.delete(parked.key);
@@ -21722,7 +22939,7 @@ class ServerRequestRouter {
21722
22939
  try {
21723
22940
  this.options.onApprovalResolved?.(parked.request, "withdrawn", "withdrawn");
21724
22941
  } catch (error) {
21725
- log10.error("approval.resolved-callback-failed", { error: formatLogError(error) });
22942
+ log11.error("approval.resolved-callback-failed", { error: formatLogError(error) });
21726
22943
  }
21727
22944
  this.pending.delete(parked.key);
21728
22945
  this.sendStarted.delete(parked.key);
@@ -21764,7 +22981,7 @@ class ServerRequestRouter {
21764
22981
  accepted = this.options.presentInteraction?.(interaction) === true;
21765
22982
  } catch (error) {
21766
22983
  deadline?.settle();
21767
- log10.error("interaction.present-failed", { error: formatLogError(error) });
22984
+ log11.error("interaction.present-failed", { error: formatLogError(error) });
21768
22985
  return false;
21769
22986
  }
21770
22987
  if (!accepted) {
@@ -21800,7 +23017,7 @@ class ServerRequestRouter {
21800
23017
  try {
21801
23018
  this.options.onInteractionResolved?.(parked.request, answer, resolution);
21802
23019
  } catch (error) {
21803
- log10.error("interaction.resolved-callback-failed", { error: formatLogError(error) });
23020
+ log11.error("interaction.resolved-callback-failed", { error: formatLogError(error) });
21804
23021
  }
21805
23022
  if (options.skipSend) {
21806
23023
  this.pending.delete(parked.key);
@@ -21833,7 +23050,7 @@ class ServerRequestRouter {
21833
23050
  try {
21834
23051
  await send();
21835
23052
  } catch (error) {
21836
- log10.error("server-request.answer-failed", {
23053
+ log11.error("server-request.answer-failed", {
21837
23054
  method: record.method,
21838
23055
  error: formatLogError(error, { stack: false })
21839
23056
  });
@@ -21850,7 +23067,7 @@ class ServerRequestRouter {
21850
23067
  }
21851
23068
  violation(method, detail) {
21852
23069
  this.options.onInvariantViolation?.(method, detail);
21853
- log10.error("app-server.invariant-violation", { method, detail });
23070
+ log11.error("app-server.invariant-violation", { method, detail });
21854
23071
  }
21855
23072
  explain(record, message) {
21856
23073
  this.options.reportToTranscript?.({
@@ -21874,7 +23091,7 @@ function asString2(value) {
21874
23091
  function assertNever(value) {}
21875
23092
 
21876
23093
  // ../../bridges/codex-bridge/src/app-server/event-reducer.ts
21877
- function isRecord10(value) {
23094
+ function isRecord11(value) {
21878
23095
  return !!value && typeof value === "object" && !Array.isArray(value);
21879
23096
  }
21880
23097
  function str3(value) {
@@ -21902,7 +23119,7 @@ function epochSecondsToIso(value) {
21902
23119
  return new Date(ms).toISOString();
21903
23120
  }
21904
23121
  function toTurnError(raw) {
21905
- if (!isRecord10(raw)) {
23122
+ if (!isRecord11(raw)) {
21906
23123
  return { message: typeof raw === "string" ? raw : "Codex reported an error" };
21907
23124
  }
21908
23125
  const code = codexErrorInfoToCode(raw.codexErrorInfo);
@@ -21981,13 +23198,13 @@ function isIgnoredNotification(method) {
21981
23198
  function reduceNotification(notification, generation, handle) {
21982
23199
  const params = notification.params;
21983
23200
  const base = { engineGeneration: generation, ...handle ? { handle } : {} };
21984
- const threadId = isRecord10(params) ? str3(params.threadId) ?? null : null;
21985
- const turnId = isRecord10(params) ? str3(params.turnId) : undefined;
23201
+ const threadId = isRecord11(params) ? str3(params.threadId) ?? null : null;
23202
+ const turnId = isRecord11(params) ? str3(params.turnId) : undefined;
21986
23203
  switch (notification.method) {
21987
23204
  case "skills/changed":
21988
23205
  return { events: [{ kind: "skills.changed", ...base }] };
21989
23206
  case "thread/settings/updated": {
21990
- const settings = isRecord10(params) && isRecord10(params.threadSettings) ? params.threadSettings : undefined;
23207
+ const settings = isRecord11(params) && isRecord11(params.threadSettings) ? params.threadSettings : undefined;
21991
23208
  const model = settings ? str3(settings.model)?.trim() : undefined;
21992
23209
  if (!threadId || !model)
21993
23210
  return { events: [] };
@@ -22003,7 +23220,7 @@ function reduceNotification(notification, generation, handle) {
22003
23220
  };
22004
23221
  }
22005
23222
  case "model/rerouted": {
22006
- const model = isRecord10(params) ? str3(params.toModel)?.trim() : undefined;
23223
+ const model = isRecord11(params) ? str3(params.toModel)?.trim() : undefined;
22007
23224
  if (!threadId || !turnId || !model)
22008
23225
  return { events: [] };
22009
23226
  return {
@@ -22020,7 +23237,7 @@ function reduceNotification(notification, generation, handle) {
22020
23237
  }
22021
23238
  case "modelProvider/authRecoveryStarted":
22022
23239
  case "modelProvider/authRecoveryCompleted": {
22023
- if (!threadId || !isRecord10(params))
23240
+ if (!threadId || !isRecord11(params))
22024
23241
  return { events: [] };
22025
23242
  const message = str3(params.message)?.trim().slice(0, 300);
22026
23243
  const provider = str3(params.provider)?.trim().slice(0, 64);
@@ -22038,11 +23255,11 @@ function reduceNotification(notification, generation, handle) {
22038
23255
  };
22039
23256
  }
22040
23257
  case "thread/tokenUsage/updated": {
22041
- if (!isRecord10(params) || !threadId || !turnId || !isRecord10(params.tokenUsage)) {
23258
+ if (!isRecord11(params) || !threadId || !turnId || !isRecord11(params.tokenUsage)) {
22042
23259
  return { events: [] };
22043
23260
  }
22044
- const total = isRecord10(params.tokenUsage.total) ? params.tokenUsage.total : {};
22045
- const last = isRecord10(params.tokenUsage.last) ? params.tokenUsage.last : {};
23261
+ const total = isRecord11(params.tokenUsage.total) ? params.tokenUsage.total : {};
23262
+ const last = isRecord11(params.tokenUsage.last) ? params.tokenUsage.last : {};
22046
23263
  const contextWindow = num(params.tokenUsage.modelContextWindow) ?? 0;
22047
23264
  const usedTokens = num(last.totalTokens) ?? 0;
22048
23265
  return {
@@ -22085,7 +23302,7 @@ function reduceNotification(notification, generation, handle) {
22085
23302
  };
22086
23303
  }
22087
23304
  case "account/rateLimits/updated": {
22088
- if (!isRecord10(params) || !isRecord10(params.rateLimits))
23305
+ if (!isRecord11(params) || !isRecord11(params.rateLimits))
22089
23306
  return { events: [] };
22090
23307
  const snapshot = params.rateLimits;
22091
23308
  const limitId = str3(snapshot.limitId);
@@ -22093,14 +23310,14 @@ function reduceNotification(notification, generation, handle) {
22093
23310
  return { events: [] };
22094
23311
  const windows = [];
22095
23312
  const limitName = typeof snapshot.limitName === "string" && snapshot.limitName.length > 0 ? snapshot.limitName : undefined;
22096
- if (!isRecord10(snapshot.primary) && limitName !== undefined) {
23313
+ if (!isRecord11(snapshot.primary) && limitName !== undefined) {
22097
23314
  windows.push({ slot: "primary", label: limitName });
22098
23315
  }
22099
23316
  for (const [key, label] of [
22100
23317
  ["primary", "Primary"],
22101
23318
  ["secondary", "Secondary"]
22102
23319
  ]) {
22103
- const window = isRecord10(snapshot[key]) ? snapshot[key] : undefined;
23320
+ const window = isRecord11(snapshot[key]) ? snapshot[key] : undefined;
22104
23321
  if (!window)
22105
23322
  continue;
22106
23323
  const resetsAt = epochSecondsToIso(window.resetsAt);
@@ -22125,8 +23342,8 @@ function reduceNotification(notification, generation, handle) {
22125
23342
  };
22126
23343
  }
22127
23344
  case "thread/started": {
22128
- const thread = isRecord10(params) ? params.thread : undefined;
22129
- const id = isRecord10(thread) ? str3(thread.id) : undefined;
23345
+ const thread = isRecord11(params) ? params.thread : undefined;
23346
+ const id = isRecord11(thread) ? str3(thread.id) : undefined;
22130
23347
  if (!id)
22131
23348
  return { events: [] };
22132
23349
  return { events: [{ kind: "thread.started", threadId: id, ...base }] };
@@ -22144,19 +23361,19 @@ function reduceNotification(notification, generation, handle) {
22144
23361
  case "thread/name/updated": {
22145
23362
  if (!threadId)
22146
23363
  return { events: [] };
22147
- const name = isRecord10(params) ? str3(params.threadName) : undefined;
23364
+ const name = isRecord11(params) ? str3(params.threadName) : undefined;
22148
23365
  return { events: [{ kind: "thread.name.updated", threadId, name, ...base }] };
22149
23366
  }
22150
23367
  case "turn/started": {
22151
- const turn = isRecord10(params) ? params.turn : undefined;
22152
- const id = isRecord10(turn) ? str3(turn.id) : undefined;
23368
+ const turn = isRecord11(params) ? params.turn : undefined;
23369
+ const id = isRecord11(turn) ? str3(turn.id) : undefined;
22153
23370
  if (!id)
22154
23371
  return { events: [] };
22155
23372
  return { events: [{ kind: "turn.started", threadId, turnId: id, ...base }] };
22156
23373
  }
22157
23374
  case "turn/completed": {
22158
- const turn = isRecord10(params) ? params.turn : undefined;
22159
- if (!isRecord10(turn))
23375
+ const turn = isRecord11(params) ? params.turn : undefined;
23376
+ if (!isRecord11(turn))
22160
23377
  return { events: [] };
22161
23378
  const id = str3(turn.id);
22162
23379
  if (!id)
@@ -22176,7 +23393,7 @@ function reduceNotification(notification, generation, handle) {
22176
23393
  };
22177
23394
  }
22178
23395
  case "error": {
22179
- if (!isRecord10(params))
23396
+ if (!isRecord11(params))
22180
23397
  return { events: [] };
22181
23398
  return {
22182
23399
  events: [
@@ -22193,7 +23410,7 @@ function reduceNotification(notification, generation, handle) {
22193
23410
  }
22194
23411
  case "item/started":
22195
23412
  case "item/completed": {
22196
- if (!isRecord10(params) || !turnId)
23413
+ if (!isRecord11(params) || !turnId)
22197
23414
  return { events: [] };
22198
23415
  const { item, unsupportedType } = adaptAppServerItem(params.item);
22199
23416
  if (!item)
@@ -22216,7 +23433,7 @@ function reduceNotification(notification, generation, handle) {
22216
23433
  };
22217
23434
  }
22218
23435
  case "item/agentMessage/delta": {
22219
- if (!isRecord10(params) || !turnId)
23436
+ if (!isRecord11(params) || !turnId)
22220
23437
  return { events: [] };
22221
23438
  const itemId = str3(params.itemId);
22222
23439
  const delta = typeof params.delta === "string" ? params.delta : undefined;
@@ -22228,7 +23445,7 @@ function reduceNotification(notification, generation, handle) {
22228
23445
  }
22229
23446
  case "item/reasoning/summaryTextDelta":
22230
23447
  case "item/reasoning/textDelta": {
22231
- if (!isRecord10(params) || !turnId)
23448
+ if (!isRecord11(params) || !turnId)
22232
23449
  return { events: [] };
22233
23450
  const itemId = str3(params.itemId);
22234
23451
  const delta = typeof params.delta === "string" ? params.delta : undefined;
@@ -22253,7 +23470,7 @@ function reduceNotification(notification, generation, handle) {
22253
23470
  case "item/reasoning/summaryPartAdded":
22254
23471
  return { events: [] };
22255
23472
  case "serverRequest/resolved": {
22256
- if (!isRecord10(params))
23473
+ if (!isRecord11(params))
22257
23474
  return { events: [] };
22258
23475
  const requestId = params.requestId;
22259
23476
  if (typeof requestId !== "string" && typeof requestId !== "number")
@@ -22265,7 +23482,7 @@ function reduceNotification(notification, generation, handle) {
22265
23482
  case "item/mcpToolCall/progress":
22266
23483
  case "item/fileChange/outputDelta":
22267
23484
  case "item/plan/delta": {
22268
- if (!isRecord10(params) || !turnId)
23485
+ if (!isRecord11(params) || !turnId)
22269
23486
  return { events: [] };
22270
23487
  const itemId = str3(params.itemId);
22271
23488
  const message = str3(params.message) ?? str3(params.delta);
@@ -22276,7 +23493,7 @@ function reduceNotification(notification, generation, handle) {
22276
23493
  };
22277
23494
  }
22278
23495
  case "item/commandExecution/outputDelta": {
22279
- if (!isRecord10(params) || !turnId)
23496
+ if (!isRecord11(params) || !turnId)
22280
23497
  return { events: [] };
22281
23498
  const itemId = str3(params.itemId);
22282
23499
  const delta = typeof params.delta === "string" ? params.delta : undefined;
@@ -22292,13 +23509,13 @@ function reduceNotification(notification, generation, handle) {
22292
23509
  return { events: [{ kind: "model.tool.called", threadId, turnId, ...base }] };
22293
23510
  }
22294
23511
  case "rawResponseItem/completed": {
22295
- if (!isRecord10(params) || !threadId || !turnId || !isRecord10(params.item)) {
23512
+ if (!isRecord11(params) || !threadId || !turnId || !isRecord11(params.item)) {
22296
23513
  return { events: [] };
22297
23514
  }
22298
23515
  const rawItem = params.item;
22299
23516
  const payloadType = str3(rawItem.type);
22300
23517
  if (payloadType === "configuration_update") {
22301
- const reasoning = isRecord10(rawItem.reasoning) ? rawItem.reasoning : undefined;
23518
+ const reasoning = isRecord11(rawItem.reasoning) ? rawItem.reasoning : undefined;
22302
23519
  const reasoningEffort = reasoning ? str3(reasoning.effort)?.trim() : undefined;
22303
23520
  if (!reasoningEffort)
22304
23521
  return { events: [] };
@@ -22357,7 +23574,7 @@ function reduceNotification(notification, generation, handle) {
22357
23574
  return { events: boundary };
22358
23575
  }
22359
23576
  case "item/fileChange/patchUpdated": {
22360
- if (!isRecord10(params) || !turnId)
23577
+ if (!isRecord11(params) || !turnId)
22361
23578
  return { events: [] };
22362
23579
  const itemId = str3(params.itemId);
22363
23580
  if (!itemId)
@@ -22373,7 +23590,7 @@ function reduceNotification(notification, generation, handle) {
22373
23590
  return { events: [{ kind: "item.updated", threadId, turnId, item, ...base }] };
22374
23591
  }
22375
23592
  case "turn/plan/updated": {
22376
- if (!isRecord10(params) || !turnId)
23593
+ if (!isRecord11(params) || !turnId)
22377
23594
  return { events: [] };
22378
23595
  const item = planUpdateToTodoList(turnId, params.plan);
22379
23596
  if (!item)
@@ -22381,7 +23598,7 @@ function reduceNotification(notification, generation, handle) {
22381
23598
  return { events: [{ kind: "item.updated", threadId, turnId, item, ...base }] };
22382
23599
  }
22383
23600
  case "turn/diff/updated": {
22384
- if (!isRecord10(params) || !turnId)
23601
+ if (!isRecord11(params) || !turnId)
22385
23602
  return { events: [] };
22386
23603
  const diff = typeof params.diff === "string" ? params.diff : undefined;
22387
23604
  if (diff === undefined)
@@ -22405,7 +23622,7 @@ function reduceHistoricalTurns(turns, generation, threadId, handle) {
22405
23622
  return { events, unsupportedItemTypes };
22406
23623
  const base = { engineGeneration: generation, ...handle ? { handle } : {} };
22407
23624
  for (const turn of turns) {
22408
- if (!isRecord10(turn))
23625
+ if (!isRecord11(turn))
22409
23626
  continue;
22410
23627
  const turnId = str3(turn.id);
22411
23628
  if (!turnId)
@@ -22436,12 +23653,12 @@ function reduceHistoricalTurns(turns, generation, threadId, handle) {
22436
23653
  }
22437
23654
 
22438
23655
  // ../../bridges/codex-bridge/src/sessions/dispatch-journal.ts
22439
- import { createHash as createHash11 } from "node:crypto";
23656
+ import { createHash as createHash12 } from "node:crypto";
22440
23657
  import { mkdir as mkdir8, open as open7, rename as rename6, rm as rm7, writeFile as writeFile5 } from "node:fs/promises";
22441
23658
  import { join as join16 } from "node:path";
22442
23659
 
22443
23660
  // ../../bridges/codex-bridge/src/sessions/persistence.ts
22444
- import { createHash as createHash10, randomUUID as randomUUID7 } from "node:crypto";
23661
+ import { createHash as createHash11, randomUUID as randomUUID8 } from "node:crypto";
22445
23662
  import {
22446
23663
  chmod,
22447
23664
  link as link2,
@@ -22454,7 +23671,7 @@ import {
22454
23671
  writeFile as writeFile4
22455
23672
  } from "node:fs/promises";
22456
23673
  import { join as join15 } from "node:path";
22457
- var log11 = createLogger("bridge.codex");
23674
+ var log12 = createLogger("bridge.codex");
22458
23675
  var BRIDGE_SESSION_REGISTRY_VERSION = 2;
22459
23676
  var SESSION_TITLE_SOURCES = new Set([
22460
23677
  "codex",
@@ -22536,7 +23753,7 @@ function isPersistedSessionTombstone(value) {
22536
23753
  return tombstone.deleted === true && typeof tombstone.bridgeSessionId === "string" && tombstone.bridgeSessionId.length > 0 && typeof tombstone.deletedAt === "string" && Number.isFinite(Date.parse(tombstone.deletedAt));
22537
23754
  }
22538
23755
  function hashCwd(cwd) {
22539
- return createHash10("sha256").update(cwd).digest("hex").slice(0, 16);
23756
+ return createHash11("sha256").update(cwd).digest("hex").slice(0, 16);
22540
23757
  }
22541
23758
  var DEFAULT_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
22542
23759
  var RECORD_FILE_MISSING = Symbol("record-file-missing");
@@ -22570,7 +23787,7 @@ class BridgeSessionStore {
22570
23787
  return directory === this.recordsDir() ? undefined : directory;
22571
23788
  }
22572
23789
  recordKey(bridgeSessionId) {
22573
- return createHash10("sha256").update(bridgeSessionId).digest("hex");
23790
+ return createHash11("sha256").update(bridgeSessionId).digest("hex");
22574
23791
  }
22575
23792
  recordPath(bridgeSessionId) {
22576
23793
  return join15(this.recordsDir(), `${this.recordKey(bridgeSessionId)}.json`);
@@ -22722,7 +23939,7 @@ class BridgeSessionStore {
22722
23939
  await this.ensurePrivateStorage();
22723
23940
  await Promise.all(sessions.map(async (session) => {
22724
23941
  const target = this.recordPath(session.bridgeSessionId);
22725
- const temporary = `${target}.${process.pid}.${randomUUID7()}.tmp`;
23942
+ const temporary = `${target}.${process.pid}.${randomUUID8()}.tmp`;
22726
23943
  await writeFile4(temporary, `${JSON.stringify(session, null, 2)}
22727
23944
  `, {
22728
23945
  encoding: "utf8",
@@ -22753,7 +23970,7 @@ class BridgeSessionStore {
22753
23970
  await Promise.all(names.map(async (name) => {
22754
23971
  const from = join15(source, name);
22755
23972
  const target = join15(this.recordsDir(), name);
22756
- const temporary = `${target}.${process.pid}.${randomUUID7()}.tmp`;
23973
+ const temporary = `${target}.${process.pid}.${randomUUID8()}.tmp`;
22757
23974
  await writeFile4(temporary, await readFile6(from), { mode: PRIVATE_FILE_MODE });
22758
23975
  await chmod(temporary, PRIVATE_FILE_MODE);
22759
23976
  try {
@@ -22778,7 +23995,7 @@ class BridgeSessionStore {
22778
23995
  `);
22779
23996
  }
22780
23997
  async writeAtomicPath(path, payload) {
22781
- const temporary = `${path}.${process.pid}.${randomUUID7()}.tmp`;
23998
+ const temporary = `${path}.${process.pid}.${randomUUID8()}.tmp`;
22782
23999
  await writeFile4(temporary, payload, {
22783
24000
  encoding: "utf8",
22784
24001
  mode: PRIVATE_FILE_MODE
@@ -22793,7 +24010,7 @@ class BridgeSessionStore {
22793
24010
  await chmod(path, PRIVATE_FILE_MODE);
22794
24011
  }
22795
24012
  warnPersistenceFailure(error) {
22796
- log11.warn("registry.persist-failed", { error: formatLogError(error, { stack: false }) });
24013
+ log12.warn("registry.persist-failed", { error: formatLogError(error, { stack: false }) });
22797
24014
  }
22798
24015
  toRecord(options) {
22799
24016
  const { agentMcp: _agentMcp, ...persistedConfig } = options.config;
@@ -22817,7 +24034,7 @@ class BridgeSessionStore {
22817
24034
  }
22818
24035
 
22819
24036
  // ../../bridges/codex-bridge/src/sessions/dispatch-journal.ts
22820
- var log12 = createLogger("bridge.codex");
24037
+ var log13 = createLogger("bridge.codex");
22821
24038
  var DISPATCH_JOURNAL_VERSION = 1;
22822
24039
  var DISPATCH_COMPLETENESS_VERSION = 1;
22823
24040
  var MAX_FRESH_SESSION_MARKERS = 256;
@@ -23233,7 +24450,7 @@ class DispatchJournal {
23233
24450
  this.filterAdd(requestId);
23234
24451
  }
23235
24452
  filterPositions(requestId) {
23236
- const digest = createHash11("sha256").update(requestId, "utf8").digest();
24453
+ const digest = createHash12("sha256").update(requestId, "utf8").digest();
23237
24454
  const positions = [];
23238
24455
  for (let index = 0;index < UNTRACKED_FILTER_HASHES; index += 1) {
23239
24456
  positions.push(digest.readUInt32BE(index * 4) % UNTRACKED_FILTER_BITS);
@@ -23356,7 +24573,7 @@ class DispatchJournal {
23356
24573
  throw error;
23357
24574
  });
23358
24575
  } catch (error) {
23359
- log12.warn("journal.persist-failed", { error: formatLogError(error, { stack: false }) });
24576
+ log13.warn("journal.persist-failed", { error: formatLogError(error, { stack: false }) });
23360
24577
  if (options.failClosed)
23361
24578
  throw error;
23362
24579
  }
@@ -23472,12 +24689,12 @@ function coordinatorCapabilityPolicy(mode) {
23472
24689
  }
23473
24690
 
23474
24691
  // ../../bridges/codex-bridge/src/codex-config.ts
23475
- import { existsSync as existsSync3, readdirSync as readdirSync3, realpathSync, statSync as statSync2 } from "node:fs";
24692
+ import { existsSync as existsSync3, readdirSync as readdirSync4, realpathSync, statSync as statSync2 } from "node:fs";
23476
24693
  import { homedir as homedir3 } from "node:os";
23477
24694
  import { isAbsolute as isAbsolute8, join as join18, relative as relative3, sep } from "node:path";
23478
24695
 
23479
24696
  // ../../bridges/codex-bridge/src/shell-exclusions.ts
23480
- import { closeSync, openSync, readSync, fstatSync } from "node:fs";
24697
+ import { closeSync as closeSync3, openSync as openSync3, readSync as readSync3, fstatSync as fstatSync3 } from "node:fs";
23481
24698
  import { homedir as homedir2 } from "node:os";
23482
24699
  import { dirname as dirname3, join as join17, resolve as resolve3 } from "node:path";
23483
24700
  function configuredShellExclusions(env) {
@@ -23499,21 +24716,21 @@ function configuredShellExclusions(env) {
23499
24716
  for (const path of paths) {
23500
24717
  let fd;
23501
24718
  try {
23502
- fd = openSync(path, "r");
24719
+ fd = openSync3(path, "r");
23503
24720
  } catch (error) {
23504
24721
  if (error.code === "ENOENT")
23505
24722
  continue;
23506
24723
  throw new Error("Cannot read Codex shell exclusions");
23507
24724
  }
23508
24725
  try {
23509
- const stat = fstatSync(fd);
24726
+ const stat = fstatSync3(fd);
23510
24727
  if (!stat.isFile() || stat.size > 1024 * 1024) {
23511
24728
  throw new Error("Invalid Codex configuration file");
23512
24729
  }
23513
24730
  const buffer = Buffer.alloc(1024 * 1024 + 1);
23514
24731
  let length = 0;
23515
24732
  while (length < buffer.length) {
23516
- const count = readSync(fd, buffer, length, buffer.length - length, null);
24733
+ const count = readSync3(fd, buffer, length, buffer.length - length, null);
23517
24734
  if (count === 0)
23518
24735
  break;
23519
24736
  length += count;
@@ -23525,7 +24742,7 @@ function configuredShellExclusions(env) {
23525
24742
  } catch {
23526
24743
  throw new Error("Cannot load Codex shell exclusions");
23527
24744
  } finally {
23528
- closeSync(fd);
24745
+ closeSync3(fd);
23529
24746
  }
23530
24747
  }
23531
24748
  return [...exclusions];
@@ -23695,7 +24912,7 @@ function codexCoordinatorSkillReadRoots(env = process.env, home = env.HOME?.trim
23695
24912
  grants.add(real);
23696
24913
  let entries;
23697
24914
  try {
23698
- entries = readdirSync3(real).filter((name) => !name.startsWith("."));
24915
+ entries = readdirSync4(real).filter((name) => !name.startsWith("."));
23699
24916
  } catch {
23700
24917
  continue;
23701
24918
  }
@@ -24108,7 +25325,7 @@ var APP_SERVER_CAPABILITIES = {
24108
25325
  };
24109
25326
 
24110
25327
  // ../../bridges/codex-bridge/src/engine/app-server-engine.ts
24111
- var log13 = createLogger("bridge.codex");
25328
+ var log14 = createLogger("bridge.codex");
24112
25329
  var AGENT_MAIL_TOOL_APPROVALS = Object.fromEntries([
24113
25330
  ...AGENT_MAIL_TOOL_NAMES,
24114
25331
  ...ARTIFACT_TOOL_NAMES,
@@ -24483,7 +25700,7 @@ async function readStoredLoginFingerprint(codexHome) {
24483
25700
  const apiKey = typeof root.OPENAI_API_KEY === "string" ? root.OPENAI_API_KEY : "";
24484
25701
  if (!refreshToken && !apiKey)
24485
25702
  return;
24486
- return createHash12("sha256").update(JSON.stringify([refreshToken, apiKey])).digest("hex");
25703
+ return createHash13("sha256").update(JSON.stringify([refreshToken, apiKey])).digest("hex");
24487
25704
  } catch {
24488
25705
  return;
24489
25706
  }
@@ -24612,6 +25829,7 @@ class AppServerEngine {
24612
25829
  onInvariantViolation: () => this.supervisor.recordUnknownServerRequest(),
24613
25830
  onUnknownRequest: () => this.supervisor.recordUnknownServerRequest(),
24614
25831
  ...options.approvalTimeoutMs === undefined ? {} : { approvalTimeoutMs: options.approvalTimeoutMs },
25832
+ ...options.interactionClock === undefined ? {} : { clock: options.interactionClock },
24615
25833
  presentApproval: (request) => this.approvalHandler?.(request) === true,
24616
25834
  onApprovalResolved: (request, decision, resolution) => this.approvalResolvedHandler?.(request, decision, resolution),
24617
25835
  presentInteraction: (request) => this.interactionHandler?.(request) === true,
@@ -24693,7 +25911,7 @@ class AppServerEngine {
24693
25911
  try {
24694
25912
  listener(event);
24695
25913
  } catch (error) {
24696
- log13.error("engine.listener-failed", { error: formatLogError(error) });
25914
+ log14.error("engine.listener-failed", { error: formatLogError(error) });
24697
25915
  }
24698
25916
  }
24699
25917
  }
@@ -24818,7 +26036,7 @@ class AppServerEngine {
24818
26036
  const sequence = ++this.accountCheckSequence;
24819
26037
  const generation = this.supervisor.getGeneration();
24820
26038
  this.supervisor.request("account/read", { refreshToken }).catch(signedOutAccountRead).then((response) => this.applyAccountRead(response, sequence, generation, accountReplaced)).catch((error) => {
24821
- log13.warn("account.sign-in-check-failed", {
26039
+ log14.warn("account.sign-in-check-failed", {
24822
26040
  error: formatLogError(error, { stack: false })
24823
26041
  });
24824
26042
  });
@@ -25405,7 +26623,7 @@ class AppServerEngine {
25405
26623
  const generation = this.supervisor.getGeneration();
25406
26624
  const response = await this.supervisor.request("account/read", { refreshToken: false }).catch(signedOutAccountRead);
25407
26625
  this.applyAccountRead(response, sequence, generation, false).catch((error) => {
25408
- log13.warn("account.connector-recovery-failed", {
26626
+ log14.warn("account.connector-recovery-failed", {
25409
26627
  error: formatLogError(error, { stack: false })
25410
26628
  });
25411
26629
  });
@@ -25618,7 +26836,7 @@ class AppServerEngine {
25618
26836
  await this.supervisor.request("thread/name/set", { threadId, name });
25619
26837
  return true;
25620
26838
  } catch (error) {
25621
- log13.warn("thread.rename-failed", { error: formatLogError(error, { stack: false }) });
26839
+ log14.warn("thread.rename-failed", { error: formatLogError(error, { stack: false }) });
25622
26840
  return false;
25623
26841
  }
25624
26842
  }
@@ -25638,7 +26856,7 @@ class AppServerEngine {
25638
26856
  } catch (error) {
25639
26857
  if (requireConfirmation)
25640
26858
  throw error;
25641
- log13.warn("thread.unsubscribe-failed", { error: formatLogError(error, { stack: false }) });
26859
+ log14.warn("thread.unsubscribe-failed", { error: formatLogError(error, { stack: false }) });
25642
26860
  }
25643
26861
  this.accountProofTurns.delete(threadId);
25644
26862
  this.rolloutPaths.delete(threadId);
@@ -26184,9 +27402,9 @@ function externalRevertCut(messages, survivingTurnIds, running) {
26184
27402
  }
26185
27403
 
26186
27404
  // ../../bridges/codex-bridge/src/app-server-runtime-sessions.ts
26187
- var log14 = createLogger("bridge.codex");
27405
+ var log15 = createLogger("bridge.codex");
26188
27406
  var SESSION_CLOSING_ERROR = "Session is closing";
26189
- var ACTIVITY_PROCESS = randomUUID8();
27407
+ var ACTIVITY_PROCESS = randomUUID9();
26190
27408
 
26191
27409
  class CodexRuntimeSessions {
26192
27410
  ctx;
@@ -26201,7 +27419,7 @@ class CodexRuntimeSessions {
26201
27419
  }
26202
27420
  createSession(body) {
26203
27421
  const clientSessionKey = typeof body.clientSessionKey === "string" && body.clientSessionKey.trim().length > 0 && body.clientSessionKey.length <= 512 ? body.clientSessionKey : undefined;
26204
- const sessionId = clientSessionKey ? `session-client-${createHash13("sha256").update(this.ctx.options.cwd).update("\x00").update(clientSessionKey).digest("hex").slice(0, 32)}` : createSessionId();
27422
+ const sessionId = clientSessionKey ? `session-client-${createHash14("sha256").update(this.ctx.options.cwd).update("\x00").update(clientSessionKey).digest("hex").slice(0, 32)}` : createSessionId();
26205
27423
  const existing = this.ctx.registry.getSession(sessionId);
26206
27424
  if (existing) {
26207
27425
  this.ctx.registry.touch(sessionId);
@@ -26339,7 +27557,7 @@ class CodexRuntimeSessions {
26339
27557
  try {
26340
27558
  fork = await this.ctx.options.engine.forkThread(parent.threadId, parent.config, lastTurnId);
26341
27559
  } catch (error) {
26342
- log14.warn("thread.fork-failed", {
27560
+ log15.warn("thread.fork-failed", {
26343
27561
  threadId: parent.threadId,
26344
27562
  error: formatLogError(error, { stack: false })
26345
27563
  });
@@ -26391,7 +27609,7 @@ class CodexRuntimeSessions {
26391
27609
  await this.ctx.callbacks.deleteSession(child.id).catch(() => {
26392
27610
  return;
26393
27611
  });
26394
- log14.warn("thread.fork-hydrate-failed", {
27612
+ log15.warn("thread.fork-hydrate-failed", {
26395
27613
  threadId: parent.threadId,
26396
27614
  error: formatLogError(error, { stack: false })
26397
27615
  });
@@ -26406,7 +27624,7 @@ class CodexRuntimeSessions {
26406
27624
  });
26407
27625
  turns = thread?.turns;
26408
27626
  } catch (error) {
26409
- log14.warn("thread.turns-read-failed", {
27627
+ log15.warn("thread.turns-read-failed", {
26410
27628
  threadId: context.threadId,
26411
27629
  error: formatLogError(error, { stack: false })
26412
27630
  });
@@ -26523,7 +27741,7 @@ class CodexRuntimeSessions {
26523
27741
  return "not-found";
26524
27742
  if (this.sessionAdmissionClosed(session))
26525
27743
  return "closing";
26526
- const inputDigest = createHash13("sha256").update(input).digest("hex");
27744
+ const inputDigest = createHash14("sha256").update(input).digest("hex");
26527
27745
  const previous = this.ctx.steerRequests.get(requestId);
26528
27746
  if (previous) {
26529
27747
  if (previous.threadId !== session.threadId || previous.turnId !== expectedTurnId || previous.inputDigest !== inputDigest) {
@@ -26898,7 +28116,7 @@ class CodexRuntimeSessions {
26898
28116
  try {
26899
28117
  turns = (await this.ctx.options.engine.readThread(context.threadId, { includeTurns: true }))?.turns;
26900
28118
  } catch (error) {
26901
- log14.warn("thread.turns-read-after-revert-failed", {
28119
+ log15.warn("thread.turns-read-after-revert-failed", {
26902
28120
  threadId: context.threadId,
26903
28121
  error: formatLogError(error, { stack: false })
26904
28122
  });
@@ -26999,7 +28217,7 @@ class CodexRuntimeSessions {
26999
28217
  }
27000
28218
  } catch (error) {
27001
28219
  await restoreEngineConfig();
27002
- log14.warn("session.config-apply-failed", {
28220
+ log15.warn("session.config-apply-failed", {
27003
28221
  sessionId,
27004
28222
  error: formatLogError(error, { stack: false })
27005
28223
  });
@@ -27042,7 +28260,7 @@ class CodexRuntimeSessions {
27042
28260
  try {
27043
28261
  context = await this.ctx.callbacks.ensureAttached(sessionId);
27044
28262
  } catch (error) {
27045
- log14.warn("transcript.serving-last-known", {
28263
+ log15.warn("transcript.serving-last-known", {
27046
28264
  sessionId,
27047
28265
  error: formatLogError(error, { stack: false })
27048
28266
  });
@@ -27245,7 +28463,7 @@ class CodexRuntimeSessions {
27245
28463
  }
27246
28464
  return "unpublished";
27247
28465
  }
27248
- log14.warn("registry.persist-failed", { error: formatLogError(error, { stack: false }) });
28466
+ log15.warn("registry.persist-failed", { error: formatLogError(error, { stack: false }) });
27249
28467
  }
27250
28468
  if (this.ctx.registry.getSession(sessionId) !== session)
27251
28469
  return "released";
@@ -27339,7 +28557,7 @@ class CodexRuntimeSessions {
27339
28557
  }
27340
28558
  }
27341
28559
  // ../../bridges/codex-bridge/src/app-server-runtime-approvals.ts
27342
- var log15 = createLogger("bridge.codex");
28560
+ var log16 = createLogger("bridge.codex");
27343
28561
 
27344
28562
  class CodexRuntimeApprovals {
27345
28563
  ctx;
@@ -27430,7 +28648,7 @@ class CodexRuntimeApprovals {
27430
28648
  if (this.ctx.options.engine.resolveApproval(approvalId, decision)) {
27431
28649
  if (decision === "cancel") {
27432
28650
  this.ctx.callbacks.abort(sessionId).catch((error) => {
27433
- log15.error("approval.cancel-failed", { error: formatLogError(error) });
28651
+ log16.error("approval.cancel-failed", { error: formatLogError(error) });
27434
28652
  });
27435
28653
  }
27436
28654
  return "applied";
@@ -27551,7 +28769,7 @@ function parseCommandToken(text, sigils = ["/"]) {
27551
28769
  }
27552
28770
 
27553
28771
  // ../../bridges/codex-bridge/src/prompts/template-discovery.ts
27554
- import { createHash as createHash14 } from "node:crypto";
28772
+ import { createHash as createHash15 } from "node:crypto";
27555
28773
  import { open as open10, readdir as readdir3, stat as stat8 } from "node:fs/promises";
27556
28774
  import { join as join21 } from "node:path";
27557
28775
  var TEMPLATE_LIMITS = Object.freeze({
@@ -27584,7 +28802,7 @@ function templateBindingRevision(origin, relativePath) {
27584
28802
  return commandBindingRevision(["template", origin, relativePath]);
27585
28803
  }
27586
28804
  function fingerprintOf(bytes) {
27587
- return createHash14("sha256").update(bytes).digest("hex").slice(0, 32);
28805
+ return createHash15("sha256").update(bytes).digest("hex").slice(0, 32);
27588
28806
  }
27589
28807
  function nameFromRelativePath(relativePath) {
27590
28808
  return `/${relativePath.replace(/\.md$/i, "")}`;
@@ -27598,7 +28816,7 @@ function isReservedName(name) {
27598
28816
  }
27599
28817
  var metadataCache = new Map;
27600
28818
  var METADATA_CACHE_MAX = 1024;
27601
- async function readBounded2(absolutePath, maxBytes) {
28819
+ async function readBounded3(absolutePath, maxBytes) {
27602
28820
  const handle = await open10(absolutePath, "r");
27603
28821
  try {
27604
28822
  const info = await handle.stat();
@@ -27741,7 +28959,7 @@ async function scanPromptTemplates(roots, limits = TEMPLATE_LIMITS) {
27741
28959
  if (candidate.size > limits.maxTemplateBytes)
27742
28960
  return null;
27743
28961
  try {
27744
- const { bytes, oversized } = await readBounded2(candidate.absolutePath, limits.maxTemplateBytes);
28962
+ const { bytes, oversized } = await readBounded3(candidate.absolutePath, limits.maxTemplateBytes);
27745
28963
  if (oversized)
27746
28964
  return null;
27747
28965
  if (bytes.length === 0)
@@ -27818,7 +29036,7 @@ async function loadTemplateBody(entry, limits = TEMPLATE_LIMITS) {
27818
29036
  }
27819
29037
  let loaded;
27820
29038
  try {
27821
- loaded = await readBounded2(entry.absolutePath, limits.maxTemplateBytes);
29039
+ loaded = await readBounded3(entry.absolutePath, limits.maxTemplateBytes);
27822
29040
  } catch {
27823
29041
  return {
27824
29042
  ok: false,
@@ -27863,7 +29081,7 @@ var SCOPE_ORIGINS = {
27863
29081
  system: "system",
27864
29082
  admin: "admin"
27865
29083
  };
27866
- function isRecord11(value) {
29084
+ function isRecord12(value) {
27867
29085
  return !!value && typeof value === "object" && !Array.isArray(value);
27868
29086
  }
27869
29087
  function nonEmpty(value) {
@@ -27879,12 +29097,12 @@ function usableSkillName(name) {
27879
29097
  return !/\s/.test(name) && utf8ByteLength(`${SKILL_ALIAS_PREFIX}${name}`) <= 255;
27880
29098
  }
27881
29099
  function normalizeSkillsList(raw, context) {
27882
- const data = isRecord11(raw) && Array.isArray(raw.data) ? raw.data : [];
29100
+ const data = isRecord12(raw) && Array.isArray(raw.data) ? raw.data : [];
27883
29101
  const byPath = new Map;
27884
- let partial = !isRecord11(raw) || !Array.isArray(raw.data);
29102
+ let partial = !isRecord12(raw) || !Array.isArray(raw.data);
27885
29103
  let truncated = false;
27886
29104
  for (const entry of data) {
27887
- if (!isRecord11(entry)) {
29105
+ if (!isRecord12(entry)) {
27888
29106
  partial = true;
27889
29107
  continue;
27890
29108
  }
@@ -27892,7 +29110,7 @@ function normalizeSkillsList(raw, context) {
27892
29110
  partial = true;
27893
29111
  const skills = Array.isArray(entry.skills) ? entry.skills : [];
27894
29112
  for (const candidate of skills) {
27895
- if (!isRecord11(candidate)) {
29113
+ if (!isRecord12(candidate)) {
27896
29114
  truncated = true;
27897
29115
  continue;
27898
29116
  }
@@ -27910,7 +29128,7 @@ function normalizeSkillsList(raw, context) {
27910
29128
  }
27911
29129
  const scope = typeof candidate.scope === "string" && candidate.scope in SCOPE_ORIGINS ? candidate.scope : "unknown";
27912
29130
  const pluginId = nonEmpty(candidate.pluginId) ?? null;
27913
- const skillInterface = isRecord11(candidate.interface) ? candidate.interface : {};
29131
+ const skillInterface = isRecord12(candidate.interface) ? candidate.interface : {};
27914
29132
  const description = nonEmpty(skillInterface.shortDescription) ?? nonEmpty(candidate.shortDescription) ?? nonEmpty(candidate.description);
27915
29133
  byPath.set(path, {
27916
29134
  id: skillCommandId(path),
@@ -28837,7 +30055,7 @@ class UpdateCoalescer {
28837
30055
 
28838
30056
  // ../../bridges/codex-bridge/src/app-server-runtime-capacity-retry.ts
28839
30057
  import { stat as stat9 } from "node:fs/promises";
28840
- var log16 = createLogger("bridge.codex");
30058
+ var log17 = createLogger("bridge.codex");
28841
30059
 
28842
30060
  class CodexCapacityRetry {
28843
30061
  ctx;
@@ -28951,7 +30169,7 @@ class CodexCapacityRetry {
28951
30169
  }
28952
30170
  entry.stage = "starting";
28953
30171
  const work = this.startContinuation(context, turn, entry).catch((error) => {
28954
- log16.error("turn.capacity-retry-failed", {
30172
+ log17.error("turn.capacity-retry-failed", {
28955
30173
  turnId: turn.turnId,
28956
30174
  error: formatLogError(error, { stack: false })
28957
30175
  });
@@ -29023,7 +30241,7 @@ class CodexCapacityRetry {
29023
30241
  });
29024
30242
  return;
29025
30243
  }
29026
- await this.ctx.journal.markAccepted(requestId, { threadId: context.threadId, turnId: started.turnId }).catch((error) => log16.warn("turn.capacity-retry-journal-failed", {
30244
+ await this.ctx.journal.markAccepted(requestId, { threadId: context.threadId, turnId: started.turnId }).catch((error) => log17.warn("turn.capacity-retry-journal-failed", {
29027
30245
  requestId,
29028
30246
  error: formatLogError(error, { stack: false })
29029
30247
  }));
@@ -29094,7 +30312,7 @@ class CodexCapacityRetry {
29094
30312
  }
29095
30313
 
29096
30314
  // ../../bridges/codex-bridge/src/app-server-runtime-lifecycle.ts
29097
- var log17 = createLogger("bridge.codex");
30315
+ var log18 = createLogger("bridge.codex");
29098
30316
  function artifactConnectionToken(value) {
29099
30317
  if (!value || typeof value !== "object" || Array.isArray(value))
29100
30318
  return;
@@ -29279,7 +30497,7 @@ class CodexRuntimeLifecycle {
29279
30497
  this.ctx.registry.setPhase(existing, "recovering");
29280
30498
  this.emitStatus(existing);
29281
30499
  this.ctx.callbacks.scheduleRecoveryBackstop(existing);
29282
- log17.warn("dispatch.restore-failed", {
30500
+ log18.warn("dispatch.restore-failed", {
29283
30501
  requestId: record.requestId,
29284
30502
  error: formatLogError(error, { stack: false })
29285
30503
  });
@@ -29379,6 +30597,7 @@ class CodexRuntimeLifecycle {
29379
30597
  if (!state)
29380
30598
  return;
29381
30599
  state.coalescer.stop();
30600
+ cancelSubagentProbe(state);
29382
30601
  state.orderedEvents.length = 0;
29383
30602
  state.orderedEventBytes = 0;
29384
30603
  state.orderedReconcilePending = false;
@@ -29458,7 +30677,7 @@ class CodexRuntimeLifecycle {
29458
30677
  });
29459
30678
  }));
29460
30679
  }
29461
- log17.warn("thread.reattach-failed", {
30680
+ log18.warn("thread.reattach-failed", {
29462
30681
  threadId,
29463
30682
  rolloutMissing: isMissingRolloutError(error),
29464
30683
  error: formatLogError(error, { stack: false })
@@ -29539,7 +30758,7 @@ class CodexRuntimeLifecycle {
29539
30758
  coalescer: new UpdateCoalescer({
29540
30759
  intervalMs: this.ctx.options.coalesceIntervalMs ?? (() => messageSnapshotIntervalMs(this.ctx.threadState.get(threadId)?.lastPublishedSnapshotChars ?? 0)),
29541
30760
  publish: () => this.ctx.callbacks.publishAssistantMessage(threadId),
29542
- onError: (error) => log17.error("message.publish-failed", { error: formatLogError(error) })
30761
+ onError: (error) => log18.error("message.publish-failed", { error: formatLogError(error) })
29543
30762
  })
29544
30763
  };
29545
30764
  this.ctx.threadState.set(threadId, state);
@@ -29575,7 +30794,7 @@ class CodexRuntimeLifecycle {
29575
30794
  this.ctx.commandCatalogue.withdrawGeneration(event.generation);
29576
30795
  const recovery = this.ctx.generationRecovery.then(() => this.ctx.callbacks.recoverAfterGenerationChange(event.generation));
29577
30796
  this.ctx.generationRecovery = recovery.catch((error) => {
29578
- log17.error("generation.recovery-failed", { error: formatLogError(error) });
30797
+ log18.error("generation.recovery-failed", { error: formatLogError(error) });
29579
30798
  });
29580
30799
  return;
29581
30800
  }
@@ -29595,7 +30814,7 @@ class CodexRuntimeLifecycle {
29595
30814
  }
29596
30815
  if (event.kind === "account.reload.requested") {
29597
30816
  this.ctx.callbacks.reloadStoredAccountLogin().catch((error) => {
29598
- log17.warn("account.login-reload-failed", { error: formatLogError(error, { stack: false }) });
30817
+ log18.warn("account.login-reload-failed", { error: formatLogError(error, { stack: false }) });
29599
30818
  });
29600
30819
  return;
29601
30820
  }
@@ -29898,7 +31117,7 @@ class CodexRuntimeLifecycle {
29898
31117
  }
29899
31118
  this.ctx.options.changeEvidence?.turn(this.evidenceSource(context, turn), event.status);
29900
31119
  const finalize = () => this.runFinalization(context, turn).catch((error) => {
29901
- log17.error("turn.finalize-failed", {
31120
+ log18.error("turn.finalize-failed", {
29902
31121
  turnId: turn.turnId,
29903
31122
  error: formatLogError(error, { stack: false })
29904
31123
  });
@@ -30116,7 +31335,7 @@ class CodexRuntimeLifecycle {
30116
31335
  }
30117
31336
  trackCommandChangeWork(work) {
30118
31337
  const tracked = work.catch((error) => {
30119
- log17.warn("command-changes.record-failed", { error: formatLogError(error, { stack: false }) });
31338
+ log18.warn("command-changes.record-failed", { error: formatLogError(error, { stack: false }) });
30120
31339
  });
30121
31340
  this.ctx.pendingCommandChanges.add(tracked);
30122
31341
  tracked.finally(() => this.ctx.pendingCommandChanges.delete(tracked));
@@ -30560,7 +31779,7 @@ class CodexRuntimeLifecycle {
30560
31779
  try {
30561
31780
  await state.coalescer.flushNow();
30562
31781
  } catch (error) {
30563
- log17.error("ordered-events.flush-failed", { error: formatLogError(error) });
31782
+ log18.error("ordered-events.flush-failed", { error: formatLogError(error) });
30564
31783
  }
30565
31784
  state.orderedReconcilePending = false;
30566
31785
  for (const sessionId of this.ctx.sessionIdsForThread(threadId)) {
@@ -30579,7 +31798,7 @@ class CodexRuntimeLifecycle {
30579
31798
  await state.coalescer.flushNow();
30580
31799
  event.publish();
30581
31800
  } catch (error) {
30582
- log17.error("ordered-events.publish-failed", { error: formatLogError(error) });
31801
+ log18.error("ordered-events.publish-failed", { error: formatLogError(error) });
30583
31802
  state.orderedEvents.length = 0;
30584
31803
  state.orderedEventBytes = 0;
30585
31804
  state.orderedReconcilePending = true;
@@ -30588,7 +31807,7 @@ class CodexRuntimeLifecycle {
30588
31807
  }
30589
31808
  }
30590
31809
  } catch (error) {
30591
- log17.error("ordered-events.reconcile-failed", { error: formatLogError(error) });
31810
+ log18.error("ordered-events.reconcile-failed", { error: formatLogError(error) });
30592
31811
  } finally {
30593
31812
  state.orderedEventDraining = false;
30594
31813
  if ((state.orderedReconcilePending || state.orderedEvents.length > 0) && this.ctx.threadState.get(threadId) === state) {
@@ -30605,8 +31824,10 @@ class CodexRuntimeLifecycle {
30605
31824
  const turn = context.activeTurn;
30606
31825
  if (!turn)
30607
31826
  return;
31827
+ const probeIntervalMs = this.ctx.options.subagentProbeIntervalMs ?? SUBAGENT_TRANSCRIPT_PROBE_INTERVAL_MS;
30608
31828
  await publishAssistantRows(context, state, turn, {
30609
31829
  cwd: context.cwd ?? this.ctx.options.cwd,
31830
+ subagentProbeIntervalMs: probeIntervalMs,
30610
31831
  emit: (event) => this.ctx.options.emit(event),
30611
31832
  bumpMessageRevision: (target, revised) => this.ctx.callbacks.bumpMessageRevision(target, revised),
30612
31833
  onRendered: (message) => {
@@ -30619,6 +31840,10 @@ class CodexRuntimeLifecycle {
30619
31840
  }
30620
31841
  }
30621
31842
  });
31843
+ scheduleSubagentProbe(state, turn, probeIntervalMs, () => {
31844
+ if (this.ctx.threadState.get(threadId) === state)
31845
+ state.coalescer.schedule(this.ctx.now());
31846
+ });
30622
31847
  }
30623
31848
  emitStatus(context) {
30624
31849
  this.ctx.callbacks.notifyThreadActivity();
@@ -30704,7 +31929,7 @@ function isTabInitialPromptRequestId(requestId) {
30704
31929
  }
30705
31930
 
30706
31931
  // ../../bridges/codex-bridge/src/app-server-runtime-prompt.ts
30707
- var log18 = createLogger("bridge.codex");
31932
+ var log19 = createLogger("bridge.codex");
30708
31933
  function commandRefusal(message) {
30709
31934
  return { ok: false, status: 422, error: message, kind: "command-unavailable" };
30710
31935
  }
@@ -31366,7 +32591,7 @@ class CodexRuntimePrompt {
31366
32591
  try {
31367
32592
  outcome = await this.ctx.options.engine.reconcileRequest(context.threadId, accumulator.providerRequestId);
31368
32593
  } catch (error) {
31369
- log18.warn("dispatch.reconcile-failed", {
32594
+ log19.warn("dispatch.reconcile-failed", {
31370
32595
  requestId,
31371
32596
  threadId: context.threadId,
31372
32597
  error: formatLogError(error, { stack: false })
@@ -31641,7 +32866,7 @@ class CodexRuntimePrompt {
31641
32866
  if (this.ctx.stopping || this.shouldAbandonDrain(expectedGeneration))
31642
32867
  return;
31643
32868
  if (Date.now() >= deadline) {
31644
- log18.warn("app-server.drain-expired");
32869
+ log19.warn("app-server.drain-expired");
31645
32870
  return;
31646
32871
  }
31647
32872
  await this.waitForThreadActivity();
@@ -31675,7 +32900,7 @@ class CodexRuntimePrompt {
31675
32900
 
31676
32901
  // ../../bridges/codex-bridge/src/app-server-runtime-tail.ts
31677
32902
  import { join as join22, relative as relative4, isAbsolute as isAbsolute11 } from "node:path";
31678
- var log19 = createLogger("bridge.codex");
32903
+ var log20 = createLogger("bridge.codex");
31679
32904
 
31680
32905
  class CodexRuntimeTail {
31681
32906
  ctx;
@@ -31824,7 +33049,7 @@ class CodexRuntimeTail {
31824
33049
  };
31825
33050
  }
31826
33051
  } catch (error) {
31827
- log19.warn("models.list-failed", { error: formatLogError(error, { stack: false }) });
33052
+ log20.warn("models.list-failed", { error: formatLogError(error, { stack: false }) });
31828
33053
  }
31829
33054
  return this.ctx.options.loadCachedModels();
31830
33055
  }
@@ -31850,7 +33075,7 @@ class CodexRuntimeTail {
31850
33075
  });
31851
33076
  }
31852
33077
  } catch (error) {
31853
- log19.warn("threads.list-failed", { error: formatLogError(error, { stack: false }) });
33078
+ log20.warn("threads.list-failed", { error: formatLogError(error, { stack: false }) });
31854
33079
  }
31855
33080
  const archived = new Set;
31856
33081
  try {
@@ -31935,7 +33160,7 @@ class CodexRuntimeTail {
31935
33160
  else
31936
33161
  await this.ctx.options.engine.unarchiveThread(threadId);
31937
33162
  } catch (error) {
31938
- log19.warn("thread.archive-failed", {
33163
+ log20.warn("thread.archive-failed", {
31939
33164
  archived,
31940
33165
  error: formatLogError(error, { stack: false })
31941
33166
  });
@@ -32581,9 +33806,9 @@ function installFatalRejectionGuard(options) {
32581
33806
  }
32582
33807
 
32583
33808
  // ../protocol/src/node/process-failure-log.ts
32584
- var log20 = createLogger("process");
33809
+ var log21 = createLogger("process");
32585
33810
  function logUnhandledRejection(reason) {
32586
- log20.throttled("error", "rejection.unhandled", {
33811
+ log21.throttled("error", "rejection.unhandled", {
32587
33812
  error: reason,
32588
33813
  fields: () => ({ error: formatLogError(reason, { message: false }) })
32589
33814
  });
@@ -32608,7 +33833,7 @@ var CODEX_FALLBACK_MODEL_CATALOG = [
32608
33833
  ];
32609
33834
 
32610
33835
  // ../../bridges/codex-bridge/src/models-cache.ts
32611
- var log21 = createLogger("bridge.codex");
33836
+ var log22 = createLogger("bridge.codex");
32612
33837
  var MODEL_REASONING_EFFORTS = new Set([
32613
33838
  "minimal",
32614
33839
  "low",
@@ -32755,13 +33980,13 @@ class ModelCatalogCache {
32755
33980
  await this.opts.writePersistedCache(models);
32756
33981
  }
32757
33982
  } catch (error) {
32758
- log21.warn("models.refresh-failed", { error: formatLogError(error, { stack: false }) });
33983
+ log22.warn("models.refresh-failed", { error: formatLogError(error, { stack: false }) });
32759
33984
  }
32760
33985
  }
32761
33986
  }
32762
33987
 
32763
33988
  // ../../bridges/codex-bridge/src/index.ts
32764
- var log22 = createLogger("bridge.codex");
33989
+ var log23 = createLogger("bridge.codex");
32765
33990
  configureBridgeLogger();
32766
33991
  var WORKFLOW_RESULT_TOOL_NAMES2 = new Set(WORKFLOW_RESULT_KINDS.map(workflowResultToolName));
32767
33992
  function isWorkflowResultTool(value) {
@@ -32791,14 +34016,14 @@ function isScopedAgentMcp(value) {
32791
34016
  var app = new Hono2;
32792
34017
  app.onError((error, c) => {
32793
34018
  if (error instanceof PolicyWideningRefusedError) {
32794
- log22.warn("session.policy-widening-refused", { widened: error.widened.join(",") });
34019
+ log23.warn("session.policy-widening-refused", { widened: error.widened.join(",") });
32795
34020
  return c.json(error.refusal(), 403);
32796
34021
  }
32797
34022
  if ("getResponse" in error) {
32798
34023
  const response = error.getResponse();
32799
34024
  return c.newResponse(response.body, response);
32800
34025
  }
32801
- log22.error("http.request-failed", {
34026
+ log23.error("http.request-failed", {
32802
34027
  method: c.req.method,
32803
34028
  path: c.req.path,
32804
34029
  error: formatLogError(error)
@@ -32816,7 +34041,7 @@ var bridgeCredential = loadBridgeCredential(BRIDGE_TOKEN_ENV);
32816
34041
  var bridgeAuthEnabledOverrideForTesting = null;
32817
34042
  var sseRouteTestHooks = null;
32818
34043
  var BRIDGE_VERSION = "1.0.0";
32819
- var execFile4 = promisify2(execFileCallback2);
34044
+ var execFile3 = promisify2(execFileCallback2);
32820
34045
  var subscribers = new Set;
32821
34046
  var observers = new Set;
32822
34047
  function observationFrameData(sessionId) {
@@ -32826,10 +34051,10 @@ function notifyObservers(event, revision) {
32826
34051
  for (const observer of observers) {
32827
34052
  try {
32828
34053
  Promise.resolve(observer(event, revision, "{}")).catch((error) => {
32829
- log22.warn("sse.observer-failed", { error: formatLogError(error) });
34054
+ log23.warn("sse.observer-failed", { error: formatLogError(error) });
32830
34055
  });
32831
34056
  } catch (error) {
32832
- log22.warn("sse.observer-failed", { error: formatLogError(error) });
34057
+ log23.warn("sse.observer-failed", { error: formatLogError(error) });
32833
34058
  }
32834
34059
  }
32835
34060
  }
@@ -32937,12 +34162,12 @@ function createShutdownHandler(timer, clearTimer = clearInterval, exit = (code)
32937
34162
  shuttingDown = true;
32938
34163
  clearTimer(timer);
32939
34164
  stopEngine().catch((error) => {
32940
- log22.warn("engine.stop-failed", { error: formatLogError(error) });
34165
+ log23.warn("engine.stop-failed", { error: formatLogError(error) });
32941
34166
  }).finally(() => exit(0));
32942
34167
  };
32943
34168
  }
32944
34169
  function createParentExitHandler(interrupt, shutdown, report = (turns, ms) => {
32945
- log22.info("turns.stopped", { turns, elapsedMs: ms });
34170
+ log23.info("turns.stopped", { turns, elapsedMs: ms });
32946
34171
  }) {
32947
34172
  return async () => {
32948
34173
  const detectedAt = performance.now();
@@ -32973,7 +34198,7 @@ function serializeSseEventData(event) {
32973
34198
  ...event.data
32974
34199
  });
32975
34200
  } catch {
32976
- log22.error("sse.payload-serialize-failed");
34201
+ log23.error("sse.payload-serialize-failed");
32977
34202
  return JSON.stringify({
32978
34203
  sessionId: event.sessionId,
32979
34204
  error: "payload could not be serialized"
@@ -33038,7 +34263,7 @@ function emit(event) {
33038
34263
  messageId = retainedMessageId(event.type, payload);
33039
34264
  bytes = eager === null ? estimateSsePayloadBytes(payload) : Buffer.byteLength(eager, "utf8");
33040
34265
  } catch {
33041
- log22.error("sse.payload-snapshot-failed");
34266
+ log23.error("sse.payload-snapshot-failed");
33042
34267
  payload = { error: "payload could not be serialized" };
33043
34268
  eager = subscribers.size > 0 ? serializeSseEventData({ sessionId, data: payload }) : null;
33044
34269
  messageId = undefined;
@@ -33055,10 +34280,10 @@ function emit(event) {
33055
34280
  for (const subscriber of subscribers) {
33056
34281
  try {
33057
34282
  Promise.resolve(subscriber(event, revision, eager ?? "{}")).catch((error) => {
33058
- log22.warn("sse.subscriber-failed", { error: formatLogError(error) });
34283
+ log23.warn("sse.subscriber-failed", { error: formatLogError(error) });
33059
34284
  });
33060
34285
  } catch (error) {
33061
- log22.warn("sse.subscriber-failed", { error: formatLogError(error) });
34286
+ log23.warn("sse.subscriber-failed", { error: formatLogError(error) });
33062
34287
  }
33063
34288
  }
33064
34289
  }
@@ -33085,7 +34310,7 @@ async function writePersistedBridgeCache(models) {
33085
34310
  await mkdir9(bridgeCacheDir(), { recursive: true });
33086
34311
  await writeFile6(bridgeCachePath(), JSON.stringify({ version: BRIDGE_MODEL_CACHE_VERSION, at: Date.now(), models }, null, 2));
33087
34312
  } catch (error) {
33088
- log22.warn("models.cache-persist-failed", { error: formatLogError(error, { stack: false }) });
34313
+ log23.warn("models.cache-persist-failed", { error: formatLogError(error, { stack: false }) });
33089
34314
  }
33090
34315
  }
33091
34316
  async function readCodexCliModelCache() {
@@ -33097,7 +34322,7 @@ async function readCodexCliModelCache() {
33097
34322
  return null;
33098
34323
  }
33099
34324
  }
33100
- async function fetchLiveModelsFromCli(run = execFile4, env = process.env) {
34325
+ async function fetchLiveModelsFromCli(run = execFile3, env = process.env) {
33101
34326
  const codexPath = env.CODEX_PATH || "codex";
33102
34327
  try {
33103
34328
  const { stdout } = await run(codexPath, ["debug", "models"], {
@@ -33107,7 +34332,7 @@ async function fetchLiveModelsFromCli(run = execFile4, env = process.env) {
33107
34332
  const models = parseModelCatalog(stdout);
33108
34333
  return models.length > 0 ? models : null;
33109
34334
  } catch (error) {
33110
- log22.warn("models.debug-read-failed", { error: formatLogError(error, { stack: false }) });
34335
+ log23.warn("models.debug-read-failed", { error: formatLogError(error, { stack: false }) });
33111
34336
  return null;
33112
34337
  }
33113
34338
  }
@@ -33152,7 +34377,7 @@ async function sweepIdleThreads(runtime = appServerRuntime) {
33152
34377
  try {
33153
34378
  await runtime.sweepIdle();
33154
34379
  } catch (error) {
33155
- log22.warn("idle-sweep.failed", { error: formatLogError(error) });
34380
+ log23.warn("idle-sweep.failed", { error: formatLogError(error) });
33156
34381
  }
33157
34382
  }
33158
34383
  function createCodexProcessDiagnostics(runtime = appServerRuntime) {
@@ -33188,9 +34413,9 @@ async function startSelectedEngine(env = process.env, runtime = appServerRuntime
33188
34413
  }
33189
34414
  try {
33190
34415
  await runtime.start();
33191
- log22.info("engine.ready", { codexVersion: runtime.getHealth().codexVersion ?? "unknown" });
34416
+ log23.info("engine.ready", { codexVersion: runtime.getHealth().codexVersion ?? "unknown" });
33192
34417
  } catch (error) {
33193
- log22.error("engine.start-failed", { error: formatLogError(error, { stack: false }) });
34418
+ log23.error("engine.start-failed", { error: formatLogError(error, { stack: false }) });
33194
34419
  }
33195
34420
  }
33196
34421
  var __testing = {
@@ -33273,7 +34498,7 @@ function startSseKeepalive(writeSSE, intervalMs = 5000, shouldSendAtActiveCadenc
33273
34498
  id: String(eventRing.latestRevision),
33274
34499
  data: "{}"
33275
34500
  }).catch((error) => {
33276
- log22.warn("sse.keepalive-failed", { error: formatLogError(error, { stack: false }) });
34501
+ log23.warn("sse.keepalive-failed", { error: formatLogError(error, { stack: false }) });
33277
34502
  });
33278
34503
  }, intervalMs);
33279
34504
  }
@@ -33339,6 +34564,12 @@ app.use("*", async (c, next) => {
33339
34564
  if (!tokenMatches(dedicatedHeaderToken) && !tokenMatches(headerToken) && !tokenMatches(eventToken)) {
33340
34565
  return c.json({ error: "Unauthorized" }, 401);
33341
34566
  }
34567
+ const admission = await admitFetchBridgeRequest(bridgeCredential.authority, c.req.raw);
34568
+ if ("refusal" in admission) {
34569
+ return c.json(admission.refusal.body, admission.refusal.status);
34570
+ }
34571
+ if (admission.request)
34572
+ c.req.raw = admission.request;
33342
34573
  }
33343
34574
  await next();
33344
34575
  });
@@ -33529,7 +34760,7 @@ app.get("/session/:id/usage", async (c) => {
33529
34760
  return c.json({ error: "Session not found" }, 404);
33530
34761
  return c.json({ contextUsage });
33531
34762
  } catch (error) {
33532
- log22.warn("account.usage-read-failed", { error: formatLogError(error, { stack: false }) });
34763
+ log23.warn("account.usage-read-failed", { error: formatLogError(error, { stack: false }) });
33533
34764
  return c.json({ error: "Account usage is temporarily unavailable" }, 503);
33534
34765
  }
33535
34766
  });
@@ -33940,7 +35171,7 @@ app.get("/event/subscribe", (c) => {
33940
35171
  if (!open)
33941
35172
  return;
33942
35173
  open = false;
33943
- log22.info("sse.closed", { reason });
35174
+ log23.info("sse.closed", { reason });
33944
35175
  resolveConnectionClosed();
33945
35176
  };
33946
35177
  const writeWhileOpen = createSerializedSseWriter(createOpenSseWriter(() => open, (event) => stream.writeSSE(event)), { onOverflow: () => failSlowSubscriber("write backlog exceeded its cap") });
@@ -34088,7 +35319,7 @@ if (parentPid !== null) {
34088
35319
  startParentWatchdog({
34089
35320
  parentPid,
34090
35321
  onParentExit: () => {
34091
- log22.warn("parent.gone", { parentPid });
35322
+ log23.warn("parent.gone", { parentPid });
34092
35323
  createParentExitHandler((budgetMs) => appServerRuntime.interruptForParentExit(budgetMs), shutdownHandler)();
34093
35324
  }
34094
35325
  });