orkestrator 2.36.3-beta → 2.36.5-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.
@@ -76,6 +76,12 @@ var BACKEND_LOG_AREAS = defineLogAreas({
76
76
  "startup.looped-review-pending": "Cleanup of the retired Looped Review stays pending.",
77
77
  "notice.failed": "A background notice after a turn or prompt failed; `step` says which.",
78
78
  "artifacts.live-unavailable": "Live interactive artifacts are unavailable.",
79
+ "previous-run": {
80
+ description: "This start read how the previous run ended: `outcome` is `clean` when it reached the end of shutdown and `crashed` when it did not, `ranForMs` its length and `lastSeenAgoMs` the time since its last health row.",
81
+ essential: true,
82
+ fields: { outcome: "label", ranForMs: "number", lastSeenAgoMs: "number" }
83
+ },
84
+ "health.write-failed": "A health summary row could not be written or read; the next sample retries.",
79
85
  "shutdown.step-failed": "One part of shutdown failed and the rest went on; `step` says which.",
80
86
  "shutdown.signal-received": {
81
87
  description: "A signal started shutdown, which tells a clean quit from the backend being killed.",
@@ -119,7 +125,8 @@ var BRIDGE_LOG_AREAS = defineLogAreas({
119
125
  description: "What every long-lived bridge does the same way: its sweep and its shutdown.",
120
126
  events: {
121
127
  "idle-sweep.failed": "An idle sweep threw; the next tick retries.",
122
- "shutdown.failed": "Releasing the bridge failed during shutdown; it still exits."
128
+ "shutdown.failed": "Releasing the bridge failed during shutdown; it still exits.",
129
+ "credential.not-hardened": "The bridge could not mark itself non-dumpable, so a same-uid process can read its memory; `reason` says why."
123
130
  }
124
131
  },
125
132
  "bridge.acp": {
@@ -253,7 +260,6 @@ var BRIDGE_LOG_AREAS = defineLogAreas({
253
260
  "parent.gone": "The backend that launched this bridge has gone; stopping turns and shutting down.",
254
261
  "queue.overflow": "The notification queue passed a bound and dropped its backlog.",
255
262
  "queue.task-failed": "A task on a per-thread queue failed.",
256
- "raw-log.write-failed": "Appending to the raw Codex log failed.",
257
263
  "recorder.notice": "The notification recorder needs attention: it is on, or was asked for without its confirmation.",
258
264
  "recorder.threw": "The notification recorder threw.",
259
265
  "recorder.write-failed": "Writing a notification recording failed; its lines were dropped.",
@@ -459,6 +465,7 @@ var ENVIRONMENT_LOG_AREAS = defineLogAreas({
459
465
  environment: {
460
466
  description: "Environment naming, setup, status, moves, deletion and cleanup afterwards.",
461
467
  events: {
468
+ "cleanup.sessions-failed": "Session metadata cleanup failed during environment deletion; deletion continues.",
462
469
  "cleanup.branch-kept": "A deleted environment's local branch was kept, as it may hold unmerged work.",
463
470
  "rename.failed": "Naming an environment from its pending prompt failed for the first time.",
464
471
  "rename.still-failing": "That rename is still failing; written at the 2nd, 4th, 8th... failure.",
@@ -532,6 +539,7 @@ var GATEWAY_LOG_AREAS = defineLogAreas({
532
539
  "websocket.upgrade-failed": "A WebSocket upgrade failed.",
533
540
  "events.client-dropped": "An event-stream client buffered too much and was dropped; it reconnects and refetches.",
534
541
  "proxy.client-disconnected": "A proxy client went away, so its upstream request was aborted.",
542
+ "traffic.burst": "Connections or requests spiked. Counts by source address, route class, client family, listener and registered invoke command; never request content.",
535
543
  "throttle.suppressed": "Repeats of the throttled `site` were counted over a window, not written.",
536
544
  "throttle.recovered": "The throttled `site` succeeded again, so its fault has cleared.",
537
545
  "throttle.evicted": "The tracked-key limit dropped the `site`, so no recovered line follows unless it fails again."
@@ -635,6 +643,8 @@ var LOGGING_LOG_AREAS = defineLogAreas({
635
643
  },
636
644
  "essential.write-failed": "Writing the essential log failed. Its entries are counted, and a marker reports them at the next write that works.",
637
645
  "policy.changed": "The logging settings changed: saving, retention and levels, with no content.",
646
+ "policy.detail-expired": "Raised log detail reached its expiry, so the backend set its raised levels back to info. Saving is unchanged.",
647
+ "policy.expiry-failed": "Checking or applying the log detail expiry failed; the next check, a minute later, tries again.",
638
648
  "policy.bridge-predates-route": "A running bridge has no logging settings route; it applies them at its next start.",
639
649
  "policy.push-failed": "A running bridge did not take the logging settings after retries; its next start resends them.",
640
650
  "prune.failed": "Removing expired log files failed; the next sweep retries.",
@@ -642,6 +652,23 @@ var LOGGING_LOG_AREAS = defineLogAreas({
642
652
  "unknown-area": "Code outside the type checker asked for an area that is not listed.",
643
653
  ...THROTTLE_LOG_EVENTS
644
654
  }
655
+ },
656
+ "renderer-errors": {
657
+ description: "Renderer failures a desktop window reported from its error ring: class, boundary, surface, count and fingerprint, never a message or stack.",
658
+ events: {
659
+ "error.recorded": {
660
+ description: "A renderer reported `count` new occurrences of one failure since its last report.",
661
+ essential: true,
662
+ fields: {
663
+ errorClass: "label",
664
+ boundary: "label",
665
+ route: "label",
666
+ fingerprint: "label",
667
+ count: "number"
668
+ }
669
+ },
670
+ "report.rate-limited": "Renderer error entries arrived faster than the backend records them, so `dropped` were counted and not written."
671
+ }
645
672
  }
646
673
  });
647
674
 
@@ -665,6 +692,7 @@ var NATIVE_AGENT_LOG_AREAS = defineLogAreas({
665
692
  "native-agent": {
666
693
  description: "Native agent sessions and what the backend reads from their bridges.",
667
694
  events: {
695
+ "session.bridge-replaced-for-policy": "An idle bridge was stopped so a resume could apply the user's wider execution policy.",
668
696
  "catalogue.outdated-bridge": "A bridge predates the command catalogue, so its commands stay unavailable.",
669
697
  "compact.instructions-ignored": "A bridge compacted without confirming the instructions sent with /compact: it predates them.",
670
698
  "handoff.summary-read-failed": "Change summaries could not be read for a handoff, so the carrier says they are unmeasured.",
@@ -698,6 +726,8 @@ var NATIVE_AGENT_LOG_AREAS = defineLogAreas({
698
726
  "usage-limit.notice-failed": "A usage-limit stop's outcome could not be read for its notice.",
699
727
  "usage-limit.resend-failed": "Resending after a usage limit failed. An unknown send stays in the journal.",
700
728
  "title.strategy-failed": "A session title strategy failed, so the next is tried. Content-free: the error can quote the prompt.",
729
+ "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.",
730
+ "steer.capability-cleared": "A projection cleared `actions.steer` because its bridge did not qualify. Identifiers and turn status only.",
701
731
  ...THROTTLE_LOG_EVENTS
702
732
  }
703
733
  },
@@ -730,7 +760,8 @@ var NATIVE_AGENT_LOG_AREAS = defineLogAreas({
730
760
  "coordinator-servers.unavailable": "OpenCode coordinator research servers are unavailable.",
731
761
  "monitor.reconnecting": "The request monitor lost its stream and is reconnecting. Error class only.",
732
762
  "worker-limit.reached": "The bounded request workers are full, so the stream restarts and a snapshot reconciles.",
733
- "request.failed": "Handling a request event failed, so the stream restarts. Error class only."
763
+ "request.failed": "Handling a request event failed, so the stream restarts. Error class only.",
764
+ "credential-plugin.skipped": "A host OpenCode server started without the credential plugin, so its tools inherit its password; `reason` says why."
734
765
  }
735
766
  }
736
767
  });
@@ -758,6 +789,7 @@ var PREVIEW_LOG_AREAS = defineLogAreas({
758
789
  "publication.start-failed": "Private preview publication did not start.",
759
790
  "publication.reconfigure-failed": "Preview publication could not be reconfigured.",
760
791
  "publication.listening": "Private preview origins are listening.",
792
+ "publication.same-site": "The preview domain is the same site as the application; publication runs with a warning.",
761
793
  "certificate.reloaded": "The preview certificate was reloaded.",
762
794
  "access.revoked-close-failed": "A revoked preview resource could not be closed. Error class only.",
763
795
  "registry.invalid-definition": "An invalid stored preview service definition was ignored.",
@@ -796,6 +828,9 @@ var RUNTIME_LOG_AREAS = defineLogAreas({
796
828
  essential: true,
797
829
  fields: { origin: "label", ...ESSENTIAL_ERROR_FIELDS }
798
830
  },
831
+ "child.reaped": "A macOS child whose exit Bun lost was reaped after its command settled, so it no longer waits as a zombie.",
832
+ "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.",
833
+ "child.reap-unavailable": "waitpid could not be loaded, so children whose exit Bun lost stay zombies until this process exits.",
799
834
  ...THROTTLE_LOG_EVENTS
800
835
  }
801
836
  }
@@ -1066,10 +1101,19 @@ var STORAGE_LOG_AREAS = defineLogAreas({
1066
1101
  "retired.turn-cleanup-pending": "Cleanup of a retired Looped Review turn did not finish and stays pending.",
1067
1102
  "handoffs.prune-failed": "Pruning agent handoffs that nothing references failed; a later prune retries.",
1068
1103
  "desktop-connections.malformed": "Stored desktop connection settings were malformed, so the local connection is used.",
1104
+ "config.restrict-mode-failed": "A config file holding provider secrets could not be set to owner-only; the backend carries on.",
1069
1105
  "legacy-json.moved": "JSON store files written after the SQLite migration were archived, not imported.",
1070
1106
  "legacy-json.archive-failed": "Imported JSON store files could not be archived.",
1107
+ "lease.timed-out": "A waiter gave up on a lease; `lease` and `family` name it, `holderAgeMs` is the time since its holder's last heartbeat (null when the holder had just gone), `waitedMs` how long the waiter waited.",
1071
1108
  "lease.heartbeat-failed": "A held lease's heartbeat failed, which shortens the lease; the next one retries.",
1072
- "scrub.checkpoint-failed": "Deleted content could not be scrubbed from the WAL because the truncating checkpoint failed or was blocked; the next checkpoint retries.",
1109
+ "scrub.vacuum-failed": "Deleted-content page reclamation failed; the checkpoint is attempted independently.",
1110
+ "scrub.checkpoint-failed": "Deleted content could not be scrubbed from the WAL yet because the truncating checkpoint failed or a reader held an older snapshot; it is retried without waiting until it succeeds.",
1111
+ "upkeep.vacuum-failed": "Periodic page reclamation failed; the next upkeep pass retries.",
1112
+ "optimize.failed": "Refreshing the query planner's statistics failed; queries still run and the next check retries.",
1113
+ "ledger.moved": "The change-tracking ledger was moved out of the main database into its own file; `rows` and `durationMs` say how much and how long.",
1114
+ "snapshot.top-tables-failed": "The sampled table sizes from a finished snapshot could not be saved; the snapshot stands and the next one retries.",
1115
+ "snapshot.ledger-skipped": "The daily change-tracking ledger snapshot was skipped because the disk or the snapshot budget lacks room; `retryAt` says when it tries again.",
1116
+ "snapshot.ledger-failed": "The daily change-tracking ledger snapshot failed; `retryAt` says when it tries again, if known.",
1073
1117
  ...THROTTLE_LOG_EVENTS
1074
1118
  }
1075
1119
  }
@@ -1086,6 +1130,7 @@ var BUILD_PIPELINE_LOG_AREAS = defineLogAreas({
1086
1130
  "consolidation.consume-deferred": "Consuming a review consolidation result failed; it stays pending and is retried.",
1087
1131
  "dispatch.prepare-failed": "Attaching the agent before dispatch failed; the prompt request does the same work and answers authoritatively.",
1088
1132
  "interaction.resolved": "A human interaction on a pipeline stage resolved. Metadata only.",
1133
+ "user-message.background-send-refused": "The bridge refused a queued user message during a background wait; it stays queued and is retried.",
1089
1134
  "transcripts.migrated": "A transcript migration pass moved stage transcripts; counts only.",
1090
1135
  "transcripts.maintenance-failed": "Migrating or sweeping stage transcripts failed; the next start retries.",
1091
1136
  "restore.skipped": "A pipeline could not be restored at startup and was skipped.",
@@ -1123,6 +1168,8 @@ var CHANGE_TRACKING_LOG_AREAS = defineLogAreas({
1123
1168
  description: "Change tracking: turn capture, evidence pulls and measurements.",
1124
1169
  events: {
1125
1170
  "journal-import.failed": "Importing surviving OpenCode command journals as legacy summaries failed.",
1171
+ "measurement-drain.failed": "Draining an owner's superseded measurements failed; the retention pass retries.",
1172
+ "retention.failed": "A retention pass failed partway; what it deleted stands and the next pass goes on.",
1126
1173
  "projection.failed": "Projecting a change event onto its environment failed.",
1127
1174
  "startup.reconcile-failed": "Reconciling change tracking at startup failed.",
1128
1175
  "turn-start.capture-failed": "Capturing a turn's start failed, so the turn is untracked.",
@@ -1153,7 +1200,16 @@ var COORDINATOR_LOG_AREAS = defineLogAreas({
1153
1200
  coordinator: {
1154
1201
  description: "Coordinators: delegations, status wakes and their store.",
1155
1202
  events: {
1203
+ ...THROTTLE_LOG_EVENTS,
1156
1204
  "delegation.open-failed": "A delegation could not be opened; `source` says for what.",
1205
+ "delegation.reconcile-failed": "One delegation could not be settled; the rest of the pass still ran and the next one retries.",
1206
+ "delegation.wake-failed": "One delegation's wake could not be delivered; the rest of the pass still ran and the next one retries.",
1207
+ "delegation.wake-held": "A wake is waiting on a state the user can change (messaging off, conversation limit), and is not counted as a failure.",
1208
+ "delegation.wake-pass-failed": "A delegation wake pass could not run; the next sweep retries.",
1209
+ "delegation.wake-retire-failed": "A wake that keeps failing could not be given up on; the next pass retries.",
1210
+ "delegation.wake-retire-notice-failed": "The one notice for a wake being retired could not be sent; the wake stays owed and the next pass retries.",
1211
+ "delegation.wake-retired": "A wake kept failing and was given up on; `kind` is the last failure.",
1212
+ "mail.reconcile-failed": "One coordinator's mail could not be reconciled; the sweep carried on with the others.",
1157
1213
  "deliver-now.drain-failed": "The mail delivery pass after deliverNow failed; the next sweep delivers.",
1158
1214
  "mail.move-failed": "Mail could not move to the new main coordinator.",
1159
1215
  "work.move-failed": "Work could not move to the main coordinator.",
@@ -1181,6 +1237,13 @@ var COORDINATOR_LOG_AREAS = defineLogAreas({
1181
1237
  "store.workflows-cleared": "The workflow store was full, so a batch of its oldest finished records was removed.",
1182
1238
  "store.workflows-in-use": "The workflow store was full and every record was still in use, so new work was refused.",
1183
1239
  "remote-worker.settle-failed": "A remote worker could not be settled.",
1240
+ "node-release.failed": "Work on a node that was forgotten or handed over could not be closed; the sweep's registry check retries.",
1241
+ "node-release.reconcile-failed": "The sweep could not check records against the node registry; the next sweep retries.",
1242
+ "node-release.unregistered": "Records named a node the registry no longer holds, so their work was closed here.",
1243
+ "node-release.notice-failed": "The notice for work closed on a released node could not be sent; it stays owed and the sweep retries.",
1244
+ "node-release.no-coordinator": "Work closed on a released node belonged to a coordinator that no longer exists, so nobody was told.",
1245
+ "node-offline.notice-failed": "The notice that a node has been unreachable for a day could not be sent; the next failed read retries.",
1246
+ "node-offline.check-failed": "Whether a long-unreachable node's coordinators were told could not be checked; the next read retries.",
1184
1247
  "checkout.merge-followed": "After an environment's PR merged, the project checkout was fast-forwarded, or `outcome` says why not.",
1185
1248
  "checkout.merge-follow-failed": "Fast-forwarding the project checkout failed, after an environment's PR merged or before mail woke the main coordinator.",
1186
1249
  "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`).",
@@ -1277,7 +1340,10 @@ var DOCKER_LOG_AREAS = defineLogAreas({
1277
1340
  events: {
1278
1341
  "portable-inputs.relay-missing": "Docker is rootless and the image predates the staged-input relay, so the container cannot read them until rebuilt.",
1279
1342
  "git-mirror.mount-unavailable": "A new container gets no project Git mirror, so its clone goes to the remote.",
1343
+ "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.",
1280
1344
  "git-mirror.refreshed": "A project's Git mirror was built or updated.",
1345
+ "git-mirror.seeded": "A project's Git mirror was built from its host checkout and only what the remote added to it.",
1346
+ "git-mirror.seed-skipped": "A project's host checkout could not seed its Git mirror, so the build downloads everything.",
1281
1347
  "git-mirror.refresh-failed": "A project's Git mirror could not be updated. New clones still work, from the mirror as it was or from the remote.",
1282
1348
  "git-mirror.low-disk": "A project's Git mirror was not updated: the disk is nearly full.",
1283
1349
  "git-mirror.oversized": "A project's repository is too large for a Git mirror, so its environments keep the blobless clone.",
@@ -1289,6 +1355,7 @@ var DOCKER_LOG_AREAS = defineLogAreas({
1289
1355
  "git-mirror.clone-fallback": "A new environment could not clone from its project's Git mirror and cloned from the remote.",
1290
1356
  "project-seed.refused": "A project .env, .env.local or opencode.json was not copied into a new container: a link, not a regular file, outside the project, too large or unreadable.",
1291
1357
  "opencode.warm-incomplete": "OpenCode did not finish loading /workspace in a container.",
1358
+ "log-driver.unbounded": "The Docker daemon offers neither the local nor the json-file log driver, so new containers keep its default driver, whose log may be uncapped. Written once per backend.",
1292
1359
  "lifecycle-event.reconcile-failed": "Reconciling an environment after a container start or stop event failed; the next status read retries.",
1293
1360
  "login-keeper.pass-failed": "A Claude login keeper pass failed; the next interval retries.",
1294
1361
  "login-keeper.refresh-failed": "Refreshing the host Claude login failed. Fixed text: CLI output can hold credentials.",
@@ -1312,6 +1379,7 @@ var DOCKER_LOG_AREAS = defineLogAreas({
1312
1379
  essential: true,
1313
1380
  fields: { staleForMs: "number" }
1314
1381
  },
1382
+ "writer-lease.listener-failed": "The callback told about a lost registry writer lease threw, so the schedules settings learn of the loss only at their next read.",
1315
1383
  "writer-lease.not-acquired": {
1316
1384
  description: "This backend started without the registry writer lease, for the fixed `reason` given. A second backend on one data directory is normal: it serves reads, runs no schedules and refuses container changes.",
1317
1385
  essential: true,
@@ -1449,6 +1517,7 @@ var NODES_LOG_AREAS = defineLogAreas({
1449
1517
  "verification.record-failed": "A node verification could not be recorded.",
1450
1518
  "profile.record-failed": "A node profile could not be recorded.",
1451
1519
  "detach.unconfirmed": "A forgotten node has not confirmed the detach yet.",
1520
+ "grant.revocation-listener-failed": "A connection could not be told its client grant was removed; the grant is still gone.",
1452
1521
  "handover.recovery-pending": "Command handover recovery is still pending.",
1453
1522
  "ticket-sync.work-record-failed": "A remote build started but its ticket work location could not be saved.",
1454
1523
  "ticket-sync.failed": "A Kanban sync with a node failed; it is retried.",
@@ -1501,7 +1570,9 @@ var HOST_LOG_AREAS = defineLogAreas({
1501
1570
  "tool.missing": "A host tool was not found.",
1502
1571
  "maintenance.listener-failed": "A host maintenance listener threw; the others still run.",
1503
1572
  "suspend.reconcile-failed": "Reconciling due work after a host suspension failed.",
1504
- "load.sample-failed": "Sampling machine load failed; the next sample retries."
1573
+ "load.sample-failed": "Sampling machine load failed; the next sample retries.",
1574
+ "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.",
1575
+ ...THROTTLE_LOG_EVENTS
1505
1576
  }
1506
1577
  }
1507
1578
  });
@@ -1966,6 +2037,7 @@ var WEB_SYNC_LOG_AREAS = defineLogAreas({
1966
2037
  events: {
1967
2038
  "events.disconnected": "The main event stream dropped; it reconnects and replays.",
1968
2039
  "terminal-stream.disconnected": "A terminal event stream dropped; it reconnects.",
2040
+ "relayed-stream.disconnected": "The relayed node event stream dropped; it reconnects.",
1969
2041
  "connection-listener.failed": "A main stream connection state listener threw.",
1970
2042
  "event-listener.failed": "A listener for a gateway event threw.",
1971
2043
  "stream-listener.failed": "A listener for the stream-connected notice threw."
@@ -2050,6 +2122,7 @@ var TEXT_RULES = [
2050
2122
  pattern: /\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/g,
2051
2123
  replacement: "[redacted]"
2052
2124
  },
2125
+ { pattern: /\bok[ab]_[A-Za-z0-9_-]{16,}/g, replacement: "[redacted]" },
2053
2126
  { pattern: /\bgh[pousr]_[A-Za-z0-9]{16,}/g, replacement: "[redacted]" },
2054
2127
  { pattern: /\bgithub_pat_[A-Za-z0-9_]{20,}/g, replacement: "[redacted]" },
2055
2128
  { pattern: /\b(?:sk|rk|pk)-[A-Za-z0-9_-]{12,}/g, replacement: "[redacted]" },
@@ -2822,6 +2895,7 @@ function effectiveLogLevel(detail, area) {
2822
2895
  return detail.level;
2823
2896
  }
2824
2897
  }
2898
+ var LOG_DETAIL_EXPIRY_MS = 24 * 60 * 60 * 1000;
2825
2899
  function logDetailEnablesBridgeDiagnostics(detail) {
2826
2900
  return LEVEL_DETAIL[effectiveLogLevel(detail, BRIDGE_DIAGNOSTICS_LOG_AREA)] >= LEVEL_DETAIL.debug;
2827
2901
  }
@@ -5226,9 +5300,6 @@ var shouldTransform = (res) => {
5226
5300
  return !cacheControl || !cacheControlNoTransformRegExp.test(cacheControl);
5227
5301
  };
5228
5302
 
5229
- // ../../bridges/claude-bridge/src/index.ts
5230
- import { randomBytes as randomBytes2, timingSafeEqual } from "node:crypto";
5231
-
5232
5303
  // ../../bridges/claude-bridge/src/routes/health.ts
5233
5304
  var health = new Hono2;
5234
5305
  health.get("/health", (c) => {
@@ -5704,6 +5775,15 @@ function claudePlanWindowFromLabel(label) {
5704
5775
  return known ? { id: known[0], ...known[1] } : claudeModelWeeklyWindow(model);
5705
5776
  }
5706
5777
 
5778
+ // ../../bridges/claude-bridge/src/services/event-message-id.ts
5779
+ function eventMessageId(event) {
5780
+ if (event.type !== "message.updated" && event.type !== "message.patched")
5781
+ return;
5782
+ const data = event.data;
5783
+ const id = event.type === "message.updated" ? data?.message?.id : data?.messageId;
5784
+ return typeof id === "string" && id.length > 0 ? id : undefined;
5785
+ }
5786
+
5707
5787
  // ../../bridges/claude-bridge/src/services/logger.ts
5708
5788
  function isDebugLoggingEnabled() {
5709
5789
  return bridgeDiagnosticsStreamEnabled("claude");
@@ -6479,11 +6559,8 @@ import { execFile } from "node:child_process";
6479
6559
  import { createHash as createHash3 } from "node:crypto";
6480
6560
  var sessions = new Map;
6481
6561
  eventEmitter.subscribe((event) => {
6482
- if (event.type !== "message.updated" && event.type !== "message.patched")
6483
- return;
6484
- const data = event.data;
6485
- const id = event.type === "message.updated" ? data?.message?.id : data?.messageId;
6486
- if (typeof id !== "string" || !event.sessionId)
6562
+ const id = eventMessageId(event);
6563
+ if (id === undefined || !event.sessionId)
6487
6564
  return;
6488
6565
  const session = sessions.get(event.sessionId);
6489
6566
  if (!session || session.messages.at(-1)?.id === id)
@@ -8068,10 +8145,13 @@ import { isAbsolute, join as join3 } from "node:path";
8068
8145
 
8069
8146
  // ../protocol/src/coordinator.ts
8070
8147
  var COORDINATOR_COMMAND_SANDBOX_ENV = "ORKESTRATOR_COORDINATOR_COMMAND_SANDBOX";
8148
+ var COORDINATOR_PROTECTED_DATA_DIR_ENV = "ORKESTRATOR_COORDINATOR_PROTECTED_DATA_DIR";
8071
8149
  function coordinatorCommandSandboxFromEnv(env) {
8072
8150
  return env[COORDINATOR_COMMAND_SANDBOX_ENV] === "unavailable" ? "unavailable" : "required";
8073
8151
  }
8074
8152
  var COORDINATOR_CLAUDE_USER_SKILLS_DIR_ENV = "ORKESTRATOR_COORDINATOR_CLAUDE_USER_SKILLS_DIR";
8153
+ var COORDINATOR_OTHER_ENVIRONMENTS_SETTING_LABEL = "Let the coordinator use environments it did not create";
8154
+ 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.`;
8075
8155
  var COORDINATOR_CONTROL_TOOL_NAMES = Object.freeze([
8076
8156
  "ack_message",
8077
8157
  "add_ticket_comment",
@@ -8111,13 +8191,11 @@ var COORDINATOR_CONTROL_TOOL_NAMES = Object.freeze([
8111
8191
  "launch_graph",
8112
8192
  "launch_job",
8113
8193
  "launch_multi_review",
8114
- "launch_node_environment",
8115
8194
  "launch_terminal",
8116
8195
  "list_agents",
8117
8196
  "list_environments",
8118
8197
  "list_graph_templates",
8119
8198
  "list_mailboxes",
8120
- "list_node_environments",
8121
8199
  "list_nodes",
8122
8200
  "list_projects",
8123
8201
  "list_provider_accounts",
@@ -8146,16 +8224,11 @@ var COORDINATOR_CONTROL_TOOL_NAMES = Object.freeze([
8146
8224
  "resume_schedule",
8147
8225
  "run_worker_command",
8148
8226
  "send_message",
8149
- "send_node_message",
8150
- "send_prompt_to_node_tab",
8151
8227
  "send_prompt_to_tab",
8152
8228
  "set_worker_goal",
8153
8229
  "start_build_pipeline",
8154
8230
  "start_environment",
8155
- "start_multi_review",
8156
- "start_node_environment",
8157
8231
  "stop_environment",
8158
- "stop_node_environment",
8159
8232
  "stop_worker_turn",
8160
8233
  "switch_provider_account",
8161
8234
  "set_account_auto_switch",
@@ -8807,6 +8880,126 @@ function claudeMcpToolPrefix(name) {
8807
8880
  return `mcp__${normalized}__`;
8808
8881
  }
8809
8882
 
8883
+ // ../../bridges/claude-bridge/src/services/read-only-path-boundary.ts
8884
+ import { realpathSync } from "node:fs";
8885
+ import { homedir as homedir2 } from "node:os";
8886
+ import { dirname, isAbsolute as isAbsolute2, join as join5, parse, resolve as resolve2, sep } from "node:path";
8887
+ function canonical(path) {
8888
+ let existing = path;
8889
+ const tail = [];
8890
+ for (;; ) {
8891
+ try {
8892
+ return join5(realpathSync.native(existing), ...tail.reverse());
8893
+ } catch {
8894
+ const parent = dirname(existing);
8895
+ if (parent === existing)
8896
+ return path;
8897
+ tail.push(existing.slice(parent.length).replace(/^[/\\]+/, ""));
8898
+ existing = parent;
8899
+ }
8900
+ }
8901
+ }
8902
+ function namedAndCanonical(paths) {
8903
+ const named = paths.flatMap((path) => path?.trim() && isAbsolute2(path) ? [path] : []);
8904
+ return [...new Set(named.flatMap((path) => [resolve2(path), canonical(path)]))];
8905
+ }
8906
+ function claudeReadOnlyWorkspacePaths(cwd) {
8907
+ return [...new Set([cwd, canonical(cwd)])];
8908
+ }
8909
+ function coordinatorReadBoundary(workspaces, env = process.env) {
8910
+ const dataDir = env[COORDINATOR_PROTECTED_DATA_DIR_ENV]?.trim();
8911
+ if (!dataDir || !isAbsolute2(dataDir))
8912
+ return null;
8913
+ const deny = namedAndCanonical([dataDir]);
8914
+ return {
8915
+ deny,
8916
+ allow: namedAndCanonical([
8917
+ env.CLAUDE_CONFIG_DIR,
8918
+ env.ORKESTRATOR_BRIDGE_ATTACHMENT_ROOT,
8919
+ env[COORDINATOR_CLAUDE_USER_SKILLS_DIR_ENV],
8920
+ join5(dataDir, "toolchains"),
8921
+ ...workspaces
8922
+ ]).filter((path) => !deny.includes(path) && deny.some((root) => isWithin(root, path)))
8923
+ };
8924
+ }
8925
+ function isWithin(root, path) {
8926
+ if (path === root)
8927
+ return true;
8928
+ const prefix = root === parse(root).root ? root : `${root}${sep}`;
8929
+ return path.startsWith(prefix);
8930
+ }
8931
+ function deniedForm(boundary, path) {
8932
+ return boundary.deny.some((root) => isWithin(root, path)) && !boundary.allow.some((root) => isWithin(root, path));
8933
+ }
8934
+ function expandedHome(path) {
8935
+ if (path === "~")
8936
+ return homedir2();
8937
+ return path.startsWith("~/") ? `${homedir2()}${sep}${path.slice(2)}` : path;
8938
+ }
8939
+ function readBoundaryRefuses(boundary, path, cwd, options = {}) {
8940
+ const expanded = expandedHome(path);
8941
+ const raw = isAbsolute2(expanded) ? expanded : `${cwd}${sep}${expanded}`;
8942
+ const lexical = resolve2(raw);
8943
+ const real = canonical(raw);
8944
+ if (deniedForm(boundary, lexical) || deniedForm(boundary, real))
8945
+ return true;
8946
+ return options.traversal === true && boundary.deny.some((root) => isWithin(lexical, root) || isWithin(real, root));
8947
+ }
8948
+ function globRoot(pattern) {
8949
+ if (!pattern.startsWith("/") && !pattern.startsWith("~") && !pattern.startsWith("..")) {
8950
+ return;
8951
+ }
8952
+ const wildcard = pattern.search(/[*?[{]/);
8953
+ return wildcard < 0 ? pattern : pattern.slice(0, wildcard);
8954
+ }
8955
+ function readToolRefused(boundary, tool, input, cwd) {
8956
+ const text = (key) => {
8957
+ const value = input[key];
8958
+ return typeof value === "string" && value.trim() ? value : undefined;
8959
+ };
8960
+ if (tool === "Read") {
8961
+ const path = text("file_path");
8962
+ return path !== undefined && readBoundaryRefuses(boundary, path, cwd);
8963
+ }
8964
+ if (tool !== "Grep" && tool !== "Glob")
8965
+ return false;
8966
+ const roots = [text("path") ?? cwd];
8967
+ const pattern = tool === "Glob" ? text("pattern") : undefined;
8968
+ const root = pattern ? globRoot(pattern) : undefined;
8969
+ if (root)
8970
+ roots.push(root);
8971
+ return roots.some((path) => readBoundaryRefuses(boundary, path, cwd, { traversal: true }));
8972
+ }
8973
+ function shellCommandRefused(boundary, command, cwd, options) {
8974
+ const [program, ...tokens] = command.trim().split(/\s+/);
8975
+ if (options.traversal) {
8976
+ const indirectOption = program === "sort" || program === "wc" ? "--files0-from" : program === "file" ? "--files-from" : ["cksum", "md5sum", "sha1sum", "sha256sum"].includes(program ?? "") ? "--check" : undefined;
8977
+ if (indirectOption && tokens.some((token) => {
8978
+ const option = token.split("=", 1)[0];
8979
+ return option.startsWith("--") && indirectOption.startsWith(option) || program === "file" && /^-[^-]*f/.test(token) || indirectOption === "--check" && /^-[^-]*c/.test(token);
8980
+ }))
8981
+ return true;
8982
+ if (program === "grep" && tokens.some((token) => /^-[^-]*[RS]/.test(token) || token.startsWith("--") && "--dereference-recursive".startsWith(token)) || program === "diff" && tokens.some((token) => /^-[^-]*r/.test(token) || token.startsWith("--") && "--recursive".startsWith(token)) || (program === "rg" || program === "ag" || program === "find" || program === "fd" || program === "du" || program === "ls") && tokens.some((token) => token === "--follow" || token === "--dereference" || /^-[^-]*L/.test(token)))
8983
+ return true;
8984
+ const searches = program === "rg" || program === "ag" || program === "find" || program === "fd" || program === "du" || program === "ls" || program === "tree" || program === "grep";
8985
+ if (searches && readBoundaryRefuses(boundary, cwd, cwd, options))
8986
+ return true;
8987
+ }
8988
+ return tokens.some((token) => {
8989
+ const attached = [];
8990
+ if (token.startsWith("--")) {
8991
+ const equals = token.indexOf("=");
8992
+ if (equals >= 0)
8993
+ attached.push(token.slice(equals + 1));
8994
+ } else if (token.startsWith("-")) {
8995
+ for (let index = 1;index < token.length && /[a-zA-Z0-9]/.test(token[index]); index++) {
8996
+ attached.push(token.slice(index + 1));
8997
+ }
8998
+ }
8999
+ return [token, ...attached].some((candidate) => candidate && readBoundaryRefuses(boundary, candidate, cwd, options));
9000
+ });
9001
+ }
9002
+
8810
9003
  // ../../bridges/claude-bridge/src/services/read-only-policy.ts
8811
9004
  var CAPABILITY_TOOLS = new Map([
8812
9005
  ["file.write", ["Write", "NotebookEdit", "EnterWorktree", "ExitWorktree"]],
@@ -9090,7 +9283,10 @@ function claudeReadOnlySandbox(policy, options = {}) {
9090
9283
  autoAllowBashIfSandboxed: true,
9091
9284
  allowUnsandboxedCommands: false,
9092
9285
  excludedCommands: [],
9093
- filesystem: { denyWrite: [...new Set(options.workspaces ?? [])] },
9286
+ filesystem: {
9287
+ denyWrite: [...new Set(options.workspaces ?? [])],
9288
+ ...options.readBoundary ? { denyRead: options.readBoundary.deny, allowRead: options.readBoundary.allow } : {}
9289
+ },
9094
9290
  network: {
9095
9291
  allowLocalBinding: policy.networkAccess === "full",
9096
9292
  strictAllowlist: true,
@@ -9117,7 +9313,8 @@ var REFUSALS = {
9117
9313
  tool: (tool) => `Coordinator is read-only, so ${tool} is not available. Delegate file changes to a worker environment.`,
9118
9314
  waiting: (tool) => `Coordinator turns do not wait, so ${tool} is not available. Delegated work reports back by waking this conversation with a message when it finishes; end your turn instead.`,
9119
9315
  mcp: (tool) => `Coordinator sessions may only use Orkestrator's own tools, so ${tool} is not available.`,
9120
- unsandboxed: "Coordinator commands may not run outside the sandbox."
9316
+ unsandboxed: "Coordinator commands may not run outside the sandbox.",
9317
+ dataDirectory: "Coordinators cannot read Orkestrator's data directory, which holds credentials with wider authority than this conversation. This conversation's own tool results, memory and attachments stay readable."
9121
9318
  },
9122
9319
  "read-only": {
9123
9320
  composition: "Shell commands in this session cannot use quotes, escapes, globs, pipes, redirection, substitution or command chaining, because the command that runs would not be the one checked.",
@@ -9132,7 +9329,8 @@ var REFUSALS = {
9132
9329
  tool: (tool) => `This session is read-only, so ${tool} is not available.`,
9133
9330
  waiting: (tool) => `This session's turns do not wait, so ${tool} is not available. End your turn instead.`,
9134
9331
  mcp: (tool) => `This session may only use Orkestrator's own tools and the MCP servers granted to it, so ${tool} is not available.`,
9135
- unsandboxed: "Commands in this session may not run outside the sandbox."
9332
+ unsandboxed: "Commands in this session may not run outside the sandbox.",
9333
+ dataDirectory: "This session cannot read Orkestrator's data directory, which holds credentials with wider authority than this session. Its own tool results, memory and attachments stay readable."
9136
9334
  }
9137
9335
  };
9138
9336
  function isReadOnlyShellCommand(command, options = {}) {
@@ -9245,6 +9443,7 @@ function createCoordinatorReadOnlyHook(policy, researchMcpServerNames = coordina
9245
9443
  ...researchMcpServerNames.map(claudeMcpToolPrefix),
9246
9444
  ...(nativeAgentUserMcpGrant(policy) ?? []).map(claudeMcpToolPrefix)
9247
9445
  ];
9446
+ const readBoundary = (cwd) => options.readBoundary !== undefined ? options.readBoundary : process.env[COORDINATOR_PROTECTED_DATA_DIR_ENV] ? coordinatorReadBoundary(claudeReadOnlyWorkspacePaths(cwd)) : null;
9248
9447
  return async (input) => {
9249
9448
  if (input.hook_event_name !== "PreToolUse")
9250
9449
  return {};
@@ -9273,6 +9472,20 @@ function createCoordinatorReadOnlyHook(policy, researchMcpServerNames = coordina
9273
9472
  const verdict = isReadOnlyShellCommand(command, options);
9274
9473
  if (!verdict.allowed)
9275
9474
  return deny(verdict.reason);
9475
+ const boundary = readBoundary(input.cwd);
9476
+ if (boundary && shellCommandRefused(boundary, command, input.cwd, {
9477
+ traversal: options.commandSandbox === "unavailable"
9478
+ })) {
9479
+ return deny(refusals.dataDirectory);
9480
+ }
9481
+ return {};
9482
+ }
9483
+ if (toolName === "Read" || toolName === "Grep" || toolName === "Glob") {
9484
+ const boundary = readBoundary(input.cwd);
9485
+ const toolInput = input.tool_input ?? {};
9486
+ if (boundary && readToolRefused(boundary, toolName, toolInput, input.cwd)) {
9487
+ return deny(refusals.dataDirectory);
9488
+ }
9276
9489
  }
9277
9490
  return {};
9278
9491
  };
@@ -9411,12 +9624,12 @@ function effectiveClaudeChrome(policy, options) {
9411
9624
  }
9412
9625
 
9413
9626
  // ../../bridges/claude-bridge/src/services/claude-execution-sandbox.ts
9414
- import { realpathSync } from "node:fs";
9627
+ import { realpathSync as realpathSync2 } from "node:fs";
9415
9628
 
9416
9629
  // ../protocol/src/node/claude-linux-sandbox.ts
9417
9630
  import { spawnSync as spawnSync2 } from "node:child_process";
9418
9631
  import { accessSync, constants, existsSync, readFileSync as readFileSync2 } from "node:fs";
9419
- import { delimiter, join as join5 } from "node:path";
9632
+ import { delimiter, join as join6 } from "node:path";
9420
9633
  var CLAUDE_LINUX_SANDBOX_PROGRAMS = Object.freeze(["bwrap", "socat"]);
9421
9634
  var APPARMOR_BWRAP_PROFILE = "/etc/apparmor.d/bwrap-userns-restrict";
9422
9635
  var CLAUDE_LINUX_SANDBOX_PROBE_TIMEOUT_MS = 5000;
@@ -9450,7 +9663,7 @@ function executableOnPath(name, path = process.env.PATH) {
9450
9663
  if (!directory)
9451
9664
  continue;
9452
9665
  try {
9453
- accessSync(join5(directory, name), constants.X_OK);
9666
+ accessSync(join6(directory, name), constants.X_OK);
9454
9667
  return true;
9455
9668
  } catch {}
9456
9669
  }
@@ -9543,7 +9756,7 @@ function claudeLinuxSandboxStatus(now = Date.now()) {
9543
9756
  function claudeReadOnlyWorkspaces(cwd) {
9544
9757
  let resolved;
9545
9758
  try {
9546
- resolved = realpathSync(cwd);
9759
+ resolved = realpathSync2(cwd);
9547
9760
  } catch {
9548
9761
  resolved = undefined;
9549
9762
  }
@@ -9570,9 +9783,11 @@ function claudeReadOnlyCommandSandbox(options = {}) {
9570
9783
  }
9571
9784
  function claudeExecutionSandbox(policy, asksForApproval, readOnly = {}) {
9572
9785
  if (policy && isCoordinatorReadOnlyPolicy(policy)) {
9786
+ const workspaces = claudeReadOnlyWorkspaces(readOnly.cwd ?? claudeWorkspaceCwd());
9573
9787
  return claudeReadOnlySandbox(policy, {
9574
- workspaces: claudeReadOnlyWorkspaces(readOnly.cwd ?? claudeWorkspaceCwd()),
9575
- commandSandbox: readOnly.commandSandbox ?? claudeReadOnlyCommandSandbox().commandSandbox
9788
+ workspaces,
9789
+ commandSandbox: readOnly.commandSandbox ?? claudeReadOnlyCommandSandbox().commandSandbox,
9790
+ readBoundary: readOnly.readBoundary ?? coordinatorReadBoundary(workspaces)
9576
9791
  });
9577
9792
  }
9578
9793
  if (policy?.sandbox !== "provider")
@@ -12033,11 +12248,24 @@ var SYSTEM_SUBTYPE_DISPOSITIONS = {
12033
12248
  files_persisted: "notice",
12034
12249
  elicitation_complete: "notice"
12035
12250
  };
12251
+ var INTERNAL_SYSTEM_SUBTYPE_DISPOSITIONS = {
12252
+ session_title_changed: "ignored",
12253
+ vcs_state_changed: "ignored",
12254
+ per_turn_effort_changed: "ignored",
12255
+ permission_check_status: "ignored",
12256
+ peer_message_hold: "ignored",
12257
+ instruction_size_warning: "notice"
12258
+ };
12036
12259
  function systemSubtypeDisposition(subtype) {
12037
- if (typeof subtype !== "string" || !Object.hasOwn(SYSTEM_SUBTYPE_DISPOSITIONS, subtype)) {
12260
+ if (typeof subtype !== "string")
12038
12261
  return;
12262
+ if (Object.hasOwn(SYSTEM_SUBTYPE_DISPOSITIONS, subtype)) {
12263
+ return SYSTEM_SUBTYPE_DISPOSITIONS[subtype];
12039
12264
  }
12040
- return SYSTEM_SUBTYPE_DISPOSITIONS[subtype];
12265
+ if (Object.hasOwn(INTERNAL_SYSTEM_SUBTYPE_DISPOSITIONS, subtype)) {
12266
+ return INTERNAL_SYSTEM_SUBTYPE_DISPOSITIONS[subtype];
12267
+ }
12268
+ return;
12041
12269
  }
12042
12270
  function sessionHealth(session) {
12043
12271
  session.health ??= new RuntimeHealthRecorder;
@@ -12399,11 +12627,11 @@ function noMessages() {
12399
12627
  // ../../bridges/claude-bridge/src/services/session-manager-persistence.ts
12400
12628
  import { constants as constants2 } from "node:fs";
12401
12629
  import { lstat as lstat2, open as open2, realpath as realpath2 } from "node:fs/promises";
12402
- import { isAbsolute as isAbsolute3, join as join10, relative, resolve as resolve3, sep } from "node:path";
12630
+ import { isAbsolute as isAbsolute4, join as join11, relative, resolve as resolve4, sep as sep2 } from "node:path";
12403
12631
 
12404
12632
  // ../protocol/src/node/command-change-journal.ts
12405
12633
  import { appendFile, mkdir as mkdir3, readFile as readFile5, rename as rename3, rm as rm3, stat as stat4, writeFile as writeFile3 } from "node:fs/promises";
12406
- import { dirname } from "node:path";
12634
+ import { dirname as dirname2 } from "node:path";
12407
12635
  var MAX_JOURNAL_ENTRIES = 1000;
12408
12636
  var MAX_JOURNAL_FILES_PER_ENTRY = 20;
12409
12637
  var MAX_JOURNAL_PATH_LENGTH = 1024;
@@ -12476,7 +12704,7 @@ class CommandChangeJournal {
12476
12704
  const line = `${JSON.stringify({ id, change: bounded })}
12477
12705
  `;
12478
12706
  this.writes = this.writes.then(async () => {
12479
- await mkdir3(dirname(this.path), { recursive: true, mode: 448 });
12707
+ await mkdir3(dirname2(this.path), { recursive: true, mode: 448 });
12480
12708
  if (!this.sizeChecked) {
12481
12709
  this.sizeChecked = true;
12482
12710
  const existing = await stat4(this.path).catch(() => {
@@ -12551,12 +12779,823 @@ async function readJournal(path, maxEntries) {
12551
12779
  }
12552
12780
 
12553
12781
  // ../protocol/src/node/workspace-change-probe.ts
12554
- import { execFile as execFile3, spawn } from "node:child_process";
12555
- import { randomUUID as randomUUID2 } from "node:crypto";
12782
+ import { randomUUID as randomUUID3 } from "node:crypto";
12556
12783
  import { rmSync } from "node:fs";
12557
12784
  import { copyFile, lstat, mkdtemp as mkdtemp2, rm as rm4 } from "node:fs/promises";
12558
12785
  import { tmpdir as tmpdir2 } from "node:os";
12559
- import { delimiter as delimiter2, isAbsolute as isAbsolute2, join as join6, resolve as resolve2 } from "node:path";
12786
+ import { delimiter as delimiter2, isAbsolute as isAbsolute3, join as join7, resolve as resolve3 } from "node:path";
12787
+
12788
+ // ../protocol/src/node/command-capture.ts
12789
+ import { spawn } from "node:child_process";
12790
+ import { randomUUID as randomUUID2 } from "node:crypto";
12791
+ import { constants as fsConstants } from "node:fs";
12792
+ import * as captureFs from "node:fs";
12793
+ import os from "node:os";
12794
+ import path3 from "node:path";
12795
+ import { inspect } from "node:util";
12796
+
12797
+ // ../protocol/src/node/command-failure-reason.ts
12798
+ var MAX_MATCHED_CHARS = 16 * 1024;
12799
+ var SIGNAL_PATTERN = /^SIG[A-Z0-9]{1,16}$/;
12800
+ var TOOL_RULES = {
12801
+ git: [
12802
+ ["branch-exists", /a branch named .* already exists/i],
12803
+ ["ref-conflict", /exists; cannot create|cannot lock ref .* is at .* but expected/i],
12804
+ ["lock-held", /could not lock config file [^\n]*: File exists/i],
12805
+ ["lock-held", /(?:unable to create '[^\n]*\.lock'|cannot lock ref)[^\n]*: File exists/i],
12806
+ ["lock-held", /another git process/i],
12807
+ ["worktree-conflict", /already (?:checked out|used by worktree)|used by worktree at/i],
12808
+ ["invalid-ref", /not a valid (?:branch name|object name)|bad (?:revision|object)/i],
12809
+ ["invalid-ref", /unknown revision|ambiguous argument|invalid reference/i],
12810
+ ["branch-not-found", /no branch named|refname .* not found|branch '.*' not found/i],
12811
+ ["branch-not-found", /did not match any file\(s\) known to git/i],
12812
+ ["dubious-ownership", /detected dubious ownership/i],
12813
+ ["no-remote", /does not appear to be a git repository|no such remote/i],
12814
+ ["no-remote", /repository (?:.* )?not found/i],
12815
+ ["not-a-repository", /not a git repository/i],
12816
+ ["remote-ref-missing", /could(?:n't| not) find remote ref|not our ref/i],
12817
+ ["merge-conflict", /\bCONFLICT \(|merge conflict|could not apply|unmerged files/i],
12818
+ ["dirty-worktree", /local changes .* would be overwritten|commit your changes or stash/i],
12819
+ ["nothing-to-commit", /nothing to commit|no changes added to commit/i],
12820
+ ["push-rejected", /\[(?:remote )?rejected\]|non-fast-forward/i],
12821
+ ["identity-unknown", /please tell me who you are|unable to auto-detect email/i],
12822
+ [
12823
+ "worktree-has-changes",
12824
+ /^fatal: [^\n]*['"] contains modified or untracked files(?:, use --force to delete it)?\.?\s*$/im
12825
+ ],
12826
+ ["not-a-worktree", /^fatal: [^\n]*['"] is not a working tree\.?\s*$/im],
12827
+ ["branch-not-merged", /^(?:error|fatal): [^\n]*['"] is not fully merged\.?\s*$/im]
12828
+ ],
12829
+ gh: [
12830
+ ["pull-request-exists", /a pull request for branch .* already exists/i],
12831
+ ["no-pull-request", /no (?:pull requests? (?:found|match)|open pull requests?\b)/i],
12832
+ ["rate-limited", /rate limit|http 429/i],
12833
+ ["forbidden", /http 403|resource not accessible/i],
12834
+ ["resource-not-found", /http 404|could not resolve to a/i],
12835
+ ["server-error", /http 5\d\d/i]
12836
+ ],
12837
+ docker: [
12838
+ ["daemon-unavailable", /cannot connect to the docker daemon|error during connect/i],
12839
+ [
12840
+ "daemon-unavailable",
12841
+ /is the docker daemon running|docker desktop is (?:not running|unable)/i
12842
+ ],
12843
+ ["container-not-found", /no such container/i],
12844
+ ["container-not-running", /container .* is (?:not running|paused|restarting)/i],
12845
+ ["container-name-conflict", /name .* is already in use/i],
12846
+ ["image-not-found", /no such image|pull access denied|manifest .* not found/i],
12847
+ ["image-not-found", /manifest unknown|repository does not exist/i],
12848
+ ["removal-in-progress", /removal of container .* is already in progress/i],
12849
+ [
12850
+ "image-in-use",
12851
+ /image is (?:being used|referenced)|unable to (?:remove|delete) .*must be forced/i
12852
+ ],
12853
+ ["volume-in-use", /volume is in use/i],
12854
+ ["volume-not-found", /no such volume/i],
12855
+ ["network-in-use", /has active endpoints/i],
12856
+ ["network-not-found", /network .* not found/i]
12857
+ ],
12858
+ tmux: [
12859
+ ["session-exists", /duplicate session/i],
12860
+ [
12861
+ "server-not-running",
12862
+ /no server running|failed to connect to server|no sessions|server exited|lost server/i
12863
+ ],
12864
+ [
12865
+ "server-not-running",
12866
+ /error connecting to \/[^\n]* \((?:No such file or directory|Connection refused)\)/i
12867
+ ],
12868
+ ["session-not-found", /can't find (?:session|window|pane)|session not found/i]
12869
+ ]
12870
+ };
12871
+ var ALL_TOOLS = Object.keys(TOOL_RULES);
12872
+ var SHARED_RULES = [
12873
+ ["disk-full", /no space left|enospc|disk quota exceeded/i],
12874
+ ["auth-failed", /authentication (?:failed|required)|could not read (?:username|password)/i],
12875
+ ["auth-failed", /terminal prompts disabled|invalid username or password|bad credentials/i],
12876
+ ["auth-failed", /permission denied \(|permission to \S+ denied|host key verification failed/i],
12877
+ ["auth-failed", /gh auth login|not logged in|unauthorized|http 401|returned error: 40[13]/i],
12878
+ ["network-failed", /could not resolve host|connection (?:timed out|refused|reset)/i],
12879
+ ["network-failed", /network is unreachable|no route to host|temporary failure in name/i],
12880
+ ["network-failed", /early eof|failed to connect|remote end hung up/i],
12881
+ ["network-failed", /unable to access ['"]?https?:\/\//i],
12882
+ ["network-failed", /tls handshake|i\/o timeout/i],
12883
+ [
12884
+ "network-failed",
12885
+ /error connecting to (?:https?:\/\/)?[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?(?::\d+)?(?:[\s/:]|$)/i
12886
+ ],
12887
+ ["port-in-use", /port is already allocated|address already in use/i],
12888
+ ["permission-denied", /permission denied|operation not permitted|read-only file system/i],
12889
+ ["command-not-found", /command not found/i],
12890
+ ["path-not-found", /no such file or directory/i],
12891
+ ["invalid-usage", /^usage: |unknown (?:option|flag|command|shorthand flag)|invalid option/im]
12892
+ ];
12893
+ var TOOL_EXIT_CODES = {
12894
+ git: { 129: "invalid-usage" },
12895
+ gh: { 2: "aborted", 4: "auth-failed" },
12896
+ docker: { 125: "daemon-error" },
12897
+ tmux: {}
12898
+ };
12899
+ var SHARED_EXIT_CODES = {
12900
+ 124: "timed-out",
12901
+ 126: "not-executable",
12902
+ 127: "command-not-found",
12903
+ 137: "killed",
12904
+ 143: "killed"
12905
+ };
12906
+ function read2(target, key) {
12907
+ return target[key];
12908
+ }
12909
+ function boundedForMatching(text) {
12910
+ if (text.length <= MAX_MATCHED_CHARS)
12911
+ return text;
12912
+ const half = MAX_MATCHED_CHARS / 2;
12913
+ return `${text.slice(0, half)}
12914
+ ${text.slice(-half)}`;
12915
+ }
12916
+ function failureText(error) {
12917
+ const stderr = read2(error, "stderr");
12918
+ if (Buffer.isBuffer(stderr) && stderr.length > 0) {
12919
+ return boundedForMatching(stderr.subarray(-MAX_MATCHED_CHARS).toString());
12920
+ }
12921
+ if (typeof stderr === "string" && stderr.length > 0)
12922
+ return boundedForMatching(stderr);
12923
+ const message = read2(error, "message");
12924
+ if (typeof message !== "string")
12925
+ return "";
12926
+ return message.startsWith("Command failed") ? "" : boundedForMatching(message);
12927
+ }
12928
+ function isRawSpawnEnoent(error) {
12929
+ const syscall = read2(error, "syscall");
12930
+ return read2(error, "code") === "ENOENT" && typeof syscall === "string" && /^(?:spawn(?:Sync)?(?:\s|$)|posix_spawnp?$)/.test(syscall);
12931
+ }
12932
+ function classifiedReason(error, exitCode, signal, options) {
12933
+ if (read2(error, "aborted") === true)
12934
+ return "aborted";
12935
+ if (read2(error, "outputLimitExceeded") === true)
12936
+ return "output-too-large";
12937
+ if (read2(error, "timedOut") === true)
12938
+ return "timed-out";
12939
+ if (read2(error, "executableMissing") === true || isRawSpawnEnoent(error)) {
12940
+ return "executable-missing";
12941
+ }
12942
+ const named = exitCode === null ? undefined : options.exitCodes?.[exitCode];
12943
+ if (named)
12944
+ return named;
12945
+ if (signal)
12946
+ return "killed";
12947
+ const text = failureText(error);
12948
+ for (const tool of options.tools ?? ALL_TOOLS) {
12949
+ for (const [reason, pattern] of TOOL_RULES[tool]) {
12950
+ if (pattern.test(text))
12951
+ return reason;
12952
+ }
12953
+ }
12954
+ for (const [reason, pattern] of SHARED_RULES) {
12955
+ if (pattern.test(text))
12956
+ return reason;
12957
+ }
12958
+ if (exitCode !== null) {
12959
+ for (const tool of options.tools ?? []) {
12960
+ const reason = TOOL_EXIT_CODES[tool][exitCode];
12961
+ if (reason)
12962
+ return reason;
12963
+ }
12964
+ const reason = SHARED_EXIT_CODES[exitCode];
12965
+ if (reason)
12966
+ return reason;
12967
+ }
12968
+ return "unclassified";
12969
+ }
12970
+ function numericExitCode(error) {
12971
+ for (const key of ["exitCode", "code"]) {
12972
+ const value = read2(error, key);
12973
+ if (typeof value === "number" && Number.isFinite(value))
12974
+ return value;
12975
+ }
12976
+ return null;
12977
+ }
12978
+ function classifyCommandFailure(error, options = {}) {
12979
+ if (typeof error !== "object" || error === null) {
12980
+ return { reason: "unclassified", exitCode: null, signal: null };
12981
+ }
12982
+ try {
12983
+ const exitCode = numericExitCode(error);
12984
+ const rawSignal = read2(error, "signal");
12985
+ const signal = typeof rawSignal === "string" && SIGNAL_PATTERN.test(rawSignal) ? rawSignal : null;
12986
+ return { reason: classifiedReason(error, exitCode, signal, options), exitCode, signal };
12987
+ } catch {
12988
+ return { reason: "unclassified", exitCode: null, signal: null };
12989
+ }
12990
+ }
12991
+
12992
+ // ../protocol/src/node/lost-exit-reaper.ts
12993
+ import { createRequire } from "node:module";
12994
+
12995
+ // ../protocol/src/node/shell-process-state.ts
12996
+ import { readdirSync, readFileSync as readFileSync3 } from "node:fs";
12997
+ import { constants as osConstants } from "node:os";
12998
+ var PROCESS_INSPECTION_OPTIONS = {
12999
+ timeout: 100,
13000
+ killSignal: "SIGKILL",
13001
+ maxBuffer: 1024 * 1024
13002
+ };
13003
+ function bunRuntime() {
13004
+ return globalThis.Bun;
13005
+ }
13006
+ function decodeWaitStatus(status) {
13007
+ const signalNumber = status & 127;
13008
+ if (signalNumber === 0)
13009
+ return { code: status >> 8 & 255, signal: null };
13010
+ const name = Object.entries(osConstants.signals).find(([, value]) => value === signalNumber)?.[0];
13011
+ return { code: null, signal: name ?? "SIGKILL" };
13012
+ }
13013
+ function readZombieExit(pid) {
13014
+ try {
13015
+ const result = bunRuntime()?.spawnSync(["/bin/ps", "-o", "stat=,xstat=", "-p", String(pid)], PROCESS_INSPECTION_OPTIONS);
13016
+ if (!result?.success)
13017
+ return;
13018
+ const { stdout } = result;
13019
+ const match = /^Z\S*\s+([0-9a-f]+)\s*$/i.exec(stdout.toString().trim());
13020
+ return match ? decodeWaitStatus(Number.parseInt(match[1], 16)) : undefined;
13021
+ } catch {
13022
+ return;
13023
+ }
13024
+ }
13025
+ var EXIT_WATCH_MS = 1000;
13026
+ var EXIT_WATCH_MAX_MS = 16000;
13027
+ function watchForLostExit(pid, onExit) {
13028
+ if (process.platform !== "darwin" || pid === undefined || !bunRuntime())
13029
+ return () => {
13030
+ return;
13031
+ };
13032
+ let timer;
13033
+ const watch = (delayMs) => {
13034
+ timer = setTimeout(() => {
13035
+ const exit = readZombieExit(pid);
13036
+ if (exit)
13037
+ onExit(exit);
13038
+ else
13039
+ watch(Math.min(delayMs * 2, EXIT_WATCH_MAX_MS));
13040
+ }, delayMs);
13041
+ };
13042
+ watch(EXIT_WATCH_MS);
13043
+ return () => clearTimeout(timer);
13044
+ }
13045
+ function isLiveMember(state, groupId, pgid) {
13046
+ return Number(groupId) === pgid && state !== undefined && !/^[ZX]/.test(state);
13047
+ }
13048
+ function linuxGroupHasLiveMember(pgid) {
13049
+ for (const entry of readdirSync("/proc")) {
13050
+ if (!/^\d+$/.test(entry))
13051
+ continue;
13052
+ let stat;
13053
+ try {
13054
+ stat = readFileSync3(`/proc/${entry}/stat`, "latin1");
13055
+ } catch {
13056
+ continue;
13057
+ }
13058
+ const [state, , groupId] = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
13059
+ if (isLiveMember(state, groupId, pgid))
13060
+ return true;
13061
+ }
13062
+ return false;
13063
+ }
13064
+ function psGroupHasLiveMember(pgid) {
13065
+ const result = bunRuntime()?.spawnSync(["/bin/ps", "-A", "-o", "pgid=,stat="], PROCESS_INSPECTION_OPTIONS);
13066
+ if (!result?.success)
13067
+ return true;
13068
+ return result.stdout.toString().split(`
13069
+ `).some((line) => {
13070
+ const [groupId, state] = line.trim().split(/\s+/);
13071
+ return isLiveMember(state, groupId, pgid);
13072
+ });
13073
+ }
13074
+ function groupHasLiveMember(pgid) {
13075
+ try {
13076
+ return process.platform === "linux" ? linuxGroupHasLiveMember(pgid) : psGroupHasLiveMember(pgid);
13077
+ } catch {
13078
+ return true;
13079
+ }
13080
+ }
13081
+
13082
+ // ../protocol/src/node/lost-exit-reaper.ts
13083
+ var log7 = createLogger("process");
13084
+ var REAP_GRACE_MS = 2000;
13085
+ var REAP_MAX_CHECK_MS = 30000;
13086
+ var REAP_MAX_CHECKS = 12;
13087
+ var REAP_MAX_PENDING = 256;
13088
+ function createLostExitReaper(options) {
13089
+ const { system } = options;
13090
+ const graceMs = options.graceMs ?? REAP_GRACE_MS;
13091
+ const maxCheckMs = options.maxCheckMs ?? REAP_MAX_CHECK_MS;
13092
+ const maxChecks = options.maxChecks ?? REAP_MAX_CHECKS;
13093
+ const maxPending = options.maxPending ?? REAP_MAX_PENDING;
13094
+ const pending = new Map;
13095
+ let reaped = 0;
13096
+ let abandoned = 0;
13097
+ const abandon = (pid, reason) => {
13098
+ abandoned += 1;
13099
+ log7.warn("child.reap-abandoned", { pid, reason });
13100
+ };
13101
+ const check = (pid, reported, startedAt) => {
13102
+ if (reported())
13103
+ return false;
13104
+ const found = system.inspect(pid);
13105
+ if (found === undefined)
13106
+ return true;
13107
+ if (found === "gone" || found.ppid !== system.selfPid)
13108
+ return false;
13109
+ if (!found.state.startsWith("Z"))
13110
+ return true;
13111
+ const result = system.waitNoHang(pid);
13112
+ if (result === pid) {
13113
+ reaped += 1;
13114
+ log7.info("child.reaped", { pid, waitedMs: Date.now() - startedAt });
13115
+ return false;
13116
+ }
13117
+ if (result === 0)
13118
+ return true;
13119
+ abandon(pid, "waitpid-failed");
13120
+ return false;
13121
+ };
13122
+ const schedule = (pid, reported, startedAt, delayMs, checks) => {
13123
+ const timer = setTimeout(() => {
13124
+ pending.delete(pid);
13125
+ let again;
13126
+ try {
13127
+ again = check(pid, reported, startedAt);
13128
+ } catch {
13129
+ again = true;
13130
+ }
13131
+ if (!again)
13132
+ return;
13133
+ if (checks + 1 >= maxChecks) {
13134
+ abandon(pid, "not-a-zombie");
13135
+ return;
13136
+ }
13137
+ schedule(pid, reported, startedAt, Math.min(delayMs * 2, maxCheckMs), checks + 1);
13138
+ }, delayMs);
13139
+ timer.unref?.();
13140
+ pending.set(pid, timer);
13141
+ };
13142
+ return {
13143
+ reap(pid, reported) {
13144
+ if (!Number.isSafeInteger(pid) || pid <= 1 || pid === system.selfPid)
13145
+ return;
13146
+ if (pending.has(pid) || reported())
13147
+ return;
13148
+ if (pending.size >= maxPending) {
13149
+ abandon(pid, "capacity");
13150
+ return;
13151
+ }
13152
+ schedule(pid, reported, Date.now(), graceMs, 0);
13153
+ },
13154
+ stats: () => ({ pending: pending.size, reaped, abandoned }),
13155
+ stop() {
13156
+ for (const timer of pending.values())
13157
+ clearTimeout(timer);
13158
+ pending.clear();
13159
+ }
13160
+ };
13161
+ }
13162
+ var WNOHANG = 1;
13163
+ function loadDarwinWaitpid(loadFfi = () => createRequire(import.meta.url)("bun:ffi")) {
13164
+ try {
13165
+ const { dlopen, FFIType } = loadFfi();
13166
+ const libSystem = dlopen("/usr/lib/libSystem.B.dylib", {
13167
+ waitpid: { args: [FFIType.i32, FFIType.ptr, FFIType.i32], returns: FFIType.i32 }
13168
+ });
13169
+ const status = new Int32Array(1);
13170
+ return (pid) => libSystem.symbols.waitpid(pid, status, WNOHANG);
13171
+ } catch {
13172
+ return;
13173
+ }
13174
+ }
13175
+ function darwinReaperSystem(loadFfi) {
13176
+ const waitNoHang = loadDarwinWaitpid(loadFfi);
13177
+ if (!waitNoHang)
13178
+ return;
13179
+ return {
13180
+ selfPid: process.pid,
13181
+ inspect(pid) {
13182
+ const result = bunRuntime()?.spawnSync(["/bin/ps", "-o", "ppid=,stat=", "-p", String(pid)], PROCESS_INSPECTION_OPTIONS);
13183
+ if (!result)
13184
+ return;
13185
+ const output = result.stdout.toString().trim();
13186
+ if (!result.success)
13187
+ return result.exitCode === 1 && output === "" ? "gone" : undefined;
13188
+ const match = /^(\d+)\s+(\S+)$/.exec(output);
13189
+ return match ? { ppid: Number(match[1]), state: match[2] } : undefined;
13190
+ },
13191
+ waitNoHang
13192
+ };
13193
+ }
13194
+ var defaultReaper;
13195
+ function createDarwinLostExitReaper(loadFfi) {
13196
+ const system = darwinReaperSystem(loadFfi);
13197
+ if (!system)
13198
+ log7.warn("child.reap-unavailable");
13199
+ return system ? createLostExitReaper({ system }) : null;
13200
+ }
13201
+ function sharedReaper() {
13202
+ if (defaultReaper === undefined) {
13203
+ defaultReaper = createDarwinLostExitReaper();
13204
+ }
13205
+ return defaultReaper ?? undefined;
13206
+ }
13207
+ function reapAfterLostExit(pid, reported) {
13208
+ if (process.platform !== "darwin" || pid === undefined || !bunRuntime())
13209
+ return;
13210
+ sharedReaper()?.reap(pid, reported);
13211
+ }
13212
+
13213
+ // ../protocol/src/node/command-capture.ts
13214
+ class CommandFailedError extends Error {
13215
+ stdout;
13216
+ stdoutBytes;
13217
+ stderr;
13218
+ timedOut;
13219
+ outputCloseTimedOut;
13220
+ executableMissing;
13221
+ aborted;
13222
+ outputLimitExceeded;
13223
+ exitCode;
13224
+ signal;
13225
+ constructor(message, details = {}) {
13226
+ super(message);
13227
+ this.name = "CommandFailedError";
13228
+ this.stdout = details.stdout ?? "";
13229
+ this.stdoutBytes = details.stdoutBytes ?? Buffer.alloc(0);
13230
+ this.stderr = details.stderr ?? "";
13231
+ this.timedOut = details.timedOut ?? false;
13232
+ this.outputCloseTimedOut = details.outputCloseTimedOut ?? false;
13233
+ this.executableMissing = details.executableMissing ?? false;
13234
+ this.aborted = details.aborted ?? false;
13235
+ this.outputLimitExceeded = details.outputLimitExceeded ?? false;
13236
+ this.exitCode = details.exitCode ?? null;
13237
+ this.signal = details.signal ?? null;
13238
+ }
13239
+ toJSON() {
13240
+ return { ...formatLogError(this), ...classifyCommandFailure(this) };
13241
+ }
13242
+ [inspect.custom]() {
13243
+ const { name, reason, exitCode, signal, stack } = this.toJSON();
13244
+ const frames = stack?.length ? ` | ${stack.join(" | ")}` : "";
13245
+ return `${name} reason=${reason} exitCode=${exitCode} signal=${signal} outputOmitted=true${frames}`;
13246
+ }
13247
+ }
13248
+ function redactCommandValues(value, redactValues) {
13249
+ const secrets = Array.from(new Set((redactValues ?? []).filter((secret) => typeof secret === "string" && secret.length > 0))).sort((left, right) => right.length - left.length);
13250
+ return secrets.reduce((redacted, secret) => redacted.split(secret).join("[REDACTED]"), value);
13251
+ }
13252
+ var COMMAND_ABORTED_MESSAGE = "Command aborted";
13253
+ var OUTPUT_LIMIT_MESSAGE = "maxBuffer length exceeded";
13254
+ function commandFailureOutcome(error) {
13255
+ const details = error ?? {};
13256
+ const message = typeof details.message === "string" ? details.message : "";
13257
+ return {
13258
+ timedOut: details.killed === true,
13259
+ executableMissing: details.code === "ENOENT",
13260
+ aborted: message === COMMAND_ABORTED_MESSAGE,
13261
+ outputLimitExceeded: details.outputLimitExceeded === true,
13262
+ exitCode: typeof details.code === "number" ? details.code : null,
13263
+ signal: details.signal ?? null
13264
+ };
13265
+ }
13266
+ var commandInvocations = new Map;
13267
+ var commandCaptureMetrics;
13268
+ var commandObservers = new Map;
13269
+ function nonInteractiveGitEnv(env) {
13270
+ const merged = { ...env ?? process.env };
13271
+ merged.GIT_TERMINAL_PROMPT ??= "0";
13272
+ if (process.platform !== "win32") {
13273
+ merged.SSH_ASKPASS ??= "/usr/bin/false";
13274
+ merged.SSH_ASKPASS_REQUIRE ??= "force";
13275
+ }
13276
+ return merged;
13277
+ }
13278
+ var MAX_COMMAND_OUTPUT_BYTES = 50 * 1024 * 1024;
13279
+ var COMMAND_KILL_GRACE_MS = 100;
13280
+ var COMMAND_OUTPUT_CHECK_MS = 100;
13281
+ var COMMAND_GROUP_POLL_MS = 5;
13282
+ var COMMAND_GROUP_POLL_MAX_MS = 200;
13283
+ function openCaptureFile() {
13284
+ const filePath = path3.join(os.tmpdir(), `orkestrator-capture-${randomUUID2()}`);
13285
+ const fd = captureFs.openSync(filePath, fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_RDWR | fsConstants.O_APPEND, 384);
13286
+ try {
13287
+ captureFs.unlinkSync(filePath);
13288
+ return fd;
13289
+ } catch (error) {
13290
+ captureFs.closeSync(fd);
13291
+ throw error;
13292
+ }
13293
+ }
13294
+ function readCaptureFile(fd, limit) {
13295
+ const size = Math.min(captureFs.fstatSync(fd).size, limit);
13296
+ const buffer = Buffer.allocUnsafe(size);
13297
+ let offset = 0;
13298
+ while (offset < size) {
13299
+ const bytesRead = captureFs.readSync(fd, buffer, offset, size - offset, offset);
13300
+ if (bytesRead === 0)
13301
+ break;
13302
+ offset += bytesRead;
13303
+ }
13304
+ return buffer.subarray(0, offset);
13305
+ }
13306
+ function spawnCaptured(command, args, options, stdoutFd, stderrFd) {
13307
+ const payload = options.stdin?.length ? Buffer.from(options.stdin) : undefined;
13308
+ const env = command === "git" ? nonInteractiveGitEnv(options.env) : options.env ?? process.env;
13309
+ const detached = process.platform !== "win32";
13310
+ const bun = bunRuntime();
13311
+ if (bun) {
13312
+ const child = bun.spawn([command, ...args], {
13313
+ cwd: options.cwd,
13314
+ env,
13315
+ detached,
13316
+ windowsHide: true,
13317
+ stdin: payload ?? "pipe",
13318
+ stdout: stdoutFd,
13319
+ stderr: stderrFd
13320
+ });
13321
+ if (!payload)
13322
+ closeStdin(child.stdin);
13323
+ const current = () => ({ code: child.exitCode, signal: child.signalCode });
13324
+ return {
13325
+ pid: child.pid,
13326
+ exited: child.exited.then(current),
13327
+ current,
13328
+ kill: (signal) => child.kill(signal)
13329
+ };
13330
+ }
13331
+ const child = spawn(command, args, {
13332
+ cwd: options.cwd,
13333
+ env,
13334
+ detached,
13335
+ windowsHide: true,
13336
+ stdio: [payload ? "pipe" : "ignore", stdoutFd, stderrFd]
13337
+ });
13338
+ if (payload) {
13339
+ child.stdin?.on("error", () => {
13340
+ return;
13341
+ });
13342
+ child.stdin?.end(payload);
13343
+ }
13344
+ return {
13345
+ pid: child.pid,
13346
+ exited: new Promise((resolve, reject) => {
13347
+ child.once("exit", (code, signal) => resolve({ code, signal }));
13348
+ child.once("error", reject);
13349
+ }),
13350
+ current: () => ({ code: child.exitCode, signal: child.signalCode }),
13351
+ kill: (signal) => {
13352
+ child.kill(signal);
13353
+ }
13354
+ };
13355
+ }
13356
+ function closeStdin(stdin) {
13357
+ try {
13358
+ Promise.resolve(stdin.end()).catch(() => {
13359
+ return;
13360
+ });
13361
+ } catch {}
13362
+ }
13363
+ function exitReported(child) {
13364
+ const { code, signal } = child.current();
13365
+ return code !== null || signal !== null;
13366
+ }
13367
+ function signalCommand(child, signal) {
13368
+ if (child.pid === undefined)
13369
+ return;
13370
+ try {
13371
+ if (process.platform !== "win32") {
13372
+ process.kill(-child.pid, signal);
13373
+ } else {
13374
+ child.kill(signal);
13375
+ }
13376
+ } catch {}
13377
+ }
13378
+ function commandGroupAlive(child) {
13379
+ if (process.platform === "win32" || child.pid === undefined)
13380
+ return false;
13381
+ try {
13382
+ process.kill(-child.pid, 0);
13383
+ } catch (error) {
13384
+ if (error.code === "ESRCH")
13385
+ return false;
13386
+ }
13387
+ return groupHasLiveMember(child.pid);
13388
+ }
13389
+ function executeCommandBytes(command, args, options, timeoutMs, outputLimit, stderrLimit) {
13390
+ return new Promise((resolve, reject) => {
13391
+ if (options.signal?.aborted) {
13392
+ reject(Object.assign(new Error(COMMAND_ABORTED_MESSAGE), { killed: true }));
13393
+ return;
13394
+ }
13395
+ const captureFds = [];
13396
+ const releaseCaptureFds = () => {
13397
+ for (const fd of captureFds.splice(0)) {
13398
+ try {
13399
+ captureFs.closeSync(fd);
13400
+ } catch {}
13401
+ }
13402
+ };
13403
+ try {
13404
+ captureFds.push(openCaptureFile());
13405
+ captureFds.push(openCaptureFile());
13406
+ } catch (error) {
13407
+ releaseCaptureFds();
13408
+ const code = error.code ?? "unknown";
13409
+ reject(new Error(`Could not open a command output file in the temporary directory: ${code}`));
13410
+ return;
13411
+ }
13412
+ const [stdoutFd, stderrFd] = captureFds;
13413
+ let child;
13414
+ try {
13415
+ child = spawnCaptured(command, args, options, stdoutFd, stderrFd);
13416
+ } catch (error) {
13417
+ releaseCaptureFds();
13418
+ reject(error);
13419
+ return;
13420
+ }
13421
+ let settled = false;
13422
+ let timedOut = false;
13423
+ let timeoutTimer;
13424
+ let groupTimer;
13425
+ let limitTimer;
13426
+ let stopExitWatch = () => {};
13427
+ let commandExit;
13428
+ const finishCapture = () => {
13429
+ settled = true;
13430
+ clearTimeout(timeoutTimer);
13431
+ clearTimeout(groupTimer);
13432
+ clearInterval(limitTimer);
13433
+ stopExitWatch();
13434
+ options.signal?.removeEventListener("abort", abort);
13435
+ if (!exitReported(child))
13436
+ reapAfterLostExit(child.pid, () => exitReported(child));
13437
+ try {
13438
+ return {
13439
+ stdout: readCaptureFile(stdoutFd, outputLimit),
13440
+ stderr: readCaptureFile(stderrFd, stderrLimit)
13441
+ };
13442
+ } catch (error) {
13443
+ reject(error);
13444
+ return;
13445
+ } finally {
13446
+ releaseCaptureFds();
13447
+ }
13448
+ };
13449
+ const fail = (error) => {
13450
+ if (settled)
13451
+ return;
13452
+ const output = finishCapture();
13453
+ if (output)
13454
+ reject(Object.assign(error, { ...output, killed: timedOut }));
13455
+ };
13456
+ const abort = () => {
13457
+ timedOut = true;
13458
+ signalCommand(child, "SIGKILL");
13459
+ fail(new Error(COMMAND_ABORTED_MESSAGE));
13460
+ };
13461
+ options.signal?.addEventListener("abort", abort, { once: true });
13462
+ const checkOutputLimit = () => {
13463
+ const stream = captureFs.fstatSync(stdoutFd).size > outputLimit ? "stdout" : captureFs.fstatSync(stderrFd).size > stderrLimit ? "stderr" : undefined;
13464
+ if (stream === undefined)
13465
+ return false;
13466
+ signalCommand(child, "SIGKILL");
13467
+ fail(Object.assign(new Error(`${stream} ${OUTPUT_LIMIT_MESSAGE}`), {
13468
+ outputLimitExceeded: true
13469
+ }));
13470
+ return true;
13471
+ };
13472
+ const failIfOverLimit = () => {
13473
+ try {
13474
+ return checkOutputLimit();
13475
+ } catch (error) {
13476
+ signalCommand(child, "SIGKILL");
13477
+ fail(error instanceof Error ? error : new Error(String(error)));
13478
+ return true;
13479
+ }
13480
+ };
13481
+ limitTimer = setInterval(() => {
13482
+ if (!settled && !timedOut)
13483
+ failIfOverLimit();
13484
+ }, COMMAND_OUTPUT_CHECK_MS);
13485
+ const settleOnExit = () => {
13486
+ if (settled || timedOut || failIfOverLimit())
13487
+ return;
13488
+ if (commandExit?.code !== 0 || commandExit.signal !== null) {
13489
+ fail(Object.assign(new Error(`Command failed: ${[command, ...args].join(" ")}`), {
13490
+ code: commandExit?.code,
13491
+ signal: commandExit?.signal
13492
+ }));
13493
+ return;
13494
+ }
13495
+ const output = finishCapture();
13496
+ if (output)
13497
+ resolve(output);
13498
+ };
13499
+ const awaitGroupExit = (delayMs) => {
13500
+ if (settled || timedOut)
13501
+ return;
13502
+ if (commandGroupAlive(child)) {
13503
+ groupTimer = setTimeout(awaitGroupExit, delayMs, Math.min(delayMs * 2, COMMAND_GROUP_POLL_MAX_MS));
13504
+ return;
13505
+ }
13506
+ settleOnExit();
13507
+ };
13508
+ const onCommandExit = (exit) => {
13509
+ if (commandExit)
13510
+ return;
13511
+ commandExit = exit;
13512
+ stopExitWatch();
13513
+ if (options.waitForDescendants)
13514
+ awaitGroupExit(COMMAND_GROUP_POLL_MS);
13515
+ else
13516
+ settleOnExit();
13517
+ };
13518
+ child.exited.then(onCommandExit, (error) => fail(error instanceof Error ? error : new Error(String(error))));
13519
+ stopExitWatch = watchForLostExit(child.pid, (exit) => {
13520
+ if (!settled && !timedOut)
13521
+ onCommandExit(exit);
13522
+ });
13523
+ if (timeoutMs > 0) {
13524
+ timeoutTimer = setTimeout(() => {
13525
+ timedOut = true;
13526
+ signalCommand(child, "SIGTERM");
13527
+ timeoutTimer = setTimeout(() => {
13528
+ signalCommand(child, "SIGKILL");
13529
+ fail(Object.assign(new Error(`Command timed out after ${timeoutMs} ms`), {
13530
+ code: child.current().code,
13531
+ signal: child.current().signal
13532
+ }));
13533
+ }, COMMAND_KILL_GRACE_MS);
13534
+ }, timeoutMs);
13535
+ }
13536
+ });
13537
+ }
13538
+ async function runCommandBytes(command, args = [], options = {}) {
13539
+ const timeoutMs = options.timeoutMs ?? 60000;
13540
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > 2147483647) {
13541
+ throw new RangeError("timeoutMs must be an integer between 0 and 2147483647");
13542
+ }
13543
+ const outputLimit = options.maxOutputBytes ?? MAX_COMMAND_OUTPUT_BYTES;
13544
+ if (!Number.isSafeInteger(outputLimit) || outputLimit <= 0) {
13545
+ throw new RangeError("maxOutputBytes must be a positive integer");
13546
+ }
13547
+ const stderrLimit = options.maxStderrBytes ?? outputLimit;
13548
+ if (!Number.isSafeInteger(stderrLimit) || stderrLimit <= 0) {
13549
+ throw new RangeError("maxStderrBytes must be a positive integer");
13550
+ }
13551
+ if (commandInvocations.size < 64 || commandInvocations.has(command)) {
13552
+ commandInvocations.set(command, (commandInvocations.get(command) ?? 0) + 1);
13553
+ }
13554
+ for (const observer of commandObservers.get(command) ?? [])
13555
+ observer(args);
13556
+ commandCaptureMetrics?.started(command, args);
13557
+ try {
13558
+ const { stdout, stderr } = await executeCommandBytes(command, args, options, timeoutMs, outputLimit, stderrLimit);
13559
+ commandCaptureMetrics?.capturedBytes(stdout.length);
13560
+ return {
13561
+ stdout: Buffer.isBuffer(stdout) ? stdout : Buffer.from(stdout),
13562
+ stderr: Buffer.isBuffer(stderr) ? stderr : Buffer.from(stderr)
13563
+ };
13564
+ } catch (error) {
13565
+ const outcome = commandFailureOutcome(error);
13566
+ const redacting = options.redactValues?.some((value) => typeof value === "string" && value.length > 0);
13567
+ if (error && typeof error === "object" && "stdout" in error && "stderr" in error) {
13568
+ const withOutput = error;
13569
+ const stderr = withOutput.stderr?.toString() ?? "";
13570
+ const stdout = withOutput.stdout?.toString() ?? "";
13571
+ const message = (stderr || stdout || withOutput.message || "Command failed").trim();
13572
+ throw new CommandFailedError(redactCommandValues(message, options.redactValues), {
13573
+ ...outcome,
13574
+ stdout: redactCommandValues(stdout, options.redactValues),
13575
+ stderr: redactCommandValues(stderr, options.redactValues),
13576
+ ...!redacting && Buffer.isBuffer(withOutput.stdout) ? { stdoutBytes: withOutput.stdout } : {}
13577
+ });
13578
+ }
13579
+ if (redacting) {
13580
+ const message = error instanceof Error ? error.message : String(error);
13581
+ throw new CommandFailedError(redactCommandValues(message || "Command failed", options.redactValues), outcome);
13582
+ }
13583
+ if (outcome.timedOut || outcome.executableMissing) {
13584
+ const message = error instanceof Error ? error.message : String(error);
13585
+ throw new CommandFailedError(message || "Command failed", outcome);
13586
+ }
13587
+ throw error;
13588
+ }
13589
+ }
13590
+ async function runCommand(command, args = [], options = {}) {
13591
+ const { stdout, stderr } = await runCommandBytes(command, args, options);
13592
+ return {
13593
+ stdout: redactCommandValues(stdout.toString(), options.redactValues),
13594
+ stderr: redactCommandValues(stderr.toString(), options.redactValues)
13595
+ };
13596
+ }
13597
+
13598
+ // ../protocol/src/node/workspace-change-probe.ts
12560
13599
  var DEFAULT_MAX_UNTRACKED_FILE_BYTES = 2 * 1024 * 1024;
12561
13600
  var DEFAULT_MAX_UNTRACKED_FILES = 5000;
12562
13601
  var DEFAULT_SLOW_SNAPSHOT_MS = 500;
@@ -12574,27 +13613,16 @@ process.once("exit", () => {
12574
13613
  } catch {}
12575
13614
  }
12576
13615
  });
12577
- var runGit = (args, options) => new Promise((resolvePromise, reject) => {
12578
- const env = { ...process.env, ...options.env, GIT_OPTIONAL_LOCKS: "0" };
12579
- if (options.stdin === undefined) {
12580
- execFile3("git", args, { cwd: options.cwd, env, timeout: GIT_TIMEOUT_MS, maxBuffer: GIT_MAX_BUFFER }, (error, stdout) => error ? reject(error) : resolvePromise({ stdout: String(stdout) }));
12581
- return;
12582
- }
12583
- const child = spawn("git", args, { cwd: options.cwd, env, timeout: GIT_TIMEOUT_MS });
12584
- let stdout = "";
12585
- let stdoutBytes = 0;
12586
- child.stdout.setEncoding("utf8");
12587
- child.stdout.on("data", (chunk) => {
12588
- stdoutBytes += chunk.length;
12589
- if (stdoutBytes <= GIT_MAX_BUFFER)
12590
- stdout += chunk;
13616
+ var runGit = async (args, options) => {
13617
+ const { stdout } = await runCommand("git", args, {
13618
+ cwd: options.cwd,
13619
+ env: { ...process.env, ...options.env, GIT_OPTIONAL_LOCKS: "0" },
13620
+ timeoutMs: GIT_TIMEOUT_MS,
13621
+ maxOutputBytes: GIT_MAX_BUFFER,
13622
+ ...options.stdin === undefined ? {} : { stdin: options.stdin }
12591
13623
  });
12592
- child.stderr.resume();
12593
- child.on("error", reject);
12594
- child.on("close", (code) => code === 0 ? resolvePromise({ stdout }) : reject(new Error(`git exited with ${code}`)));
12595
- child.stdin.on("error", () => {});
12596
- child.stdin.end(options.stdin);
12597
- });
13624
+ return { stdout };
13625
+ };
12598
13626
 
12599
13627
  class WorkspaceChangeProbe {
12600
13628
  git;
@@ -12838,8 +13866,8 @@ class WorkspaceChangeProbe {
12838
13866
  return;
12839
13867
  return {
12840
13868
  root,
12841
- indexPath: isAbsolute2(index) ? index : resolve2(cwd, index),
12842
- objectsPath: isAbsolute2(objects) ? objects : resolve2(cwd, objects)
13869
+ indexPath: isAbsolute3(index) ? index : resolve3(cwd, index),
13870
+ objectsPath: isAbsolute3(objects) ? objects : resolve3(cwd, objects)
12843
13871
  };
12844
13872
  }).catch(() => {
12845
13873
  return;
@@ -12882,8 +13910,8 @@ class WorkspaceChangeProbe {
12882
13910
  return;
12883
13911
  const { root, indexPath } = repo.location;
12884
13912
  const started = this.now();
12885
- const tempIndex = join6(this.tempDir, `orkestrator-probe-${randomUUID2()}.index`);
12886
- const objectDirectory = await mkdtemp2(join6(this.tempDir, "orkestrator-probe-objects-"));
13913
+ const tempIndex = join7(this.tempDir, `orkestrator-probe-${randomUUID3()}.index`);
13914
+ const objectDirectory = await mkdtemp2(join7(this.tempDir, "orkestrator-probe-objects-"));
12887
13915
  temporaryObjectDirectories.add(objectDirectory);
12888
13916
  let retained = false;
12889
13917
  try {
@@ -12900,7 +13928,7 @@ class WorkspaceChangeProbe {
12900
13928
  const included = [];
12901
13929
  const skipped = new Map;
12902
13930
  for (const path of untracked) {
12903
- const stats = await lstat(join6(root, path)).catch(() => {
13931
+ const stats = await lstat(join7(root, path)).catch(() => {
12904
13932
  return;
12905
13933
  });
12906
13934
  if (!stats)
@@ -13046,20 +14074,20 @@ function parseNumstatZ(output) {
13046
14074
  }
13047
14075
 
13048
14076
  // ../../bridges/claude-bridge/src/services/command-changes.ts
13049
- import { join as join9 } from "node:path";
14077
+ import { join as join10 } from "node:path";
13050
14078
 
13051
14079
  // ../../bridges/claude-bridge/src/services/change-evidence.ts
13052
14080
  import { createHash as createHash8 } from "node:crypto";
13053
14081
  import {
13054
- closeSync,
14082
+ closeSync as closeSync2,
13055
14083
  existsSync as existsSync2,
13056
14084
  mkdirSync,
13057
- openSync,
13058
- readFileSync as readFileSync4,
14085
+ openSync as openSync2,
14086
+ readFileSync as readFileSync5,
13059
14087
  rmSync as rmSync2,
13060
14088
  writeSync
13061
14089
  } from "node:fs";
13062
- import { join as join8 } from "node:path";
14090
+ import { join as join9 } from "node:path";
13063
14091
 
13064
14092
  // ../protocol/src/field-validation.ts
13065
14093
  function isPlainRecord(value) {
@@ -13462,10 +14490,10 @@ function workspaceObservationReportIssues(value) {
13462
14490
  }
13463
14491
 
13464
14492
  // ../protocol/src/node/change-tracking/evidence-spool.ts
13465
- import { createHash as createHash7, randomUUID as randomUUID3 } from "node:crypto";
13466
- import { readdirSync, readFileSync as readFileSync3 } from "node:fs";
14493
+ import { createHash as createHash7, randomUUID as randomUUID4 } from "node:crypto";
14494
+ import { readdirSync as readdirSync2, readFileSync as readFileSync4 } from "node:fs";
13467
14495
  import { appendFile as appendFile2, mkdir as mkdir4, rename as rename4, rm as rm5, writeFile as writeFile4 } from "node:fs/promises";
13468
- import { join as join7 } from "node:path";
14496
+ import { join as join8 } from "node:path";
13469
14497
  var DEFAULT_EVIDENCE_SPOOL_LIMITS = {
13470
14498
  maxEntries: 2048,
13471
14499
  maxEntryBytes: 256 * 1024,
@@ -13508,7 +14536,7 @@ class ChangeEvidenceSpool {
13508
14536
  restoring = false;
13509
14537
  constructor(options = {}) {
13510
14538
  this.limits = { ...DEFAULT_EVIDENCE_SPOOL_LIMITS, ...options.limits };
13511
- this.runtimeEpoch = options.runtimeEpoch ?? randomUUID3();
14539
+ this.runtimeEpoch = options.runtimeEpoch ?? randomUUID4();
13512
14540
  this.directory = options.directory;
13513
14541
  if (this.directory) {
13514
14542
  this.restoring = true;
@@ -13611,7 +14639,7 @@ class ChangeEvidenceSpool {
13611
14639
  return;
13612
14640
  if (this.entries.length >= this.limits.maxEntries - 1)
13613
14641
  return;
13614
- const gapId = randomUUID3();
14642
+ const gapId = randomUUID4();
13615
14643
  const coverage = this.droppedUnknown ? {
13616
14644
  kind: "unknown-range",
13617
14645
  bindingId: this.gapBindingId || "unknown",
@@ -13728,7 +14756,7 @@ class ChangeEvidenceSpool {
13728
14756
  const lines = this.pendingLines.splice(0).join("");
13729
14757
  this.enqueueIo(async () => {
13730
14758
  await mkdir4(directory, { recursive: true, mode: 448 });
13731
- await appendFile2(join7(directory, ENTRIES_FILE), lines, { mode: 384 });
14759
+ await appendFile2(join8(directory, ENTRIES_FILE), lines, { mode: 384 });
13732
14760
  });
13733
14761
  }
13734
14762
  persistBody(id, bytes) {
@@ -13736,9 +14764,9 @@ class ChangeEvidenceSpool {
13736
14764
  if (!directory || this.restoring)
13737
14765
  return;
13738
14766
  this.enqueueIo(async () => {
13739
- const bodies = join7(directory, BODY_DIRECTORY);
14767
+ const bodies = join8(directory, BODY_DIRECTORY);
13740
14768
  await mkdir4(bodies, { recursive: true, mode: 448 });
13741
- await writeFile4(join7(bodies, bodyFileName(id)), bytes, { mode: 384, flag: "wx" }).catch((error) => {
14769
+ await writeFile4(join8(bodies, bodyFileName(id)), bytes, { mode: 384, flag: "wx" }).catch((error) => {
13742
14770
  if (error.code !== "EEXIST")
13743
14771
  throw error;
13744
14772
  });
@@ -13748,7 +14776,7 @@ class ChangeEvidenceSpool {
13748
14776
  const directory = this.directory;
13749
14777
  if (!directory)
13750
14778
  return;
13751
- this.enqueueIo(() => rm5(join7(directory, BODY_DIRECTORY, bodyFileName(id)), { force: true }));
14779
+ this.enqueueIo(() => rm5(join8(directory, BODY_DIRECTORY, bodyFileName(id)), { force: true }));
13752
14780
  }
13753
14781
  compactPersisted() {
13754
14782
  const directory = this.directory;
@@ -13759,7 +14787,7 @@ class ChangeEvidenceSpool {
13759
14787
  `);
13760
14788
  this.enqueueIo(async () => {
13761
14789
  await mkdir4(directory, { recursive: true, mode: 448 });
13762
- const file = join7(directory, ENTRIES_FILE);
14790
+ const file = join8(directory, ENTRIES_FILE);
13763
14791
  const temp = `${file}.${process.pid}.tmp`;
13764
14792
  await writeFile4(temp, body ? `${body}
13765
14793
  ` : "", { mode: 384 });
@@ -13771,10 +14799,10 @@ class ChangeEvidenceSpool {
13771
14799
  await this.io;
13772
14800
  }
13773
14801
  restore(directory) {
13774
- const bodyDirectory = join7(directory, BODY_DIRECTORY);
14802
+ const bodyDirectory = join8(directory, BODY_DIRECTORY);
13775
14803
  try {
13776
- for (const name of readdirSync(bodyDirectory)) {
13777
- const bytes = new Uint8Array(readFileSync3(join7(bodyDirectory, name)));
14804
+ for (const name of readdirSync2(bodyDirectory)) {
14805
+ const bytes = new Uint8Array(readFileSync4(join8(bodyDirectory, name)));
13778
14806
  const id = evidenceBodyId(bytes);
13779
14807
  if (bodyFileName(id) !== name)
13780
14808
  continue;
@@ -13786,7 +14814,7 @@ class ChangeEvidenceSpool {
13786
14814
  } catch {}
13787
14815
  let text = "";
13788
14816
  try {
13789
- text = readFileSync3(join7(directory, ENTRIES_FILE), "utf8");
14817
+ text = readFileSync4(join8(directory, ENTRIES_FILE), "utf8");
13790
14818
  } catch {
13791
14819
  return;
13792
14820
  }
@@ -14167,14 +15195,14 @@ function record(value) {
14167
15195
  function text(value) {
14168
15196
  return typeof value === "string" ? value : undefined;
14169
15197
  }
14170
- function path3(value) {
15198
+ function path4(value) {
14171
15199
  return typeof value === "string" && value.length > 0 ? value : undefined;
14172
15200
  }
14173
15201
  function claudeProposalEvidence(toolName, input) {
14174
15202
  const fields = record(input);
14175
15203
  switch (toolName) {
14176
15204
  case "Edit": {
14177
- const filePath = path3(fields.file_path);
15205
+ const filePath = path4(fields.file_path);
14178
15206
  if (!filePath)
14179
15207
  return [];
14180
15208
  return [
@@ -14192,7 +15220,7 @@ function claudeProposalEvidence(toolName, input) {
14192
15220
  ];
14193
15221
  }
14194
15222
  case "MultiEdit": {
14195
- const filePath = path3(fields.file_path);
15223
+ const filePath = path4(fields.file_path);
14196
15224
  if (!filePath || !Array.isArray(fields.edits))
14197
15225
  return [];
14198
15226
  return fields.edits.map((edit, index) => {
@@ -14211,7 +15239,7 @@ function claudeProposalEvidence(toolName, input) {
14211
15239
  });
14212
15240
  }
14213
15241
  case "Write": {
14214
- const filePath = path3(fields.file_path);
15242
+ const filePath = path4(fields.file_path);
14215
15243
  if (!filePath)
14216
15244
  return [];
14217
15245
  return [
@@ -14229,7 +15257,7 @@ function claudeProposalEvidence(toolName, input) {
14229
15257
  ];
14230
15258
  }
14231
15259
  case "NotebookEdit": {
14232
- const filePath = path3(fields.notebook_path);
15260
+ const filePath = path4(fields.notebook_path);
14233
15261
  if (!filePath)
14234
15262
  return [];
14235
15263
  const deleting = fields.edit_mode === "delete";
@@ -14298,20 +15326,20 @@ function createChangeEvidence(options) {
14298
15326
  };
14299
15327
  }
14300
15328
  function claimSpoolDirectory(root = claudeChangeEvidenceDir(), scope = process.env.CWD || process.cwd()) {
14301
- const directory = join8(root, createHash8("sha256").update(scope).digest("hex").slice(0, 32));
14302
- const owner = join8(directory, "owner.pid");
15329
+ const directory = join9(root, createHash8("sha256").update(scope).digest("hex").slice(0, 32));
15330
+ const owner = join9(directory, "owner.pid");
14303
15331
  try {
14304
15332
  mkdirSync(directory, { recursive: true, mode: 448 });
14305
15333
  for (let attempt = 0;attempt < 2; attempt++) {
14306
15334
  try {
14307
- const fd = openSync(owner, "wx", 384);
15335
+ const fd = openSync2(owner, "wx", 384);
14308
15336
  writeSync(fd, ownerFileContents());
14309
- closeSync(fd);
15337
+ closeSync2(fd);
14310
15338
  return directory;
14311
15339
  } catch (error) {
14312
15340
  if (error.code !== "EEXIST")
14313
15341
  return;
14314
- const holder = parseOwnerFile(readFileSync4(owner, "utf8"));
15342
+ const holder = parseOwnerFile(readFileSync5(owner, "utf8"));
14315
15343
  if (holder) {
14316
15344
  const state = recordedOwnerState(holder, { slowPath: true });
14317
15345
  if (state === "current")
@@ -14482,6 +15510,9 @@ function claudeEvidenceTurnId(turn) {
14482
15510
 
14483
15511
  // ../../bridges/claude-bridge/src/services/command-changes.ts
14484
15512
  var commandChangeProbe = new WorkspaceChangeProbe;
15513
+ function discardCommandChangeWindow(toolUseId) {
15514
+ commandChangeProbe.discard(toolUseId);
15515
+ }
14485
15516
  var COMMAND_CHANGE_HOOK_MATCHER = "^(Bash|Edit|Write|MultiEdit|NotebookEdit)$";
14486
15517
  var COMMAND_CHANGE_HOOK_TIMEOUT_SECONDS = 60;
14487
15518
  var MAX_CACHED_JOURNALS = 64;
@@ -14494,7 +15525,7 @@ function commandChangeJournal(sdkSessionId) {
14494
15525
  if (journal) {
14495
15526
  journals.delete(sdkSessionId);
14496
15527
  } else {
14497
- journal = new CommandChangeJournal(join9(claudeCommandChangesDir(), `${sdkSessionId}.jsonl`));
15528
+ journal = new CommandChangeJournal(join10(claudeCommandChangesDir(), `${sdkSessionId}.jsonl`));
14498
15529
  }
14499
15530
  journals.set(sdkSessionId, journal);
14500
15531
  while (journals.size > MAX_CACHED_JOURNALS) {
@@ -15261,17 +16292,17 @@ class ClaudeAttachmentError extends Error {
15261
16292
  var BRIDGE_ATTACHMENT_ROOT_ENV = "ORKESTRATOR_BRIDGE_ATTACHMENT_ROOT";
15262
16293
  function configuredAttachmentRoot(env = process.env) {
15263
16294
  const value = env[BRIDGE_ATTACHMENT_ROOT_ENV]?.trim();
15264
- return value && isAbsolute3(value) ? resolve3(value) : undefined;
16295
+ return value && isAbsolute4(value) ? resolve4(value) : undefined;
15265
16296
  }
15266
16297
  function attachmentContainmentRoot(filePath, cwd, extraRoot = configuredAttachmentRoot()) {
15267
- if (extraRoot && isAbsolute3(filePath) && isPathWithin2(extraRoot, resolve3(filePath))) {
16298
+ if (extraRoot && isAbsolute4(filePath) && isPathWithin2(extraRoot, resolve4(filePath))) {
15268
16299
  return extraRoot;
15269
16300
  }
15270
- return resolve3(cwd);
16301
+ return resolve4(cwd);
15271
16302
  }
15272
16303
  function isPathWithin2(rootPath, targetPath) {
15273
16304
  const childPath = relative(rootPath, targetPath);
15274
- return childPath === "" || childPath !== ".." && !childPath.startsWith(`..${sep}`) && !isAbsolute3(childPath);
16305
+ return childPath === "" || childPath !== ".." && !childPath.startsWith(`..${sep2}`) && !isAbsolute4(childPath);
15275
16306
  }
15276
16307
  function attachmentErrorForFsFailure(error) {
15277
16308
  const code = error?.code;
@@ -15286,8 +16317,8 @@ function attachmentErrorForFsFailure(error) {
15286
16317
  async function assertNoSymlinkComponents(lexicalRoot, targetPath) {
15287
16318
  const childPath = relative(lexicalRoot, targetPath);
15288
16319
  let currentPath = lexicalRoot;
15289
- for (const segment of childPath.split(sep).filter(Boolean)) {
15290
- currentPath = join10(currentPath, segment);
16320
+ for (const segment of childPath.split(sep2).filter(Boolean)) {
16321
+ currentPath = join11(currentPath, segment);
15291
16322
  const stats = await lstat2(currentPath).catch((error) => {
15292
16323
  throw attachmentErrorForFsFailure(error);
15293
16324
  });
@@ -15315,7 +16346,7 @@ async function assertOpenedWorkspaceFile(targetPath, canonicalRoot, openedStats)
15315
16346
  }
15316
16347
  async function readWorkspaceImageAttachment(filePath, cwd, afterSymlinkValidation, afterCanonicalValidation, afterInitialValidation) {
15317
16348
  const lexicalRoot = attachmentContainmentRoot(filePath, cwd);
15318
- const targetPath = isAbsolute3(filePath) ? resolve3(filePath) : resolve3(lexicalRoot, filePath);
16349
+ const targetPath = isAbsolute4(filePath) ? resolve4(filePath) : resolve4(lexicalRoot, filePath);
15319
16350
  if (!isPathWithin2(lexicalRoot, targetPath)) {
15320
16351
  throw new ClaudeAttachmentError("attachment_outside_workspace", "Image attachment must be contained in the current workspace.");
15321
16352
  }
@@ -16345,7 +17376,7 @@ function reconcileClaudeUsage(terminal, streamed) {
16345
17376
  }
16346
17377
 
16347
17378
  // ../../bridges/claude-bridge/src/services/session-manager-prompt-turn-lifecycle.ts
16348
- var log7 = createLogger("bridge.claude");
17379
+ var log8 = createLogger("bridge.claude");
16349
17380
  function diagnosticErrorClass(error) {
16350
17381
  try {
16351
17382
  if (!(error instanceof Error))
@@ -16414,7 +17445,7 @@ async function reconcilePlanModeFromStatus(turn, reported) {
16414
17445
  try {
16415
17446
  await applySessionPlanMode(session, false);
16416
17447
  } catch (error) {
16417
- log7.warn("plan-mode.record-failed", { sessionId, errorClass: diagnosticErrorClass(error) });
17448
+ log8.warn("plan-mode.record-failed", { sessionId, errorClass: diagnosticErrorClass(error) });
16418
17449
  }
16419
17450
  }
16420
17451
  function setCompletionBlockedByBackgroundTasks(turn, blocked) {
@@ -16579,6 +17610,7 @@ function captureTurnStartup(session) {
16579
17610
  turnStartedAt: session.turnStartedAt,
16580
17611
  abortController: session.abortController,
16581
17612
  error: session.error,
17613
+ errorCode: session.errorCode,
16582
17614
  interruption: session.interruption,
16583
17615
  interruptedRequestId: session.interruptedRequestId,
16584
17616
  lastActivity: session.lastActivity,
@@ -16638,6 +17670,7 @@ function createTurnState(session, sessionId, init) {
16638
17670
  receivedPromptResult: false,
16639
17671
  settlingResult: false,
16640
17672
  localCommandOutputSeen: false,
17673
+ rateLimitRejected: false,
16641
17674
  lastThinkingTokensEmitAt: 0,
16642
17675
  compactedTokensBefore: undefined,
16643
17676
  pendingPlanRejectionFeedback: null,
@@ -16657,7 +17690,7 @@ function createTurnState(session, sessionId, init) {
16657
17690
  }
16658
17691
 
16659
17692
  // ../../bridges/claude-bridge/src/services/session-manager-prompt-admission.ts
16660
- var log8 = createLogger("bridge.claude");
17693
+ var log9 = createLogger("bridge.claude");
16661
17694
  var STREAM_EVENT_COALESCE_MS = 100;
16662
17695
  function admitPrompt(sessionId, options) {
16663
17696
  const session = sessions.get(sessionId);
@@ -16752,6 +17785,7 @@ async function applyPromptPlanMode(admission, planMode) {
16752
17785
  session.status = beforeStartup.status;
16753
17786
  session.turnStartedAt = beforeStartup.turnStartedAt;
16754
17787
  session.error = beforeStartup.error;
17788
+ session.errorCode = beforeStartup.errorCode;
16755
17789
  session.interruption = beforeStartup.interruption;
16756
17790
  session.interruptedRequestId = beforeStartup.interruptedRequestId;
16757
17791
  session.lastActivity = beforeStartup.lastActivity;
@@ -16773,6 +17807,7 @@ async function applyPromptPlanMode(admission, planMode) {
16773
17807
  function beginPromptActivity(admission) {
16774
17808
  const { session, sessionId } = admission;
16775
17809
  session.error = undefined;
17810
+ session.errorCode = undefined;
16776
17811
  session.interruption = undefined;
16777
17812
  session.interruptedRequestId = undefined;
16778
17813
  session.lastActivity = new Date;
@@ -16790,7 +17825,7 @@ async function readTranscriptForPrompt(session) {
16790
17825
  try {
16791
17826
  return await readPersistedSessionMessagesOnce(session);
16792
17827
  } catch (error) {
16793
- log8.warn("transcript.hydrate-failed", { error: formatLogError(error, { stack: false }) });
17828
+ log9.warn("transcript.hydrate-failed", { error: formatLogError(error, { stack: false }) });
16794
17829
  return TRANSCRIPT_READ_FAILED;
16795
17830
  }
16796
17831
  }
@@ -16877,7 +17912,7 @@ import { query as query2 } from "@anthropic-ai/claude-agent-sdk";
16877
17912
 
16878
17913
  // ../../bridges/claude-bridge/src/services/mcp-config.ts
16879
17914
  import { createHash as createHash9 } from "node:crypto";
16880
- import { join as join11 } from "node:path";
17915
+ import { join as join12 } from "node:path";
16881
17916
 
16882
17917
  // ../protocol/src/agent-mail.ts
16883
17918
  var AGENT_MAIL_MAX_BODY_BYTES = 32 * 1024;
@@ -16945,7 +17980,7 @@ var ORKESTRATOR_ARTIFACT_MCP_SERVER_NAME = "orkestrator-artifacts";
16945
17980
  var ORKESTRATOR_ARTIFACT_MCP_PATH = "/artifact-mcp";
16946
17981
 
16947
17982
  // ../../bridges/claude-bridge/src/services/mcp-config.ts
16948
- var log9 = createLogger("bridge.claude");
17983
+ var log10 = createLogger("bridge.claude");
16949
17984
  var AGENT_MCP_SERVER_NAME = "orkestrator";
16950
17985
  var AGENT_MCP_URL_ENV = "ORKESTRATOR_AGENT_MCP_URL";
16951
17986
  var AGENT_MCP_TOKEN_ENV = "ORKESTRATOR_AGENT_MCP_TOKEN";
@@ -16992,7 +18027,7 @@ async function loadGlobalMcpServers() {
16992
18027
  return servers ?? {};
16993
18028
  }
16994
18029
  async function loadProjectMcpServers(cwd) {
16995
- const servers = await readJsonSliceCached(join11(cwd, ".mcp.json"), "mcpServers", (config) => config?.mcpServers);
18030
+ const servers = await readJsonSliceCached(join12(cwd, ".mcp.json"), "mcpServers", (config) => config?.mcpServers);
16996
18031
  return servers ?? {};
16997
18032
  }
16998
18033
  async function loadProjectOverridesFromGlobal2(cwd) {
@@ -17030,7 +18065,7 @@ function toSdkServers(configs) {
17030
18065
  if (sdkConfig) {
17031
18066
  servers[name] = sdkConfig;
17032
18067
  } else {
17033
- log9.warn("mcp.config-ignored");
18068
+ log10.warn("mcp.config-ignored");
17034
18069
  }
17035
18070
  }
17036
18071
  return servers;
@@ -17112,7 +18147,7 @@ async function loadScopedMcpServers(cwd, scope) {
17112
18147
  const [global2, projectGlobal, projectLocal] = await Promise.all([
17113
18148
  readJsonSliceCachedWithDigest(path, "mcpServers", (config) => config?.mcpServers),
17114
18149
  scope === "all" ? readJsonSliceCachedWithDigest(path, `projects:${cwd}:mcpServers`, (config) => config?.projects?.[cwd]?.mcpServers) : null,
17115
- scope === "all" ? readJsonSliceCachedWithDigest(join11(cwd, ".mcp.json"), "mcpServers", (config) => config?.mcpServers) : null
18150
+ scope === "all" ? readJsonSliceCachedWithDigest(join12(cwd, ".mcp.json"), "mcpServers", (config) => config?.mcpServers) : null
17116
18151
  ]);
17117
18152
  const configs = {
17118
18153
  ...global2.value,
@@ -17193,11 +18228,11 @@ async function getMcpRuntimeConfig(cwd, env = process.env, connection, sources =
17193
18228
  }
17194
18229
 
17195
18230
  // ../../bridges/claude-bridge/src/services/session-manager-commands.ts
17196
- import { randomUUID as randomUUID4 } from "node:crypto";
18231
+ import { randomUUID as randomUUID5 } from "node:crypto";
17197
18232
 
17198
18233
  // ../../bridges/claude-bridge/src/services/claude-model-catalog.ts
17199
- import { homedir as homedir2 } from "node:os";
17200
- import { join as join12 } from "node:path";
18234
+ import { homedir as homedir3 } from "node:os";
18235
+ import { join as join13 } from "node:path";
17201
18236
  import { stat as stat5 } from "node:fs/promises";
17202
18237
 
17203
18238
  // ../../bridges/claude-bridge/src/services/live-claude-control.ts
@@ -17395,7 +18430,7 @@ function claudeReadiness() {
17395
18430
  }
17396
18431
 
17397
18432
  // ../../bridges/claude-bridge/src/services/claude-model-catalog.ts
17398
- var log10 = createLogger("bridge.claude");
18433
+ var log11 = createLogger("bridge.claude");
17399
18434
  var CLAUDE_MODEL_CACHE_TTL_MS = 60 * 60000;
17400
18435
  var CLAUDE_MODEL_PROBE_TIMEOUT_MS = 25000;
17401
18436
  var remembered;
@@ -17423,15 +18458,15 @@ function catalogModels(models) {
17423
18458
  }));
17424
18459
  }
17425
18460
  async function claudeCliIdentity() {
17426
- const configDir = process.env.CLAUDE_CONFIG_DIR?.trim() || join12(homedir2(), ".claude");
18461
+ const configDir = process.env.CLAUDE_CONFIG_DIR?.trim() || join13(homedir3(), ".claude");
17427
18462
  const executable = process.env.CLAUDE_CLI_PATH?.trim();
17428
18463
  const resolved = executable ? Bun.which(executable, { PATH: process.env.PATH }) || executable : undefined;
17429
18464
  const cwd = process.env.CWD || process.cwd();
17430
18465
  const paths = [
17431
18466
  resolved,
17432
- join12(configDir, "settings.json"),
17433
- join12(cwd, ".claude/settings.json"),
17434
- join12(cwd, ".claude/settings.local.json")
18467
+ join13(configDir, "settings.json"),
18468
+ join13(cwd, ".claude/settings.json"),
18469
+ join13(cwd, ".claude/settings.local.json")
17435
18470
  ];
17436
18471
  const files = await Promise.all(paths.map(async (path) => {
17437
18472
  const file = path ? await stat5(path).catch(() => {
@@ -17536,7 +18571,7 @@ async function probeModels(at) {
17536
18571
  await rememberModels(models, account, at);
17537
18572
  return { source: "sdk", models: catalogModels(models) };
17538
18573
  } catch (error) {
17539
- log10.warn("models.fetch-failed", { error: formatLogError(error) });
18574
+ log11.warn("models.fetch-failed", { error: formatLogError(error) });
17540
18575
  return fallbackCatalog();
17541
18576
  } finally {
17542
18577
  clearTimeout(timer);
@@ -17878,7 +18913,7 @@ function idleSteerPromptReply(prompt, agentLabel) {
17878
18913
 
17879
18914
  // ../../bridges/claude-bridge/src/services/claude-terminal-commands.ts
17880
18915
  import { mkdir as mkdir5, readFile as readFile6, rename as rename5, writeFile as writeFile5 } from "node:fs/promises";
17881
- import { join as join13 } from "node:path";
18916
+ import { join as join14 } from "node:path";
17882
18917
  var FILE_NAME = "terminal-slash-commands.json";
17883
18918
  var MAX_VERSIONS = 4;
17884
18919
  var MAX_NAMES = 512;
@@ -17889,7 +18924,7 @@ var dirty = false;
17889
18924
  var entries = [];
17890
18925
  var writes = Promise.resolve();
17891
18926
  function filePath() {
17892
- return join13(claudeOrkestratorDir(), FILE_NAME);
18927
+ return join14(claudeOrkestratorDir(), FILE_NAME);
17893
18928
  }
17894
18929
  function validVersion(value) {
17895
18930
  return typeof value === "string" && value.length > 0 && value.length <= MAX_VERSION_LENGTH;
@@ -18442,7 +19477,7 @@ async function gracefulInterruptClaudeSession(sessionId) {
18442
19477
  }
18443
19478
 
18444
19479
  // ../../bridges/claude-bridge/src/services/session-manager-commands.ts
18445
- var CATALOGUE_GENERATION = randomUUID4();
19480
+ var CATALOGUE_GENERATION = randomUUID5();
18446
19481
  var COMMAND_PROBE_TIMEOUT_MS = 30000;
18447
19482
  var MAX_LOCAL_COMMAND_OUTPUT_BYTES = 64 * 1024;
18448
19483
  var MAX_MESSAGE_BYTES = 512;
@@ -19336,12 +20371,180 @@ function claudeArtifactServerTools(servers) {
19336
20371
 
19337
20372
  // ../protocol/src/node/repository-instructions.ts
19338
20373
  import { open as open3, realpath as realpath3 } from "node:fs/promises";
19339
- import { join as join14, relative as relative2, isAbsolute as isAbsolute4 } from "node:path";
20374
+ import { join as join15, relative as relative2, isAbsolute as isAbsolute5 } from "node:path";
20375
+
20376
+ // ../protocol/src/rich-content-policy.ts
20377
+ var KIB = 1024;
20378
+ var MIB = 1024 * KIB;
20379
+ var CODE_BLOCK_POLICY = {
20380
+ maxHighlightBytes: 32 * KIB,
20381
+ maxHighlightLines: 2000,
20382
+ initialVisualLines: 24
20383
+ };
20384
+ var MERMAID_POLICY = {
20385
+ maxSourceBytes: 32 * KIB,
20386
+ maxEdges: 250,
20387
+ maxSvgBytes: 1 * MIB,
20388
+ maxSvgElements: 5000,
20389
+ renderTimeoutMs: 5000
20390
+ };
20391
+ var CHART_POLICY = {
20392
+ maxPayloadBytes: 256 * KIB,
20393
+ maxSeries: 6,
20394
+ maxBarCategories: 100,
20395
+ maxCartesianPoints: 2000,
20396
+ maxDonutSlices: 24,
20397
+ maxTitleCharacters: 200,
20398
+ maxLabelCharacters: 200,
20399
+ maxDescriptionCharacters: 2000,
20400
+ maxSourceNotes: 8,
20401
+ maxSourceNoteCharacters: 500,
20402
+ maxIdCharacters: 64,
20403
+ maxUnitCharacters: 32,
20404
+ maxAbsoluteValue: 1000000000000000,
20405
+ maxJsonDepth: 16
20406
+ };
20407
+ var WORKFLOW_SNAPSHOT_POLICY = {
20408
+ maxNormalizedBytes: 256 * KIB,
20409
+ maxNodes: 200,
20410
+ maxEdges: 400,
20411
+ maxIdCharacters: 128,
20412
+ maxLabelCharacters: 200,
20413
+ maxDescriptionCharacters: 2000,
20414
+ maxRawStatusCharacters: 100,
20415
+ maxLinksPerNode: 8
20416
+ };
20417
+ var STATIC_HTML_POLICY = {
20418
+ maxSourceBytes: 256 * KIB,
20419
+ maxPreparedBytes: 16 * MIB,
20420
+ maxElements: 5000
20421
+ };
20422
+ var STATIC_PRESENTATION_POLICY = {
20423
+ maxDocumentBytes: STATIC_HTML_POLICY.maxSourceBytes,
20424
+ maxElements: STATIC_HTML_POLICY.maxElements,
20425
+ maxFramesPerWindow: 4,
20426
+ renderTimeoutMs: 15000,
20427
+ maxSizeChangesPerWindow: 16,
20428
+ sizeChangeWindowMs: 5000,
20429
+ maxRefusedMessages: 100,
20430
+ maxSearchTextCharacters: 64 * KIB,
20431
+ searchTextChunkCharacters: 2 * KIB
20432
+ };
20433
+ var INTERACTIVE_HTML_POLICY = {
20434
+ maxAuthoredBytes: 512 * KIB,
20435
+ maxAssets: 32,
20436
+ maxAssetBytesTotal: 10 * MIB,
20437
+ maxDependencies: 4,
20438
+ maxPreparedBytes: 16 * MIB,
20439
+ maxRuntimeElements: 1e4,
20440
+ maxProbeSteps: 20,
20441
+ maxProbeStepMs: 2000,
20442
+ defaultWaitVisibleMs: 1000,
20443
+ maxProbeTextCharacters: 1024,
20444
+ probeTargetPattern: /^[A-Za-z][A-Za-z0-9_-]{0,63}$/
20445
+ };
20446
+ var PREVIEW_CAPTURE_POLICY = {
20447
+ maxPngBytes: 8 * MIB,
20448
+ maxPixels: 12000000,
20449
+ maxDimension: 4096,
20450
+ minDimension: 240,
20451
+ maxCapturesPerReceipt: 3,
20452
+ defaultViewport: { width: 960, height: 640, deviceScaleFactor: 1 }
20453
+ };
20454
+ var PREVIEW_ADMISSION_POLICY = {
20455
+ runningPerEnvironment: 1,
20456
+ runningGlobal: 2,
20457
+ queuedPerEnvironment: 8,
20458
+ queuedGlobal: 16,
20459
+ nonterminalPerConversation: 2,
20460
+ queuedMetadataBytesGlobal: 8 * MIB,
20461
+ queueWaitMs: 15000,
20462
+ workerWallMs: 30000,
20463
+ readinessMs: 5000,
20464
+ operationDeadlineMs: 45000,
20465
+ cleanupGraceMs: 2000,
20466
+ workerMemoryBytes: 1024 * MIB,
20467
+ workerCpus: 2,
20468
+ workerPids: 128
20469
+ };
20470
+ var FRONTEND_RENDER_POLICY = {
20471
+ highlightConcurrency: 2,
20472
+ diagramConcurrency: 1,
20473
+ maxQueuedJobs: 32,
20474
+ maxQueuedSourceBytes: 2 * MIB,
20475
+ maxSettledCacheEntries: 128,
20476
+ maxSettledCacheBytes: 16 * MIB,
20477
+ maxInactiveViewStateEntries: 500,
20478
+ maxActiveViewStateEntries: 200,
20479
+ maxPinnedViewStateEntries: 50,
20480
+ liveExecutableHostsPerWindow: 1,
20481
+ imageDecodeMaxPixels: 40000000,
20482
+ pdfPreviewMaxPages: 100,
20483
+ pdfPreviewMaxBytes: 20 * MIB
20484
+ };
20485
+ var PDF_POLICY = {
20486
+ maxPages: 100,
20487
+ maxBytes: 20 * MIB,
20488
+ thumbnailMaxDimension: 1024,
20489
+ thumbnailMaxPngBytes: 4 * MIB,
20490
+ imageDecodeMaxPixels: 40000000,
20491
+ printMarginMm: 10,
20492
+ previewCacheEntries: 32,
20493
+ previewCacheBytes: 16 * MIB
20494
+ };
20495
+ var DIAGNOSTIC_POLICY = {
20496
+ maxPersistedEntries: 50,
20497
+ maxEntryBytes: 2 * KIB,
20498
+ maxPersistedBytes: 32 * KIB,
20499
+ maxToolFieldErrors: 20,
20500
+ maxToolDiagnosticBytes: 8 * KIB
20501
+ };
20502
+ var ARTIFACT_TOOL_POLICY = {
20503
+ maxResultBytes: 16 * KIB,
20504
+ maxSourceSliceBytes: 8 * KIB,
20505
+ maxTitleCharacters: 120,
20506
+ maxSummaryCharacters: 400,
20507
+ maxRequestKeyCharacters: 128,
20508
+ maxRepairRevisions: 2,
20509
+ maxTransientRetries: 2,
20510
+ maxUnpublishedArtifactsPerConversation: 100,
20511
+ maxRevisionsPerArtifact: 100,
20512
+ assetStoreBytesPerEnvironment: 1024 * MIB,
20513
+ scopeCapabilityTtlMs: 24 * 60 * 60 * 1000
20514
+ };
20515
+ var ARTIFACT_RETENTION_POLICY = {
20516
+ cleanupIntervalMs: 60 * 60 * 1000,
20517
+ abandonedStagingMs: 60 * 60 * 1000,
20518
+ unpublishedDraftMs: 7 * 24 * 60 * 60 * 1000,
20519
+ unreferencedPreviewAssetMs: 24 * 60 * 60 * 1000
20520
+ };
20521
+ var FRAME_CHANNEL_POLICY = {
20522
+ maxMessageBytes: 8 * KIB,
20523
+ messagesPerSecond: 20,
20524
+ burst: 40,
20525
+ sizeUpdatesPerSecond: 4,
20526
+ minInlineHeight: 120,
20527
+ maxInlineHeight: 1600,
20528
+ maxLinkCharacters: 2048,
20529
+ maxLinkLabelCharacters: 200
20530
+ };
19340
20531
 
19341
20532
  // ../protocol/src/agent-system-instructions.ts
19342
- var AGENT_IMAGE_PREVIEW_INSTRUCTION = "Orkestrator renders Markdown images inline in the transcript. When you show the user an image in your reply (a screenshot, rendered preview, or chart) using Markdown image syntax, reference it by its absolute path. In a managed worktree or container environment, save the file inside the working directory, preferably in a git-ignored folder so preview files stay out of the change set. Local image previews are limited to Orkestrator-managed workspace storage or the container's /workspace. Project-home checkouts are excluded from host preview reads, even when they are the working directory, so images saved there cannot be previewed from a local Markdown path. Paths outside previewable storage, such as /tmp, also show a placeholder.";
20533
+ var AGENT_IMAGE_PREVIEW_INSTRUCTION = "Orkestrator renders Markdown images inline in the transcript. When you show the user an image in your reply (a photograph, screenshot, rendered preview, or a requested image file) using Markdown image syntax, reference it by its absolute path. In a managed worktree or container environment, save the file inside the working directory, preferably in a git-ignored folder so preview files stay out of the change set. Local image previews are limited to Orkestrator-managed workspace storage or the container's /workspace. Project-home checkouts are excluded from host preview reads, even when they are the working directory, so images saved there cannot be previewed from a local Markdown path. Paths outside previewable storage, such as /tmp, also show a placeholder.";
19343
20534
  var AGENT_DOCUMENT_INSTRUCTION = "When the user asks for a document (a report, design doc, plan, analysis, guide, or other writing to keep), prefer writing it as a Markdown file in a `docs/` folder at the root of the working directory, and tell the user the file's path. Project instructions (such as AGENTS.md or CLAUDE.md), local skills, and the user's own request take priority over this default when they say where or how to write documents.";
20535
+ var AGENT_CHART_SPEC_SHAPES = "bar adds xAxis:{kind:'category',label}, yAxis:{label,unit?}, categories:[{id,label}], series:[{id,label,points:[{categoryId,value|null}]}] (one point per category); " + "line/area/scatter add xAxis:{kind:'number'|'utc-time',label,unit?}, yAxis:{label,unit?}, series:[{id,label,points:[{x,y|null}]}]; " + "donut adds valueLabel, unit?, slices:[{id,label,value}]";
20536
+ var AGENT_CHART_FENCE_EXAMPLE = '{"schemaVersion":1,"kind":"bar","title":"Passing tests","description":"Passing tests per suite.","xAxis":{"kind":"category","label":"Suite"},"yAxis":{"label":"Tests"},"categories":[{"id":"unit","label":"Unit"},{"id":"browser","label":"Browser"}],"series":[{"id":"passed","label":"Passed","points":[{"categoryId":"unit","value":40},{"categoryId":"browser","value":8}]}]}';
20537
+ var AGENT_VISUAL_OUTPUT_INSTRUCTION = [
20538
+ "Orkestrator displays rich visuals directly in the conversation; choose one when it helps answer the question.",
20539
+ `Flows, architecture, sequences and relationships: a \`mermaid\` code fence. Standard bar, line, area, scatter and donut charts: a \`chart\` code fence holding one ChartSpecV1 JSON object with schemaVersion 1, kind, title and description; ${AGENT_CHART_SPEC_SHAPES}. For example: ${AGENT_CHART_FENCE_EXAMPLE}.`,
20540
+ "When this session has the Orkestrator artifact tools, use them for durable visuals: create_artifact, preview_artifact, get_artifact_operation to inspect the diagnostics and capture, then publish_artifact, and respect their repair limits.",
20541
+ `A custom report, timeline or layout combining text and graphics is an html-static artifact: self-contained HTML, CSS and inline SVG, with no scripts or network resources. Its verified document is displayed in the transcript as real, selectable content, so keep it within ${STATIC_PRESENTATION_POLICY.maxDocumentBytes / 1024} KiB and ${STATIC_PRESENTATION_POLICY.maxElements} elements, use fluid widths, let content set the height (no 100vh on the root), and colour it with the --ork-foreground, --ork-muted-foreground, --ork-background, --ork-border, --ork-primary and --ork-chart-1 to --ork-chart-8 CSS variables, which follow the application theme. Always give them a fallback, such as var(--ork-foreground, #18181b), because the preview defines none of them.`,
20542
+ "Behaviour that needs authored JavaScript, such as a calculator or a filterable dashboard, is an html-interactive artifact; it runs when the reader activates it.",
20543
+ "Use ordinary images only for photographs, screenshots and requested image files.",
20544
+ "HTML, SVG and JavaScript code fences are shown as source and a file path alone publishes nothing: a visual is in the conversation only once publish_artifact succeeds. If verification is unavailable, say so and use a supported form such as a Mermaid or chart fence."
20545
+ ].join(" ");
19344
20546
  var GENERAL_AGENT_INSTRUCTIONS = [
20547
+ AGENT_VISUAL_OUTPUT_INSTRUCTION,
19345
20548
  AGENT_IMAGE_PREVIEW_INSTRUCTION,
19346
20549
  AGENT_DOCUMENT_INSTRUCTION
19347
20550
  ];
@@ -19367,11 +20570,11 @@ function repositoryInstructionsBlock(path, content, truncated) {
19367
20570
  // ../protocol/src/node/repository-instructions.ts
19368
20571
  var MAX_REPOSITORY_INSTRUCTIONS_BYTES = 256 * 1024;
19369
20572
  async function readRepositoryInstructions(cwd, maxBytes = MAX_REPOSITORY_INSTRUCTIONS_BYTES) {
19370
- const path = join14(cwd, REPOSITORY_INSTRUCTIONS_FILE);
20573
+ const path = join15(cwd, REPOSITORY_INSTRUCTIONS_FILE);
19371
20574
  try {
19372
20575
  const [root, target] = await Promise.all([realpath3(cwd), realpath3(path)]);
19373
20576
  const inside = relative2(root, target);
19374
- if (!inside || inside.startsWith("..") || isAbsolute4(inside))
20577
+ if (!inside || inside.startsWith("..") || isAbsolute5(inside))
19375
20578
  return;
19376
20579
  const handle = await open3(target, "r");
19377
20580
  try {
@@ -19668,14 +20871,14 @@ function isValidMcpFormContent(schema, content) {
19668
20871
  }
19669
20872
 
19670
20873
  // ../../bridges/claude-bridge/src/services/session-manager-interactions.ts
19671
- var log11 = createLogger("bridge.claude");
20874
+ var log12 = createLogger("bridge.claude");
19672
20875
  function answerQuestion(requestId, answers) {
19673
20876
  const question = pendingQuestions.get(requestId);
19674
20877
  if (!question) {
19675
20878
  debugLog("[session-manager] Question not found for requestId:", requestId);
19676
20879
  return false;
19677
20880
  }
19678
- log11.info("question.answering", { requestId, answerCount: Object.keys(answers).length });
20881
+ log12.info("question.answering", { requestId, answerCount: Object.keys(answers).length });
19679
20882
  const resolver = questionResolvers.get(requestId);
19680
20883
  if (resolver) {
19681
20884
  debugLog("[session-manager] Resolving promise for question:", requestId);
@@ -19727,7 +20930,7 @@ function respondToPlanApproval(requestId, approved, feedback) {
19727
20930
  debugLog("[session-manager] Refusing incomplete plan approval", { requestId });
19728
20931
  return false;
19729
20932
  }
19730
- log11.info("plan-approval.responding", {
20933
+ log12.info("plan-approval.responding", {
19731
20934
  requestId,
19732
20935
  approved,
19733
20936
  hasFeedback: typeof feedback === "string" && feedback.length > 0
@@ -20825,6 +22028,9 @@ function handlePromptSuggestion(turn, message) {
20825
22028
  function handleRateLimitEvent(turn, message) {
20826
22029
  const { session, sessionId } = turn;
20827
22030
  const info = message.rate_limit_info;
22031
+ if (info?.status) {
22032
+ turn.rateLimitRejected = info.status === "rejected" && info.isUsingOverage !== true && info.overageInUse !== true && info.overageStatus !== "allowed" && info.overageStatus !== "allowed_warning";
22033
+ }
20828
22034
  if (info) {
20829
22035
  const nextWindows = rateLimitsFromEventInfo(info);
20830
22036
  const nextLabels = new Set(nextWindows.map((window) => window.label));
@@ -20970,9 +22176,10 @@ function classifyUsageLimitError(text) {
20970
22176
  const hint = reset?.[1]?.trim();
20971
22177
  return hint ? { resetHint: hint } : {};
20972
22178
  }
22179
+ var USAGE_LIMIT_ERROR_CODE = "usage-limit";
20973
22180
 
20974
22181
  // ../../bridges/claude-bridge/src/services/session-manager-prompt-handlers/result.ts
20975
- var log12 = createLogger("bridge.claude");
22182
+ var log13 = createLogger("bridge.claude");
20976
22183
  function claudeStartupFailureMessage(reason) {
20977
22184
  switch (reason) {
20978
22185
  case "org_pin_api_key_conflict":
@@ -21145,7 +22352,7 @@ async function handleResultMessage(turn, message) {
21145
22352
  debugLog("[session-manager] Query stopped by the user", { sessionId });
21146
22353
  finishTurnInputIfSettled(turn);
21147
22354
  } else {
21148
- log12.error("query.failed", { subtype: resultMsg.subtype, sessionId, isError: resultIsError });
22355
+ log13.error("query.failed", { subtype: resultMsg.subtype, sessionId, isError: resultIsError });
21149
22356
  const startupFailure = resultMsg.startup_failure_reason ? claudeStartupFailureMessage(resultMsg.startup_failure_reason) : undefined;
21150
22357
  const usageLimit = resultMsg.subtype === "success" && classifyUsageLimitError(resultMsg.result) ? resultMsg.result.trim().slice(0, MAX_USAGE_LIMIT_ERROR_CHARS) : undefined;
21151
22358
  const resultError = startupFailure || resultMsg.errors?.filter(Boolean).join(`
@@ -21495,7 +22702,7 @@ function handlePermissionDenied(turn, message) {
21495
22702
  const denial = message;
21496
22703
  const reason = boundedNoticeText(denial.decision_reason ?? denial.message);
21497
22704
  if (typeof denial.tool_use_id === "string") {
21498
- commandChangeProbe.discard(denial.tool_use_id);
22705
+ discardCommandChangeWindow(denial.tool_use_id);
21499
22706
  recordClaudeToolDenied(sessionId, denial.tool_use_id, typeof denial.tool_name === "string" ? { toolName: denial.tool_name } : {});
21500
22707
  }
21501
22708
  const marked = typeof denial.tool_use_id === "string" && toolTracker.recordDenial(denial.tool_use_id, {
@@ -21575,7 +22782,7 @@ async function handleSystemMessage(turn, message) {
21575
22782
  }
21576
22783
 
21577
22784
  // ../../bridges/claude-bridge/src/services/session-manager-prompt-handlers/user.ts
21578
- var log13 = createLogger("bridge.claude");
22785
+ var log14 = createLogger("bridge.claude");
21579
22786
  function handleUserMessage(turn, message) {
21580
22787
  const { session, sessionId, stream } = turn;
21581
22788
  const { toolTracker, taskRegistry, activeTaskIds } = stream;
@@ -21590,7 +22797,7 @@ function handleUserMessage(turn, message) {
21590
22797
  } = parseMessageContent(message, toolTracker, turn.mcpServerNames, activeTaskIds, taskRegistry, receivedAt, recordUnknownContentBlock);
21591
22798
  const sdkUserMessage = message;
21592
22799
  for (const toolUseId of toolResultIds(sdkUserMessage)) {
21593
- commandChangeProbe.discard(toolUseId);
22800
+ discardCommandChangeWindow(toolUseId);
21594
22801
  const pending = turn.pendingCommandChanges.get(toolUseId);
21595
22802
  if (pending) {
21596
22803
  turn.pendingCommandChanges.delete(toolUseId);
@@ -21625,7 +22832,7 @@ function handleUserMessage(turn, message) {
21625
22832
  if (turn.planApprovedThisTurn) {
21626
22833
  for (const tool of toolTracker.getTools()) {
21627
22834
  if (tool.toolName === "ExitPlanMode" && tool.toolState === "failure" && tool.toolUseId) {
21628
- log13.warn("plan-exit.failure-overridden", { sessionId, toolUseId: tool.toolUseId });
22835
+ log14.warn("plan-exit.failure-overridden", { sessionId, toolUseId: tool.toolUseId });
21629
22836
  toolTracker.updateToolResult(tool.toolUseId, {
21630
22837
  state: "success",
21631
22838
  output: "Plan approved by the user. Proceeding with implementation.",
@@ -21697,7 +22904,7 @@ async function handleTurnMessage(turn, message) {
21697
22904
  }
21698
22905
 
21699
22906
  // ../../bridges/claude-bridge/src/services/session-manager-prompt-can-use-tool.ts
21700
- var log14 = createLogger("bridge.claude");
22907
+ var log15 = createLogger("bridge.claude");
21701
22908
  function boundedPlan(content) {
21702
22909
  if (typeof content !== "string" || content.trim().length === 0)
21703
22910
  return {};
@@ -21756,7 +22963,7 @@ async function askUserQuestion(turn, input, permissionContext) {
21756
22963
  });
21757
22964
  try {
21758
22965
  const answers = await Promise.race([answerPromise, timeoutPromise]);
21759
- log14.info("question.answers-received", { questionId, answerCount: Object.keys(answers).length });
22966
+ log15.info("question.answers-received", { questionId, answerCount: Object.keys(answers).length });
21760
22967
  return {
21761
22968
  behavior: "allow",
21762
22969
  updatedInput: {
@@ -21765,7 +22972,7 @@ async function askUserQuestion(turn, input, permissionContext) {
21765
22972
  }
21766
22973
  };
21767
22974
  } catch (error) {
21768
- log14.warn("question.wait-failed", { error: formatLogError(error) });
22975
+ log15.warn("question.wait-failed", { error: formatLogError(error) });
21769
22976
  const message = error instanceof Error ? error.message : "Question was cancelled";
21770
22977
  if (pendingQuestions.has(questionId)) {
21771
22978
  eventEmitter.emit({
@@ -21846,7 +23053,7 @@ async function requestPlanApproval(turn, input, permissionContext) {
21846
23053
  });
21847
23054
  try {
21848
23055
  const response = await Promise.race([approvalPromise, timeoutPromise]);
21849
- log14.info("plan-approval.result", {
23056
+ log15.info("plan-approval.result", {
21850
23057
  approvalId,
21851
23058
  approved: response.approved,
21852
23059
  hasFeedback: typeof response.feedback === "string" && response.feedback.length > 0
@@ -21895,7 +23102,7 @@ Please revise the plan based on this feedback.` : `I've reviewed the plan and I
21895
23102
  };
21896
23103
  }
21897
23104
  } catch (error) {
21898
- log14.warn("plan-approval.wait-failed", { error: formatLogError(error) });
23105
+ log15.warn("plan-approval.wait-failed", { error: formatLogError(error) });
21899
23106
  const errorMessage = error instanceof Error ? error.message : "Plan approval was cancelled";
21900
23107
  if (pendingPlanApprovals.has(approvalId)) {
21901
23108
  eventEmitter.emit({
@@ -21985,7 +23192,7 @@ function createClaudeRuntimeTurn(turn) {
21985
23192
  }
21986
23193
 
21987
23194
  // ../../bridges/claude-bridge/src/services/session-manager-prompt-launch.ts
21988
- var log15 = createLogger("bridge.claude");
23195
+ var log16 = createLogger("bridge.claude");
21989
23196
  async function consumeClaudeRuntime(runtime, frames, markEnded) {
21990
23197
  let failure;
21991
23198
  try {
@@ -22021,6 +23228,7 @@ function endClaudeRuntime(runtime, failure) {
22021
23228
  if (interruptedOutsidePrompt) {
22022
23229
  session.status = "error";
22023
23230
  session.error = claudeProcessKilledMessage(killedBy);
23231
+ session.errorCode = undefined;
22024
23232
  session.interruption = "restart";
22025
23233
  session.interruptedRequestId = session.turnInFlightRequestId;
22026
23234
  session.turnStartedAt = undefined;
@@ -22061,9 +23269,10 @@ function releaseOrphanedForeground(runtime, error) {
22061
23269
  eventEmitter.emit({ type: "session.idle", sessionId, data: { success: true } });
22062
23270
  return;
22063
23271
  }
22064
- log15.error("runtime.ended-under-resumed-turn", { sessionId });
23272
+ log16.error("runtime.ended-under-resumed-turn", { sessionId });
22065
23273
  session.status = "error";
22066
23274
  session.error = error instanceof Error ? error.message : String(error);
23275
+ session.errorCode = undefined;
22067
23276
  eventEmitter.emit({ type: "session.error", sessionId, data: { error: session.error } });
22068
23277
  }
22069
23278
  function abandonJoin(turn, running) {
@@ -22225,7 +23434,7 @@ async function runTurnOnRuntime(turn, plan, testHooks) {
22225
23434
  }
22226
23435
 
22227
23436
  // ../../bridges/claude-bridge/src/services/session-manager-prompt-settle.ts
22228
- var log16 = createLogger("bridge.claude");
23437
+ var log17 = createLogger("bridge.claude");
22229
23438
  function settleTurnEnd(turn) {
22230
23439
  const { session, sessionId, options, structuredRequestId, abortController, stream, diagnostics } = turn;
22231
23440
  diagnostics?.streamSettled("resolved");
@@ -22331,6 +23540,7 @@ function settleFailedTurn(turn, error) {
22331
23540
  session.turnStartedAt = turn.beforeStartup.turnStartedAt;
22332
23541
  session.abortController = turn.beforeStartup.abortController;
22333
23542
  session.error = turn.beforeStartup.error;
23543
+ session.errorCode = turn.beforeStartup.errorCode;
22334
23544
  session.interruption = turn.beforeStartup.interruption;
22335
23545
  session.interruptedRequestId = turn.beforeStartup.interruptedRequestId;
22336
23546
  session.inProgressUsage = turn.beforeStartup.inProgressUsage;
@@ -22346,7 +23556,7 @@ function settleFailedTurn(turn, error) {
22346
23556
  recordInterruptedStructuredOutputIfCurrent(turn);
22347
23557
  return;
22348
23558
  }
22349
- log16.error("prompt.failed", { errorClass: diagnosticErrorClass(error) });
23559
+ log17.error("prompt.failed", { errorClass: diagnosticErrorClass(error) });
22350
23560
  if (session.abortController === abortController) {
22351
23561
  const killedBy = killedClaudeProcessSignal(error);
22352
23562
  const failure = killedBy ? claudeProcessKilledMessage(killedBy) : error instanceof Error ? error.message : String(error);
@@ -22358,6 +23568,7 @@ function settleFailedTurn(turn, error) {
22358
23568
  session.status = "error";
22359
23569
  session.turnStartedAt = undefined;
22360
23570
  session.error = failure;
23571
+ session.errorCode = turn.rateLimitRejected && !killedBy ? USAGE_LIMIT_ERROR_CODE : undefined;
22361
23572
  session.interruption = killedBy ? "restart" : undefined;
22362
23573
  session.interruptedRequestId = killedBy ? turn.dispatchRequestId : undefined;
22363
23574
  session.abortController = undefined;
@@ -22455,7 +23666,7 @@ function finalizeTurn(turn) {
22455
23666
  }
22456
23667
 
22457
23668
  // ../../bridges/claude-bridge/src/services/session-manager-prompt.ts
22458
- var log17 = createLogger("bridge.claude");
23669
+ var log18 = createLogger("bridge.claude");
22459
23670
  function turnWriterLiveness(turn) {
22460
23671
  const tasks = Object.values(turn.session.backgroundTasks ?? {});
22461
23672
  if (tasks.some((task) => LIVE_BACKGROUND_TASK_STATUSES.has(task.status)))
@@ -22498,7 +23709,7 @@ async function sendPrompt(sessionId, prompt, options, testHooks) {
22498
23709
  try {
22499
23710
  await sendPrompt(sessionId, followUp.prompt, followUp.options);
22500
23711
  } catch (repromptError) {
22501
- log17.error(followUp.failureEvent, { error: formatLogError(repromptError) });
23712
+ log18.error(followUp.failureEvent, { error: formatLogError(repromptError) });
22502
23713
  return Promise.reject(repromptError);
22503
23714
  }
22504
23715
  } catch (error) {
@@ -22510,7 +23721,7 @@ async function sendPrompt(sessionId, prompt, options, testHooks) {
22510
23721
  }
22511
23722
  }
22512
23723
  // ../../bridges/claude-bridge/src/services/session-manager-close.ts
22513
- var log18 = createLogger("bridge.claude");
23724
+ var log19 = createLogger("bridge.claude");
22514
23725
  var CLOSE_CONFIRMATION_BUDGET_MS = 1e4;
22515
23726
 
22516
23727
  class SessionCloseNotConfirmedError extends Error {
@@ -22573,7 +23784,7 @@ async function closeQueryControls(controls, deadline) {
22573
23784
  if (await settlesBy(Promise.resolve(control.close()), deadline))
22574
23785
  return;
22575
23786
  } catch (error) {
22576
- log18.error("query.close-failed", {
23787
+ log19.error("query.close-failed", {
22577
23788
  errorClass: error instanceof Error ? error.name : typeof error
22578
23789
  });
22579
23790
  }
@@ -22593,18 +23804,18 @@ async function settlesBy(work, deadline) {
22593
23804
  }
22594
23805
  }
22595
23806
  // ../../bridges/claude-bridge/src/routes/config.ts
22596
- var log19 = createLogger("bridge.claude");
23807
+ var log20 = createLogger("bridge.claude");
22597
23808
  var config2 = new Hono2;
22598
23809
  config2.get("/models", async (c) => {
22599
23810
  if (c.req.query("forceRefresh") === "true")
22600
23811
  invalidateClaudeModelCatalog();
22601
23812
  const startedAt = Date.now();
22602
- log19.debug("models.requested");
23813
+ log20.debug("models.requested");
22603
23814
  const [{ models, source }, versions] = await Promise.all([
22604
23815
  getAvailableModelCatalog(),
22605
23816
  getClaudeRuntimeVersions()
22606
23817
  ]);
22607
- log19.debug("models.responded", { count: models.length, durationMs: Date.now() - startedAt });
23818
+ log20.debug("models.responded", { count: models.length, durationMs: Date.now() - startedAt });
22608
23819
  const response = {
22609
23820
  models,
22610
23821
  source,
@@ -22617,6 +23828,18 @@ var config_default = config2;
22617
23828
 
22618
23829
  // ../protocol/src/human-prompts.ts
22619
23830
  var HUMAN_PROMPT_SCAN_BYTES = 16 * 1024;
23831
+ var HUMAN_PROMPT_KINDS = new Set([
23832
+ "sign-in",
23833
+ "device-code",
23834
+ "press-enter",
23835
+ "secret",
23836
+ "host-key"
23837
+ ]);
23838
+ var HUMAN_PROMPT_SOURCES = new Set([
23839
+ "user-command",
23840
+ "agent-tool",
23841
+ "agent-background-task"
23842
+ ]);
22620
23843
  var HUMAN_PROMPT_OBSERVATION_ROWS = 64;
22621
23844
  function humanPromptObservation(messages, tasks) {
22622
23845
  const object = (value) => !!value && typeof value === "object" && !Array.isArray(value);
@@ -22669,7 +23892,7 @@ function humanPromptObservation(messages, tasks) {
22669
23892
  }
22670
23893
 
22671
23894
  // ../../bridges/claude-bridge/src/routes/session.ts
22672
- import { randomUUID as randomUUID5 } from "node:crypto";
23895
+ import { randomUUID as randomUUID6 } from "node:crypto";
22673
23896
 
22674
23897
  // ../../node_modules/.bun/hono@4.13.13/node_modules/hono/dist/middleware/body-limit/index.js
22675
23898
  var ERROR_MESSAGE = "Payload Too Large";
@@ -23585,7 +24808,7 @@ function bridgeTranscriptPageRouteBody(source, query) {
23585
24808
  }
23586
24809
 
23587
24810
  // ../../bridges/claude-bridge/src/routes/session-transcript.ts
23588
- var log20 = createLogger("bridge.claude");
24811
+ var log21 = createLogger("bridge.claude");
23589
24812
  function claudeTranscriptSource(id, generation) {
23590
24813
  const sessionData = peekSession(id);
23591
24814
  if (!sessionData)
@@ -23638,7 +24861,7 @@ function registerSessionTranscriptRoutes(app, generation, materialize) {
23638
24861
  const response = c.json(bridgeTranscriptRouteBody(read.source, query3(c)));
23639
24862
  if (read.needsHydration) {
23640
24863
  hydratePersistedSessionMessages(id).catch((error) => {
23641
- log20.warn("transcript.background-hydrate-failed", {
24864
+ log21.warn("transcript.background-hydrate-failed", {
23642
24865
  error: formatLogError(error, { stack: false })
23643
24866
  });
23644
24867
  });
@@ -23650,9 +24873,9 @@ function registerSessionTranscriptRoutes(app, generation, materialize) {
23650
24873
  }
23651
24874
 
23652
24875
  // ../../bridges/claude-bridge/src/routes/session.ts
23653
- var log21 = createLogger("bridge.claude");
24876
+ var log22 = createLogger("bridge.claude");
23654
24877
  var session = new Hono2;
23655
- var TRANSCRIPT_GENERATION = randomUUID5();
24878
+ var TRANSCRIPT_GENERATION = randomUUID6();
23656
24879
  var MAX_QUESTION_ANSWER_REQUEST_BYTES = AGENT_INTERACTION_LIMITS.maxSerializedPayloadBytes + 1024;
23657
24880
  var MAX_CLAUDE_TRANSCRIPT_RESPONSE_BYTES = 16 * 1024 * 1024;
23658
24881
  function boundClaudeTranscriptResponse(messages, tailMessages) {
@@ -23730,7 +24953,7 @@ session.post("/create", async (c) => {
23730
24953
  const clientSessionKey = body.clientSessionKey;
23731
24954
  const policy = effectiveExecutionPolicy(isNativeAgentExecutionPolicy(body.policy) ? body.policy : undefined);
23732
24955
  const newSession = policy ? await createOrRecoverSession(title, clientSessionKey, policy) : await createOrRecoverSession(title, clientSessionKey);
23733
- log21.info("session.created", { sessionId: newSession.id });
24956
+ log22.info("session.created", { sessionId: newSession.id });
23734
24957
  const response = {
23735
24958
  sessionId: newSession.id,
23736
24959
  title: newSession.title
@@ -23738,10 +24961,10 @@ session.post("/create", async (c) => {
23738
24961
  return c.json(response, 201);
23739
24962
  } catch (error) {
23740
24963
  if (error instanceof PolicyWideningRefusedError) {
23741
- log21.warn("session.policy-widening-refused", { widened: error.widened.join(",") });
24964
+ log22.warn("session.policy-widening-refused", { widened: error.widened.join(",") });
23742
24965
  return c.json(error.refusal(), 403);
23743
24966
  }
23744
- log21.error("session.create-failed", { error: formatLogError(error) });
24967
+ log22.error("session.create-failed", { error: formatLogError(error) });
23745
24968
  return c.json({ error: error instanceof Error ? error.message : "Failed to create session" }, 500);
23746
24969
  }
23747
24970
  });
@@ -23749,7 +24972,7 @@ session.get("/list", async (c) => {
23749
24972
  try {
23750
24973
  await reconcilePersistedSessions();
23751
24974
  } catch (error) {
23752
- log21.warn("sessions.reconcile-failed", { error: formatLogError(error) });
24975
+ log22.warn("sessions.reconcile-failed", { error: formatLogError(error) });
23753
24976
  }
23754
24977
  const sessions = listSessions();
23755
24978
  const response = {
@@ -23768,7 +24991,7 @@ async function resolveSession(id, failureMessage) {
23768
24991
  try {
23769
24992
  return { ok: true, session: getSession(id) ?? await ensurePersistedSession(id) };
23770
24993
  } catch (error) {
23771
- log21.error("session.resolve-failed", { action: failureMessage, error: formatLogError(error) });
24994
+ log22.error("session.resolve-failed", { action: failureMessage, error: formatLogError(error) });
23772
24995
  return {
23773
24996
  ok: false,
23774
24997
  body: { error: errorMessage(error, failureMessage) },
@@ -23789,7 +25012,7 @@ session.get("/:id", async (c) => {
23789
25012
  try {
23790
25013
  await hydratePersistedSessionMessages(id);
23791
25014
  } catch (error) {
23792
- log21.error("session.task-state-hydrate-failed", { error: formatLogError(error) });
25015
+ log22.error("session.task-state-hydrate-failed", { error: formatLogError(error) });
23793
25016
  return c.json({ error: errorMessage(error, "Failed to hydrate session task state") }, sessionErrorStatus(error));
23794
25017
  }
23795
25018
  }
@@ -23801,6 +25024,7 @@ session.get("/:id", async (c) => {
23801
25024
  createdAt: sessionData.createdAt.toISOString(),
23802
25025
  lastActivity: sessionData.lastActivity.toISOString(),
23803
25026
  error: sessionData.error,
25027
+ ...sessionData.status === "error" && sessionData.errorCode ? { errorCode: sessionData.errorCode } : {},
23804
25028
  ...sessionData.status === "error" && sessionData.interruption ? {
23805
25029
  interruption: sessionData.interruption,
23806
25030
  ...sessionData.interruptedRequestId ? { interruptedRequestId: sessionData.interruptedRequestId } : {}
@@ -23840,7 +25064,7 @@ session.get("/:id/usage", async (c) => {
23840
25064
  const contextUsage = await refreshClaudeContextUsage(resolved.session);
23841
25065
  return c.json({ contextUsage });
23842
25066
  } catch (error) {
23843
- log21.warn("context-usage.read-failed", { error: formatLogError(error, { stack: false }) });
25067
+ log22.warn("context-usage.read-failed", { error: formatLogError(error, { stack: false }) });
23844
25068
  return c.json({ error: "Context usage is temporarily unavailable" }, 503);
23845
25069
  }
23846
25070
  });
@@ -23890,7 +25114,7 @@ session.post("/:id/config", async (c) => {
23890
25114
  const refusePolicyWidening = () => {
23891
25115
  const widened = nextPolicy ? executionPolicyWidenings(sessionData.executionPolicy, nextPolicy) : [];
23892
25116
  if (widened.length > 0) {
23893
- log21.warn("session.policy-widening-refused", {
25117
+ log22.warn("session.policy-widening-refused", {
23894
25118
  sessionId: sessionData.id,
23895
25119
  widened: widened.join(",")
23896
25120
  });
@@ -23931,7 +25155,7 @@ session.get("/:id/commands", async (c) => {
23931
25155
  try {
23932
25156
  return c.json(await readClaudeCommandCatalogue(c.req.param("id")));
23933
25157
  } catch (error) {
23934
- log21.warn("commands.read-failed", { error: formatLogError(error, { stack: false }) });
25158
+ log22.warn("commands.read-failed", { error: formatLogError(error, { stack: false }) });
23935
25159
  return c.json({ error: errorMessage(error, "Claude command discovery failed") }, 503);
23936
25160
  }
23937
25161
  });
@@ -24176,7 +25400,7 @@ session.post("/:id/prompt", async (c) => {
24176
25400
  rejectStarted?.(sessionOperationError("conflict", "Prompt stopped before launch"));
24177
25401
  }, (error) => {
24178
25402
  rejectStarted?.(error);
24179
- log21.error("prompt.processing-failed", { error: formatLogError(error) });
25403
+ log22.error("prompt.processing-failed", { error: formatLogError(error) });
24180
25404
  });
24181
25405
  return { started, completion };
24182
25406
  });
@@ -24190,7 +25414,7 @@ session.post("/:id/prompt", async (c) => {
24190
25414
  duplicate: true
24191
25415
  });
24192
25416
  }
24193
- log21.debug("prompt.accepted", { sessionId: id });
25417
+ log22.debug("prompt.accepted", { sessionId: id });
24194
25418
  return c.json({
24195
25419
  status: "processing",
24196
25420
  requestId,
@@ -24203,7 +25427,7 @@ session.post("/:id/prompt", async (c) => {
24203
25427
  if (sessionData.rewindInProgress === true) {
24204
25428
  return c.json({ error: "Session is restoring files from a checkpoint" }, 409);
24205
25429
  }
24206
- log21.info("prompt.received", {
25430
+ log22.info("prompt.received", {
24207
25431
  sessionId: id,
24208
25432
  promptLength: prompt.length,
24209
25433
  model,
@@ -24231,16 +25455,16 @@ session.post("/:id/prompt", async (c) => {
24231
25455
  ...workflowResultTurn ? { workflowResultTurn } : {},
24232
25456
  ...providerPrompt !== undefined ? { providerPrompt } : {}
24233
25457
  }).catch((error) => {
24234
- log21.error("prompt.processing-failed", { error: formatLogError(error) });
25458
+ log22.error("prompt.processing-failed", { error: formatLogError(error) });
24235
25459
  });
24236
- log21.debug("prompt.accepted", { sessionId: id });
25460
+ log22.debug("prompt.accepted", { sessionId: id });
24237
25461
  return c.json({
24238
25462
  status: "processing",
24239
25463
  requestId,
24240
25464
  turnStartedAt: sessionData.turnStartedAt
24241
25465
  }, 202);
24242
25466
  } catch (error) {
24243
- log21.error("prompt.send-failed", { error: formatLogError(error) });
25467
+ log22.error("prompt.send-failed", { error: formatLogError(error) });
24244
25468
  return c.json({ error: errorMessage(error, "Failed to send prompt") }, sessionErrorStatus(error));
24245
25469
  }
24246
25470
  });
@@ -24284,7 +25508,7 @@ session.delete("/:id", async (c) => {
24284
25508
  }
24285
25509
  return c.json({ error: "Session not found" }, 404);
24286
25510
  } catch (error) {
24287
- log21.error("session.delete-failed", { error: formatLogError(error) });
25511
+ log22.error("session.delete-failed", { error: formatLogError(error) });
24288
25512
  return c.json({ error: errorMessage(error, "Failed to delete session") }, sessionErrorStatus(error));
24289
25513
  }
24290
25514
  });
@@ -24299,7 +25523,7 @@ session.post("/:id/rename", async (c) => {
24299
25523
  const renamed = await renameSessionDurably(id, title);
24300
25524
  return renamed ? c.json({ status: "renamed", title }) : c.json({ error: "Session not found" }, 404);
24301
25525
  } catch (error) {
24302
- log21.error("session.rename-failed", { error: formatLogError(error) });
25526
+ log22.error("session.rename-failed", { error: formatLogError(error) });
24303
25527
  return c.json({ error: errorMessage(error, "Failed to rename session") }, sessionErrorStatus(error));
24304
25528
  }
24305
25529
  });
@@ -24328,7 +25552,7 @@ session.post("/:id/fork", async (c) => {
24328
25552
  title: forked.title
24329
25553
  }, 201);
24330
25554
  } catch (error) {
24331
- log21.error("session.fork-failed", { error: formatLogError(error) });
25555
+ log22.error("session.fork-failed", { error: formatLogError(error) });
24332
25556
  return c.json({ error: errorMessage(error, "Failed to fork session") }, sessionErrorStatus(error));
24333
25557
  }
24334
25558
  });
@@ -24360,7 +25584,7 @@ session.post("/:id/compact", compactBodyLimit, async (c) => {
24360
25584
  }
24361
25585
  const { instructions } = parsed;
24362
25586
  sendPrompt(id, instructions ? `/compact ${instructions}` : "/compact").catch((error) => {
24363
- log21.error("session.compact-failed", { error: formatLogError(error) });
25587
+ log22.error("session.compact-failed", { error: formatLogError(error) });
24364
25588
  });
24365
25589
  return c.json(instructions ? { status: "processing", instructions: "applied" } : { status: "processing" }, 202);
24366
25590
  });
@@ -24378,7 +25602,7 @@ session.post("/:id/rewind", async (c) => {
24378
25602
  const result = await rewindSessionFiles(id, messageId, dryRun);
24379
25603
  return c.json({ status: dryRun ? "previewed" : "rewound", result });
24380
25604
  } catch (error) {
24381
- log21.error("session.rewind-failed", { error: formatLogError(error) });
25605
+ log22.error("session.rewind-failed", { error: formatLogError(error) });
24382
25606
  return c.json({ error: errorMessage(error, "Failed to rewind session files") }, sessionErrorStatus(error));
24383
25607
  }
24384
25608
  });
@@ -24389,7 +25613,7 @@ session.post("/:id/tasks/:taskId/stop", async (c) => {
24389
25613
  return c.json({ status: "stopped" });
24390
25614
  return c.json({ error: stopped.message }, stopped.reason === "no_control_channel" ? 409 : 404);
24391
25615
  } catch (error) {
24392
- log21.error("task.stop-route-failed", { error: formatLogError(error) });
25616
+ log22.error("task.stop-route-failed", { error: formatLogError(error) });
24393
25617
  return c.json({ error: errorMessage(error, "Failed to stop background task") }, sessionErrorStatus(error));
24394
25618
  }
24395
25619
  });
@@ -24460,7 +25684,7 @@ session.post("/:id/questions/:questionId/answer", questionAnswerBodyLimit, async
24460
25684
  const pendingQuestions = getPendingQuestions(sessionId);
24461
25685
  const pendingQuestion = pendingQuestions.find((q) => q.id === questionId);
24462
25686
  if (!pendingQuestion) {
24463
- log21.info("question.stale", { questionId });
25687
+ log22.info("question.stale", { questionId });
24464
25688
  return c.json(stalePrompt("Question is no longer pending"), STALE_PROMPT_STATUS);
24465
25689
  }
24466
25690
  if (!isBoundedClaudeQuestionAnswers(answersArray, pendingQuestion.questions.length)) {
@@ -24471,7 +25695,7 @@ session.post("/:id/questions/:questionId/answer", questionAnswerBodyLimit, async
24471
25695
  const questionAnswers = answersArray[index] || [];
24472
25696
  answersRecord[q.question] = serializeClaudeQuestionAnswer(questionAnswers, q.multiSelect === true);
24473
25697
  });
24474
- log21.debug("question.answers-prepared", {
25698
+ log22.debug("question.answers-prepared", {
24475
25699
  questionId,
24476
25700
  questionCount: pendingQuestion.questions.length,
24477
25701
  answerCount: answersArray.reduce((count, answers) => count + answers.length, 0)
@@ -24483,7 +25707,7 @@ session.post("/:id/questions/:questionId/answer", questionAnswerBodyLimit, async
24483
25707
  return c.json(stalePrompt("Question is no longer pending"), STALE_PROMPT_STATUS);
24484
25708
  }
24485
25709
  } catch (error) {
24486
- log21.error("question.answer-failed", { error: formatLogError(error) });
25710
+ log22.error("question.answer-failed", { error: formatLogError(error) });
24487
25711
  return c.json({ error: error instanceof Error ? error.message : "Failed to answer question" }, 500);
24488
25712
  }
24489
25713
  });
@@ -24523,7 +25747,7 @@ session.post("/:id/plan-approvals/:approvalId/respond", planApprovalBodyLimit, a
24523
25747
  if (approved && (typeof pendingApproval.plan !== "string" || pendingApproval.plan.trim().length === 0 || pendingApproval.planTruncated === true)) {
24524
25748
  return c.json({ error: "A complete plan is required before approval", status: "rejected" }, 409);
24525
25749
  }
24526
- log21.info("plan-approval.response-received", {
25750
+ log22.info("plan-approval.response-received", {
24527
25751
  sessionId,
24528
25752
  approvalId,
24529
25753
  approved,
@@ -24536,7 +25760,7 @@ session.post("/:id/plan-approvals/:approvalId/respond", planApprovalBodyLimit, a
24536
25760
  return c.json(stalePrompt("Plan approval is no longer pending"), STALE_PROMPT_STATUS);
24537
25761
  }
24538
25762
  } catch (error) {
24539
- log21.error("plan-approval.response-failed", { error: formatLogError(error) });
25763
+ log22.error("plan-approval.response-failed", { error: formatLogError(error) });
24540
25764
  return c.json({ error: error instanceof Error ? error.message : "Failed to respond to plan approval" }, 500);
24541
25765
  }
24542
25766
  });
@@ -24817,22 +26041,163 @@ var streamSSE = (c, cb, onError) => {
24817
26041
  return c.newResponse(stream.responseReadable);
24818
26042
  };
24819
26043
 
26044
+ // ../protocol/src/node/event-ring.ts
26045
+ var DEFAULT_RING_CAPACITY = 512;
26046
+
26047
+ class EventRing {
26048
+ capacity;
26049
+ maxBytes;
26050
+ measureBytes;
26051
+ supersede;
26052
+ buffer = [];
26053
+ revision = 0;
26054
+ droppedEvents = 0;
26055
+ retainedBytes = 0;
26056
+ constructor(capacity = DEFAULT_RING_CAPACITY, options = {}) {
26057
+ this.capacity = Math.max(1, capacity);
26058
+ if (options.maxBytes !== undefined && !options.measureBytes) {
26059
+ throw new TypeError("EventRing: maxBytes requires measureBytes");
26060
+ }
26061
+ this.maxBytes = Math.max(0, options.maxBytes ?? Number.POSITIVE_INFINITY);
26062
+ this.measureBytes = options.measureBytes ?? (() => 0);
26063
+ this.supersede = options.supersede ?? null;
26064
+ }
26065
+ get latestRevision() {
26066
+ return this.revision;
26067
+ }
26068
+ get oldestRevision() {
26069
+ return this.buffer[0]?.revision ?? 0;
26070
+ }
26071
+ getStats() {
26072
+ return {
26073
+ retained: this.buffer.length,
26074
+ capacity: this.capacity,
26075
+ latestRevision: this.revision,
26076
+ dropped: this.droppedEvents,
26077
+ retainedBytes: this.retainedBytes,
26078
+ maxBytes: Number.isFinite(this.maxBytes) ? this.maxBytes : null
26079
+ };
26080
+ }
26081
+ append(event) {
26082
+ this.revision += 1;
26083
+ this.retain(event);
26084
+ return this.revision;
26085
+ }
26086
+ appendAt(revision, event) {
26087
+ this.skipTo(revision - 1);
26088
+ this.revision = revision;
26089
+ this.retain(event);
26090
+ }
26091
+ advance() {
26092
+ this.advanceTo(this.revision + 1);
26093
+ return this.revision;
26094
+ }
26095
+ advanceTo(revision) {
26096
+ this.skipTo(revision);
26097
+ this.revision = revision;
26098
+ }
26099
+ skipTo(revision) {
26100
+ if (!Number.isSafeInteger(revision) || revision < this.revision) {
26101
+ throw new RangeError("EventRing: revisions must not go backwards");
26102
+ }
26103
+ if (revision > this.revision && this.buffer.length > 0) {
26104
+ this.droppedEvents += this.buffer.length;
26105
+ this.clear();
26106
+ }
26107
+ }
26108
+ retain(event) {
26109
+ if (this.supersede)
26110
+ this.collapseSuperseded(event);
26111
+ this.retainedBytes += Math.max(0, this.measureBytes(event));
26112
+ this.buffer.push({ revision: this.revision, event });
26113
+ while (this.buffer.length > this.capacity || this.retainedBytes > this.maxBytes) {
26114
+ const removed = this.buffer.shift();
26115
+ if (!removed)
26116
+ break;
26117
+ this.retainedBytes -= Math.max(0, this.measureBytes(removed.event));
26118
+ this.droppedEvents += 1;
26119
+ }
26120
+ }
26121
+ collapseSuperseded(incoming) {
26122
+ const supersede = this.supersede;
26123
+ if (!supersede)
26124
+ return;
26125
+ for (let index = this.buffer.length - 1;index >= 0; index -= 1) {
26126
+ const entry = this.buffer[index];
26127
+ const replacement = supersede(incoming, entry.event);
26128
+ if (replacement === null)
26129
+ continue;
26130
+ if (replacement === entry.event)
26131
+ return;
26132
+ this.retainedBytes -= Math.max(0, this.measureBytes(entry.event));
26133
+ entry.event = replacement;
26134
+ this.retainedBytes += Math.max(0, this.measureBytes(replacement));
26135
+ }
26136
+ }
26137
+ since(cursor) {
26138
+ if (!Number.isFinite(cursor) || cursor < 0) {
26139
+ return { events: [], complete: false, latestRevision: this.revision };
26140
+ }
26141
+ if (cursor > this.revision) {
26142
+ return { events: [], complete: false, latestRevision: this.revision };
26143
+ }
26144
+ if (cursor === this.revision) {
26145
+ return { events: [], complete: true, latestRevision: this.revision };
26146
+ }
26147
+ const oldest = this.oldestRevision;
26148
+ const complete = oldest !== 0 && cursor + 1 >= oldest;
26149
+ return {
26150
+ events: complete ? this.buffer.filter((entry) => entry.revision > cursor) : [],
26151
+ complete,
26152
+ latestRevision: this.revision
26153
+ };
26154
+ }
26155
+ clear() {
26156
+ this.buffer.length = 0;
26157
+ this.retainedBytes = 0;
26158
+ }
26159
+ }
26160
+
24820
26161
  // ../../bridges/claude-bridge/src/routes/events.ts
24821
- var log22 = createLogger("bridge.claude");
24822
- var serializedEventData = new WeakMap;
24823
- function serializeEventData(event) {
24824
- let data = serializedEventData.get(event);
24825
- if (data === undefined) {
24826
- data = JSON.stringify({
26162
+ var log23 = createLogger("bridge.claude");
26163
+ var serializedEvents = new WeakMap;
26164
+ function serializeEvent(event) {
26165
+ let serialized = serializedEvents.get(event);
26166
+ if (serialized === undefined) {
26167
+ const data = JSON.stringify({
24827
26168
  sessionId: event.sessionId,
24828
26169
  ...event.data
24829
26170
  });
24830
- serializedEventData.set(event, data);
26171
+ serialized = { data, dataBytes: Buffer.byteLength(data) };
26172
+ serializedEvents.set(event, serialized);
24831
26173
  }
24832
- return data;
26174
+ return serialized;
24833
26175
  }
24834
26176
  var MAX_PENDING_SSE_FRAMES = 1000;
24835
26177
  var MAX_PENDING_SSE_BYTES = 16 * 1024 * 1024;
26178
+ var SUPERSEDED_FRAME_BYTES = 64;
26179
+ function supersedeReplayFrame(incoming, retained) {
26180
+ if (incoming.event !== "message.updated" || incoming.messageId === undefined)
26181
+ return null;
26182
+ if (retained.event !== "message.updated" && retained.event !== "message.patched")
26183
+ return null;
26184
+ if (retained.messageId !== incoming.messageId || retained.sessionId !== incoming.sessionId) {
26185
+ return null;
26186
+ }
26187
+ if (retained.superseded)
26188
+ return retained;
26189
+ return {
26190
+ revision: retained.revision,
26191
+ ...retained.id === undefined ? {} : { id: retained.id },
26192
+ event: retained.event,
26193
+ data: "{}",
26194
+ dataBytes: 2,
26195
+ bytes: SUPERSEDED_FRAME_BYTES,
26196
+ ...retained.sessionId === undefined ? {} : { sessionId: retained.sessionId },
26197
+ messageId: retained.messageId,
26198
+ superseded: true
26199
+ };
26200
+ }
24836
26201
  function observationFrameData(sessionId) {
24837
26202
  return JSON.stringify(sessionId === undefined ? {} : { sessionId });
24838
26203
  }
@@ -24840,47 +26205,52 @@ var MAX_REPLAY_SSE_FRAMES = 512;
24840
26205
  var MAX_REPLAY_SSE_BYTES = 4 * 1024 * 1024;
24841
26206
  var REPLAY_IDLE_RETENTION_MS = 60000;
24842
26207
  function createReplayBuffer(limits = {}) {
24843
- const maxFrames = limits.maxFrames ?? MAX_REPLAY_SSE_FRAMES;
24844
- const maxBytes = limits.maxBytes ?? MAX_REPLAY_SSE_BYTES;
24845
- const frames = [];
24846
- let bytes = 0;
26208
+ const ring = new EventRing(limits.maxFrames ?? MAX_REPLAY_SSE_FRAMES, {
26209
+ maxBytes: limits.maxBytes ?? MAX_REPLAY_SSE_BYTES,
26210
+ measureBytes: (frame) => frame.bytes,
26211
+ supersede: supersedeReplayFrame
26212
+ });
24847
26213
  return {
24848
26214
  append(event, revision, generation) {
24849
- const data = serializeEventData(event);
24850
- const frame = {
26215
+ const { data, dataBytes } = serializeEvent(event);
26216
+ const messageId = eventMessageId(event);
26217
+ ring.appendAt(revision, {
24851
26218
  revision,
24852
26219
  id: `${generation}:${revision}`,
24853
26220
  event: event.type,
24854
26221
  data,
24855
- bytes: Buffer.byteLength(data) + Buffer.byteLength(event.type),
24856
- ...event.sessionId === undefined ? {} : { sessionId: event.sessionId }
24857
- };
24858
- frames.push(frame);
24859
- bytes += frame.bytes;
24860
- while (frames.length > maxFrames || bytes > maxBytes) {
24861
- const removed = frames.shift();
24862
- if (!removed)
24863
- break;
24864
- bytes -= removed.bytes;
24865
- }
26222
+ dataBytes,
26223
+ bytes: dataBytes + Buffer.byteLength(event.type),
26224
+ ...event.sessionId === undefined ? {} : { sessionId: event.sessionId },
26225
+ ...messageId === undefined ? {} : { messageId }
26226
+ });
26227
+ },
26228
+ skip(revision) {
26229
+ ring.advanceTo(revision);
24866
26230
  },
24867
26231
  getFrames(since, through, generation) {
24868
26232
  if (since.generation !== generation || since.revision > through) {
24869
26233
  return { frames: [], resetRequired: true };
24870
26234
  }
24871
- const oldest = frames[0]?.revision;
24872
- const resetRequired = since.revision < through && (oldest === undefined || since.revision < oldest - 1);
24873
- return {
24874
- frames: resetRequired ? [] : frames.filter((frame) => frame.revision > since.revision && frame.revision <= through),
24875
- resetRequired
24876
- };
26235
+ if (since.revision === through)
26236
+ return { frames: [], resetRequired: false };
26237
+ const replay = ring.since(since.revision);
26238
+ if (!replay.complete)
26239
+ return { frames: [], resetRequired: true };
26240
+ const frames = [];
26241
+ for (const entry of replay.events) {
26242
+ if (entry.revision > through)
26243
+ break;
26244
+ frames.push(entry.event);
26245
+ }
26246
+ return { frames, resetRequired: false };
24877
26247
  },
24878
26248
  clear() {
24879
- frames.length = 0;
24880
- bytes = 0;
26249
+ ring.clear();
24881
26250
  },
24882
26251
  stats() {
24883
- return { frames: frames.length, bytes };
26252
+ const stats = ring.getStats();
26253
+ return { frames: stats.retained, bytes: stats.retainedBytes };
24884
26254
  }
24885
26255
  };
24886
26256
  }
@@ -24933,8 +26303,10 @@ function formatReplayCursor(revision) {
24933
26303
  return `${eventEmitter.generation}:${revision}`;
24934
26304
  }
24935
26305
  eventEmitter.subscribe((event, revision) => {
24936
- if (!replayRetention.shouldRetain())
26306
+ if (!replayRetention.shouldRetain()) {
26307
+ replayBuffer.skip(revision);
24937
26308
  return;
26309
+ }
24938
26310
  replayBuffer.append(event, revision, eventEmitter.generation);
24939
26311
  });
24940
26312
  function parseReplayCursor(value) {
@@ -24964,7 +26336,7 @@ function createBoundedSseWriter(write, onOverflow, limits = {}) {
24964
26336
  return (frame) => {
24965
26337
  if (overflowed)
24966
26338
  return Promise.resolve();
24967
- const frameBytes = Buffer.byteLength(frame.data);
26339
+ const frameBytes = frame.dataBytes ?? Buffer.byteLength(frame.data);
24968
26340
  if (pendingFrames > 0 && (pendingFrames >= maxPendingFrames || pendingBytes + frameBytes > maxPendingBytes)) {
24969
26341
  overflowed = true;
24970
26342
  onOverflow();
@@ -24993,10 +26365,10 @@ function createEventsRouter(limits = {}) {
24993
26365
  events.get("/subscribe", (c) => {
24994
26366
  const origin = c.req.header("origin");
24995
26367
  const userAgent = c.req.header("user-agent");
24996
- log22.debug("sse.subscribe-requested", { origin, userAgent });
26368
+ log23.debug("sse.subscribe-requested", { origin, userAgent });
24997
26369
  return streamSSE(c, async (stream) => {
24998
26370
  const connectedAt = new Date().toISOString();
24999
- log22.debug("sse.opened", { connectedAt });
26371
+ log23.debug("sse.opened", { connectedAt });
25000
26372
  let isOpen = true;
25001
26373
  let resolveConnectionClosed;
25002
26374
  const connectionClosed = new Promise((resolve) => {
@@ -25007,7 +26379,7 @@ function createEventsRouter(limits = {}) {
25007
26379
  resolveRequestAborted = resolve;
25008
26380
  });
25009
26381
  const onRequestAbort = () => {
25010
- log22.debug("sse.aborted");
26382
+ log23.debug("sse.aborted");
25011
26383
  isOpen = false;
25012
26384
  resolveRequestAborted();
25013
26385
  };
@@ -25021,7 +26393,7 @@ function createEventsRouter(limits = {}) {
25021
26393
  if (!isOpen)
25022
26394
  return;
25023
26395
  isOpen = false;
25024
- log22.info("sse.closed", { reason });
26396
+ log23.info("sse.closed", { reason });
25025
26397
  resolveConnectionClosed();
25026
26398
  };
25027
26399
  const writeFrame = createBoundedSseWriter(async (frame) => {
@@ -25045,13 +26417,21 @@ function createEventsRouter(limits = {}) {
25045
26417
  unsubscribe = eventEmitter.subscribe((event, revision) => {
25046
26418
  if (!isOpen)
25047
26419
  return;
25048
- const data = observe ? observationFrameData(event.sessionId) : serializeEventData(event);
26420
+ let data;
26421
+ let dataBytes;
26422
+ if (observe) {
26423
+ data = observationFrameData(event.sessionId);
26424
+ dataBytes = Buffer.byteLength(data);
26425
+ } else {
26426
+ ({ data, dataBytes } = serializeEvent(event));
26427
+ }
25049
26428
  const frame = {
25050
26429
  revision,
25051
26430
  id: formatReplayCursor(revision),
25052
26431
  event: event.type,
25053
26432
  data,
25054
- bytes: Buffer.byteLength(data) + Buffer.byteLength(event.type)
26433
+ dataBytes,
26434
+ bytes: dataBytes + Buffer.byteLength(event.type)
25055
26435
  };
25056
26436
  if (replaying) {
25057
26437
  if (pendingLiveFrames.length >= maxPendingFrames || pendingLiveBytes + frame.bytes > maxPendingBytes) {
@@ -25064,7 +26444,7 @@ function createEventsRouter(limits = {}) {
25064
26444
  }
25065
26445
  writeFrame(frame).catch((error) => {
25066
26446
  if (!c.req.raw.signal.aborted) {
25067
- log22.warn("sse.write-failed", { error: formatLogError(error) });
26447
+ log23.warn("sse.write-failed", { error: formatLogError(error) });
25068
26448
  closeConnection("write failed");
25069
26449
  }
25070
26450
  });
@@ -25094,7 +26474,17 @@ function createEventsRouter(limits = {}) {
25094
26474
  });
25095
26475
  } else {
25096
26476
  for (const frame of replay.frames) {
25097
- await writeFrame(observe ? { ...frame, data: observationFrameData(frame.sessionId) } : frame);
26477
+ if (observe) {
26478
+ await writeFrame({
26479
+ id: frame.id,
26480
+ event: frame.event,
26481
+ data: observationFrameData(frame.sessionId)
26482
+ });
26483
+ } else if (frame.superseded) {
26484
+ await writeFrame({ id: frame.id, event: "bridge.cursor", data: "{}" });
26485
+ } else {
26486
+ await writeFrame(frame);
26487
+ }
25098
26488
  }
25099
26489
  }
25100
26490
  const drained = pendingLiveFrames.splice(0);
@@ -25116,7 +26506,7 @@ function createEventsRouter(limits = {}) {
25116
26506
  data: JSON.stringify({ timestamp: new Date().toISOString() })
25117
26507
  }).catch((error) => {
25118
26508
  if (!c.req.raw.signal.aborted) {
25119
- log22.warn("sse.keepalive-failed", { error: formatLogError(error, { stack: false }) });
26509
+ log23.warn("sse.keepalive-failed", { error: formatLogError(error, { stack: false }) });
25120
26510
  closeConnection("keepalive failed");
25121
26511
  }
25122
26512
  });
@@ -25124,10 +26514,10 @@ function createEventsRouter(limits = {}) {
25124
26514
  await Promise.race([connectionClosed, requestAborted]);
25125
26515
  } catch (error) {
25126
26516
  if (!c.req.raw.signal.aborted) {
25127
- log22.warn("sse.handshake-failed", { error: formatLogError(error) });
26517
+ log23.warn("sse.handshake-failed", { error: formatLogError(error) });
25128
26518
  }
25129
26519
  } finally {
25130
- log22.debug("sse.cleanup");
26520
+ log23.debug("sse.cleanup");
25131
26521
  isOpen = false;
25132
26522
  c.req.raw.signal.removeEventListener("abort", onRequestAbort);
25133
26523
  if (keepaliveInterval)
@@ -25143,7 +26533,7 @@ var events = createEventsRouter();
25143
26533
  var events_default = events;
25144
26534
 
25145
26535
  // ../../bridges/claude-bridge/src/routes/mcp.ts
25146
- var log23 = createLogger("bridge.claude");
26536
+ var log24 = createLogger("bridge.claude");
25147
26537
  var mcp = new Hono2;
25148
26538
  mcp.get("/servers", async (c) => {
25149
26539
  try {
@@ -25154,14 +26544,14 @@ mcp.get("/servers", async (c) => {
25154
26544
  cwd
25155
26545
  });
25156
26546
  } catch (error) {
25157
- log23.error("mcp.read-failed", { error: formatLogError(error) });
26547
+ log24.error("mcp.read-failed", { error: formatLogError(error) });
25158
26548
  return c.json({ error: error instanceof Error ? error.message : "Failed to get MCP servers" }, 500);
25159
26549
  }
25160
26550
  });
25161
26551
  var mcp_default = mcp;
25162
26552
 
25163
26553
  // ../../bridges/claude-bridge/src/routes/plugins.ts
25164
- var log24 = createLogger("bridge.claude");
26554
+ var log25 = createLogger("bridge.claude");
25165
26555
  var plugins = new Hono2;
25166
26556
  plugins.get("/", async (c) => {
25167
26557
  try {
@@ -25172,7 +26562,7 @@ plugins.get("/", async (c) => {
25172
26562
  cwd
25173
26563
  });
25174
26564
  } catch (error) {
25175
- log24.error("plugins.read-failed", { error: formatLogError(error) });
26565
+ log25.error("plugins.read-failed", { error: formatLogError(error) });
25176
26566
  return c.json({ error: error instanceof Error ? error.message : "Failed to get plugins" }, 500);
25177
26567
  }
25178
26568
  });
@@ -25237,6 +26627,7 @@ function installFatalRejectionGuard(options) {
25237
26627
  const APP_PATH = /(?:^|\/)((?:apps\/(?:backend|desktop|web|web-public)|packages\/(?:protocol|cli|toolchain)|bridges\/[\w-]+|[\w-]+-bridge)\/.*)$/;
25238
26628
  const PACKAGED_PATH = /\/((?:app\.asar(?:\.unpacked)?|resources)\/.*)$/i;
25239
26629
  const CREDENTIALS = [
26630
+ { pattern: /\bok[ab]_[A-Za-z0-9_-]{16,}/g, replacement: "[redacted]" },
25240
26631
  {
25241
26632
  pattern: /([a-z][a-z0-9+.-]*:\/\/)[^/\s:@]+(?::[^/\s@]*)?@/gi,
25242
26633
  replacement: "$1[redacted]@"
@@ -25364,9 +26755,9 @@ function installFatalRejectionGuard(options) {
25364
26755
  }
25365
26756
 
25366
26757
  // ../protocol/src/node/process-failure-log.ts
25367
- var log25 = createLogger("process");
26758
+ var log26 = createLogger("process");
25368
26759
  function logUnhandledRejection(reason) {
25369
- log25.throttled("error", "rejection.unhandled", {
26760
+ log26.throttled("error", "rejection.unhandled", {
25370
26761
  error: reason,
25371
26762
  fields: () => ({ error: formatLogError(reason, { message: false }) })
25372
26763
  });
@@ -26856,12 +28247,79 @@ var serve = (options, listeningListener) => {
26856
28247
  return server;
26857
28248
  };
26858
28249
 
28250
+ // ../protocol/src/node/bridge-credential.ts
28251
+ import { createHash as createHash13, randomBytes as randomBytes2, timingSafeEqual } from "node:crypto";
28252
+ import { createRequire as createRequire2 } from "node:module";
28253
+ var BRIDGE_TOKEN_PREFIX = "okb_";
28254
+ var PR_SET_DUMPABLE = 4;
28255
+ var VERIFIER_PATTERN = /^[0-9a-f]{64}$/;
28256
+ var log27 = createLogger("bridge.lifecycle");
28257
+ function mintBridgeToken() {
28258
+ return `${BRIDGE_TOKEN_PREFIX}${randomBytes2(32).toString("base64url")}`;
28259
+ }
28260
+ function bridgeTokenVerifier(token) {
28261
+ return createHash13("sha256").update(token).digest("hex");
28262
+ }
28263
+ function bridgeTokenVerifierEnv(tokenEnv) {
28264
+ return `${tokenEnv}_SHA256`;
28265
+ }
28266
+ function credentialFromVerifier(verifier, plainToken) {
28267
+ const expected = Buffer.from(verifier, "hex");
28268
+ return {
28269
+ plainToken,
28270
+ matches(candidate) {
28271
+ if (!candidate)
28272
+ return false;
28273
+ return timingSafeEqual(expected, createHash13("sha256").update(candidate).digest());
28274
+ }
28275
+ };
28276
+ }
28277
+ function bridgeCredentialFromToken(token) {
28278
+ return credentialFromVerifier(bridgeTokenVerifier(token), token);
28279
+ }
28280
+ function markProcessNonDumpable(loadFfi = () => createRequire2(import.meta.url)("bun:ffi")) {
28281
+ if (process.platform !== "linux" || !process.versions.bun)
28282
+ return false;
28283
+ try {
28284
+ const { dlopen, FFIType } = loadFfi();
28285
+ const libc = dlopen("libc.so.6", {
28286
+ prctl: {
28287
+ args: [FFIType.i32, FFIType.u64, FFIType.u64, FFIType.u64, FFIType.u64],
28288
+ returns: FFIType.i32
28289
+ }
28290
+ });
28291
+ try {
28292
+ if (libc.symbols.prctl(PR_SET_DUMPABLE, 0n, 0n, 0n, 0n) === 0)
28293
+ return true;
28294
+ } finally {
28295
+ libc.close();
28296
+ }
28297
+ log27.warn("credential.not-hardened", { reason: "prctl-refused" });
28298
+ } catch {
28299
+ log27.warn("credential.not-hardened", { reason: "ffi-unavailable" });
28300
+ }
28301
+ return false;
28302
+ }
28303
+ function loadBridgeCredential(tokenEnv, options = {}) {
28304
+ const env = options.env ?? process.env;
28305
+ const verifierEnv = bridgeTokenVerifierEnv(tokenEnv);
28306
+ const verifier = env[verifierEnv]?.trim();
28307
+ const token = env[tokenEnv]?.trim();
28308
+ delete env[verifierEnv];
28309
+ delete env[tokenEnv];
28310
+ if (verifier) {
28311
+ (options.harden ?? markProcessNonDumpable)();
28312
+ return VERIFIER_PATTERN.test(verifier) ? credentialFromVerifier(verifier, undefined) : bridgeCredentialFromToken(mintBridgeToken());
28313
+ }
28314
+ return bridgeCredentialFromToken(token || mintBridgeToken());
28315
+ }
28316
+
26859
28317
  // ../../bridges/claude-bridge/src/index.ts
26860
- var log26 = createLogger("bridge.claude");
28318
+ var log28 = createLogger("bridge.claude");
26861
28319
  configureBridgeLogger();
26862
28320
  var app = new Hono2;
26863
28321
  app.onError((error, c) => {
26864
- log26.error("http.request-failed", {
28322
+ log28.error("http.request-failed", {
26865
28323
  method: c.req.method,
26866
28324
  path: c.req.path,
26867
28325
  error: formatLogError(error)
@@ -26870,9 +28328,7 @@ app.onError((error, c) => {
26870
28328
  });
26871
28329
  var BRIDGE_TOKEN_ENV = "CLAUDE_BRIDGE_TOKEN";
26872
28330
  var BRIDGE_ALLOWED_ORIGINS_ENV = "CLAUDE_BRIDGE_ALLOWED_ORIGINS";
26873
- var configuredBridgeAuthToken = process.env[BRIDGE_TOKEN_ENV]?.trim();
26874
- var bridgeAuthToken = configuredBridgeAuthToken || randomBytes2(32).toString("base64url");
26875
- delete process.env[BRIDGE_TOKEN_ENV];
28331
+ var bridgeCredential = loadBridgeCredential(BRIDGE_TOKEN_ENV);
26876
28332
  process.env.ORKESTRATOR_NATIVE_AGENT_BRIDGE = "claude";
26877
28333
  var bridgeAuthEnabledOverrideForTesting = null;
26878
28334
  function isBridgeAuthEnabled() {
@@ -26882,11 +28338,7 @@ function isBridgeAuthEnabled() {
26882
28338
  return !(process.env.CLAUDE_BRIDGE_NO_SERVER === "1" && process.env.CLAUDE_BRIDGE_AUTH_DISABLED_FOR_TESTING === "1");
26883
28339
  }
26884
28340
  function tokenMatches(candidate) {
26885
- if (!candidate)
26886
- return false;
26887
- const expected = Buffer.from(bridgeAuthToken);
26888
- const actual = Buffer.from(candidate);
26889
- return expected.length === actual.length && timingSafeEqual(expected, actual);
28341
+ return bridgeCredential.matches(candidate);
26890
28342
  }
26891
28343
  function bearerToken(header) {
26892
28344
  if (!header)
@@ -26990,7 +28442,7 @@ if (parentPid !== null) {
26990
28442
  startParentWatchdog({
26991
28443
  parentPid,
26992
28444
  onParentExit: () => {
26993
- log26.warn("parent.gone", { parentPid });
28445
+ log28.warn("parent.gone", { parentPid });
26994
28446
  process.exit(0);
26995
28447
  }
26996
28448
  });
@@ -27001,13 +28453,13 @@ function startBridgeServer(env = process.env, start = serve) {
27001
28453
  }
27002
28454
  const port = parseInt(env.PORT || "4097", 10);
27003
28455
  const hostname = env.HOSTNAME || "0.0.0.0";
27004
- log26.debug("server.starting", { hostname, port });
28456
+ log28.debug("server.starting", { hostname, port });
27005
28457
  const server = start({
27006
28458
  fetch: app.fetch,
27007
28459
  port,
27008
28460
  hostname
27009
28461
  });
27010
- log26.info("server.listening", { hostname, port });
28462
+ log28.info("server.listening", { hostname, port });
27011
28463
  return server;
27012
28464
  }
27013
28465
  var __testing = {
@@ -27017,7 +28469,7 @@ var __testing = {
27017
28469
  bridgeAuthEnabledOverrideForTesting = null;
27018
28470
  return;
27019
28471
  }
27020
- bridgeAuthToken = token;
28472
+ bridgeCredential = bridgeCredentialFromToken(token);
27021
28473
  bridgeAuthEnabledOverrideForTesting = true;
27022
28474
  },
27023
28475
  startBridgeServerForTesting: startBridgeServer