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.
@@ -17,6 +17,7 @@ var TEXT_RULES = [
17
17
  pattern: /\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/g,
18
18
  replacement: "[redacted]"
19
19
  },
20
+ { pattern: /\bok[ab]_[A-Za-z0-9_-]{16,}/g, replacement: "[redacted]" },
20
21
  { pattern: /\bgh[pousr]_[A-Za-z0-9]{16,}/g, replacement: "[redacted]" },
21
22
  { pattern: /\bgithub_pat_[A-Za-z0-9_]{20,}/g, replacement: "[redacted]" },
22
23
  { pattern: /\b(?:sk|rk|pk)-[A-Za-z0-9_-]{12,}/g, replacement: "[redacted]" },
@@ -257,6 +258,12 @@ var BACKEND_LOG_AREAS = defineLogAreas({
257
258
  "startup.looped-review-pending": "Cleanup of the retired Looped Review stays pending.",
258
259
  "notice.failed": "A background notice after a turn or prompt failed; `step` says which.",
259
260
  "artifacts.live-unavailable": "Live interactive artifacts are unavailable.",
261
+ "previous-run": {
262
+ 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.",
263
+ essential: true,
264
+ fields: { outcome: "label", ranForMs: "number", lastSeenAgoMs: "number" }
265
+ },
266
+ "health.write-failed": "A health summary row could not be written or read; the next sample retries.",
260
267
  "shutdown.step-failed": "One part of shutdown failed and the rest went on; `step` says which.",
261
268
  "shutdown.signal-received": {
262
269
  description: "A signal started shutdown, which tells a clean quit from the backend being killed.",
@@ -300,7 +307,8 @@ var BRIDGE_LOG_AREAS = defineLogAreas({
300
307
  description: "What every long-lived bridge does the same way: its sweep and its shutdown.",
301
308
  events: {
302
309
  "idle-sweep.failed": "An idle sweep threw; the next tick retries.",
303
- "shutdown.failed": "Releasing the bridge failed during shutdown; it still exits."
310
+ "shutdown.failed": "Releasing the bridge failed during shutdown; it still exits.",
311
+ "credential.not-hardened": "The bridge could not mark itself non-dumpable, so a same-uid process can read its memory; `reason` says why."
304
312
  }
305
313
  },
306
314
  "bridge.acp": {
@@ -434,7 +442,6 @@ var BRIDGE_LOG_AREAS = defineLogAreas({
434
442
  "parent.gone": "The backend that launched this bridge has gone; stopping turns and shutting down.",
435
443
  "queue.overflow": "The notification queue passed a bound and dropped its backlog.",
436
444
  "queue.task-failed": "A task on a per-thread queue failed.",
437
- "raw-log.write-failed": "Appending to the raw Codex log failed.",
438
445
  "recorder.notice": "The notification recorder needs attention: it is on, or was asked for without its confirmation.",
439
446
  "recorder.threw": "The notification recorder threw.",
440
447
  "recorder.write-failed": "Writing a notification recording failed; its lines were dropped.",
@@ -640,6 +647,7 @@ var ENVIRONMENT_LOG_AREAS = defineLogAreas({
640
647
  environment: {
641
648
  description: "Environment naming, setup, status, moves, deletion and cleanup afterwards.",
642
649
  events: {
650
+ "cleanup.sessions-failed": "Session metadata cleanup failed during environment deletion; deletion continues.",
643
651
  "cleanup.branch-kept": "A deleted environment's local branch was kept, as it may hold unmerged work.",
644
652
  "rename.failed": "Naming an environment from its pending prompt failed for the first time.",
645
653
  "rename.still-failing": "That rename is still failing; written at the 2nd, 4th, 8th... failure.",
@@ -713,6 +721,7 @@ var GATEWAY_LOG_AREAS = defineLogAreas({
713
721
  "websocket.upgrade-failed": "A WebSocket upgrade failed.",
714
722
  "events.client-dropped": "An event-stream client buffered too much and was dropped; it reconnects and refetches.",
715
723
  "proxy.client-disconnected": "A proxy client went away, so its upstream request was aborted.",
724
+ "traffic.burst": "Connections or requests spiked. Counts by source address, route class, client family, listener and registered invoke command; never request content.",
716
725
  "throttle.suppressed": "Repeats of the throttled `site` were counted over a window, not written.",
717
726
  "throttle.recovered": "The throttled `site` succeeded again, so its fault has cleared.",
718
727
  "throttle.evicted": "The tracked-key limit dropped the `site`, so no recovered line follows unless it fails again."
@@ -816,6 +825,8 @@ var LOGGING_LOG_AREAS = defineLogAreas({
816
825
  },
817
826
  "essential.write-failed": "Writing the essential log failed. Its entries are counted, and a marker reports them at the next write that works.",
818
827
  "policy.changed": "The logging settings changed: saving, retention and levels, with no content.",
828
+ "policy.detail-expired": "Raised log detail reached its expiry, so the backend set its raised levels back to info. Saving is unchanged.",
829
+ "policy.expiry-failed": "Checking or applying the log detail expiry failed; the next check, a minute later, tries again.",
819
830
  "policy.bridge-predates-route": "A running bridge has no logging settings route; it applies them at its next start.",
820
831
  "policy.push-failed": "A running bridge did not take the logging settings after retries; its next start resends them.",
821
832
  "prune.failed": "Removing expired log files failed; the next sweep retries.",
@@ -823,6 +834,23 @@ var LOGGING_LOG_AREAS = defineLogAreas({
823
834
  "unknown-area": "Code outside the type checker asked for an area that is not listed.",
824
835
  ...THROTTLE_LOG_EVENTS
825
836
  }
837
+ },
838
+ "renderer-errors": {
839
+ description: "Renderer failures a desktop window reported from its error ring: class, boundary, surface, count and fingerprint, never a message or stack.",
840
+ events: {
841
+ "error.recorded": {
842
+ description: "A renderer reported `count` new occurrences of one failure since its last report.",
843
+ essential: true,
844
+ fields: {
845
+ errorClass: "label",
846
+ boundary: "label",
847
+ route: "label",
848
+ fingerprint: "label",
849
+ count: "number"
850
+ }
851
+ },
852
+ "report.rate-limited": "Renderer error entries arrived faster than the backend records them, so `dropped` were counted and not written."
853
+ }
826
854
  }
827
855
  });
828
856
 
@@ -846,6 +874,7 @@ var NATIVE_AGENT_LOG_AREAS = defineLogAreas({
846
874
  "native-agent": {
847
875
  description: "Native agent sessions and what the backend reads from their bridges.",
848
876
  events: {
877
+ "session.bridge-replaced-for-policy": "An idle bridge was stopped so a resume could apply the user's wider execution policy.",
849
878
  "catalogue.outdated-bridge": "A bridge predates the command catalogue, so its commands stay unavailable.",
850
879
  "compact.instructions-ignored": "A bridge compacted without confirming the instructions sent with /compact: it predates them.",
851
880
  "handoff.summary-read-failed": "Change summaries could not be read for a handoff, so the carrier says they are unmeasured.",
@@ -879,6 +908,8 @@ var NATIVE_AGENT_LOG_AREAS = defineLogAreas({
879
908
  "usage-limit.notice-failed": "A usage-limit stop's outcome could not be read for its notice.",
880
909
  "usage-limit.resend-failed": "Resending after a usage limit failed. An unknown send stays in the journal.",
881
910
  "title.strategy-failed": "A session title strategy failed, so the next is tried. Content-free: the error can quote the prompt.",
911
+ "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.",
912
+ "steer.capability-cleared": "A projection cleared `actions.steer` because its bridge did not qualify. Identifiers and turn status only.",
882
913
  ...THROTTLE_LOG_EVENTS
883
914
  }
884
915
  },
@@ -911,7 +942,8 @@ var NATIVE_AGENT_LOG_AREAS = defineLogAreas({
911
942
  "coordinator-servers.unavailable": "OpenCode coordinator research servers are unavailable.",
912
943
  "monitor.reconnecting": "The request monitor lost its stream and is reconnecting. Error class only.",
913
944
  "worker-limit.reached": "The bounded request workers are full, so the stream restarts and a snapshot reconciles.",
914
- "request.failed": "Handling a request event failed, so the stream restarts. Error class only."
945
+ "request.failed": "Handling a request event failed, so the stream restarts. Error class only.",
946
+ "credential-plugin.skipped": "A host OpenCode server started without the credential plugin, so its tools inherit its password; `reason` says why."
915
947
  }
916
948
  }
917
949
  });
@@ -939,6 +971,7 @@ var PREVIEW_LOG_AREAS = defineLogAreas({
939
971
  "publication.start-failed": "Private preview publication did not start.",
940
972
  "publication.reconfigure-failed": "Preview publication could not be reconfigured.",
941
973
  "publication.listening": "Private preview origins are listening.",
974
+ "publication.same-site": "The preview domain is the same site as the application; publication runs with a warning.",
942
975
  "certificate.reloaded": "The preview certificate was reloaded.",
943
976
  "access.revoked-close-failed": "A revoked preview resource could not be closed. Error class only.",
944
977
  "registry.invalid-definition": "An invalid stored preview service definition was ignored.",
@@ -977,6 +1010,9 @@ var RUNTIME_LOG_AREAS = defineLogAreas({
977
1010
  essential: true,
978
1011
  fields: { origin: "label", ...ESSENTIAL_ERROR_FIELDS }
979
1012
  },
1013
+ "child.reaped": "A macOS child whose exit Bun lost was reaped after its command settled, so it no longer waits as a zombie.",
1014
+ "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.",
1015
+ "child.reap-unavailable": "waitpid could not be loaded, so children whose exit Bun lost stay zombies until this process exits.",
980
1016
  ...THROTTLE_LOG_EVENTS
981
1017
  }
982
1018
  }
@@ -1247,10 +1283,19 @@ var STORAGE_LOG_AREAS = defineLogAreas({
1247
1283
  "retired.turn-cleanup-pending": "Cleanup of a retired Looped Review turn did not finish and stays pending.",
1248
1284
  "handoffs.prune-failed": "Pruning agent handoffs that nothing references failed; a later prune retries.",
1249
1285
  "desktop-connections.malformed": "Stored desktop connection settings were malformed, so the local connection is used.",
1286
+ "config.restrict-mode-failed": "A config file holding provider secrets could not be set to owner-only; the backend carries on.",
1250
1287
  "legacy-json.moved": "JSON store files written after the SQLite migration were archived, not imported.",
1251
1288
  "legacy-json.archive-failed": "Imported JSON store files could not be archived.",
1289
+ "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.",
1252
1290
  "lease.heartbeat-failed": "A held lease's heartbeat failed, which shortens the lease; the next one retries.",
1253
- "scrub.checkpoint-failed": "Deleted content could not be scrubbed from the WAL because the truncating checkpoint failed or was blocked; the next checkpoint retries.",
1291
+ "scrub.vacuum-failed": "Deleted-content page reclamation failed; the checkpoint is attempted independently.",
1292
+ "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.",
1293
+ "upkeep.vacuum-failed": "Periodic page reclamation failed; the next upkeep pass retries.",
1294
+ "optimize.failed": "Refreshing the query planner's statistics failed; queries still run and the next check retries.",
1295
+ "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.",
1296
+ "snapshot.top-tables-failed": "The sampled table sizes from a finished snapshot could not be saved; the snapshot stands and the next one retries.",
1297
+ "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.",
1298
+ "snapshot.ledger-failed": "The daily change-tracking ledger snapshot failed; `retryAt` says when it tries again, if known.",
1254
1299
  ...THROTTLE_LOG_EVENTS
1255
1300
  }
1256
1301
  }
@@ -1267,6 +1312,7 @@ var BUILD_PIPELINE_LOG_AREAS = defineLogAreas({
1267
1312
  "consolidation.consume-deferred": "Consuming a review consolidation result failed; it stays pending and is retried.",
1268
1313
  "dispatch.prepare-failed": "Attaching the agent before dispatch failed; the prompt request does the same work and answers authoritatively.",
1269
1314
  "interaction.resolved": "A human interaction on a pipeline stage resolved. Metadata only.",
1315
+ "user-message.background-send-refused": "The bridge refused a queued user message during a background wait; it stays queued and is retried.",
1270
1316
  "transcripts.migrated": "A transcript migration pass moved stage transcripts; counts only.",
1271
1317
  "transcripts.maintenance-failed": "Migrating or sweeping stage transcripts failed; the next start retries.",
1272
1318
  "restore.skipped": "A pipeline could not be restored at startup and was skipped.",
@@ -1304,6 +1350,8 @@ var CHANGE_TRACKING_LOG_AREAS = defineLogAreas({
1304
1350
  description: "Change tracking: turn capture, evidence pulls and measurements.",
1305
1351
  events: {
1306
1352
  "journal-import.failed": "Importing surviving OpenCode command journals as legacy summaries failed.",
1353
+ "measurement-drain.failed": "Draining an owner's superseded measurements failed; the retention pass retries.",
1354
+ "retention.failed": "A retention pass failed partway; what it deleted stands and the next pass goes on.",
1307
1355
  "projection.failed": "Projecting a change event onto its environment failed.",
1308
1356
  "startup.reconcile-failed": "Reconciling change tracking at startup failed.",
1309
1357
  "turn-start.capture-failed": "Capturing a turn's start failed, so the turn is untracked.",
@@ -1334,7 +1382,16 @@ var COORDINATOR_LOG_AREAS = defineLogAreas({
1334
1382
  coordinator: {
1335
1383
  description: "Coordinators: delegations, status wakes and their store.",
1336
1384
  events: {
1385
+ ...THROTTLE_LOG_EVENTS,
1337
1386
  "delegation.open-failed": "A delegation could not be opened; `source` says for what.",
1387
+ "delegation.reconcile-failed": "One delegation could not be settled; the rest of the pass still ran and the next one retries.",
1388
+ "delegation.wake-failed": "One delegation's wake could not be delivered; the rest of the pass still ran and the next one retries.",
1389
+ "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.",
1390
+ "delegation.wake-pass-failed": "A delegation wake pass could not run; the next sweep retries.",
1391
+ "delegation.wake-retire-failed": "A wake that keeps failing could not be given up on; the next pass retries.",
1392
+ "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.",
1393
+ "delegation.wake-retired": "A wake kept failing and was given up on; `kind` is the last failure.",
1394
+ "mail.reconcile-failed": "One coordinator's mail could not be reconciled; the sweep carried on with the others.",
1338
1395
  "deliver-now.drain-failed": "The mail delivery pass after deliverNow failed; the next sweep delivers.",
1339
1396
  "mail.move-failed": "Mail could not move to the new main coordinator.",
1340
1397
  "work.move-failed": "Work could not move to the main coordinator.",
@@ -1362,6 +1419,13 @@ var COORDINATOR_LOG_AREAS = defineLogAreas({
1362
1419
  "store.workflows-cleared": "The workflow store was full, so a batch of its oldest finished records was removed.",
1363
1420
  "store.workflows-in-use": "The workflow store was full and every record was still in use, so new work was refused.",
1364
1421
  "remote-worker.settle-failed": "A remote worker could not be settled.",
1422
+ "node-release.failed": "Work on a node that was forgotten or handed over could not be closed; the sweep's registry check retries.",
1423
+ "node-release.reconcile-failed": "The sweep could not check records against the node registry; the next sweep retries.",
1424
+ "node-release.unregistered": "Records named a node the registry no longer holds, so their work was closed here.",
1425
+ "node-release.notice-failed": "The notice for work closed on a released node could not be sent; it stays owed and the sweep retries.",
1426
+ "node-release.no-coordinator": "Work closed on a released node belonged to a coordinator that no longer exists, so nobody was told.",
1427
+ "node-offline.notice-failed": "The notice that a node has been unreachable for a day could not be sent; the next failed read retries.",
1428
+ "node-offline.check-failed": "Whether a long-unreachable node's coordinators were told could not be checked; the next read retries.",
1365
1429
  "checkout.merge-followed": "After an environment's PR merged, the project checkout was fast-forwarded, or `outcome` says why not.",
1366
1430
  "checkout.merge-follow-failed": "Fast-forwarding the project checkout failed, after an environment's PR merged or before mail woke the main coordinator.",
1367
1431
  "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`).",
@@ -1458,7 +1522,10 @@ var DOCKER_LOG_AREAS = defineLogAreas({
1458
1522
  events: {
1459
1523
  "portable-inputs.relay-missing": "Docker is rootless and the image predates the staged-input relay, so the container cannot read them until rebuilt.",
1460
1524
  "git-mirror.mount-unavailable": "A new container gets no project Git mirror, so its clone goes to the remote.",
1525
+ "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.",
1461
1526
  "git-mirror.refreshed": "A project's Git mirror was built or updated.",
1527
+ "git-mirror.seeded": "A project's Git mirror was built from its host checkout and only what the remote added to it.",
1528
+ "git-mirror.seed-skipped": "A project's host checkout could not seed its Git mirror, so the build downloads everything.",
1462
1529
  "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.",
1463
1530
  "git-mirror.low-disk": "A project's Git mirror was not updated: the disk is nearly full.",
1464
1531
  "git-mirror.oversized": "A project's repository is too large for a Git mirror, so its environments keep the blobless clone.",
@@ -1470,6 +1537,7 @@ var DOCKER_LOG_AREAS = defineLogAreas({
1470
1537
  "git-mirror.clone-fallback": "A new environment could not clone from its project's Git mirror and cloned from the remote.",
1471
1538
  "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.",
1472
1539
  "opencode.warm-incomplete": "OpenCode did not finish loading /workspace in a container.",
1540
+ "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.",
1473
1541
  "lifecycle-event.reconcile-failed": "Reconciling an environment after a container start or stop event failed; the next status read retries.",
1474
1542
  "login-keeper.pass-failed": "A Claude login keeper pass failed; the next interval retries.",
1475
1543
  "login-keeper.refresh-failed": "Refreshing the host Claude login failed. Fixed text: CLI output can hold credentials.",
@@ -1493,6 +1561,7 @@ var DOCKER_LOG_AREAS = defineLogAreas({
1493
1561
  essential: true,
1494
1562
  fields: { staleForMs: "number" }
1495
1563
  },
1564
+ "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.",
1496
1565
  "writer-lease.not-acquired": {
1497
1566
  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.",
1498
1567
  essential: true,
@@ -1630,6 +1699,7 @@ var NODES_LOG_AREAS = defineLogAreas({
1630
1699
  "verification.record-failed": "A node verification could not be recorded.",
1631
1700
  "profile.record-failed": "A node profile could not be recorded.",
1632
1701
  "detach.unconfirmed": "A forgotten node has not confirmed the detach yet.",
1702
+ "grant.revocation-listener-failed": "A connection could not be told its client grant was removed; the grant is still gone.",
1633
1703
  "handover.recovery-pending": "Command handover recovery is still pending.",
1634
1704
  "ticket-sync.work-record-failed": "A remote build started but its ticket work location could not be saved.",
1635
1705
  "ticket-sync.failed": "A Kanban sync with a node failed; it is retried.",
@@ -1682,7 +1752,9 @@ var HOST_LOG_AREAS = defineLogAreas({
1682
1752
  "tool.missing": "A host tool was not found.",
1683
1753
  "maintenance.listener-failed": "A host maintenance listener threw; the others still run.",
1684
1754
  "suspend.reconcile-failed": "Reconciling due work after a host suspension failed.",
1685
- "load.sample-failed": "Sampling machine load failed; the next sample retries."
1755
+ "load.sample-failed": "Sampling machine load failed; the next sample retries.",
1756
+ "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.",
1757
+ ...THROTTLE_LOG_EVENTS
1686
1758
  }
1687
1759
  }
1688
1760
  });
@@ -2147,6 +2219,7 @@ var WEB_SYNC_LOG_AREAS = defineLogAreas({
2147
2219
  events: {
2148
2220
  "events.disconnected": "The main event stream dropped; it reconnects and replays.",
2149
2221
  "terminal-stream.disconnected": "A terminal event stream dropped; it reconnects.",
2222
+ "relayed-stream.disconnected": "The relayed node event stream dropped; it reconnects.",
2150
2223
  "connection-listener.failed": "A main stream connection state listener threw.",
2151
2224
  "event-listener.failed": "A listener for a gateway event threw.",
2152
2225
  "stream-listener.failed": "A listener for the stream-connected notice threw."
@@ -3277,9 +3350,76 @@ function createBridgeDiagnostics(bridge, state, metrics) {
3277
3350
  }
3278
3351
  var bufferedFlushes = new Set;
3279
3352
 
3353
+ // ../protocol/src/node/bridge-credential.ts
3354
+ import { createHash as createHash2, randomBytes, timingSafeEqual } from "node:crypto";
3355
+ import { createRequire } from "node:module";
3356
+ var BRIDGE_TOKEN_PREFIX = "okb_";
3357
+ var PR_SET_DUMPABLE = 4;
3358
+ var VERIFIER_PATTERN = /^[0-9a-f]{64}$/;
3359
+ var log3 = createLogger("bridge.lifecycle");
3360
+ function mintBridgeToken() {
3361
+ return `${BRIDGE_TOKEN_PREFIX}${randomBytes(32).toString("base64url")}`;
3362
+ }
3363
+ function bridgeTokenVerifier(token) {
3364
+ return createHash2("sha256").update(token).digest("hex");
3365
+ }
3366
+ function bridgeTokenVerifierEnv(tokenEnv) {
3367
+ return `${tokenEnv}_SHA256`;
3368
+ }
3369
+ function credentialFromVerifier(verifier, plainToken) {
3370
+ const expected = Buffer.from(verifier, "hex");
3371
+ return {
3372
+ plainToken,
3373
+ matches(candidate) {
3374
+ if (!candidate)
3375
+ return false;
3376
+ return timingSafeEqual(expected, createHash2("sha256").update(candidate).digest());
3377
+ }
3378
+ };
3379
+ }
3380
+ function bridgeCredentialFromToken(token) {
3381
+ return credentialFromVerifier(bridgeTokenVerifier(token), token);
3382
+ }
3383
+ function markProcessNonDumpable(loadFfi = () => createRequire(import.meta.url)("bun:ffi")) {
3384
+ if (process.platform !== "linux" || !process.versions.bun)
3385
+ return false;
3386
+ try {
3387
+ const { dlopen, FFIType } = loadFfi();
3388
+ const libc = dlopen("libc.so.6", {
3389
+ prctl: {
3390
+ args: [FFIType.i32, FFIType.u64, FFIType.u64, FFIType.u64, FFIType.u64],
3391
+ returns: FFIType.i32
3392
+ }
3393
+ });
3394
+ try {
3395
+ if (libc.symbols.prctl(PR_SET_DUMPABLE, 0n, 0n, 0n, 0n) === 0)
3396
+ return true;
3397
+ } finally {
3398
+ libc.close();
3399
+ }
3400
+ log3.warn("credential.not-hardened", { reason: "prctl-refused" });
3401
+ } catch {
3402
+ log3.warn("credential.not-hardened", { reason: "ffi-unavailable" });
3403
+ }
3404
+ return false;
3405
+ }
3406
+ function loadBridgeCredential(tokenEnv, options = {}) {
3407
+ const env = options.env ?? process.env;
3408
+ const verifierEnv = bridgeTokenVerifierEnv(tokenEnv);
3409
+ const verifier = env[verifierEnv]?.trim();
3410
+ const token = env[tokenEnv]?.trim();
3411
+ delete env[verifierEnv];
3412
+ delete env[tokenEnv];
3413
+ if (verifier) {
3414
+ (options.harden ?? markProcessNonDumpable)();
3415
+ return VERIFIER_PATTERN.test(verifier) ? credentialFromVerifier(verifier, undefined) : bridgeCredentialFromToken(mintBridgeToken());
3416
+ }
3417
+ return bridgeCredentialFromToken(token || mintBridgeToken());
3418
+ }
3419
+
3280
3420
  // ../../bridges/acp-bridge/src/acp-context.ts
3281
3421
  import { spawn as spawn2 } from "node:child_process";
3282
- import { createHmac, randomBytes as randomBytes2, timingSafeEqual } from "node:crypto";
3422
+ import { createHmac, randomBytes as randomBytes3, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
3283
3423
  import { resolve as resolve3 } from "node:path";
3284
3424
 
3285
3425
  // ../protocol/src/capacity-retry.ts
@@ -12104,7 +12244,7 @@ import { spawn } from "node:child_process";
12104
12244
  import { constants } from "node:fs";
12105
12245
  import { lstat, open as open2, realpath } from "node:fs/promises";
12106
12246
  import { dirname, isAbsolute, join as join2, relative, resolve, sep } from "node:path";
12107
- import { randomBytes } from "node:crypto";
12247
+ import { randomBytes as randomBytes2 } from "node:crypto";
12108
12248
 
12109
12249
  // ../protocol/src/coordinator-web-research.ts
12110
12250
  var DEFAULT_COORDINATOR_RESEARCH_MCP_SERVERS = Object.freeze([{ name: "context7", url: "https://mcp.context7.com/mcp" }]);
@@ -12520,7 +12660,7 @@ class AcpClientMethods {
12520
12660
  }
12521
12661
  const cwd = await secureTerminalCwd(request.cwd, this.workspaceRoot);
12522
12662
  const outputLimit = Math.min(MAX_TERMINAL_OUTPUT_BYTES, Number.isSafeInteger(request.outputByteLimit) && (request.outputByteLimit ?? 0) > 0 ? request.outputByteLimit : DEFAULT_TERMINAL_OUTPUT_BYTES);
12523
- const terminalId = randomBytes(16).toString("hex");
12663
+ const terminalId = randomBytes2(16).toString("hex");
12524
12664
  const child = this.spawnTerminalImpl(request.command, request.args ?? [], {
12525
12665
  cwd,
12526
12666
  env: withoutBridgeControlEnvironment({
@@ -12918,7 +13058,7 @@ function grokQuestionTimeoutFromEnv(env) {
12918
13058
  }
12919
13059
 
12920
13060
  // ../../bridges/acp-bridge/src/acp-mcp-inventory.ts
12921
- import { createHash as createHash2 } from "node:crypto";
13061
+ import { createHash as createHash3 } from "node:crypto";
12922
13062
  import { readFile, stat } from "node:fs/promises";
12923
13063
  import { homedir as homedir2 } from "node:os";
12924
13064
  import { join as join4, resolve as resolve2 } from "node:path";
@@ -13009,7 +13149,7 @@ function grokMcpConfigFiles(options = { cwd: process.cwd() }) {
13009
13149
  }
13010
13150
  async function fileDigest(file) {
13011
13151
  try {
13012
- return `sha256:${createHash2("sha256").update(await readFile(file)).digest("base64url")}`;
13152
+ return `sha256:${createHash3("sha256").update(await readFile(file)).digest("base64url")}`;
13013
13153
  } catch {
13014
13154
  return "absent";
13015
13155
  }
@@ -13017,7 +13157,7 @@ async function fileDigest(file) {
13017
13157
  async function grokMcpConfigFingerprint(files) {
13018
13158
  const [user, project] = await Promise.all([fileDigest(files.user), fileDigest(files.project)]);
13019
13159
  return {
13020
- fingerprint: createHash2("sha256").update(`user=${user}\x00project=${project}`).digest("base64url"),
13160
+ fingerprint: createHash3("sha256").update(`user=${user}\x00project=${project}`).digest("base64url"),
13021
13161
  sources: { user, project }
13022
13162
  };
13023
13163
  }
@@ -13076,26 +13216,20 @@ function grokMcpConfigStatus(loaded, current) {
13076
13216
  }
13077
13217
 
13078
13218
  // ../../bridges/acp-bridge/src/acp-context.ts
13079
- var log3 = createLogger("bridge.acp");
13219
+ var log4 = createLogger("bridge.acp");
13080
13220
  var CURSOR_TODO_STATUSES = ["pending", "in_progress", "completed", "cancelled"];
13081
13221
  var providerConfig = loadAcpProviderConfig();
13082
13222
  var provider = providerConfig.id;
13083
13223
  var port = parsePort(process.env.PORT);
13084
13224
  var hostname = process.env.HOSTNAME?.trim() || "127.0.0.1";
13085
13225
  var workingDirectory = resolve3(process.env.CWD?.trim() || process.cwd());
13086
- var authToken = process.env.ACP_BRIDGE_TOKEN?.trim() || randomBytes2(32).toString("base64url");
13087
- delete process.env.ACP_BRIDGE_TOKEN;
13226
+ var bridgeCredential = loadBridgeCredential("ACP_BRIDGE_TOKEN");
13227
+ var authToken = bridgeCredential.plainToken ?? "";
13228
+ var externalSessionKey = randomBytes3(32);
13088
13229
  var executable = providerConfig.executable;
13089
13230
  var stateDirectory = process.env.ACP_STATE_DIR?.trim();
13090
13231
  var stateFile = stateDirectory ? resolve3(stateDirectory, "state.json") : null;
13091
13232
  var sessions = new Map;
13092
- var cursorDiscoveryRevision = 0;
13093
- function currentCursorDiscoveryRevision() {
13094
- return cursorDiscoveryRevision;
13095
- }
13096
- function bumpCursorDiscoveryRevision() {
13097
- cursorDiscoveryRevision = cursorDiscoveryRevision >= Number.MAX_SAFE_INTEGER ? 0 : cursorDiscoveryRevision + 1;
13098
- }
13099
13233
  var acpToolSourceStates = new WeakMap;
13100
13234
  var saturatedText = new WeakSet;
13101
13235
  var trimmedToolCalls = new WeakMap;
@@ -13209,18 +13343,6 @@ var CLOSE_ATTACH_WAIT_MS = parseDuration(process.env.ACP_CLOSE_ATTACH_WAIT_MS, 5
13209
13343
  var CLOSE_CANCEL_WAIT_MS = parseDuration(process.env.ACP_CLOSE_CANCEL_WAIT_MS, 2000);
13210
13344
  var CLOSE_SESSION_WAIT_MS = parseDuration(process.env.ACP_CLOSE_SESSION_WAIT_MS, 2000);
13211
13345
  var SESSION_CLOSING_ERROR = "Session is closing";
13212
- var CURSOR_BACKGROUND_WAIT_MS = parseDuration(process.env.ACP_CURSOR_BACKGROUND_WAIT_MS, 30 * 60000);
13213
- var MAX_CURSOR_BACKGROUND_CONTINUATIONS = 4;
13214
- var MAX_CURSOR_CHILD_RESULT_BYTES = 64 * 1024;
13215
- var MAX_CURSOR_CHILD_PARTS = 64;
13216
- var MAX_CURSOR_TRANSCRIPT_HYDRATE_CHILDREN = 8;
13217
- var MAX_CURSOR_SETTLED_CLAIMS = 64;
13218
- var CURSOR_JSONL_SOURCE_PREFIX = "cursor-jsonl:";
13219
- var MAX_CURSOR_DISCOVERY_ENTRIES = 4096;
13220
- var CURSOR_CHILD_DISCOVERY_SKEW_MS = 5000;
13221
- var MAX_CURSOR_CHILD_PROMPT_BYTES = 4 * 1024;
13222
- var MAX_CURSOR_CHILD_PROMPT_RECORDS = 8;
13223
- var CURSOR_BACKGROUND_CONTINUATION_PREFIX = "Background subagent finished.";
13224
13346
  var POLICY_DENIAL_MAX_CONTINUATIONS = 8;
13225
13347
  var RETRIABLE_PROVIDER_RETRY_POLICY = {
13226
13348
  ...DEFAULT_CAPACITY_RETRY_POLICY,
@@ -13315,7 +13437,7 @@ class AcpProcess {
13315
13437
  }
13316
13438
  this.child.once("error", (error) => this.#close(error));
13317
13439
  this.child.once("exit", (code, signal) => {
13318
- log3.warn("agent.exited", {
13440
+ log4.warn("agent.exited", {
13319
13441
  provider,
13320
13442
  pid: this.child.pid ?? null,
13321
13443
  code,
@@ -13562,7 +13684,7 @@ function activeSessionReservations() {
13562
13684
  var EXTERNAL_SESSION_PREFIX = "acp-session:";
13563
13685
  function externalSessionToken(acpSessionId) {
13564
13686
  const encoded = Buffer.from(acpSessionId).toString("base64url");
13565
- const signature = createHmac("sha256", authToken).update(encoded).digest("base64url");
13687
+ const signature = createHmac("sha256", externalSessionKey).update(encoded).digest("base64url");
13566
13688
  return `${EXTERNAL_SESSION_PREFIX}${encoded}.${signature}`;
13567
13689
  }
13568
13690
  function parseExternalSessionToken(value) {
@@ -13576,14 +13698,14 @@ function parseExternalSessionToken(value) {
13576
13698
  const signature = token.slice(separator + 1);
13577
13699
  if (!encoded || encoded.length > 1024 || !signature)
13578
13700
  return null;
13579
- const expected = createHmac("sha256", authToken).update(encoded).digest();
13701
+ const expected = createHmac("sha256", externalSessionKey).update(encoded).digest();
13580
13702
  let supplied;
13581
13703
  try {
13582
13704
  supplied = Buffer.from(signature, "base64url");
13583
13705
  } catch {
13584
13706
  return null;
13585
13707
  }
13586
- if (supplied.length !== expected.length || !timingSafeEqual(supplied, expected))
13708
+ if (supplied.length !== expected.length || !timingSafeEqual2(supplied, expected))
13587
13709
  return null;
13588
13710
  let decoded;
13589
13711
  try {
@@ -14420,7 +14542,7 @@ function encodedStringBytes(value, previous) {
14420
14542
  // ../../bridges/acp-bridge/src/acp-persist-writer.ts
14421
14543
  import { promises as fs2 } from "node:fs";
14422
14544
  import { dirname as dirname2 } from "node:path";
14423
- import { randomBytes as randomBytes3 } from "node:crypto";
14545
+ import { randomBytes as randomBytes4 } from "node:crypto";
14424
14546
 
14425
14547
  // ../protocol/src/node/transcript-window.ts
14426
14548
  import { Buffer as Buffer4 } from "node:buffer";
@@ -14510,7 +14632,7 @@ function boundTranscriptResponse(messages, maximumBytes, options = {}) {
14510
14632
  }
14511
14633
 
14512
14634
  // ../../bridges/acp-bridge/src/acp-persist-writer.ts
14513
- var log4 = createLogger("bridge.acp");
14635
+ var log5 = createLogger("bridge.acp");
14514
14636
  function boundPersistedSnapshot(snapshot) {
14515
14637
  const bounded = {
14516
14638
  ...snapshot,
@@ -14665,10 +14787,7 @@ function persistedSnapshot() {
14665
14787
  ...state.commandsRevision === undefined ? {} : { commandsRevision: state.commandsRevision },
14666
14788
  ...state.commandsTruncated ? { commandsTruncated: true } : {},
14667
14789
  ...state.title ? { title: state.title } : {},
14668
- ...state.subagentLimitExceeded ? { subagentLimitExceeded: true } : {},
14669
- ...state.settledCursorAgentIds.size > 0 ? {
14670
- settledCursorAgentIds: Array.from(state.settledCursorAgentIds).slice(-MAX_CURSOR_SETTLED_CLAIMS)
14671
- } : {}
14790
+ ...state.subagentLimitExceeded ? { subagentLimitExceeded: true } : {}
14672
14791
  }))
14673
14792
  };
14674
14793
  return boundPersistedSnapshot(snapshot);
@@ -14707,7 +14826,7 @@ function schedulePersist() {
14707
14826
  await writePersistedState();
14708
14827
  });
14709
14828
  setPersistenceTail(operation.catch((error) => {
14710
- log4.warn("state.persist-failed", { error: formatLogError(error, { stack: false }) });
14829
+ log5.warn("state.persist-failed", { error: formatLogError(error, { stack: false }) });
14711
14830
  }));
14712
14831
  }
14713
14832
  function persistState() {
@@ -14727,16 +14846,16 @@ async function writePersistedState() {
14727
14846
  throw new Error("ACP persisted state exceeds its byte limit");
14728
14847
  }
14729
14848
  await fs2.mkdir(dirname2(file), { recursive: true, mode: 448 });
14730
- const temporary = `${file}.${process.pid}.${randomBytes3(6).toString("hex")}.tmp`;
14849
+ const temporary = `${file}.${process.pid}.${randomBytes4(6).toString("hex")}.tmp`;
14731
14850
  await fs2.writeFile(temporary, payload, { mode: 384 });
14732
14851
  await fs2.rename(temporary, file);
14733
14852
  }
14734
14853
 
14735
14854
  // ../../bridges/acp-bridge/src/acp-rows.ts
14736
- import { randomBytes as randomBytes4 } from "node:crypto";
14855
+ import { randomBytes as randomBytes5 } from "node:crypto";
14737
14856
 
14738
14857
  // ../protocol/src/node/revised-rows.ts
14739
- import { createHash as createHash3 } from "node:crypto";
14858
+ import { createHash as createHash4 } from "node:crypto";
14740
14859
  var RECENTLY_REVISED_ROWS_MAX = 128;
14741
14860
 
14742
14861
  class RecentlyRevisedRows {
@@ -14774,7 +14893,7 @@ class RecentlyRevisedRows {
14774
14893
  function revisedRowsReconciliationToken(overflowVersion, omitted) {
14775
14894
  if (overflowVersion === 0 && omitted.length === 0)
14776
14895
  return;
14777
- const digest = createHash3("sha256").update(String(overflowVersion));
14896
+ const digest = createHash4("sha256").update(String(overflowVersion));
14778
14897
  for (const row of omitted)
14779
14898
  digest.update(JSON.stringify(row) ?? "null");
14780
14899
  return digest.digest("hex");
@@ -14823,7 +14942,7 @@ function currentAssistantMessage(state) {
14823
14942
  if (!message || message.role !== "assistant" || rowIsFull(message) || state.status !== "running" && state.historyReplay !== "hydrate") {
14824
14943
  const modelId = boundedModelId(state.sessionConfig.composer.selectedModelId);
14825
14944
  message = {
14826
- id: randomBytes4(12).toString("hex"),
14945
+ id: randomBytes5(12).toString("hex"),
14827
14946
  role: "assistant",
14828
14947
  content: "",
14829
14948
  parts: [],
@@ -15759,44 +15878,12 @@ function ensureAcpToolSource(part) {
15759
15878
  acpToolSourceStates.set(part, source);
15760
15879
  return source;
15761
15880
  }
15762
- function recordCursorTaskPrompt(part, prompt) {
15763
- const bounded = truncateUtf8(prompt.trim(), MAX_CURSOR_CHILD_PROMPT_BYTES);
15764
- if (!bounded)
15765
- return false;
15766
- const source = ensureAcpToolSource(part);
15767
- if (source.cursorTask?.prompt)
15768
- return false;
15769
- source.cursorTask = { ...source.cursorTask, prompt: bounded };
15770
- renderAcpToolSource(part, source);
15771
- return true;
15772
- }
15773
- function toolPartAgentId(part) {
15774
- if (typeof part.toolArgs?.agentId === "string") {
15775
- return truncateUtf8(part.toolArgs.agentId.trim(), MAX_TOOL_ID_BYTES);
15776
- }
15777
- if (typeof part.toolArgs?.agent_id === "string") {
15778
- return truncateUtf8(part.toolArgs.agent_id.trim(), MAX_TOOL_ID_BYTES);
15779
- }
15780
- const lifecycle = toolCallLifecycle(part.toolOutput);
15781
- if (typeof lifecycle?.agentId === "string") {
15782
- return truncateUtf8(lifecycle.agentId.trim(), MAX_TOOL_ID_BYTES);
15783
- }
15784
- if (typeof lifecycle?.agent_id === "string") {
15785
- return truncateUtf8(lifecycle.agent_id.trim(), MAX_TOOL_ID_BYTES);
15786
- }
15787
- return;
15788
- }
15789
15881
  function syncActiveSubagentTool(state, part) {
15790
15882
  if (part.agentState === "active") {
15791
- const agentId = toolPartAgentId(part);
15792
- const reportedPrompt = part.cursorTaskPromptReported === true && typeof part.toolArgs?.prompt === "string" ? truncateUtf8(part.toolArgs.prompt.trim(), MAX_CURSOR_CHILD_PROMPT_BYTES) : undefined;
15793
15883
  const activated = activateSubagent(state, part.toolUseId, {
15794
15884
  ...typeof part.toolArgs?.description === "string" ? { description: truncateUtf8(part.toolArgs.description.trim(), MAX_TOOL_TITLE_BYTES) } : {},
15795
15885
  ...typeof part.toolArgs?.subagent_type === "string" ? { subagentType: truncateUtf8(part.toolArgs.subagent_type.trim(), MAX_TOOL_NAME_BYTES) } : {},
15796
- ...part.toolState ? { toolState: part.toolState } : {},
15797
- ...reportedPrompt ? { reportedPrompt } : {},
15798
- ...agentId ? { agentId, agentIdDiscovered: false } : {},
15799
- ...agentId ? { agentIdSettlementSafe: false } : {}
15886
+ ...part.toolState ? { toolState: part.toolState } : {}
15800
15887
  });
15801
15888
  if (!activated) {
15802
15889
  part.agentState = "failed";
@@ -15833,32 +15920,25 @@ function activateSubagent(state, toolUseId, descriptor) {
15833
15920
  state.child?.notify("session/cancel", { sessionId: state.acpSessionId });
15834
15921
  return false;
15835
15922
  }
15836
- const wasActive = state.activeSubagentToolIds.has(toolUseId);
15837
15923
  const previous = state.activeSubagentDescriptors.get(toolUseId);
15838
15924
  const next = {
15839
15925
  ...previous,
15840
15926
  ...descriptor,
15841
- agentId: descriptor.agentId ?? previous?.agentId,
15842
15927
  description: descriptor.description ?? previous?.description,
15843
15928
  subagentType: descriptor.subagentType ?? previous?.subagentType,
15844
15929
  toolState: descriptor.toolState ?? previous?.toolState
15845
15930
  };
15846
15931
  state.activeSubagentToolIds.add(toolUseId);
15847
15932
  state.activeSubagentDescriptors.set(toolUseId, next);
15848
- if (!wasActive || previous?.agentId !== next.agentId || previous?.agentIdDiscovered !== next.agentIdDiscovered || previous?.agentIdSettlementSafe !== next.agentIdSettlementSafe || previous?.reportedPrompt !== next.reportedPrompt) {
15849
- bumpCursorDiscoveryRevision();
15850
- }
15851
15933
  return true;
15852
15934
  }
15853
15935
  function settleActiveSubagent(state, toolUseId) {
15854
- const activeDeleted = state.activeSubagentToolIds.delete(toolUseId);
15855
- const descriptorDeleted = state.activeSubagentDescriptors.delete(toolUseId);
15936
+ state.activeSubagentToolIds.delete(toolUseId);
15937
+ state.activeSubagentDescriptors.delete(toolUseId);
15856
15938
  for (const [subagentId, mappedToolUseId] of state.subagentToolIds) {
15857
15939
  if (mappedToolUseId === toolUseId)
15858
15940
  state.subagentToolIds.delete(subagentId);
15859
15941
  }
15860
- if (activeDeleted || descriptorDeleted)
15861
- bumpCursorDiscoveryRevision();
15862
15942
  }
15863
15943
  var MAX_CURSOR_TASK_PROMPT_BYTES = 64 * 1024;
15864
15944
  var TASK_LAUNCH_ARG_KEYS = [
@@ -16340,8 +16420,6 @@ function applyCursorTask(state, params) {
16340
16420
  }
16341
16421
  }
16342
16422
  renderAcpToolSource(part, source);
16343
- if (prompt)
16344
- part.cursorTaskPromptReported = true;
16345
16423
  if (part.agentState === "finished" || part.agentState === "failed") {
16346
16424
  stampSubagentRuntimeDuration(part);
16347
16425
  }
@@ -16349,7 +16427,6 @@ function applyCursorTask(state, params) {
16349
16427
  commitToolPartMutation(state, part, source);
16350
16428
  }
16351
16429
  function failAllActiveSubagents(state) {
16352
- const hadActiveSubagents = state.activeSubagentToolIds.size > 0 || state.activeSubagentDescriptors.size > 0;
16353
16430
  for (const message of state.messages) {
16354
16431
  for (const part of message.parts) {
16355
16432
  if (part.type !== "tool-invocation" || !state.activeSubagentToolIds.has(part.toolUseId))
@@ -16365,8 +16442,6 @@ function failAllActiveSubagents(state) {
16365
16442
  state.activeSubagentToolIds.clear();
16366
16443
  state.activeSubagentDescriptors.clear();
16367
16444
  state.subagentToolIds.clear();
16368
- if (hadActiveSubagents)
16369
- bumpCursorDiscoveryRevision();
16370
16445
  }
16371
16446
  function settleEvictedSubagentFromToolUpdate(state, toolUseId, update) {
16372
16447
  const toolState = mapAcpToolState(update.status);
@@ -16702,7 +16777,7 @@ var DEFAULT_WORKFLOW_RESULT_TOOLS_SETTINGS = {
16702
16777
  };
16703
16778
 
16704
16779
  // ../../bridges/acp-bridge/src/acp-session.ts
16705
- import { randomBytes as randomBytes7 } from "node:crypto";
16780
+ import { randomBytes as randomBytes8 } from "node:crypto";
16706
16781
  import { resolve as resolve7 } from "node:path";
16707
16782
 
16708
16783
  // ../../bridges/acp-bridge/src/session-config.ts
@@ -17930,18 +18005,18 @@ async function readJournal(path, maxEntries) {
17930
18005
  }
17931
18006
 
17932
18007
  // ../../bridges/acp-bridge/src/grok-interjection.ts
17933
- import { createHash as createHash4, randomBytes as randomBytes5 } from "node:crypto";
18008
+ import { createHash as createHash5, randomBytes as randomBytes6 } from "node:crypto";
17934
18009
  var GROK_INTERJECT_METHOD = "_x.ai/interject";
17935
18010
  var GROK_INTERJECTION_NOTIFICATION = "_x.ai/session/interjection";
17936
18011
  var MAX_GROK_INTERJECTION_JOURNAL = 256;
17937
18012
  var MAX_GROK_INTERJECTION_ID_BYTES = 512;
17938
18013
  var MAX_GROK_INTERJECTION_TEXT_BYTES = 64 * 1024;
17939
- var grokBridgeGeneration = randomBytes5(12).toString("base64url");
18014
+ var grokBridgeGeneration = randomBytes6(12).toString("base64url");
17940
18015
  function grokRunId(promptSequence) {
17941
18016
  return `grok:${grokBridgeGeneration}:${promptSequence}`;
17942
18017
  }
17943
18018
  function grokInterjectionDigest(text) {
17944
- return createHash4("sha256").update(text).digest("hex");
18019
+ return createHash5("sha256").update(text).digest("hex");
17945
18020
  }
17946
18021
  function parseGrokInterjectResult(value) {
17947
18022
  if (!isObject6(value) || value.status !== "queued")
@@ -18033,7 +18108,7 @@ function applyGrokInterjectionBroadcast(journal, acpSessionId, method, params, n
18033
18108
  return broadcast;
18034
18109
  }
18035
18110
  async function probeGrokInterjectionExtension(requester) {
18036
- const probeId = `orkestrator-qualification-${randomBytes5(12).toString("base64url")}`;
18111
+ const probeId = `orkestrator-qualification-${randomBytes6(12).toString("base64url")}`;
18037
18112
  try {
18038
18113
  await requestGrokInterjection(requester, {
18039
18114
  sessionId: probeId,
@@ -18069,7 +18144,7 @@ function isObject6(value) {
18069
18144
  }
18070
18145
 
18071
18146
  // ../../bridges/acp-bridge/src/acp-commands.ts
18072
- import { randomBytes as randomBytes6 } from "node:crypto";
18147
+ import { randomBytes as randomBytes7 } from "node:crypto";
18073
18148
 
18074
18149
  // ../protocol/src/agent-command-catalogue.ts
18075
18150
  var NATIVE_AGENT_COMMAND_CATALOGUE_VERSION = 1;
@@ -18200,7 +18275,7 @@ function commandUnavailableResponse(message) {
18200
18275
  }
18201
18276
 
18202
18277
  // ../../bridges/acp-bridge/src/acp-commands.ts
18203
- var COMMAND_CATALOGUE_GENERATION = `${provider}:${randomBytes6(8).toString("hex")}`;
18278
+ var COMMAND_CATALOGUE_GENERATION = `${provider}:${randomBytes7(8).toString("hex")}`;
18204
18279
  var COMMAND_ROWS_BYTE_BUDGET = COMMAND_CATALOGUE_LIMITS.maxWireBytes - 16 * 1024;
18205
18280
  var PROVIDER_LABEL = `${provider.charAt(0).toUpperCase()}${provider.slice(1)}`;
18206
18281
  function commandId(name) {
@@ -18372,7 +18447,7 @@ function compactCommandSelection(state) {
18372
18447
  }
18373
18448
 
18374
18449
  // ../../bridges/acp-bridge/src/acp-persistence.ts
18375
- var log5 = createLogger("bridge.acp");
18450
+ var log6 = createLogger("bridge.acp");
18376
18451
  async function listNormalizedModels(signal) {
18377
18452
  const live = mergeComposerCatalog(provider, [
18378
18453
  ...catalogCache ? [catalogCache] : [],
@@ -18420,14 +18495,14 @@ function restoreSessionConfig(candidate) {
18420
18495
  const restored = parsePersistedAcpSessionConfig(provider, candidate.sessionConfig);
18421
18496
  if (restored)
18422
18497
  return restored;
18423
- log5.warn("state.session-config-reset");
18498
+ log6.warn("state.session-config-reset");
18424
18499
  return emptySessionConfig();
18425
18500
  }
18426
18501
  if (candidate.composer !== undefined) {
18427
18502
  const composer = parsePersistedComposerState(provider, candidate.composer);
18428
18503
  if (composer)
18429
18504
  return { ...emptySessionConfig(), composer };
18430
- log5.warn("state.composer-reset");
18505
+ log6.warn("state.composer-reset");
18431
18506
  }
18432
18507
  return emptySessionConfig();
18433
18508
  }
@@ -18508,9 +18583,8 @@ async function restorePersistedState() {
18508
18583
  await loadPersistedState();
18509
18584
  } catch (error) {
18510
18585
  sessions.clear();
18511
- bumpCursorDiscoveryRevision();
18512
18586
  clientSessionKeys.clear();
18513
- log5.warn("state.discarded", { error: formatLogError(error, { stack: false }) });
18587
+ log6.warn("state.discarded", { error: formatLogError(error, { stack: false }) });
18514
18588
  const file = stateFile;
18515
18589
  if (!file)
18516
18590
  return;
@@ -18562,7 +18636,6 @@ async function loadPersistedState() {
18562
18636
  messages,
18563
18637
  activeSubagentToolIds: new Set,
18564
18638
  activeSubagentDescriptors: new Map,
18565
- settledCursorAgentIds: new Set,
18566
18639
  subagentLimitExceeded: candidate.subagentLimitExceeded === true,
18567
18640
  subagentToolIds: new Map,
18568
18641
  cursorTodos: restoreCursorTodosFromMessages(messages),
@@ -18749,7 +18822,6 @@ function normalizeBridgePart(value, index, messageId) {
18749
18822
  ...isObject3(value.toolArgs) ? { toolArgs: boundedToolArguments(value.toolArgs) } : {},
18750
18823
  ...toolState ? { toolState } : {},
18751
18824
  ...agentState ? { agentState } : {},
18752
- ...value.cursorTaskPromptReported === true ? { cursorTaskPromptReported: true } : {},
18753
18825
  ...toolTitle ? { toolTitle } : {},
18754
18826
  ...toolOutput !== undefined ? { toolOutput } : {},
18755
18827
  ...toolError !== undefined ? { toolError } : {},
@@ -18786,10 +18858,178 @@ function isStringTuple(value) {
18786
18858
  return Array.isArray(value) && value.length === 2 && typeof value[0] === "string";
18787
18859
  }
18788
18860
 
18861
+ // ../protocol/src/rich-content-policy.ts
18862
+ var KIB = 1024;
18863
+ var MIB = 1024 * KIB;
18864
+ var CODE_BLOCK_POLICY = {
18865
+ maxHighlightBytes: 32 * KIB,
18866
+ maxHighlightLines: 2000,
18867
+ initialVisualLines: 24
18868
+ };
18869
+ var MERMAID_POLICY = {
18870
+ maxSourceBytes: 32 * KIB,
18871
+ maxEdges: 250,
18872
+ maxSvgBytes: 1 * MIB,
18873
+ maxSvgElements: 5000,
18874
+ renderTimeoutMs: 5000
18875
+ };
18876
+ var CHART_POLICY = {
18877
+ maxPayloadBytes: 256 * KIB,
18878
+ maxSeries: 6,
18879
+ maxBarCategories: 100,
18880
+ maxCartesianPoints: 2000,
18881
+ maxDonutSlices: 24,
18882
+ maxTitleCharacters: 200,
18883
+ maxLabelCharacters: 200,
18884
+ maxDescriptionCharacters: 2000,
18885
+ maxSourceNotes: 8,
18886
+ maxSourceNoteCharacters: 500,
18887
+ maxIdCharacters: 64,
18888
+ maxUnitCharacters: 32,
18889
+ maxAbsoluteValue: 1000000000000000,
18890
+ maxJsonDepth: 16
18891
+ };
18892
+ var WORKFLOW_SNAPSHOT_POLICY = {
18893
+ maxNormalizedBytes: 256 * KIB,
18894
+ maxNodes: 200,
18895
+ maxEdges: 400,
18896
+ maxIdCharacters: 128,
18897
+ maxLabelCharacters: 200,
18898
+ maxDescriptionCharacters: 2000,
18899
+ maxRawStatusCharacters: 100,
18900
+ maxLinksPerNode: 8
18901
+ };
18902
+ var STATIC_HTML_POLICY = {
18903
+ maxSourceBytes: 256 * KIB,
18904
+ maxPreparedBytes: 16 * MIB,
18905
+ maxElements: 5000
18906
+ };
18907
+ var STATIC_PRESENTATION_POLICY = {
18908
+ maxDocumentBytes: STATIC_HTML_POLICY.maxSourceBytes,
18909
+ maxElements: STATIC_HTML_POLICY.maxElements,
18910
+ maxFramesPerWindow: 4,
18911
+ renderTimeoutMs: 15000,
18912
+ maxSizeChangesPerWindow: 16,
18913
+ sizeChangeWindowMs: 5000,
18914
+ maxRefusedMessages: 100,
18915
+ maxSearchTextCharacters: 64 * KIB,
18916
+ searchTextChunkCharacters: 2 * KIB
18917
+ };
18918
+ var INTERACTIVE_HTML_POLICY = {
18919
+ maxAuthoredBytes: 512 * KIB,
18920
+ maxAssets: 32,
18921
+ maxAssetBytesTotal: 10 * MIB,
18922
+ maxDependencies: 4,
18923
+ maxPreparedBytes: 16 * MIB,
18924
+ maxRuntimeElements: 1e4,
18925
+ maxProbeSteps: 20,
18926
+ maxProbeStepMs: 2000,
18927
+ defaultWaitVisibleMs: 1000,
18928
+ maxProbeTextCharacters: 1024,
18929
+ probeTargetPattern: /^[A-Za-z][A-Za-z0-9_-]{0,63}$/
18930
+ };
18931
+ var PREVIEW_CAPTURE_POLICY = {
18932
+ maxPngBytes: 8 * MIB,
18933
+ maxPixels: 12000000,
18934
+ maxDimension: 4096,
18935
+ minDimension: 240,
18936
+ maxCapturesPerReceipt: 3,
18937
+ defaultViewport: { width: 960, height: 640, deviceScaleFactor: 1 }
18938
+ };
18939
+ var PREVIEW_ADMISSION_POLICY = {
18940
+ runningPerEnvironment: 1,
18941
+ runningGlobal: 2,
18942
+ queuedPerEnvironment: 8,
18943
+ queuedGlobal: 16,
18944
+ nonterminalPerConversation: 2,
18945
+ queuedMetadataBytesGlobal: 8 * MIB,
18946
+ queueWaitMs: 15000,
18947
+ workerWallMs: 30000,
18948
+ readinessMs: 5000,
18949
+ operationDeadlineMs: 45000,
18950
+ cleanupGraceMs: 2000,
18951
+ workerMemoryBytes: 1024 * MIB,
18952
+ workerCpus: 2,
18953
+ workerPids: 128
18954
+ };
18955
+ var FRONTEND_RENDER_POLICY = {
18956
+ highlightConcurrency: 2,
18957
+ diagramConcurrency: 1,
18958
+ maxQueuedJobs: 32,
18959
+ maxQueuedSourceBytes: 2 * MIB,
18960
+ maxSettledCacheEntries: 128,
18961
+ maxSettledCacheBytes: 16 * MIB,
18962
+ maxInactiveViewStateEntries: 500,
18963
+ maxActiveViewStateEntries: 200,
18964
+ maxPinnedViewStateEntries: 50,
18965
+ liveExecutableHostsPerWindow: 1,
18966
+ imageDecodeMaxPixels: 40000000,
18967
+ pdfPreviewMaxPages: 100,
18968
+ pdfPreviewMaxBytes: 20 * MIB
18969
+ };
18970
+ var PDF_POLICY = {
18971
+ maxPages: 100,
18972
+ maxBytes: 20 * MIB,
18973
+ thumbnailMaxDimension: 1024,
18974
+ thumbnailMaxPngBytes: 4 * MIB,
18975
+ imageDecodeMaxPixels: 40000000,
18976
+ printMarginMm: 10,
18977
+ previewCacheEntries: 32,
18978
+ previewCacheBytes: 16 * MIB
18979
+ };
18980
+ var DIAGNOSTIC_POLICY = {
18981
+ maxPersistedEntries: 50,
18982
+ maxEntryBytes: 2 * KIB,
18983
+ maxPersistedBytes: 32 * KIB,
18984
+ maxToolFieldErrors: 20,
18985
+ maxToolDiagnosticBytes: 8 * KIB
18986
+ };
18987
+ var ARTIFACT_TOOL_POLICY = {
18988
+ maxResultBytes: 16 * KIB,
18989
+ maxSourceSliceBytes: 8 * KIB,
18990
+ maxTitleCharacters: 120,
18991
+ maxSummaryCharacters: 400,
18992
+ maxRequestKeyCharacters: 128,
18993
+ maxRepairRevisions: 2,
18994
+ maxTransientRetries: 2,
18995
+ maxUnpublishedArtifactsPerConversation: 100,
18996
+ maxRevisionsPerArtifact: 100,
18997
+ assetStoreBytesPerEnvironment: 1024 * MIB,
18998
+ scopeCapabilityTtlMs: 24 * 60 * 60 * 1000
18999
+ };
19000
+ var ARTIFACT_RETENTION_POLICY = {
19001
+ cleanupIntervalMs: 60 * 60 * 1000,
19002
+ abandonedStagingMs: 60 * 60 * 1000,
19003
+ unpublishedDraftMs: 7 * 24 * 60 * 60 * 1000,
19004
+ unreferencedPreviewAssetMs: 24 * 60 * 60 * 1000
19005
+ };
19006
+ var FRAME_CHANNEL_POLICY = {
19007
+ maxMessageBytes: 8 * KIB,
19008
+ messagesPerSecond: 20,
19009
+ burst: 40,
19010
+ sizeUpdatesPerSecond: 4,
19011
+ minInlineHeight: 120,
19012
+ maxInlineHeight: 1600,
19013
+ maxLinkCharacters: 2048,
19014
+ maxLinkLabelCharacters: 200
19015
+ };
19016
+
18789
19017
  // ../protocol/src/agent-system-instructions.ts
18790
- 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.";
19018
+ 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.";
18791
19019
  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.";
19020
+ 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}]";
19021
+ 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}]}]}';
19022
+ var AGENT_VISUAL_OUTPUT_INSTRUCTION = [
19023
+ "Orkestrator displays rich visuals directly in the conversation; choose one when it helps answer the question.",
19024
+ `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}.`,
19025
+ "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.",
19026
+ `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.`,
19027
+ "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.",
19028
+ "Use ordinary images only for photographs, screenshots and requested image files.",
19029
+ "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."
19030
+ ].join(" ");
18792
19031
  var GENERAL_AGENT_INSTRUCTIONS = [
19032
+ AGENT_VISUAL_OUTPUT_INSTRUCTION,
18793
19033
  AGENT_IMAGE_PREVIEW_INSTRUCTION,
18794
19034
  AGENT_DOCUMENT_INSTRUCTION
18795
19035
  ];
@@ -19038,16 +19278,827 @@ class InteractionDeadline {
19038
19278
  }
19039
19279
 
19040
19280
  // ../../bridges/acp-bridge/src/acp-command-changes.ts
19041
- import { createHash as createHash6 } from "node:crypto";
19281
+ import { createHash as createHash7 } from "node:crypto";
19042
19282
  import { resolve as resolve6 } from "node:path";
19043
19283
 
19044
19284
  // ../protocol/src/node/workspace-change-probe.ts
19045
- import { execFile, spawn as spawn3 } from "node:child_process";
19046
- import { randomUUID } from "node:crypto";
19285
+ import { randomUUID as randomUUID2 } from "node:crypto";
19047
19286
  import { rmSync as rmSync2 } from "node:fs";
19048
19287
  import { copyFile, lstat as lstat2, mkdtemp, rm as rm2 } from "node:fs/promises";
19049
19288
  import { tmpdir as tmpdir3 } from "node:os";
19050
19289
  import { delimiter, isAbsolute as isAbsolute3, join as join6, resolve as resolve4 } from "node:path";
19290
+
19291
+ // ../protocol/src/node/command-capture.ts
19292
+ import { spawn as spawn3 } from "node:child_process";
19293
+ import { randomUUID } from "node:crypto";
19294
+ import { constants as fsConstants } from "node:fs";
19295
+ import * as captureFs from "node:fs";
19296
+ import os from "node:os";
19297
+ import path2 from "node:path";
19298
+ import { inspect } from "node:util";
19299
+
19300
+ // ../protocol/src/node/command-failure-reason.ts
19301
+ var MAX_MATCHED_CHARS = 16 * 1024;
19302
+ var SIGNAL_PATTERN = /^SIG[A-Z0-9]{1,16}$/;
19303
+ var TOOL_RULES = {
19304
+ git: [
19305
+ ["branch-exists", /a branch named .* already exists/i],
19306
+ ["ref-conflict", /exists; cannot create|cannot lock ref .* is at .* but expected/i],
19307
+ ["lock-held", /could not lock config file [^\n]*: File exists/i],
19308
+ ["lock-held", /(?:unable to create '[^\n]*\.lock'|cannot lock ref)[^\n]*: File exists/i],
19309
+ ["lock-held", /another git process/i],
19310
+ ["worktree-conflict", /already (?:checked out|used by worktree)|used by worktree at/i],
19311
+ ["invalid-ref", /not a valid (?:branch name|object name)|bad (?:revision|object)/i],
19312
+ ["invalid-ref", /unknown revision|ambiguous argument|invalid reference/i],
19313
+ ["branch-not-found", /no branch named|refname .* not found|branch '.*' not found/i],
19314
+ ["branch-not-found", /did not match any file\(s\) known to git/i],
19315
+ ["dubious-ownership", /detected dubious ownership/i],
19316
+ ["no-remote", /does not appear to be a git repository|no such remote/i],
19317
+ ["no-remote", /repository (?:.* )?not found/i],
19318
+ ["not-a-repository", /not a git repository/i],
19319
+ ["remote-ref-missing", /could(?:n't| not) find remote ref|not our ref/i],
19320
+ ["merge-conflict", /\bCONFLICT \(|merge conflict|could not apply|unmerged files/i],
19321
+ ["dirty-worktree", /local changes .* would be overwritten|commit your changes or stash/i],
19322
+ ["nothing-to-commit", /nothing to commit|no changes added to commit/i],
19323
+ ["push-rejected", /\[(?:remote )?rejected\]|non-fast-forward/i],
19324
+ ["identity-unknown", /please tell me who you are|unable to auto-detect email/i],
19325
+ [
19326
+ "worktree-has-changes",
19327
+ /^fatal: [^\n]*['"] contains modified or untracked files(?:, use --force to delete it)?\.?\s*$/im
19328
+ ],
19329
+ ["not-a-worktree", /^fatal: [^\n]*['"] is not a working tree\.?\s*$/im],
19330
+ ["branch-not-merged", /^(?:error|fatal): [^\n]*['"] is not fully merged\.?\s*$/im]
19331
+ ],
19332
+ gh: [
19333
+ ["pull-request-exists", /a pull request for branch .* already exists/i],
19334
+ ["no-pull-request", /no (?:pull requests? (?:found|match)|open pull requests?\b)/i],
19335
+ ["rate-limited", /rate limit|http 429/i],
19336
+ ["forbidden", /http 403|resource not accessible/i],
19337
+ ["resource-not-found", /http 404|could not resolve to a/i],
19338
+ ["server-error", /http 5\d\d/i]
19339
+ ],
19340
+ docker: [
19341
+ ["daemon-unavailable", /cannot connect to the docker daemon|error during connect/i],
19342
+ [
19343
+ "daemon-unavailable",
19344
+ /is the docker daemon running|docker desktop is (?:not running|unable)/i
19345
+ ],
19346
+ ["container-not-found", /no such container/i],
19347
+ ["container-not-running", /container .* is (?:not running|paused|restarting)/i],
19348
+ ["container-name-conflict", /name .* is already in use/i],
19349
+ ["image-not-found", /no such image|pull access denied|manifest .* not found/i],
19350
+ ["image-not-found", /manifest unknown|repository does not exist/i],
19351
+ ["removal-in-progress", /removal of container .* is already in progress/i],
19352
+ [
19353
+ "image-in-use",
19354
+ /image is (?:being used|referenced)|unable to (?:remove|delete) .*must be forced/i
19355
+ ],
19356
+ ["volume-in-use", /volume is in use/i],
19357
+ ["volume-not-found", /no such volume/i],
19358
+ ["network-in-use", /has active endpoints/i],
19359
+ ["network-not-found", /network .* not found/i]
19360
+ ],
19361
+ tmux: [
19362
+ ["session-exists", /duplicate session/i],
19363
+ [
19364
+ "server-not-running",
19365
+ /no server running|failed to connect to server|no sessions|server exited|lost server/i
19366
+ ],
19367
+ [
19368
+ "server-not-running",
19369
+ /error connecting to \/[^\n]* \((?:No such file or directory|Connection refused)\)/i
19370
+ ],
19371
+ ["session-not-found", /can't find (?:session|window|pane)|session not found/i]
19372
+ ]
19373
+ };
19374
+ var ALL_TOOLS = Object.keys(TOOL_RULES);
19375
+ var SHARED_RULES = [
19376
+ ["disk-full", /no space left|enospc|disk quota exceeded/i],
19377
+ ["auth-failed", /authentication (?:failed|required)|could not read (?:username|password)/i],
19378
+ ["auth-failed", /terminal prompts disabled|invalid username or password|bad credentials/i],
19379
+ ["auth-failed", /permission denied \(|permission to \S+ denied|host key verification failed/i],
19380
+ ["auth-failed", /gh auth login|not logged in|unauthorized|http 401|returned error: 40[13]/i],
19381
+ ["network-failed", /could not resolve host|connection (?:timed out|refused|reset)/i],
19382
+ ["network-failed", /network is unreachable|no route to host|temporary failure in name/i],
19383
+ ["network-failed", /early eof|failed to connect|remote end hung up/i],
19384
+ ["network-failed", /unable to access ['"]?https?:\/\//i],
19385
+ ["network-failed", /tls handshake|i\/o timeout/i],
19386
+ [
19387
+ "network-failed",
19388
+ /error connecting to (?:https?:\/\/)?[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?(?::\d+)?(?:[\s/:]|$)/i
19389
+ ],
19390
+ ["port-in-use", /port is already allocated|address already in use/i],
19391
+ ["permission-denied", /permission denied|operation not permitted|read-only file system/i],
19392
+ ["command-not-found", /command not found/i],
19393
+ ["path-not-found", /no such file or directory/i],
19394
+ ["invalid-usage", /^usage: |unknown (?:option|flag|command|shorthand flag)|invalid option/im]
19395
+ ];
19396
+ var TOOL_EXIT_CODES = {
19397
+ git: { 129: "invalid-usage" },
19398
+ gh: { 2: "aborted", 4: "auth-failed" },
19399
+ docker: { 125: "daemon-error" },
19400
+ tmux: {}
19401
+ };
19402
+ var SHARED_EXIT_CODES = {
19403
+ 124: "timed-out",
19404
+ 126: "not-executable",
19405
+ 127: "command-not-found",
19406
+ 137: "killed",
19407
+ 143: "killed"
19408
+ };
19409
+ function read2(target, key) {
19410
+ return target[key];
19411
+ }
19412
+ function boundedForMatching(text) {
19413
+ if (text.length <= MAX_MATCHED_CHARS)
19414
+ return text;
19415
+ const half = MAX_MATCHED_CHARS / 2;
19416
+ return `${text.slice(0, half)}
19417
+ ${text.slice(-half)}`;
19418
+ }
19419
+ function failureText(error) {
19420
+ const stderr = read2(error, "stderr");
19421
+ if (Buffer.isBuffer(stderr) && stderr.length > 0) {
19422
+ return boundedForMatching(stderr.subarray(-MAX_MATCHED_CHARS).toString());
19423
+ }
19424
+ if (typeof stderr === "string" && stderr.length > 0)
19425
+ return boundedForMatching(stderr);
19426
+ const message = read2(error, "message");
19427
+ if (typeof message !== "string")
19428
+ return "";
19429
+ return message.startsWith("Command failed") ? "" : boundedForMatching(message);
19430
+ }
19431
+ function isRawSpawnEnoent(error) {
19432
+ const syscall = read2(error, "syscall");
19433
+ return read2(error, "code") === "ENOENT" && typeof syscall === "string" && /^(?:spawn(?:Sync)?(?:\s|$)|posix_spawnp?$)/.test(syscall);
19434
+ }
19435
+ function classifiedReason(error, exitCode, signal, options) {
19436
+ if (read2(error, "aborted") === true)
19437
+ return "aborted";
19438
+ if (read2(error, "outputLimitExceeded") === true)
19439
+ return "output-too-large";
19440
+ if (read2(error, "timedOut") === true)
19441
+ return "timed-out";
19442
+ if (read2(error, "executableMissing") === true || isRawSpawnEnoent(error)) {
19443
+ return "executable-missing";
19444
+ }
19445
+ const named = exitCode === null ? undefined : options.exitCodes?.[exitCode];
19446
+ if (named)
19447
+ return named;
19448
+ if (signal)
19449
+ return "killed";
19450
+ const text = failureText(error);
19451
+ for (const tool of options.tools ?? ALL_TOOLS) {
19452
+ for (const [reason, pattern] of TOOL_RULES[tool]) {
19453
+ if (pattern.test(text))
19454
+ return reason;
19455
+ }
19456
+ }
19457
+ for (const [reason, pattern] of SHARED_RULES) {
19458
+ if (pattern.test(text))
19459
+ return reason;
19460
+ }
19461
+ if (exitCode !== null) {
19462
+ for (const tool of options.tools ?? []) {
19463
+ const reason = TOOL_EXIT_CODES[tool][exitCode];
19464
+ if (reason)
19465
+ return reason;
19466
+ }
19467
+ const reason = SHARED_EXIT_CODES[exitCode];
19468
+ if (reason)
19469
+ return reason;
19470
+ }
19471
+ return "unclassified";
19472
+ }
19473
+ function numericExitCode(error) {
19474
+ for (const key of ["exitCode", "code"]) {
19475
+ const value = read2(error, key);
19476
+ if (typeof value === "number" && Number.isFinite(value))
19477
+ return value;
19478
+ }
19479
+ return null;
19480
+ }
19481
+ function classifyCommandFailure(error, options = {}) {
19482
+ if (typeof error !== "object" || error === null) {
19483
+ return { reason: "unclassified", exitCode: null, signal: null };
19484
+ }
19485
+ try {
19486
+ const exitCode = numericExitCode(error);
19487
+ const rawSignal = read2(error, "signal");
19488
+ const signal = typeof rawSignal === "string" && SIGNAL_PATTERN.test(rawSignal) ? rawSignal : null;
19489
+ return { reason: classifiedReason(error, exitCode, signal, options), exitCode, signal };
19490
+ } catch {
19491
+ return { reason: "unclassified", exitCode: null, signal: null };
19492
+ }
19493
+ }
19494
+
19495
+ // ../protocol/src/node/lost-exit-reaper.ts
19496
+ import { createRequire as createRequire2 } from "node:module";
19497
+
19498
+ // ../protocol/src/node/shell-process-state.ts
19499
+ import { readdirSync, readFileSync as readFileSync2 } from "node:fs";
19500
+ import { constants as osConstants } from "node:os";
19501
+ var PROCESS_INSPECTION_OPTIONS = {
19502
+ timeout: 100,
19503
+ killSignal: "SIGKILL",
19504
+ maxBuffer: 1024 * 1024
19505
+ };
19506
+ function bunRuntime() {
19507
+ return globalThis.Bun;
19508
+ }
19509
+ function decodeWaitStatus(status) {
19510
+ const signalNumber = status & 127;
19511
+ if (signalNumber === 0)
19512
+ return { code: status >> 8 & 255, signal: null };
19513
+ const name = Object.entries(osConstants.signals).find(([, value]) => value === signalNumber)?.[0];
19514
+ return { code: null, signal: name ?? "SIGKILL" };
19515
+ }
19516
+ function readZombieExit(pid) {
19517
+ try {
19518
+ const result = bunRuntime()?.spawnSync(["/bin/ps", "-o", "stat=,xstat=", "-p", String(pid)], PROCESS_INSPECTION_OPTIONS);
19519
+ if (!result?.success)
19520
+ return;
19521
+ const { stdout } = result;
19522
+ const match = /^Z\S*\s+([0-9a-f]+)\s*$/i.exec(stdout.toString().trim());
19523
+ return match ? decodeWaitStatus(Number.parseInt(match[1], 16)) : undefined;
19524
+ } catch {
19525
+ return;
19526
+ }
19527
+ }
19528
+ var EXIT_WATCH_MS = 1000;
19529
+ var EXIT_WATCH_MAX_MS = 16000;
19530
+ function watchForLostExit(pid, onExit) {
19531
+ if (process.platform !== "darwin" || pid === undefined || !bunRuntime())
19532
+ return () => {
19533
+ return;
19534
+ };
19535
+ let timer;
19536
+ const watch = (delayMs) => {
19537
+ timer = setTimeout(() => {
19538
+ const exit = readZombieExit(pid);
19539
+ if (exit)
19540
+ onExit(exit);
19541
+ else
19542
+ watch(Math.min(delayMs * 2, EXIT_WATCH_MAX_MS));
19543
+ }, delayMs);
19544
+ };
19545
+ watch(EXIT_WATCH_MS);
19546
+ return () => clearTimeout(timer);
19547
+ }
19548
+ function isLiveMember(state, groupId, pgid) {
19549
+ return Number(groupId) === pgid && state !== undefined && !/^[ZX]/.test(state);
19550
+ }
19551
+ function linuxGroupHasLiveMember(pgid) {
19552
+ for (const entry of readdirSync("/proc")) {
19553
+ if (!/^\d+$/.test(entry))
19554
+ continue;
19555
+ let stat;
19556
+ try {
19557
+ stat = readFileSync2(`/proc/${entry}/stat`, "latin1");
19558
+ } catch {
19559
+ continue;
19560
+ }
19561
+ const [state, , groupId] = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
19562
+ if (isLiveMember(state, groupId, pgid))
19563
+ return true;
19564
+ }
19565
+ return false;
19566
+ }
19567
+ function psGroupHasLiveMember(pgid) {
19568
+ const result = bunRuntime()?.spawnSync(["/bin/ps", "-A", "-o", "pgid=,stat="], PROCESS_INSPECTION_OPTIONS);
19569
+ if (!result?.success)
19570
+ return true;
19571
+ return result.stdout.toString().split(`
19572
+ `).some((line) => {
19573
+ const [groupId, state] = line.trim().split(/\s+/);
19574
+ return isLiveMember(state, groupId, pgid);
19575
+ });
19576
+ }
19577
+ function groupHasLiveMember(pgid) {
19578
+ try {
19579
+ return process.platform === "linux" ? linuxGroupHasLiveMember(pgid) : psGroupHasLiveMember(pgid);
19580
+ } catch {
19581
+ return true;
19582
+ }
19583
+ }
19584
+
19585
+ // ../protocol/src/node/lost-exit-reaper.ts
19586
+ var log7 = createLogger("process");
19587
+ var REAP_GRACE_MS = 2000;
19588
+ var REAP_MAX_CHECK_MS = 30000;
19589
+ var REAP_MAX_CHECKS = 12;
19590
+ var REAP_MAX_PENDING = 256;
19591
+ function createLostExitReaper(options) {
19592
+ const { system } = options;
19593
+ const graceMs = options.graceMs ?? REAP_GRACE_MS;
19594
+ const maxCheckMs = options.maxCheckMs ?? REAP_MAX_CHECK_MS;
19595
+ const maxChecks = options.maxChecks ?? REAP_MAX_CHECKS;
19596
+ const maxPending = options.maxPending ?? REAP_MAX_PENDING;
19597
+ const pending = new Map;
19598
+ let reaped = 0;
19599
+ let abandoned = 0;
19600
+ const abandon = (pid, reason) => {
19601
+ abandoned += 1;
19602
+ log7.warn("child.reap-abandoned", { pid, reason });
19603
+ };
19604
+ const check = (pid, reported, startedAt) => {
19605
+ if (reported())
19606
+ return false;
19607
+ const found = system.inspect(pid);
19608
+ if (found === undefined)
19609
+ return true;
19610
+ if (found === "gone" || found.ppid !== system.selfPid)
19611
+ return false;
19612
+ if (!found.state.startsWith("Z"))
19613
+ return true;
19614
+ const result = system.waitNoHang(pid);
19615
+ if (result === pid) {
19616
+ reaped += 1;
19617
+ log7.info("child.reaped", { pid, waitedMs: Date.now() - startedAt });
19618
+ return false;
19619
+ }
19620
+ if (result === 0)
19621
+ return true;
19622
+ abandon(pid, "waitpid-failed");
19623
+ return false;
19624
+ };
19625
+ const schedule = (pid, reported, startedAt, delayMs, checks) => {
19626
+ const timer = setTimeout(() => {
19627
+ pending.delete(pid);
19628
+ let again;
19629
+ try {
19630
+ again = check(pid, reported, startedAt);
19631
+ } catch {
19632
+ again = true;
19633
+ }
19634
+ if (!again)
19635
+ return;
19636
+ if (checks + 1 >= maxChecks) {
19637
+ abandon(pid, "not-a-zombie");
19638
+ return;
19639
+ }
19640
+ schedule(pid, reported, startedAt, Math.min(delayMs * 2, maxCheckMs), checks + 1);
19641
+ }, delayMs);
19642
+ timer.unref?.();
19643
+ pending.set(pid, timer);
19644
+ };
19645
+ return {
19646
+ reap(pid, reported) {
19647
+ if (!Number.isSafeInteger(pid) || pid <= 1 || pid === system.selfPid)
19648
+ return;
19649
+ if (pending.has(pid) || reported())
19650
+ return;
19651
+ if (pending.size >= maxPending) {
19652
+ abandon(pid, "capacity");
19653
+ return;
19654
+ }
19655
+ schedule(pid, reported, Date.now(), graceMs, 0);
19656
+ },
19657
+ stats: () => ({ pending: pending.size, reaped, abandoned }),
19658
+ stop() {
19659
+ for (const timer of pending.values())
19660
+ clearTimeout(timer);
19661
+ pending.clear();
19662
+ }
19663
+ };
19664
+ }
19665
+ var WNOHANG = 1;
19666
+ function loadDarwinWaitpid(loadFfi = () => createRequire2(import.meta.url)("bun:ffi")) {
19667
+ try {
19668
+ const { dlopen, FFIType } = loadFfi();
19669
+ const libSystem = dlopen("/usr/lib/libSystem.B.dylib", {
19670
+ waitpid: { args: [FFIType.i32, FFIType.ptr, FFIType.i32], returns: FFIType.i32 }
19671
+ });
19672
+ const status = new Int32Array(1);
19673
+ return (pid) => libSystem.symbols.waitpid(pid, status, WNOHANG);
19674
+ } catch {
19675
+ return;
19676
+ }
19677
+ }
19678
+ function darwinReaperSystem(loadFfi) {
19679
+ const waitNoHang = loadDarwinWaitpid(loadFfi);
19680
+ if (!waitNoHang)
19681
+ return;
19682
+ return {
19683
+ selfPid: process.pid,
19684
+ inspect(pid) {
19685
+ const result = bunRuntime()?.spawnSync(["/bin/ps", "-o", "ppid=,stat=", "-p", String(pid)], PROCESS_INSPECTION_OPTIONS);
19686
+ if (!result)
19687
+ return;
19688
+ const output = result.stdout.toString().trim();
19689
+ if (!result.success)
19690
+ return result.exitCode === 1 && output === "" ? "gone" : undefined;
19691
+ const match = /^(\d+)\s+(\S+)$/.exec(output);
19692
+ return match ? { ppid: Number(match[1]), state: match[2] } : undefined;
19693
+ },
19694
+ waitNoHang
19695
+ };
19696
+ }
19697
+ var defaultReaper;
19698
+ function createDarwinLostExitReaper(loadFfi) {
19699
+ const system = darwinReaperSystem(loadFfi);
19700
+ if (!system)
19701
+ log7.warn("child.reap-unavailable");
19702
+ return system ? createLostExitReaper({ system }) : null;
19703
+ }
19704
+ function sharedReaper() {
19705
+ if (defaultReaper === undefined) {
19706
+ defaultReaper = createDarwinLostExitReaper();
19707
+ }
19708
+ return defaultReaper ?? undefined;
19709
+ }
19710
+ function reapAfterLostExit(pid, reported) {
19711
+ if (process.platform !== "darwin" || pid === undefined || !bunRuntime())
19712
+ return;
19713
+ sharedReaper()?.reap(pid, reported);
19714
+ }
19715
+
19716
+ // ../protocol/src/node/command-capture.ts
19717
+ class CommandFailedError extends Error {
19718
+ stdout;
19719
+ stdoutBytes;
19720
+ stderr;
19721
+ timedOut;
19722
+ outputCloseTimedOut;
19723
+ executableMissing;
19724
+ aborted;
19725
+ outputLimitExceeded;
19726
+ exitCode;
19727
+ signal;
19728
+ constructor(message, details = {}) {
19729
+ super(message);
19730
+ this.name = "CommandFailedError";
19731
+ this.stdout = details.stdout ?? "";
19732
+ this.stdoutBytes = details.stdoutBytes ?? Buffer.alloc(0);
19733
+ this.stderr = details.stderr ?? "";
19734
+ this.timedOut = details.timedOut ?? false;
19735
+ this.outputCloseTimedOut = details.outputCloseTimedOut ?? false;
19736
+ this.executableMissing = details.executableMissing ?? false;
19737
+ this.aborted = details.aborted ?? false;
19738
+ this.outputLimitExceeded = details.outputLimitExceeded ?? false;
19739
+ this.exitCode = details.exitCode ?? null;
19740
+ this.signal = details.signal ?? null;
19741
+ }
19742
+ toJSON() {
19743
+ return { ...formatLogError(this), ...classifyCommandFailure(this) };
19744
+ }
19745
+ [inspect.custom]() {
19746
+ const { name, reason, exitCode, signal, stack } = this.toJSON();
19747
+ const frames = stack?.length ? ` | ${stack.join(" | ")}` : "";
19748
+ return `${name} reason=${reason} exitCode=${exitCode} signal=${signal} outputOmitted=true${frames}`;
19749
+ }
19750
+ }
19751
+ function redactCommandValues(value, redactValues) {
19752
+ const secrets = Array.from(new Set((redactValues ?? []).filter((secret) => typeof secret === "string" && secret.length > 0))).sort((left, right) => right.length - left.length);
19753
+ return secrets.reduce((redacted, secret) => redacted.split(secret).join("[REDACTED]"), value);
19754
+ }
19755
+ var COMMAND_ABORTED_MESSAGE = "Command aborted";
19756
+ var OUTPUT_LIMIT_MESSAGE = "maxBuffer length exceeded";
19757
+ function commandFailureOutcome(error) {
19758
+ const details = error ?? {};
19759
+ const message = typeof details.message === "string" ? details.message : "";
19760
+ return {
19761
+ timedOut: details.killed === true,
19762
+ executableMissing: details.code === "ENOENT",
19763
+ aborted: message === COMMAND_ABORTED_MESSAGE,
19764
+ outputLimitExceeded: details.outputLimitExceeded === true,
19765
+ exitCode: typeof details.code === "number" ? details.code : null,
19766
+ signal: details.signal ?? null
19767
+ };
19768
+ }
19769
+ var commandInvocations = new Map;
19770
+ var commandCaptureMetrics;
19771
+ var commandObservers = new Map;
19772
+ function nonInteractiveGitEnv(env) {
19773
+ const merged = { ...env ?? process.env };
19774
+ merged.GIT_TERMINAL_PROMPT ??= "0";
19775
+ if (process.platform !== "win32") {
19776
+ merged.SSH_ASKPASS ??= "/usr/bin/false";
19777
+ merged.SSH_ASKPASS_REQUIRE ??= "force";
19778
+ }
19779
+ return merged;
19780
+ }
19781
+ var MAX_COMMAND_OUTPUT_BYTES = 50 * 1024 * 1024;
19782
+ var COMMAND_KILL_GRACE_MS = 100;
19783
+ var COMMAND_OUTPUT_CHECK_MS = 100;
19784
+ var COMMAND_GROUP_POLL_MS = 5;
19785
+ var COMMAND_GROUP_POLL_MAX_MS = 200;
19786
+ function openCaptureFile() {
19787
+ const filePath = path2.join(os.tmpdir(), `orkestrator-capture-${randomUUID()}`);
19788
+ const fd = captureFs.openSync(filePath, fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_RDWR | fsConstants.O_APPEND, 384);
19789
+ try {
19790
+ captureFs.unlinkSync(filePath);
19791
+ return fd;
19792
+ } catch (error) {
19793
+ captureFs.closeSync(fd);
19794
+ throw error;
19795
+ }
19796
+ }
19797
+ function readCaptureFile(fd, limit) {
19798
+ const size = Math.min(captureFs.fstatSync(fd).size, limit);
19799
+ const buffer = Buffer.allocUnsafe(size);
19800
+ let offset = 0;
19801
+ while (offset < size) {
19802
+ const bytesRead = captureFs.readSync(fd, buffer, offset, size - offset, offset);
19803
+ if (bytesRead === 0)
19804
+ break;
19805
+ offset += bytesRead;
19806
+ }
19807
+ return buffer.subarray(0, offset);
19808
+ }
19809
+ function spawnCaptured(command, args, options, stdoutFd, stderrFd) {
19810
+ const payload = options.stdin?.length ? Buffer.from(options.stdin) : undefined;
19811
+ const env = command === "git" ? nonInteractiveGitEnv(options.env) : options.env ?? process.env;
19812
+ const detached = process.platform !== "win32";
19813
+ const bun = bunRuntime();
19814
+ if (bun) {
19815
+ const child = bun.spawn([command, ...args], {
19816
+ cwd: options.cwd,
19817
+ env,
19818
+ detached,
19819
+ windowsHide: true,
19820
+ stdin: payload ?? "pipe",
19821
+ stdout: stdoutFd,
19822
+ stderr: stderrFd
19823
+ });
19824
+ if (!payload)
19825
+ closeStdin(child.stdin);
19826
+ const current = () => ({ code: child.exitCode, signal: child.signalCode });
19827
+ return {
19828
+ pid: child.pid,
19829
+ exited: child.exited.then(current),
19830
+ current,
19831
+ kill: (signal) => child.kill(signal)
19832
+ };
19833
+ }
19834
+ const child = spawn3(command, args, {
19835
+ cwd: options.cwd,
19836
+ env,
19837
+ detached,
19838
+ windowsHide: true,
19839
+ stdio: [payload ? "pipe" : "ignore", stdoutFd, stderrFd]
19840
+ });
19841
+ if (payload) {
19842
+ child.stdin?.on("error", () => {
19843
+ return;
19844
+ });
19845
+ child.stdin?.end(payload);
19846
+ }
19847
+ return {
19848
+ pid: child.pid,
19849
+ exited: new Promise((resolve, reject) => {
19850
+ child.once("exit", (code, signal) => resolve({ code, signal }));
19851
+ child.once("error", reject);
19852
+ }),
19853
+ current: () => ({ code: child.exitCode, signal: child.signalCode }),
19854
+ kill: (signal) => {
19855
+ child.kill(signal);
19856
+ }
19857
+ };
19858
+ }
19859
+ function closeStdin(stdin) {
19860
+ try {
19861
+ Promise.resolve(stdin.end()).catch(() => {
19862
+ return;
19863
+ });
19864
+ } catch {}
19865
+ }
19866
+ function exitReported(child) {
19867
+ const { code, signal } = child.current();
19868
+ return code !== null || signal !== null;
19869
+ }
19870
+ function signalCommand(child, signal) {
19871
+ if (child.pid === undefined)
19872
+ return;
19873
+ try {
19874
+ if (process.platform !== "win32") {
19875
+ process.kill(-child.pid, signal);
19876
+ } else {
19877
+ child.kill(signal);
19878
+ }
19879
+ } catch {}
19880
+ }
19881
+ function commandGroupAlive(child) {
19882
+ if (process.platform === "win32" || child.pid === undefined)
19883
+ return false;
19884
+ try {
19885
+ process.kill(-child.pid, 0);
19886
+ } catch (error) {
19887
+ if (error.code === "ESRCH")
19888
+ return false;
19889
+ }
19890
+ return groupHasLiveMember(child.pid);
19891
+ }
19892
+ function executeCommandBytes(command, args, options, timeoutMs, outputLimit, stderrLimit) {
19893
+ return new Promise((resolve, reject) => {
19894
+ if (options.signal?.aborted) {
19895
+ reject(Object.assign(new Error(COMMAND_ABORTED_MESSAGE), { killed: true }));
19896
+ return;
19897
+ }
19898
+ const captureFds = [];
19899
+ const releaseCaptureFds = () => {
19900
+ for (const fd of captureFds.splice(0)) {
19901
+ try {
19902
+ captureFs.closeSync(fd);
19903
+ } catch {}
19904
+ }
19905
+ };
19906
+ try {
19907
+ captureFds.push(openCaptureFile());
19908
+ captureFds.push(openCaptureFile());
19909
+ } catch (error) {
19910
+ releaseCaptureFds();
19911
+ const code = error.code ?? "unknown";
19912
+ reject(new Error(`Could not open a command output file in the temporary directory: ${code}`));
19913
+ return;
19914
+ }
19915
+ const [stdoutFd, stderrFd] = captureFds;
19916
+ let child;
19917
+ try {
19918
+ child = spawnCaptured(command, args, options, stdoutFd, stderrFd);
19919
+ } catch (error) {
19920
+ releaseCaptureFds();
19921
+ reject(error);
19922
+ return;
19923
+ }
19924
+ let settled = false;
19925
+ let timedOut = false;
19926
+ let timeoutTimer;
19927
+ let groupTimer;
19928
+ let limitTimer;
19929
+ let stopExitWatch = () => {};
19930
+ let commandExit;
19931
+ const finishCapture = () => {
19932
+ settled = true;
19933
+ clearTimeout(timeoutTimer);
19934
+ clearTimeout(groupTimer);
19935
+ clearInterval(limitTimer);
19936
+ stopExitWatch();
19937
+ options.signal?.removeEventListener("abort", abort);
19938
+ if (!exitReported(child))
19939
+ reapAfterLostExit(child.pid, () => exitReported(child));
19940
+ try {
19941
+ return {
19942
+ stdout: readCaptureFile(stdoutFd, outputLimit),
19943
+ stderr: readCaptureFile(stderrFd, stderrLimit)
19944
+ };
19945
+ } catch (error) {
19946
+ reject(error);
19947
+ return;
19948
+ } finally {
19949
+ releaseCaptureFds();
19950
+ }
19951
+ };
19952
+ const fail = (error) => {
19953
+ if (settled)
19954
+ return;
19955
+ const output = finishCapture();
19956
+ if (output)
19957
+ reject(Object.assign(error, { ...output, killed: timedOut }));
19958
+ };
19959
+ const abort = () => {
19960
+ timedOut = true;
19961
+ signalCommand(child, "SIGKILL");
19962
+ fail(new Error(COMMAND_ABORTED_MESSAGE));
19963
+ };
19964
+ options.signal?.addEventListener("abort", abort, { once: true });
19965
+ const checkOutputLimit = () => {
19966
+ const stream = captureFs.fstatSync(stdoutFd).size > outputLimit ? "stdout" : captureFs.fstatSync(stderrFd).size > stderrLimit ? "stderr" : undefined;
19967
+ if (stream === undefined)
19968
+ return false;
19969
+ signalCommand(child, "SIGKILL");
19970
+ fail(Object.assign(new Error(`${stream} ${OUTPUT_LIMIT_MESSAGE}`), {
19971
+ outputLimitExceeded: true
19972
+ }));
19973
+ return true;
19974
+ };
19975
+ const failIfOverLimit = () => {
19976
+ try {
19977
+ return checkOutputLimit();
19978
+ } catch (error) {
19979
+ signalCommand(child, "SIGKILL");
19980
+ fail(error instanceof Error ? error : new Error(String(error)));
19981
+ return true;
19982
+ }
19983
+ };
19984
+ limitTimer = setInterval(() => {
19985
+ if (!settled && !timedOut)
19986
+ failIfOverLimit();
19987
+ }, COMMAND_OUTPUT_CHECK_MS);
19988
+ const settleOnExit = () => {
19989
+ if (settled || timedOut || failIfOverLimit())
19990
+ return;
19991
+ if (commandExit?.code !== 0 || commandExit.signal !== null) {
19992
+ fail(Object.assign(new Error(`Command failed: ${[command, ...args].join(" ")}`), {
19993
+ code: commandExit?.code,
19994
+ signal: commandExit?.signal
19995
+ }));
19996
+ return;
19997
+ }
19998
+ const output = finishCapture();
19999
+ if (output)
20000
+ resolve(output);
20001
+ };
20002
+ const awaitGroupExit = (delayMs) => {
20003
+ if (settled || timedOut)
20004
+ return;
20005
+ if (commandGroupAlive(child)) {
20006
+ groupTimer = setTimeout(awaitGroupExit, delayMs, Math.min(delayMs * 2, COMMAND_GROUP_POLL_MAX_MS));
20007
+ return;
20008
+ }
20009
+ settleOnExit();
20010
+ };
20011
+ const onCommandExit = (exit) => {
20012
+ if (commandExit)
20013
+ return;
20014
+ commandExit = exit;
20015
+ stopExitWatch();
20016
+ if (options.waitForDescendants)
20017
+ awaitGroupExit(COMMAND_GROUP_POLL_MS);
20018
+ else
20019
+ settleOnExit();
20020
+ };
20021
+ child.exited.then(onCommandExit, (error) => fail(error instanceof Error ? error : new Error(String(error))));
20022
+ stopExitWatch = watchForLostExit(child.pid, (exit) => {
20023
+ if (!settled && !timedOut)
20024
+ onCommandExit(exit);
20025
+ });
20026
+ if (timeoutMs > 0) {
20027
+ timeoutTimer = setTimeout(() => {
20028
+ timedOut = true;
20029
+ signalCommand(child, "SIGTERM");
20030
+ timeoutTimer = setTimeout(() => {
20031
+ signalCommand(child, "SIGKILL");
20032
+ fail(Object.assign(new Error(`Command timed out after ${timeoutMs} ms`), {
20033
+ code: child.current().code,
20034
+ signal: child.current().signal
20035
+ }));
20036
+ }, COMMAND_KILL_GRACE_MS);
20037
+ }, timeoutMs);
20038
+ }
20039
+ });
20040
+ }
20041
+ async function runCommandBytes(command, args = [], options = {}) {
20042
+ const timeoutMs = options.timeoutMs ?? 60000;
20043
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > 2147483647) {
20044
+ throw new RangeError("timeoutMs must be an integer between 0 and 2147483647");
20045
+ }
20046
+ const outputLimit = options.maxOutputBytes ?? MAX_COMMAND_OUTPUT_BYTES;
20047
+ if (!Number.isSafeInteger(outputLimit) || outputLimit <= 0) {
20048
+ throw new RangeError("maxOutputBytes must be a positive integer");
20049
+ }
20050
+ const stderrLimit = options.maxStderrBytes ?? outputLimit;
20051
+ if (!Number.isSafeInteger(stderrLimit) || stderrLimit <= 0) {
20052
+ throw new RangeError("maxStderrBytes must be a positive integer");
20053
+ }
20054
+ if (commandInvocations.size < 64 || commandInvocations.has(command)) {
20055
+ commandInvocations.set(command, (commandInvocations.get(command) ?? 0) + 1);
20056
+ }
20057
+ for (const observer of commandObservers.get(command) ?? [])
20058
+ observer(args);
20059
+ commandCaptureMetrics?.started(command, args);
20060
+ try {
20061
+ const { stdout, stderr } = await executeCommandBytes(command, args, options, timeoutMs, outputLimit, stderrLimit);
20062
+ commandCaptureMetrics?.capturedBytes(stdout.length);
20063
+ return {
20064
+ stdout: Buffer.isBuffer(stdout) ? stdout : Buffer.from(stdout),
20065
+ stderr: Buffer.isBuffer(stderr) ? stderr : Buffer.from(stderr)
20066
+ };
20067
+ } catch (error) {
20068
+ const outcome = commandFailureOutcome(error);
20069
+ const redacting = options.redactValues?.some((value) => typeof value === "string" && value.length > 0);
20070
+ if (error && typeof error === "object" && "stdout" in error && "stderr" in error) {
20071
+ const withOutput = error;
20072
+ const stderr = withOutput.stderr?.toString() ?? "";
20073
+ const stdout = withOutput.stdout?.toString() ?? "";
20074
+ const message = (stderr || stdout || withOutput.message || "Command failed").trim();
20075
+ throw new CommandFailedError(redactCommandValues(message, options.redactValues), {
20076
+ ...outcome,
20077
+ stdout: redactCommandValues(stdout, options.redactValues),
20078
+ stderr: redactCommandValues(stderr, options.redactValues),
20079
+ ...!redacting && Buffer.isBuffer(withOutput.stdout) ? { stdoutBytes: withOutput.stdout } : {}
20080
+ });
20081
+ }
20082
+ if (redacting) {
20083
+ const message = error instanceof Error ? error.message : String(error);
20084
+ throw new CommandFailedError(redactCommandValues(message || "Command failed", options.redactValues), outcome);
20085
+ }
20086
+ if (outcome.timedOut || outcome.executableMissing) {
20087
+ const message = error instanceof Error ? error.message : String(error);
20088
+ throw new CommandFailedError(message || "Command failed", outcome);
20089
+ }
20090
+ throw error;
20091
+ }
20092
+ }
20093
+ async function runCommand(command, args = [], options = {}) {
20094
+ const { stdout, stderr } = await runCommandBytes(command, args, options);
20095
+ return {
20096
+ stdout: redactCommandValues(stdout.toString(), options.redactValues),
20097
+ stderr: redactCommandValues(stderr.toString(), options.redactValues)
20098
+ };
20099
+ }
20100
+
20101
+ // ../protocol/src/node/workspace-change-probe.ts
19051
20102
  var DEFAULT_MAX_UNTRACKED_FILE_BYTES = 2 * 1024 * 1024;
19052
20103
  var DEFAULT_MAX_UNTRACKED_FILES = 5000;
19053
20104
  var DEFAULT_SLOW_SNAPSHOT_MS = 500;
@@ -19065,27 +20116,16 @@ process.once("exit", () => {
19065
20116
  } catch {}
19066
20117
  }
19067
20118
  });
19068
- var runGit = (args, options) => new Promise((resolvePromise, reject) => {
19069
- const env = { ...process.env, ...options.env, GIT_OPTIONAL_LOCKS: "0" };
19070
- if (options.stdin === undefined) {
19071
- execFile("git", args, { cwd: options.cwd, env, timeout: GIT_TIMEOUT_MS, maxBuffer: GIT_MAX_BUFFER }, (error, stdout) => error ? reject(error) : resolvePromise({ stdout: String(stdout) }));
19072
- return;
19073
- }
19074
- const child = spawn3("git", args, { cwd: options.cwd, env, timeout: GIT_TIMEOUT_MS });
19075
- let stdout = "";
19076
- let stdoutBytes = 0;
19077
- child.stdout.setEncoding("utf8");
19078
- child.stdout.on("data", (chunk) => {
19079
- stdoutBytes += chunk.length;
19080
- if (stdoutBytes <= GIT_MAX_BUFFER)
19081
- stdout += chunk;
20119
+ var runGit = async (args, options) => {
20120
+ const { stdout } = await runCommand("git", args, {
20121
+ cwd: options.cwd,
20122
+ env: { ...process.env, ...options.env, GIT_OPTIONAL_LOCKS: "0" },
20123
+ timeoutMs: GIT_TIMEOUT_MS,
20124
+ maxOutputBytes: GIT_MAX_BUFFER,
20125
+ ...options.stdin === undefined ? {} : { stdin: options.stdin }
19082
20126
  });
19083
- child.stderr.resume();
19084
- child.on("error", reject);
19085
- child.on("close", (code) => code === 0 ? resolvePromise({ stdout }) : reject(new Error(`git exited with ${code}`)));
19086
- child.stdin.on("error", () => {});
19087
- child.stdin.end(options.stdin);
19088
- });
20127
+ return { stdout };
20128
+ };
19089
20129
 
19090
20130
  class WorkspaceChangeProbe {
19091
20131
  git;
@@ -19373,7 +20413,7 @@ class WorkspaceChangeProbe {
19373
20413
  return;
19374
20414
  const { root, indexPath } = repo.location;
19375
20415
  const started = this.now();
19376
- const tempIndex = join6(this.tempDir, `orkestrator-probe-${randomUUID()}.index`);
20416
+ const tempIndex = join6(this.tempDir, `orkestrator-probe-${randomUUID2()}.index`);
19377
20417
  const objectDirectory = await mkdtemp(join6(this.tempDir, "orkestrator-probe-objects-"));
19378
20418
  temporaryObjectDirectories.add(objectDirectory);
19379
20419
  let retained = false;
@@ -19636,7 +20676,7 @@ function acpToolKind(source, runtime) {
19636
20676
  }
19637
20677
 
19638
20678
  // ../../bridges/acp-bridge/src/change-evidence.ts
19639
- import { randomUUID as randomUUID3 } from "node:crypto";
20679
+ import { randomUUID as randomUUID4 } from "node:crypto";
19640
20680
  import { resolve as resolve5 } from "node:path";
19641
20681
 
19642
20682
  // ../protocol/src/field-validation.ts
@@ -20040,8 +21080,8 @@ function workspaceObservationReportIssues(value) {
20040
21080
  }
20041
21081
 
20042
21082
  // ../protocol/src/node/change-tracking/evidence-spool.ts
20043
- import { createHash as createHash5, randomUUID as randomUUID2 } from "node:crypto";
20044
- import { readdirSync, readFileSync as readFileSync2 } from "node:fs";
21083
+ import { createHash as createHash6, randomUUID as randomUUID3 } from "node:crypto";
21084
+ import { readdirSync as readdirSync2, readFileSync as readFileSync3 } from "node:fs";
20045
21085
  import { appendFile as appendFile2, mkdir as mkdir2, rename as rename2, rm as rm3, writeFile as writeFile2 } from "node:fs/promises";
20046
21086
  import { join as join7 } from "node:path";
20047
21087
  var DEFAULT_EVIDENCE_SPOOL_LIMITS = {
@@ -20056,10 +21096,10 @@ var DEFAULT_EVIDENCE_SPOOL_LIMITS = {
20056
21096
  var ENTRIES_FILE = "entries.jsonl";
20057
21097
  var BODY_DIRECTORY = "bodies";
20058
21098
  function evidenceBodyId(bytes) {
20059
- return `sha256:${createHash5("sha256").update(bytes).digest("hex")}`;
21099
+ return `sha256:${createHash6("sha256").update(bytes).digest("hex")}`;
20060
21100
  }
20061
21101
  function stableEvidenceId(...parts) {
20062
- const hash = createHash5("sha256");
21102
+ const hash = createHash6("sha256");
20063
21103
  for (const part of parts)
20064
21104
  hash.update(`${part ?? ""}\x00`);
20065
21105
  return hash.digest("hex").slice(0, 40);
@@ -20086,7 +21126,7 @@ class ChangeEvidenceSpool {
20086
21126
  restoring = false;
20087
21127
  constructor(options = {}) {
20088
21128
  this.limits = { ...DEFAULT_EVIDENCE_SPOOL_LIMITS, ...options.limits };
20089
- this.runtimeEpoch = options.runtimeEpoch ?? randomUUID2();
21129
+ this.runtimeEpoch = options.runtimeEpoch ?? randomUUID3();
20090
21130
  this.directory = options.directory;
20091
21131
  if (this.directory) {
20092
21132
  this.restoring = true;
@@ -20189,7 +21229,7 @@ class ChangeEvidenceSpool {
20189
21229
  return;
20190
21230
  if (this.entries.length >= this.limits.maxEntries - 1)
20191
21231
  return;
20192
- const gapId = randomUUID2();
21232
+ const gapId = randomUUID3();
20193
21233
  const coverage = this.droppedUnknown ? {
20194
21234
  kind: "unknown-range",
20195
21235
  bindingId: this.gapBindingId || "unknown",
@@ -20351,8 +21391,8 @@ class ChangeEvidenceSpool {
20351
21391
  restore(directory) {
20352
21392
  const bodyDirectory = join7(directory, BODY_DIRECTORY);
20353
21393
  try {
20354
- for (const name of readdirSync(bodyDirectory)) {
20355
- const bytes = new Uint8Array(readFileSync2(join7(bodyDirectory, name)));
21394
+ for (const name of readdirSync2(bodyDirectory)) {
21395
+ const bytes = new Uint8Array(readFileSync3(join7(bodyDirectory, name)));
20356
21396
  const id = evidenceBodyId(bytes);
20357
21397
  if (bodyFileName(id) !== name)
20358
21398
  continue;
@@ -20364,7 +21404,7 @@ class ChangeEvidenceSpool {
20364
21404
  } catch {}
20365
21405
  let text = "";
20366
21406
  try {
20367
- text = readFileSync2(join7(directory, ENTRIES_FILE), "utf8");
21407
+ text = readFileSync3(join7(directory, ENTRIES_FILE), "utf8");
20368
21408
  } catch {
20369
21409
  return;
20370
21410
  }
@@ -20702,7 +21742,7 @@ function canonicalEvidence(evidence) {
20702
21742
  }
20703
21743
 
20704
21744
  // ../../bridges/acp-bridge/src/change-evidence.ts
20705
- var log6 = createLogger("bridge.acp");
21745
+ var log8 = createLogger("bridge.acp");
20706
21746
  var MAX_DIFF_BLOCKS_PER_CALL = 100;
20707
21747
  var MAX_HELD_DIFF_BYTES = 32 * 1024 * 1024;
20708
21748
  var MAX_SEEN_CALL_IDS = 8192;
@@ -20826,7 +21866,7 @@ function recordFor(state, part) {
20826
21866
  evidence.pendingApprovals.delete(part.toolUseId);
20827
21867
  record = {
20828
21868
  callId: part.toolUseId,
20829
- ...isReusedCallId(state, evidence, part) ? { attemptId: `reuse:${turnId ?? randomUUID3()}` } : {},
21869
+ ...isReusedCallId(state, evidence, part) ? { attemptId: `reuse:${turnId ?? randomUUID4()}` } : {},
20830
21870
  ...turnId ? { turnId } : {},
20831
21871
  awaitingApproval: approval === "awaiting",
20832
21872
  approved: false,
@@ -21001,7 +22041,7 @@ function recordAcpToolEvidence(state, part, update) {
21001
22041
  if (isTerminal(phase))
21002
22042
  settleRecord(state, part, record);
21003
22043
  } catch (error) {
21004
- log6.warn("evidence.record-failed", {
22044
+ log8.warn("evidence.record-failed", {
21005
22045
  errorClass: error instanceof Error ? error.name : "unknown"
21006
22046
  });
21007
22047
  }
@@ -21045,13 +22085,13 @@ function recordAcpShellObservation(state, toolUseId, observation) {
21045
22085
  ...observation.unavailableReason ? { unavailableReason: observation.unavailableReason } : {}
21046
22086
  });
21047
22087
  } catch (error) {
21048
- log6.warn("evidence.shell-record-failed", {
22088
+ log8.warn("evidence.shell-record-failed", {
21049
22089
  errorClass: error instanceof Error ? error.name : "unknown"
21050
22090
  });
21051
22091
  }
21052
22092
  }
21053
22093
  function beginAcpTurnEvidence(state, requestId) {
21054
- const turnId = requestId || `turn:${randomUUID3()}`;
22094
+ const turnId = requestId || `turn:${randomUUID4()}`;
21055
22095
  evidenceFor(state).turn = { turnId, backgroundLaunched: false };
21056
22096
  changeEvidenceRecorder().turn({ conversationId: state.id, turnId }, "running", "may-write");
21057
22097
  }
@@ -21077,14 +22117,14 @@ function endAcpTurnEvidence(state, outcome) {
21077
22117
  const writers = state.activeSubagentToolIds.size > 0 || turn.backgroundLaunched ? "may-write" : "quiescent";
21078
22118
  changeEvidenceRecorder().turn({ conversationId: state.id, turnId: turn.turnId }, outcome, writers);
21079
22119
  } catch (error) {
21080
- log6.warn("evidence.turn-record-failed", {
22120
+ log8.warn("evidence.turn-record-failed", {
21081
22121
  errorClass: error instanceof Error ? error.name : "unknown"
21082
22122
  });
21083
22123
  }
21084
22124
  }
21085
22125
 
21086
22126
  // ../../bridges/acp-bridge/src/acp-command-changes.ts
21087
- var log7 = createLogger("bridge.acp");
22127
+ var log9 = createLogger("bridge.acp");
21088
22128
  var MAX_WINDOWS_PER_SESSION = 256;
21089
22129
  var MAX_CACHED_JOURNALS = MAX_RESUMABLE_SESSIONS;
21090
22130
  var probe;
@@ -21198,7 +22238,7 @@ function closeWindow(active, state, toolUseId, role) {
21198
22238
  recordAcpShellObservation(state, toolUseId, observation);
21199
22239
  recordCommandChange(state, toolUseId, legacyCommandChange(observation));
21200
22240
  }).catch((error) => {
21201
- log7.warn("command-change.record-failed", {
22241
+ log9.warn("command-change.record-failed", {
21202
22242
  errorClass: error instanceof Error ? error.name : "unknown"
21203
22243
  });
21204
22244
  });
@@ -21257,7 +22297,7 @@ async function applyJournaledCommandChanges(state) {
21257
22297
  function journalFor(acpSessionId) {
21258
22298
  if (!journalDirectory || !acpSessionId)
21259
22299
  return;
21260
- const name = createHash6("sha256").update(acpSessionId).digest("hex").slice(0, 40);
22300
+ const name = createHash7("sha256").update(acpSessionId).digest("hex").slice(0, 40);
21261
22301
  const path = resolve6(journalDirectory, `${name}.jsonl`);
21262
22302
  let journal = journals.get(path);
21263
22303
  if (journal) {
@@ -21415,13 +22455,12 @@ async function resumeSessionReserved(acpSessionId, signal, patch, policy, agentM
21415
22455
  throw new HttpError(410, `${provider} cannot reload persisted ACP sessions`);
21416
22456
  }
21417
22457
  state = {
21418
- id: randomBytes7(16).toString("hex"),
22458
+ id: randomBytes8(16).toString("hex"),
21419
22459
  acpSessionId,
21420
22460
  status: "idle",
21421
22461
  messages: [],
21422
22462
  activeSubagentToolIds: new Set,
21423
22463
  activeSubagentDescriptors: new Map,
21424
- settledCursorAgentIds: new Set,
21425
22464
  subagentLimitExceeded: false,
21426
22465
  subagentToolIds: new Map,
21427
22466
  cursorTodos: [],
@@ -21480,10 +22519,8 @@ async function resumeSessionReserved(acpSessionId, signal, patch, policy, agentM
21480
22519
  await persistState();
21481
22520
  return state;
21482
22521
  } catch (error) {
21483
- if (state && sessions.get(state.id) === state) {
22522
+ if (state && sessions.get(state.id) === state)
21484
22523
  sessions.delete(state.id);
21485
- bumpCursorDiscoveryRevision();
21486
- }
21487
22524
  if (state)
21488
22525
  clearApprovals(state);
21489
22526
  await child.close();
@@ -21575,7 +22612,7 @@ async function createSessionReserved(clientSessionKey, signal, spawnOptions = {}
21575
22612
  if (!isObject3(created) || typeof created.sessionId !== "string") {
21576
22613
  throw new Error(`${provider} returned an invalid ACP session`);
21577
22614
  }
21578
- const id = randomBytes7(16).toString("hex");
22615
+ const id = randomBytes8(16).toString("hex");
21579
22616
  const sessionConfig = normalizeAcpSessionConfig(provider, created);
21580
22617
  rememberCatalog(sessionConfig.composer);
21581
22618
  const state = newSessionState(id, clientSessionKey, created.sessionId, child, sessionConfig, spawnOptions);
@@ -21592,10 +22629,8 @@ async function createSessionReserved(clientSessionKey, signal, spawnOptions = {}
21592
22629
  return state;
21593
22630
  } catch (error) {
21594
22631
  state.dispatching = false;
21595
- if (sessions.get(id) === state) {
22632
+ if (sessions.get(id) === state)
21596
22633
  sessions.delete(id);
21597
- bumpCursorDiscoveryRevision();
21598
- }
21599
22634
  if (clientSessionKey && clientSessionKeys.get(clientSessionKey) === id) {
21600
22635
  clientSessionKeys.delete(clientSessionKey);
21601
22636
  }
@@ -21616,7 +22651,6 @@ function newSessionState(id, clientSessionKey, acpSessionId, child, sessionConfi
21616
22651
  messages: [],
21617
22652
  activeSubagentToolIds: new Set,
21618
22653
  activeSubagentDescriptors: new Map,
21619
- settledCursorAgentIds: new Set,
21620
22654
  subagentLimitExceeded: false,
21621
22655
  subagentToolIds: new Map,
21622
22656
  cursorTodos: [],
@@ -21647,7 +22681,7 @@ function newSessionState(id, clientSessionKey, acpSessionId, child, sessionConfi
21647
22681
  };
21648
22682
  }
21649
22683
  async function createDeferredSession(clientSessionKey, spawnOptions) {
21650
- const id = randomBytes7(16).toString("hex");
22684
+ const id = randomBytes8(16).toString("hex");
21651
22685
  const empty = normalizeAcpSessionConfig(provider, {});
21652
22686
  const sessionConfig = withRequestedSelection({ ...empty, composer: { ...empty.composer, models: catalogCache?.models ?? [] } }, composerPatchFromSpawn(spawnOptions));
21653
22687
  const state = newSessionState(id, clientSessionKey, "", null, sessionConfig, spawnOptions);
@@ -22359,7 +23393,7 @@ function parkPermission(state, child, requestId, params) {
22359
23393
  }
22360
23394
  ];
22361
23395
  }).slice(0, 20) : [];
22362
- const id = randomBytes7(12).toString("hex");
23396
+ const id = randomBytes8(12).toString("hex");
22363
23397
  const requestedAt = Date.now();
22364
23398
  const promptSequence = state.promptSequence;
22365
23399
  const toolCallId = isObject3(params.toolCall) ? params.toolCall.toolCallId : undefined;
@@ -22416,7 +23450,7 @@ function permissionTitle(params) {
22416
23450
  return title.slice(0, 500);
22417
23451
  }
22418
23452
  function appendNonTextContent(state, update, role) {
22419
- const messageId = randomBytes7(12).toString("hex");
23453
+ const messageId = randomBytes8(12).toString("hex");
22420
23454
  const parts = contentBlockParts(update.content, messageId, 0);
22421
23455
  if (parts.length === 0)
22422
23456
  return;
@@ -22556,7 +23590,7 @@ function applySessionUpdate(state, params) {
22556
23590
  if (!message) {
22557
23591
  const modelId = role === "assistant" ? boundedModelId(state.sessionConfig.composer.selectedModelId) : undefined;
22558
23592
  message = {
22559
- id: randomBytes7(12).toString("hex"),
23593
+ id: randomBytes8(12).toString("hex"),
22560
23594
  role,
22561
23595
  content: "",
22562
23596
  parts: [],
@@ -22983,7 +24017,7 @@ function setPromptJournal(state, entry) {
22983
24017
  state.promptJournal.set(entry.requestId, entry);
22984
24018
  }
22985
24019
  // ../../bridges/acp-bridge/src/acp-prompt.ts
22986
- import { randomBytes as randomBytes8 } from "node:crypto";
24020
+ import { randomBytes as randomBytes9 } from "node:crypto";
22987
24021
 
22988
24022
  // ../../bridges/acp-bridge/src/structured-prompt-marker.ts
22989
24023
  var STRUCTURED_PROMPT_INSTRUCTION_PREFIX = "End your turn with exactly one JSON value";
@@ -23060,7 +24094,7 @@ function openRetryCard(state, text) {
23060
24094
  type: "retry",
23061
24095
  content: text,
23062
24096
  toolState: "pending",
23063
- sourcePartId: randomBytes8(12).toString("hex"),
24097
+ sourcePartId: randomBytes9(12).toString("hex"),
23064
24098
  sourceMessageId: message.id,
23065
24099
  createdAt: new Date().toISOString()
23066
24100
  };
@@ -23251,6 +24285,7 @@ function effectiveLogLevel(detail, area) {
23251
24285
  return detail.level;
23252
24286
  }
23253
24287
  }
24288
+ var LOG_DETAIL_EXPIRY_MS = 24 * 60 * 60 * 1000;
23254
24289
  function logDetailEnablesBridgeDiagnostics(detail) {
23255
24290
  return LEVEL_DETAIL[effectiveLogLevel(detail, BRIDGE_DIAGNOSTICS_LOG_AREA)] >= LEVEL_DETAIL.debug;
23256
24291
  }
@@ -23462,6 +24497,18 @@ async function forkAcpSession(state, upToMessageId, signal) {
23462
24497
 
23463
24498
  // ../protocol/src/human-prompts.ts
23464
24499
  var HUMAN_PROMPT_SCAN_BYTES = 16 * 1024;
24500
+ var HUMAN_PROMPT_KINDS = new Set([
24501
+ "sign-in",
24502
+ "device-code",
24503
+ "press-enter",
24504
+ "secret",
24505
+ "host-key"
24506
+ ]);
24507
+ var HUMAN_PROMPT_SOURCES = new Set([
24508
+ "user-command",
24509
+ "agent-tool",
24510
+ "agent-background-task"
24511
+ ]);
23465
24512
  var HUMAN_PROMPT_OBSERVATION_ROWS = 64;
23466
24513
  function humanPromptObservation(messages, tasks) {
23467
24514
  const object = (value) => !!value && typeof value === "object" && !Array.isArray(value);
@@ -23514,7 +24561,7 @@ function humanPromptObservation(messages, tasks) {
23514
24561
  }
23515
24562
 
23516
24563
  // ../../bridges/acp-bridge/src/acp-http.ts
23517
- import { randomBytes as randomBytes9, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
24564
+ import { randomBytes as randomBytes10 } from "node:crypto";
23518
24565
  import { pathToFileURL } from "node:url";
23519
24566
  import { gzip } from "node:zlib";
23520
24567
 
@@ -23953,7 +25000,7 @@ var DEFAULT_MCP_MANAGEMENT_ROLLOUT = Object.freeze({
23953
25000
 
23954
25001
  // ../protocol/src/node/bridge-transcript-summary.ts
23955
25002
  import { Buffer as Buffer5 } from "node:buffer";
23956
- import { createHash as createHash7 } from "node:crypto";
25003
+ import { createHash as createHash8 } from "node:crypto";
23957
25004
 
23958
25005
  // ../protocol/src/node/progressive-transcript.ts
23959
25006
  var BRIDGE_TRANSCRIPT_MAX_MESSAGES = 100;
@@ -24119,7 +25166,7 @@ function digestPayload(payload) {
24119
25166
  const serialized = JSON.stringify(payload);
24120
25167
  return {
24121
25168
  bytes: Buffer5.byteLength(serialized),
24122
- digest: createHash7("sha256").update(serialized).digest("base64url").slice(0, 32)
25169
+ digest: createHash8("sha256").update(serialized).digest("base64url").slice(0, 32)
24123
25170
  };
24124
25171
  }
24125
25172
  function topLevelKey(part, index) {
@@ -24555,10 +25602,8 @@ async function runClose(state) {
24555
25602
  schedulePersist();
24556
25603
  return "pending";
24557
25604
  }
24558
- if (sessions.get(state.id) === state) {
25605
+ if (sessions.get(state.id) === state)
24559
25606
  sessions.delete(state.id);
24560
- bumpCursorDiscoveryRevision();
24561
- }
24562
25607
  const clientKey = state.clientSessionKey;
24563
25608
  if (clientKey !== undefined && clientSessionKeys.get(clientKey) === state.id) {
24564
25609
  clientSessionKeys.delete(clientKey);
@@ -24834,7 +25879,8 @@ function holdParkedRequest(state, family, id, held) {
24834
25879
  }
24835
25880
 
24836
25881
  // ../../bridges/acp-bridge/src/acp-http.ts
24837
- var TRANSCRIPT_GENERATION = randomBytes9(16).toString("hex");
25882
+ var TRANSCRIPT_GENERATION = randomBytes10(16).toString("hex");
25883
+ var log10 = createLogger("bridge.acp");
24838
25884
 
24839
25885
  class CommandUnavailableError extends Error {
24840
25886
  }
@@ -24883,7 +25929,17 @@ async function route(request, response, clientSignal) {
24883
25929
  return json(response, 200, { models });
24884
25930
  }
24885
25931
  if (url.pathname === "/session/list" && request.method === "GET") {
24886
- return json(response, 200, { sessions: await listResumableSessions() });
25932
+ try {
25933
+ return json(response, 200, { sessions: await listResumableSessions() });
25934
+ } catch (error) {
25935
+ if (error instanceof HttpError || error instanceof CredentialError)
25936
+ throw error;
25937
+ log10.warn("http.route-failed", {
25938
+ method: request.method,
25939
+ error: formatLogError(error, { message: false })
25940
+ });
25941
+ return json(response, 500, { error: "Failed to read session history" });
25942
+ }
24887
25943
  }
24888
25944
  if (url.pathname === "/session/resume" && request.method === "POST") {
24889
25945
  const body = await readJson(request);
@@ -25271,7 +26327,7 @@ async function route(request, response, clientSignal) {
25271
26327
  }
25272
26328
  throw error;
25273
26329
  }
25274
- const userMessageId = randomBytes9(12).toString("hex");
26330
+ const userMessageId = randomBytes10(12).toString("hex");
25275
26331
  const userVisiblePrompt = selectedCommand ? displayPrompt || prompt : prompt;
25276
26332
  state.messages.push({
25277
26333
  id: userMessageId,
@@ -25494,11 +26550,7 @@ function authenticated(request) {
25494
26550
  Array.isArray(dedicated) ? dedicated[0] : dedicated,
25495
26551
  request.headers.authorization?.replace(/^Bearer\s+/i, "")
25496
26552
  ];
25497
- const right = Buffer.from(authToken);
25498
- return candidates.some((candidate) => {
25499
- const left = Buffer.from(candidate?.trim() || "");
25500
- return left.length === right.length && timingSafeEqual2(left, right);
25501
- });
26553
+ return candidates.some((candidate) => bridgeCredential.matches(candidate?.trim()));
25502
26554
  }
25503
26555
  function isTrustedBridgeOrigin(origin) {
25504
26556
  if (!origin)
@@ -25644,6 +26696,7 @@ function installFatalRejectionGuard(options) {
25644
26696
  const APP_PATH = /(?:^|\/)((?:apps\/(?:backend|desktop|web|web-public)|packages\/(?:protocol|cli|toolchain)|bridges\/[\w-]+|[\w-]+-bridge)\/.*)$/;
25645
26697
  const PACKAGED_PATH = /\/((?:app\.asar(?:\.unpacked)?|resources)\/.*)$/i;
25646
26698
  const CREDENTIALS = [
26699
+ { pattern: /\bok[ab]_[A-Za-z0-9_-]{16,}/g, replacement: "[redacted]" },
25647
26700
  {
25648
26701
  pattern: /([a-z][a-z0-9+.-]*:\/\/)[^/\s:@]+(?::[^/\s@]*)?@/gi,
25649
26702
  replacement: "$1[redacted]@"
@@ -25771,9 +26824,9 @@ function installFatalRejectionGuard(options) {
25771
26824
  }
25772
26825
 
25773
26826
  // ../protocol/src/node/process-failure-log.ts
25774
- var log8 = createLogger("process");
26827
+ var log11 = createLogger("process");
25775
26828
  function logUnhandledRejection(reason) {
25776
- log8.throttled("error", "rejection.unhandled", {
26829
+ log11.throttled("error", "rejection.unhandled", {
25777
26830
  error: reason,
25778
26831
  fields: () => ({ error: formatLogError(reason, { message: false }) })
25779
26832
  });
@@ -25806,7 +26859,7 @@ function watchClientDisconnect(request, response, onDisconnect) {
25806
26859
  }
25807
26860
 
25808
26861
  // ../../bridges/acp-bridge/src/acp-server.ts
25809
- var log9 = createLogger("bridge.acp");
26862
+ var log12 = createLogger("bridge.acp");
25810
26863
  configureBridgeLogger();
25811
26864
  await restorePersistedState();
25812
26865
  var server = createServer((request, response) => {
@@ -25821,13 +26874,13 @@ var server = createServer((request, response) => {
25821
26874
  return;
25822
26875
  }
25823
26876
  if (error instanceof PolicyWideningRefusedError) {
25824
- log9.warn("session.policy-widening-refused", { widened: error.widened.join(",") });
26877
+ log12.warn("session.policy-widening-refused", { widened: error.widened.join(",") });
25825
26878
  json(response, 403, error.refusal());
25826
26879
  return;
25827
26880
  }
25828
26881
  const status = error instanceof HttpError ? error.status : 500;
25829
26882
  if (status === 500 && !controller.signal.aborted) {
25830
- log9.warn("http.route-failed", {
26883
+ log12.warn("http.route-failed", {
25831
26884
  method: request.method,
25832
26885
  error: formatLogError(error, { message: false })
25833
26886
  });
@@ -25835,7 +26888,7 @@ var server = createServer((request, response) => {
25835
26888
  json(response, status, { error: error instanceof Error ? error.message : String(error) });
25836
26889
  }).finally(stopWatchingClient);
25837
26890
  });
25838
- server.listen(port, hostname, () => log9.info("server.listening", { provider, hostname, port }));
26891
+ server.listen(port, hostname, () => log12.info("server.listening", { provider, hostname, port }));
25839
26892
  var shutdownPromise = null;
25840
26893
  function shutdown() {
25841
26894
  if (shutdownPromise)
@@ -25877,10 +26930,6 @@ export {
25877
26930
  CLOSE_ATTACH_WAIT_MS,
25878
26931
  CLOSE_CANCEL_WAIT_MS,
25879
26932
  CLOSE_SESSION_WAIT_MS,
25880
- CURSOR_BACKGROUND_CONTINUATION_PREFIX,
25881
- CURSOR_BACKGROUND_WAIT_MS,
25882
- CURSOR_CHILD_DISCOVERY_SKEW_MS,
25883
- CURSOR_JSONL_SOURCE_PREFIX,
25884
26933
  CURSOR_TODO_STATUSES,
25885
26934
  DIFF_CONTEXT_LINES,
25886
26935
  EXTERNAL_SESSION_PREFIX,
@@ -25894,17 +26943,9 @@ export {
25894
26943
  MAX_APPROVALS_PER_SESSION,
25895
26944
  MAX_BODY_BYTES,
25896
26945
  MAX_CHILD_PARTS_PER_CALL,
25897
- MAX_CURSOR_BACKGROUND_CONTINUATIONS,
25898
- MAX_CURSOR_CHILD_PARTS,
25899
- MAX_CURSOR_CHILD_PROMPT_BYTES,
25900
- MAX_CURSOR_CHILD_PROMPT_RECORDS,
25901
- MAX_CURSOR_CHILD_RESULT_BYTES,
25902
- MAX_CURSOR_DISCOVERY_ENTRIES,
25903
- MAX_CURSOR_SETTLED_CLAIMS,
25904
26946
  MAX_CURSOR_TASK_PROMPT_BYTES,
25905
26947
  MAX_CURSOR_TODOS,
25906
26948
  MAX_CURSOR_TODO_CANDIDATES,
25907
- MAX_CURSOR_TRANSCRIPT_HYDRATE_CHILDREN,
25908
26949
  MAX_DIFF_EDIT_DISTANCE,
25909
26950
  MAX_EVICTED_TOOL_CALL_IDS,
25910
26951
  MAX_GROK_INTERJECTION_ID_BYTES,
@@ -25996,7 +27037,7 @@ export {
25996
27037
  boundedNullableString,
25997
27038
  boundedString2 as boundedString,
25998
27039
  boundedToolArguments,
25999
- bumpCursorDiscoveryRevision,
27040
+ bridgeCredential,
26000
27041
  catalogCache,
26001
27042
  catalogProbe,
26002
27043
  clearApprovals,
@@ -26012,7 +27053,6 @@ export {
26012
27053
  createDisplayDiff,
26013
27054
  createSession,
26014
27055
  createSessionReserved,
26015
- currentCursorDiscoveryRevision,
26016
27056
  cursorSubagentTypeLabel,
26017
27057
  cursorTaskNamedState,
26018
27058
  diffFileLines,
@@ -26113,7 +27153,6 @@ export {
26113
27153
  raceAbort,
26114
27154
  readJson,
26115
27155
  reconcileStaleToolParts,
26116
- recordCursorTaskPrompt,
26117
27156
  recordTurnUsage,
26118
27157
  rememberCatalog,
26119
27158
  rememberHistoryMessage,
@@ -26178,7 +27217,6 @@ export {
26178
27217
  toolCallContentText,
26179
27218
  toolCallLifecycle,
26180
27219
  toolCallLocationPath,
26181
- toolPartAgentId,
26182
27220
  trimNoticePartId,
26183
27221
  trimPartsTo,
26184
27222
  trimmedToolCalls,