orkestrator 2.36.1 → 2.36.2-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.
@@ -4082,6 +4082,7 @@ var COORDINATOR_CONTROL_TOOL_NAMES = Object.freeze([
4082
4082
  "request_project_on_node",
4083
4083
  "request_root_changes",
4084
4084
  "resolve_conflicts",
4085
+ "restart_build_pipeline_step",
4085
4086
  "resume_build_pipeline",
4086
4087
  "resume_schedule",
4087
4088
  "run_worker_command",
@@ -4109,6 +4110,8 @@ var COORDINATOR_PROJECT_HOME_MESSAGE_WINDOW_MS = 3 * 60 * 60000;
4109
4110
  var AGENT_MAIL_MAX_BODY_BYTES = 32 * 1024;
4110
4111
  var AGENT_MAIL_MAX_STORE_BYTES = 32 * 1024 * 1024;
4111
4112
  var AGENT_MAIL_DEFAULT_RETENTION_DAYS = 14;
4113
+ var AGENT_MAIL_MAX_ATTACHMENT_BYTES = 8 * 1024 * 1024;
4114
+ var AGENT_MAIL_MAX_TOTAL_ATTACHMENT_BYTES = 32 * 1024 * 1024;
4112
4115
  var AGENT_MAIL_DEFAULT_AUTONOMOUS_WAKE_BUDGET = 16;
4113
4116
  var AGENT_MAIL_DEFAULT_HOURLY_WAKE_LIMIT = 40;
4114
4117
  var AGENT_MAIL_TOOL_NAMES = Object.freeze([
@@ -28907,6 +28910,16 @@ function logErrorKind(error) {
28907
28910
  }
28908
28911
 
28909
28912
  // ../protocol/src/log-vocabulary/define.ts
28913
+ var ESSENTIAL_ERROR_FIELDS = {
28914
+ "error.name": "label",
28915
+ "error.code": "label",
28916
+ "error.errno": "number",
28917
+ "error.syscall": "label",
28918
+ "error.exitCode": "number",
28919
+ "error.signal": "label",
28920
+ "error.outputOmitted": "boolean",
28921
+ "error.errorCount": "number"
28922
+ };
28910
28923
  var THROTTLE_LOG_EVENTS = {
28911
28924
  "throttle.suppressed": "Repeats of the throttled `site` were counted over a window, not written.",
28912
28925
  "throttle.recovered": "The throttled `site` succeeded again, so its fault has cleared.",
@@ -28956,7 +28969,11 @@ var BACKEND_LOG_AREAS = defineLogAreas({
28956
28969
  backend: {
28957
28970
  description: "The backend process: startup, background notices and shutdown.",
28958
28971
  events: {
28959
- starting: "The backend process is starting.",
28972
+ starting: {
28973
+ description: "The backend process is starting.",
28974
+ essential: true,
28975
+ fields: { version: "label" }
28976
+ },
28960
28977
  "ssh-socket.resolved": "An SSH agent socket was found.",
28961
28978
  "ssh-socket.missing": "No usable SSH agent socket was found.",
28962
28979
  "standalone-updater.mismatch": "--standalone-updater does not match --data-dir, so self-update is off.",
@@ -28971,8 +28988,16 @@ var BACKEND_LOG_AREAS = defineLogAreas({
28971
28988
  "notice.failed": "A background notice after a turn or prompt failed; `step` says which.",
28972
28989
  "artifacts.live-unavailable": "Live interactive artifacts are unavailable.",
28973
28990
  "shutdown.step-failed": "One part of shutdown failed and the rest went on; `step` says which.",
28974
- "shutdown.signal-received": "A signal started shutdown, which tells a clean quit from the backend being killed.",
28975
- "shutdown.finished": "Shutdown finished, and the process exits with `code`.",
28991
+ "shutdown.signal-received": {
28992
+ description: "A signal started shutdown, which tells a clean quit from the backend being killed.",
28993
+ essential: true,
28994
+ fields: { signal: "label" }
28995
+ },
28996
+ "shutdown.finished": {
28997
+ description: "Shutdown finished, and the process exits with `code`.",
28998
+ essential: true,
28999
+ fields: { code: "number" }
29000
+ },
28976
29001
  "port-policy.second-backend": "Another backend serves the default data directory, so this one avoids its ports.",
28977
29002
  "port-policy.serve-on-free-port": "--tailscale-serve is on a free gateway port; pass --port with --strict-gateway-port to keep one."
28978
29003
  }
@@ -29015,7 +29040,10 @@ var BRIDGE_LOG_AREAS = defineLogAreas({
29015
29040
  "evidence.record-failed": "Change evidence could not be recorded; the read loop carries on.",
29016
29041
  "evidence.shell-record-failed": "A shell observation could not be recorded.",
29017
29042
  "evidence.turn-record-failed": "Turn change evidence could not be recorded.",
29043
+ "agent.exited": "An ACP agent process exited, with its `code` and `signal`, always at `warn`. `requested` is true when the bridge closed it normally, false for an unrequested or fault-driven exit.",
29044
+ "http.route-failed": "An HTTP route answered 500; its error message is not logged because it can hold content.",
29018
29045
  "server.listening": "The HTTP server is listening.",
29046
+ "session.policy-widening-refused": "A request tried to widen a live session's execution policy and was refused; widened names the axes.",
29019
29047
  "state.composer-reset": "A saved composer state was malformed and was reset.",
29020
29048
  "state.discarded": "Saved bridge state could not be used and was discarded.",
29021
29049
  "state.persist-failed": "Saving bridge state failed; a later write retries.",
@@ -29069,7 +29097,7 @@ var BRIDGE_LOG_AREAS = defineLogAreas({
29069
29097
  "session.created": "A session was created or recovered.",
29070
29098
  "session.delete-failed": "Deleting a session failed.",
29071
29099
  "session.fork-failed": "Forking a session failed.",
29072
- "session.policy-widening-refused": "A config request tried to widen a live session's execution policy and was refused; widened names the axes.",
29100
+ "session.policy-widening-refused": "A request tried to widen a live session's execution policy and was refused; widened names the axes.",
29073
29101
  "session.rename-failed": "Renaming a session failed.",
29074
29102
  "session.resolve-failed": "A session could not be found or loaded for a request; action names the request.",
29075
29103
  "session.rewind-failed": "Rewinding session files failed.",
@@ -29103,6 +29131,7 @@ var BRIDGE_LOG_AREAS = defineLogAreas({
29103
29131
  "app-server.exited": "app-server exited unexpectedly; the code and signal say how.",
29104
29132
  "app-server.invariant-violation": "app-server asked for something its configuration forbids.",
29105
29133
  "app-server.protocol-violation": "app-server wrote a line that is not valid protocol; it was ignored.",
29134
+ "app-server.overflow-restart-failed": "Replacing the child after a notification queue overflow failed; the next request tries again.",
29106
29135
  "app-server.recording": "Notification recording is on; recordings hold content.",
29107
29136
  "app-server.stale-reaped": "A stale app-server left by an earlier bridge was stopped.",
29108
29137
  "app-server.stderr": "Metadata of an app-server stderr line, never its content.",
@@ -29133,6 +29162,7 @@ var BRIDGE_LOG_AREAS = defineLogAreas({
29133
29162
  "ordered-events.publish-failed": "Publishing an ordered event failed; clients are told to rehydrate.",
29134
29163
  "ordered-events.reconcile-failed": "Reconciling ordered events failed.",
29135
29164
  "parent.gone": "The backend that launched this bridge has gone; stopping turns and shutting down.",
29165
+ "queue.overflow": "The notification queue passed a bound and dropped its backlog.",
29136
29166
  "queue.task-failed": "A task on a per-thread queue failed.",
29137
29167
  "raw-log.write-failed": "Appending to the raw Codex log failed.",
29138
29168
  "recorder.notice": "The notification recorder needs attention: it is on, or was asked for without its confirmation.",
@@ -29146,6 +29176,7 @@ var BRIDGE_LOG_AREAS = defineLogAreas({
29146
29176
  "server-request.flush-timeout": "An answer to a server request did not flush in time.",
29147
29177
  "server-request.handoff-failed": "Handing a server request to the router threw.",
29148
29178
  "session.config-apply-failed": "Applying session configuration failed; the route answers unavailable.",
29179
+ "session.policy-widening-refused": "A request tried to widen a live session's execution policy and was refused; widened names the axes.",
29149
29180
  "sse.closed": "An event stream was closed by the bridge; the client reconnects and replays.",
29150
29181
  "sse.keepalive-failed": "An event stream keepalive failed.",
29151
29182
  "sse.observer-failed": "An event stream observer failed; it reconnects.",
@@ -29174,19 +29205,39 @@ var BRIDGE_LOG_AREAS = defineLogAreas({
29174
29205
  events: {
29175
29206
  "agent.archive-failed": "Archiving or unarchiving an agent failed.",
29176
29207
  "http.route-failed": "An HTTP route failed unexpectedly; its error is not logged because it can hold content.",
29208
+ "session.policy-widening-refused": "A request tried to widen a live session's execution policy and was refused; widened names the axes.",
29177
29209
  "startup.closes-failed": "Finishing closes a previous process left behind failed at startup.",
29178
29210
  "startup.closes-incomplete": "Some closes a previous process left behind did not finish at startup; a retried close finishes them.",
29179
29211
  "state.publication-failing": "Saving bridge state is failing; new prompts and steers are refused until it recovers.",
29180
29212
  "state.publication-recovered": "Saving bridge state recovered.",
29181
- "state.transcripts-shortened": "The state file reached its limit, so some sessions were saved with a shortened transcript copy."
29213
+ "state.transcripts-shortened": "The state file reached its limit, so some sessions were saved with a shortened transcript copy.",
29214
+ "session.resume-fell-back": {
29215
+ description: "A saved conversation could not be resumed, so a new one started; its error message is not logged because it can hold content.",
29216
+ essential: true,
29217
+ fields: ESSENTIAL_ERROR_FIELDS
29218
+ },
29219
+ "turn.failed": "A turn failed; its error message is not logged because it can hold content. A cancelled turn is not a failure.",
29220
+ "turn.recovery-failed": "A run recovered after a bridge restart ended in failure, or could not be followed. A cancelled run is not a failure.",
29221
+ "turn.send-failed": "Sending a prompt to Cursor failed, so whether its run started is unknown; its error message is not logged because it can hold content.",
29222
+ "turn.timed-out": "A turn outlived its time budget, so its run was asked to cancel; `turn.failed` follows if it never stops."
29182
29223
  }
29183
29224
  },
29184
29225
  "bridge.pi": {
29185
29226
  description: "The Pi bridge: its routes, sessions and saved state.",
29186
29227
  events: {
29187
29228
  "http.route-failed": "An HTTP route failed unexpectedly; its error is not logged because it can hold content.",
29229
+ "session.policy-widening-refused": "A request tried to widen a live session's execution policy and was refused; widened names the axes.",
29230
+ "session-list.failed": "Reading the resumable sessions failed, so none were offered; its error message is not logged because it can hold content.",
29188
29231
  "state.over-budget": "The state file stayed over budget after shedding transcripts, so the write was skipped.",
29189
- "state.transcripts-shed": "The state file was over budget, so some sessions were saved without their transcript."
29232
+ "state.transcripts-shed": "The state file was over budget, so some sessions were saved without their transcript.",
29233
+ "session.resume-fell-back": {
29234
+ description: "A saved conversation could not be reopened, so a new one started; its error message is not logged because it can hold content.",
29235
+ essential: true,
29236
+ fields: ESSENTIAL_ERROR_FIELDS
29237
+ },
29238
+ "turn.failed": "A turn failed; its error message is not logged because it can hold content. A cancelled turn is not a failure.",
29239
+ "turn.refused": "Pi refused a prompt before starting a run, so nothing ran; its error message is not logged because it can hold content.",
29240
+ "turn.startup-timed-out": "Pi did not start a turn within its startup deadline, so the prompt was abandoned."
29190
29241
  }
29191
29242
  }
29192
29243
  });
@@ -29197,14 +29248,31 @@ var DESKTOP_LOG_AREAS = defineLogAreas({
29197
29248
  description: "The Electron main process: startup, windows, quit and the Local backend's life.",
29198
29249
  events: {
29199
29250
  "backend.docker-context-seed-failed": "An agent-test profile fell back to the default Docker context.",
29200
- "backend.exited": "The Local backend exited unexpectedly; Local work is unavailable.",
29201
- "backend.exited-recovering": "The Local backend exited just after a remote update; relaunching unattended.",
29251
+ "backend.exited": {
29252
+ description: "The Local backend exited unexpectedly; Local work is unavailable. `error.exitCode` and `error.signal` say how.",
29253
+ essential: true,
29254
+ fields: ESSENTIAL_ERROR_FIELDS
29255
+ },
29256
+ "backend.exited-recovering": {
29257
+ description: "The Local backend exited just after a remote update; relaunching unattended. `error.exitCode` and `error.signal` say how.",
29258
+ essential: true,
29259
+ fields: ESSENTIAL_ERROR_FIELDS
29260
+ },
29202
29261
  "backend.keychain-link-remove-failed": "An agent-test profile kept a legacy link to the host keychain.",
29203
- "backend.start-failed": "The Local backend did not start; continuing with remote machines.",
29262
+ "backend.start-failed": {
29263
+ description: "The Local backend did not start; continuing with remote machines.",
29264
+ essential: true,
29265
+ fields: ESSENTIAL_ERROR_FIELDS
29266
+ },
29204
29267
  "clipboard.write-failed": "Writing text to the system clipboard failed.",
29205
29268
  "dev-mode.ignored-packaged": "A packaged app was launched with ELECTRON_DEV=1 and ignored it; it loads its bundled renderer.",
29206
29269
  "instance.already-running": "Another instance holds this data directory; this one will quit.",
29207
- "main-thread.stalled": "A timer fired late, so windows, IPC and the stdout reader waited.",
29270
+ "main-thread.stalled": {
29271
+ description: "A timer fired late, so windows, IPC and the stdout reader waited.",
29272
+ essential: true,
29273
+ minLevel: "error",
29274
+ fields: { lagMs: "number", intervalMs: "number" }
29275
+ },
29208
29276
  "quit.stopping-backend": "The app is quitting and has asked the Local backend to stop.",
29209
29277
  "relaunch.schedule-failed": "The AppImage relaunch waiter failed; using Electron's relauncher.",
29210
29278
  "relaunch.service-register-failed": "The AppImage relaunch service was refused; using a detached waiter.",
@@ -29215,7 +29283,11 @@ var DESKTOP_LOG_AREAS = defineLogAreas({
29215
29283
  "saved-machines.attach-failed": "Saved machines were not imported into the command node yet.",
29216
29284
  "saved-machines.attached": "Saved machines were imported into the local command node.",
29217
29285
  "startup.failed": "The application failed to start.",
29218
- "uncaught-exception": "The main process hit an uncaught exception.",
29286
+ "uncaught-exception": {
29287
+ description: "The main process hit an uncaught exception.",
29288
+ essential: true,
29289
+ fields: ESSENTIAL_ERROR_FIELDS
29290
+ },
29219
29291
  "uncaught-exception.dialog-failed": "The uncaught exception sheet could not be shown.",
29220
29292
  "window.create-failed": "A menu-driven new window could not be created.",
29221
29293
  "window.recreate-failed": "The main window could not be recreated on activation.",
@@ -29238,6 +29310,12 @@ var DESKTOP_LOG_AREAS = defineLogAreas({
29238
29310
  "unhandled-rejection": "An unhandled rejection occurred while the renderer was starting."
29239
29311
  }
29240
29312
  },
29313
+ "desktop.permissions": {
29314
+ description: "Permission requests refused on the renderer and workspace realm sessions.",
29315
+ events: {
29316
+ denied: "A renderer asked for a permission the policy does not grant."
29317
+ }
29318
+ },
29241
29319
  "desktop.dialog": {
29242
29320
  description: "Native dialogs, whose modal loops hold the main thread while they are open.",
29243
29321
  events: {
@@ -29356,6 +29434,8 @@ var GATEWAY_LOG_AREAS = defineLogAreas({
29356
29434
  "loopback.unavailable": "The loopback client listener could not start.",
29357
29435
  "auth-token.stored": "The gateway token's file was written. The path only, never the token.",
29358
29436
  "auth-token.persist-failed": "The gateway token could not be saved.",
29437
+ "auth-guess.throttled": "A listener saw enough different wrong tokens that it now pauses new ones. Never the values.",
29438
+ "host.refused": "A request named a host this gateway does not answer to. Logged once per name, up to a limit.",
29359
29439
  "port.fallback": "The preferred port was taken, so a nearby one is used.",
29360
29440
  "port.fallback-distant": "The preferred port and those nearby were taken, so another is used.",
29361
29441
  "request.failed": "A gateway request failed. Throttled: repeats are counted, not written.",
@@ -29399,6 +29479,22 @@ var LOCAL_SERVER_LOG_AREAS = defineLogAreas({
29399
29479
  "bridge-runtime.installed": "A bridge runtime finished installing.",
29400
29480
  "opencode.database-lost-retrying": "OpenCode lost its shared database at startup, so it is retried.",
29401
29481
  "server.stopping": "A local server is being stopped, for the fixed `reason` given.",
29482
+ "bridge.started": {
29483
+ description: "A local bridge process was spawned; `key` names its kind and environment.",
29484
+ essential: true,
29485
+ fields: { key: "label", pid: "number" }
29486
+ },
29487
+ "bridge.exited": {
29488
+ description: "A local bridge process exited, with its `code` and `signal`. `warn` when nothing asked it to, whatever the code; `info` when the backend stopped it, which `server.stopping` explains.",
29489
+ essential: true,
29490
+ fields: {
29491
+ key: "label",
29492
+ pid: "number",
29493
+ code: "number",
29494
+ signal: "label",
29495
+ requested: "boolean"
29496
+ }
29497
+ },
29402
29498
  "reaper.tmux-list-failed": "Orphaned claude-tmux sessions could not be listed.",
29403
29499
  "reaper.tmux-kill-failed": "An orphaned tmux session could not be killed.",
29404
29500
  "reaper.tmux-reaped": "Orphaned claude-tmux sessions of a deleted environment were killed.",
@@ -29432,13 +29528,29 @@ var LOGGING_LOG_AREAS = defineLogAreas({
29432
29528
  "capture.started": "Saving logs to disk began for this process.",
29433
29529
  "capture.stopped": "Saving logs to disk stopped for this process.",
29434
29530
  "config.invalid": "A logging environment variable held a value that was ignored.",
29435
- "entries.dropped": "The log queue was full, so entries were dropped and counted.",
29531
+ "entries.dropped": {
29532
+ description: "Entries were dropped and counted, for the fixed `reason` given: the queue was full, a write failed or, in the essential log, one event was repeating too fast.",
29533
+ essential: true,
29534
+ fields: { entries: "number", bytes: "number", reason: "label" }
29535
+ },
29536
+ "essential.started": {
29537
+ description: "This process began writing the essential log. One with no `essential.stopped` before it means the last writer died.",
29538
+ essential: true,
29539
+ fields: { owner: "label" }
29540
+ },
29541
+ "essential.stopped": {
29542
+ description: "This process stopped writing the essential log, in an orderly exit.",
29543
+ essential: true,
29544
+ fields: { owner: "label" }
29545
+ },
29546
+ "essential.write-failed": "Writing the essential log failed. Its entries are counted, and a marker reports them at the next write that works.",
29436
29547
  "policy.changed": "The logging settings changed: saving, retention and levels, with no content.",
29437
29548
  "policy.bridge-predates-route": "A running bridge has no logging settings route; it applies them at its next start.",
29438
29549
  "policy.push-failed": "A running bridge did not take the logging settings after retries; its next start resends them.",
29439
29550
  "prune.failed": "Removing expired log files failed; the next sweep retries.",
29440
29551
  "write.failed": "Appending to the log file failed.",
29441
- "unknown-area": "Code outside the type checker asked for an area that is not listed."
29552
+ "unknown-area": "Code outside the type checker asked for an area that is not listed.",
29553
+ ...THROTTLE_LOG_EVENTS
29442
29554
  }
29443
29555
  }
29444
29556
  });
@@ -29563,7 +29675,28 @@ var RUNTIME_LOG_AREAS = defineLogAreas({
29563
29675
  "event-loop": {
29564
29676
  description: "This process's event loop. A stall of 10 seconds or more is written at error, so no level hides it.",
29565
29677
  events: {
29566
- stalled: "A timer fired late, so every request in that window waited."
29678
+ stalled: {
29679
+ description: "A timer fired late, so every request in that window waited.",
29680
+ essential: true,
29681
+ minLevel: "error",
29682
+ fields: { lagMs: "number", intervalMs: "number" }
29683
+ }
29684
+ }
29685
+ },
29686
+ process: {
29687
+ description: "Failures of a whole process that nothing in it handled.",
29688
+ events: {
29689
+ "rejection.unhandled": {
29690
+ description: "A promise rejection reached the fatal rejection guard, which keeps the process running.",
29691
+ essential: true,
29692
+ fields: { kind: "label", ...ESSENTIAL_ERROR_FIELDS }
29693
+ },
29694
+ "uncaught-exception": {
29695
+ description: "An exception reached the top of the backend, which is about to die with it. `origin` says whether it was thrown or a rejected top-level await.",
29696
+ essential: true,
29697
+ fields: { origin: "label", ...ESSENTIAL_ERROR_FIELDS }
29698
+ },
29699
+ ...THROTTLE_LOG_EVENTS
29567
29700
  }
29568
29701
  }
29569
29702
  });
@@ -29801,21 +29934,43 @@ var STORAGE_LOG_AREAS = defineLogAreas({
29801
29934
  description: "The SQLite-backed stores, their snapshots and imports from older formats.",
29802
29935
  events: {
29803
29936
  "usage.environment-label-failed": "Usage labels could not be retained for a removed environment; deletion continues.",
29804
- "snapshot.integrity-failed": "An hourly database snapshot failed its integrity check and was discarded.",
29937
+ "migration.failed": {
29938
+ description: "The database could not be brought to this build's schema, so it did not open; `step` says whether the safety copy or the migration itself failed.",
29939
+ essential: true,
29940
+ fields: {
29941
+ fromVersion: "number",
29942
+ toVersion: "number",
29943
+ step: "label",
29944
+ ...ESSENTIAL_ERROR_FIELDS
29945
+ }
29946
+ },
29947
+ "snapshot.integrity-failed": {
29948
+ description: "A database snapshot failed its integrity check and was discarded.",
29949
+ essential: true,
29950
+ fields: {}
29951
+ },
29805
29952
  "snapshot.skipped-low-disk": "The hourly database snapshot was skipped because the disk lacks room; `retryAt` says when it tries again.",
29806
- "snapshot.failed": "The hourly database snapshot failed; `retryAt` says when it tries again, if known.",
29953
+ "snapshot.failed": {
29954
+ description: "The hourly database snapshot failed; `retryAt` says when it tries again, if known.",
29955
+ essential: true,
29956
+ fields: { retryAt: "label", ...ESSENTIAL_ERROR_FIELDS }
29957
+ },
29807
29958
  "listener.attention-failed": "An environment attention listener threw; the committed mutation stands.",
29808
29959
  "listener.change-failed": "A resource change listener threw; the committed mutation stands.",
29809
29960
  "kanban.image-cleanup-failed": "An orphaned Kanban image could not be removed after its retries; it is safe to remove later.",
29810
29961
  "nodes.entries-dropped": "Unreadable node registry entries were ignored.",
29811
29962
  "preview-identity.reminted": "The data directory moved or was copied, so previews get a new backend identity.",
29963
+ "preview-settings.invalid": "Invalid preview settings disabled transport and relay.",
29812
29964
  "machine-profile.invalid": "The stored machine profile was invalid and the default was restored.",
29813
29965
  "permission-rules.cleanup-failed": "A deleted project's permission rules could not be removed.",
29814
29966
  "retired.turn-cleanup-pending": "Cleanup of a retired Looped Review turn did not finish and stays pending.",
29815
29967
  "handoffs.prune-failed": "Pruning agent handoffs that nothing references failed; a later prune retries.",
29816
29968
  "desktop-connections.malformed": "Stored desktop connection settings were malformed, so the local connection is used.",
29817
29969
  "legacy-json.moved": "JSON store files written after the SQLite migration were archived, not imported.",
29818
- "legacy-json.archive-failed": "Imported JSON store files could not be archived."
29970
+ "legacy-json.archive-failed": "Imported JSON store files could not be archived.",
29971
+ "lease.heartbeat-failed": "A held lease's heartbeat failed, which shortens the lease; the next one retries.",
29972
+ "scrub.checkpoint-failed": "Deleted content could not be scrubbed from the WAL because the truncating checkpoint failed or was blocked; the next checkpoint retries.",
29973
+ ...THROTTLE_LOG_EVENTS
29819
29974
  }
29820
29975
  }
29821
29976
  });
@@ -29923,8 +30078,10 @@ var COORDINATOR_LOG_AREAS = defineLogAreas({
29923
30078
  "remote-worker.settle-failed": "A remote worker could not be settled.",
29924
30079
  "checkout.merge-followed": "After an environment's PR merged, the project checkout was fast-forwarded, or `outcome` says why not.",
29925
30080
  "checkout.merge-follow-failed": "Fast-forwarding the project checkout failed, after an environment's PR merged or before mail woke the main coordinator.",
29926
- "checkout.mail-follow": "Before mail woke the main coordinator, the project checkout was fast-forwarded, or `outcome` says why not (`timed-out`, `failed`).",
29927
- "checkout.mail-follow-failed": "Before mail woke the main coordinator, checking whether to fast-forward the project checkout failed; the mail was delivered anyway."
30081
+ "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`).",
30082
+ "checkout.mail-follow-failed": "Before mail woke the main coordinator, checking whether to fast-forward the project checkout failed; the mail was delivered anyway.",
30083
+ "checkout.message-check": "Before a typed message to the main coordinator, the backend answered whether to fast-forward the project checkout: `outcome` (`offer`, `fast-forwarded`, `turn-running`, `not-behind`, `blocked`, `no-status`), `fetch` (`fetched`, `failed`, `timed-out`, `skipped`) and `durationMs`.",
30084
+ "checkout.message-check-failed": "Before a typed message to the main coordinator, fast-forwarding to the upstream commit already fetched failed after a slow or failed fetch; the message was sent anyway."
29928
30085
  }
29929
30086
  }
29930
30087
  });
@@ -30027,7 +30184,27 @@ var DOCKER_LOG_AREAS = defineLogAreas({
30027
30184
  "recovery.clear-terminals-failed": "Terminal sessions could not be cleared after a recovery restore.",
30028
30185
  "github-ranges.seed-not-copied": "The GitHub ranges seed could not be copied into a container, so its firewall fetches them.",
30029
30186
  "availability.probe-failed": "Docker is not available; written when the diagnostic changes. Fixed-shape metadata only: messages can hold daemon endpoints.",
30030
- "start.port-collision-retrying": "An automatic host port collided on start, so it is retried once with fresh ports."
30187
+ "start.port-collision-retrying": "An automatic host port collided on start, so it is retried once with fresh ports.",
30188
+ "writer-lease.lost": {
30189
+ description: "This backend lost the registry writer lease, for the fixed `reason` given. Schedules stop and container changes are refused until it restarts.",
30190
+ essential: true,
30191
+ fields: { reason: "label" }
30192
+ },
30193
+ "writer-lease.regained": {
30194
+ description: "This backend took the registry writer lease over from a holder that stopped refreshing it (it crashed, was killed or stalled), `staleForMs` after its last refresh. The counterpart of that holder's `writer-lease.lost` with reason `reclaimed`; a lease left by a clean shutdown is acquired silently.",
30195
+ essential: true,
30196
+ fields: { staleForMs: "number" }
30197
+ },
30198
+ "writer-lease.not-acquired": {
30199
+ 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.",
30200
+ essential: true,
30201
+ fields: { reason: "label" }
30202
+ },
30203
+ "bridge.launched": {
30204
+ description: "A bridge process was launched in a container, for the first time there or as a relaunch; `provider` names it. A relaunch keeps the run before it in the previous log.",
30205
+ essential: true,
30206
+ fields: { provider: "label", containerPort: "number" }
30207
+ }
30031
30208
  }
30032
30209
  },
30033
30210
  "docker.reachability": {
@@ -30735,6 +30912,146 @@ var LOG_VOCABULARY = {
30735
30912
  ...WEB_SYNC_LOG_AREAS
30736
30913
  };
30737
30914
 
30915
+ // ../protocol/src/log-essential-labels.ts
30916
+ var ERROR_NAMES = new Set([
30917
+ "Error",
30918
+ "TypeError",
30919
+ "RangeError",
30920
+ "ReferenceError",
30921
+ "SyntaxError",
30922
+ "URIError",
30923
+ "EvalError",
30924
+ "AggregateError",
30925
+ "AbortError",
30926
+ "TimeoutError",
30927
+ "SystemError"
30928
+ ]);
30929
+ var ERROR_CODES2 = new Set([
30930
+ "EACCES",
30931
+ "EADDRINUSE",
30932
+ "EADDRNOTAVAIL",
30933
+ "EAGAIN",
30934
+ "EBADF",
30935
+ "EBUSY",
30936
+ "ECANCELED",
30937
+ "ECONNABORTED",
30938
+ "ECONNREFUSED",
30939
+ "ECONNRESET",
30940
+ "EEXIST",
30941
+ "EHOSTUNREACH",
30942
+ "EINTR",
30943
+ "EINVAL",
30944
+ "EIO",
30945
+ "EISDIR",
30946
+ "EMFILE",
30947
+ "ENETUNREACH",
30948
+ "ENFILE",
30949
+ "ENOENT",
30950
+ "ENOMEM",
30951
+ "ENOSPC",
30952
+ "ENOSYS",
30953
+ "ENOTDIR",
30954
+ "ENOTEMPTY",
30955
+ "ENOTFOUND",
30956
+ "EPERM",
30957
+ "EPIPE",
30958
+ "EROFS",
30959
+ "ETIMEDOUT",
30960
+ "EXDEV",
30961
+ "SQLITE_BUSY",
30962
+ "SQLITE_CORRUPT",
30963
+ "SQLITE_FULL",
30964
+ "SQLITE_IOERR",
30965
+ "SQLITE_NOTADB",
30966
+ "SQLITE_READONLY",
30967
+ "ERR_CANCELED",
30968
+ "ERR_STREAM_DESTROYED"
30969
+ ]);
30970
+ var SYSCALLS = new Set([
30971
+ "open",
30972
+ "read",
30973
+ "write",
30974
+ "stat",
30975
+ "lstat",
30976
+ "mkdir",
30977
+ "rmdir",
30978
+ "readdir",
30979
+ "rename",
30980
+ "unlink",
30981
+ "fsync",
30982
+ "fdatasync",
30983
+ "close",
30984
+ "access",
30985
+ "chmod",
30986
+ "copyfile",
30987
+ "connect",
30988
+ "listen",
30989
+ "bind",
30990
+ "spawn",
30991
+ "kill",
30992
+ "getaddrinfo"
30993
+ ]);
30994
+ var SIGNALS = new Set([
30995
+ "SIGABRT",
30996
+ "SIGALRM",
30997
+ "SIGBUS",
30998
+ "SIGCHLD",
30999
+ "SIGCONT",
31000
+ "SIGFPE",
31001
+ "SIGHUP",
31002
+ "SIGILL",
31003
+ "SIGINT",
31004
+ "SIGKILL",
31005
+ "SIGPIPE",
31006
+ "SIGQUIT",
31007
+ "SIGSEGV",
31008
+ "SIGSTOP",
31009
+ "SIGTERM",
31010
+ "SIGTRAP",
31011
+ "SIGTSTP",
31012
+ "SIGTTIN",
31013
+ "SIGTTOU",
31014
+ "SIGUSR1",
31015
+ "SIGUSR2",
31016
+ "SIGWINCH",
31017
+ "SIGXCPU",
31018
+ "SIGXFSZ"
31019
+ ]);
31020
+ var PROVIDERS3 = new Set(["claude", "codex", "opencode", "cursor", "grok", "acp", "pi"]);
31021
+ var UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
31022
+ var SOURCE = new RegExp(`^(?:claude|codex|opencode|cursor|grok|acp|pi):${UUID}$`, "i");
31023
+
31024
+ // ../protocol/src/log-essential.ts
31025
+ var vocabulary = LOG_VOCABULARY;
31026
+ var UNDECLARED_ERROR_LABELS = new Set([
31027
+ "site",
31028
+ "kind",
31029
+ "step",
31030
+ "reason",
31031
+ "signal",
31032
+ "code"
31033
+ ]);
31034
+ function eventSpec(area, event) {
31035
+ const spec = Object.hasOwn(vocabulary, area) ? vocabulary[area] : undefined;
31036
+ if (!spec || !Object.hasOwn(spec.events, event))
31037
+ return null;
31038
+ const definition = spec.events[event];
31039
+ return typeof definition === "object" && definition.essential ? definition : null;
31040
+ }
31041
+ function declaredEssential(area, event, level) {
31042
+ const spec = eventSpec(area, event);
31043
+ return spec && (spec.minLevel !== "error" || level === "error") ? spec : null;
31044
+ }
31045
+ function hasEssentialEvents(area) {
31046
+ const spec = Object.hasOwn(vocabulary, area) ? vocabulary[area] : undefined;
31047
+ return spec !== undefined && Object.values(spec.events).some((event) => typeof event === "object" && event.essential);
31048
+ }
31049
+ function isEssentialEntry(area, event, level) {
31050
+ if (area === "logging" && event === "essential.write-failed")
31051
+ return false;
31052
+ return level === "error" || declaredEssential(area, event, level) !== null;
31053
+ }
31054
+
30738
31055
  // ../protocol/src/logger.ts
30739
31056
  var LOG_LEVELS = ["error", "warn", "info", "debug", "trace"];
30740
31057
  var MAX_FIELD_CHARS = 2048;
@@ -30779,7 +31096,9 @@ var DEFAULT_CONFIG = {
30779
31096
  level: "info",
30780
31097
  areaLevels: {},
30781
31098
  format: "text",
30782
- sink: consoleSink
31099
+ sink: consoleSink,
31100
+ essentialSink: null,
31101
+ relayEssential: false
30783
31102
  };
30784
31103
  var config2 = DEFAULT_CONFIG;
30785
31104
  var generation = 0;
@@ -30890,17 +31209,38 @@ function renderText(record) {
30890
31209
  function renderJson(record) {
30891
31210
  return escapeLogLine(JSON.stringify(record));
30892
31211
  }
31212
+ function offerEssential(record) {
31213
+ if (!config2.essentialSink || !isEssentialEntry(record.area, record.event, record.level))
31214
+ return;
31215
+ try {
31216
+ config2.essentialSink(record);
31217
+ } catch {}
31218
+ }
30893
31219
  function deliver(record) {
31220
+ let delivered = true;
30894
31221
  try {
30895
31222
  config2.sink({
30896
31223
  method: OUTPUT_METHOD[record.level],
30897
31224
  line: config2.format === "json" ? renderJson(record) : renderText(record),
30898
31225
  record
30899
31226
  });
30900
- return true;
30901
31227
  } catch {
30902
- return false;
31228
+ delivered = false;
30903
31229
  }
31230
+ offerEssential(record);
31231
+ return delivered;
31232
+ }
31233
+ function deliverEssentialOnly(record) {
31234
+ if (config2.essentialSink) {
31235
+ offerEssential(record);
31236
+ return;
31237
+ }
31238
+ if (!config2.relayEssential)
31239
+ return;
31240
+ const marked = { ...record, essentialOnly: true };
31241
+ try {
31242
+ config2.sink({ method: OUTPUT_METHOD[record.level], line: renderJson(marked), record: marked });
31243
+ } catch {}
30904
31244
  }
30905
31245
  function buildRecord(level, area, event, fields) {
30906
31246
  const clean = fields ? sanitizeFields(fields, areaSpec(area)?.maxStringChars ?? MAX_FIELD_CHARS) : undefined;
@@ -31065,12 +31405,17 @@ function deliverEvent(level, area, event, fields) {
31065
31405
  return deliver(buildRecord(level, area, event, fields));
31066
31406
  }
31067
31407
  function tryWriteLog(level, area, event, fields) {
31068
- if (LEVEL_RANK[level] > thresholdRank(area))
31408
+ if (LEVEL_RANK[level] > thresholdRank(area)) {
31409
+ if (isEssentialEntry(area, event, level)) {
31410
+ deliverEssentialOnly(buildRecord(level, area, event, resolveFields(fields)));
31411
+ }
31069
31412
  return false;
31413
+ }
31070
31414
  return deliverEvent(level, area, event, resolveFields(fields));
31071
31415
  }
31072
31416
  function createLogger(area) {
31073
31417
  const spec = areaSpec(area);
31418
+ const mayHoldEssential = hasEssentialEvents(area);
31074
31419
  let seenGeneration = -1;
31075
31420
  let rank = 0;
31076
31421
  const enabled = (level) => {
@@ -31083,9 +31428,16 @@ function createLogger(area) {
31083
31428
  const writeResolved = (level, event, resolved) => {
31084
31429
  deliverEvent(level, area, event, resolved);
31085
31430
  };
31431
+ const writeFiltered = (level, event, fields) => {
31432
+ if (!mayHoldEssential || !isEssentialEntry(area, event, level))
31433
+ return;
31434
+ deliverEssentialOnly(buildRecord(level, area, event, resolveFields(fields)));
31435
+ };
31086
31436
  const write = (level, event, fields) => {
31087
- if (!enabled(level))
31437
+ if (!enabled(level)) {
31438
+ writeFiltered(level, event, fields);
31088
31439
  return;
31440
+ }
31089
31441
  writeResolved(level, event, resolveFields(fields));
31090
31442
  };
31091
31443
  return {
@@ -31096,8 +31448,10 @@ function createLogger(area) {
31096
31448
  trace: (event, fields) => write("trace", event, fields),
31097
31449
  throttled: (level, event, options) => {
31098
31450
  syncThrottleLevels();
31099
- if (!enabled(level))
31451
+ if (!enabled(level)) {
31452
+ writeFiltered(level, event, options.fields);
31100
31453
  return;
31454
+ }
31101
31455
  if (!spec || !Object.hasOwn(spec.events, event) || event.startsWith("throttle.") || !Object.hasOwn(spec.events, "throttle.recovered")) {
31102
31456
  deliver(buildRecord(level, spec ? area : "logging", spec ? "invalid-event" : "unknown-area", undefined));
31103
31457
  return;
@@ -31171,41 +31525,46 @@ async function drainPersistence() {
31171
31525
  return;
31172
31526
  });
31173
31527
  }
31174
- function shedToFit(payload, order) {
31175
- const byOldest = [...payload.sessions].sort((left, right) => (order.get(left.id) ?? 0) - (order.get(right.id) ?? 0));
31176
- let shed = 0;
31177
- for (const session of byOldest) {
31178
- if (session.messages.length === 0)
31179
- continue;
31180
- session.droppedMessages = (session.droppedMessages ?? 0) + session.messages.length;
31181
- session.messages = [];
31182
- session.transcriptTruncated = true;
31183
- shed += 1;
31184
- if (Buffer.byteLength(JSON.stringify(payload)) <= MAX_STATE_FILE_BYTES) {
31185
- log.warn("state.transcripts-shed", { sessions: shed });
31186
- return true;
31528
+ function encodeStateWithinBudget(payload, lastAccessedById, budget) {
31529
+ const envelope = JSON.stringify({ ...payload, sessions: [] });
31530
+ const head = envelope.slice(0, -2);
31531
+ const records = payload.sessions.map((session) => JSON.stringify(session));
31532
+ const separators = Math.max(0, records.length - 1);
31533
+ let total = Buffer.byteLength(envelope) + separators;
31534
+ for (const record of records)
31535
+ total += Buffer.byteLength(record);
31536
+ if (total > budget) {
31537
+ const oldestFirst = payload.sessions.map((session, index) => ({ session, index })).sort((left, right) => (lastAccessedById.get(left.session.id) ?? 0) - (lastAccessedById.get(right.session.id) ?? 0));
31538
+ let shed = 0;
31539
+ for (const { session, index } of oldestFirst) {
31540
+ if (total <= budget)
31541
+ break;
31542
+ if (session.messages.length === 0)
31543
+ continue;
31544
+ session.droppedMessages = (session.droppedMessages ?? 0) + session.messages.length;
31545
+ session.messages = [];
31546
+ session.transcriptTruncated = true;
31547
+ shed += 1;
31548
+ const trimmed = JSON.stringify(session);
31549
+ total += Buffer.byteLength(trimmed) - Buffer.byteLength(records[index]);
31550
+ records[index] = trimmed;
31551
+ }
31552
+ if (total > budget) {
31553
+ log.warn("state.over-budget", { sessions: shed });
31554
+ return;
31187
31555
  }
31556
+ log.warn("state.transcripts-shed", { sessions: shed });
31188
31557
  }
31189
- log.warn("state.over-budget", { sessions: shed });
31190
- return false;
31558
+ return `${head}${records.join(",")}]}`;
31191
31559
  }
31192
31560
  async function persistNow(write = { barrier: false }) {
31193
31561
  const stateFile = stateFilePath();
31194
31562
  if (!stateFile)
31195
31563
  return;
31196
31564
  const live = Array.from(sessions.values()).filter((state) => !isPendingRemoval(state));
31197
- const payload = {
31198
- version: 1,
31199
- provider: "pi",
31200
- sessions: live.map(toPersisted)
31201
- };
31202
- let serialized = JSON.stringify(payload);
31203
- if (Buffer.byteLength(serialized) > MAX_STATE_FILE_BYTES) {
31204
- const order = new Map(live.map((state) => [state.id, state.lastAccessed]));
31205
- if (!shedToFit(payload, order)) {
31206
- throw new Error("Pi bridge state exceeds its persistence budget");
31207
- }
31208
- serialized = JSON.stringify(payload);
31565
+ const serialized = encodeStateWithinBudget({ version: 1, provider: "pi", sessions: live.map(toPersisted) }, new Map(live.map((state) => [state.id, state.lastAccessed])), MAX_STATE_FILE_BYTES);
31566
+ if (serialized === undefined) {
31567
+ throw new Error("Pi bridge state exceeds its persistence budget");
31209
31568
  }
31210
31569
  await mkdir(dirname(stateFile), { recursive: true, mode: 448 });
31211
31570
  if (writeGateForTests)
@@ -31281,6 +31640,7 @@ function restoreSession(entry) {
31281
31640
  state.id = entry.id;
31282
31641
  if (isNativeAgentExecutionPolicy(entry.policy))
31283
31642
  state.policy = entry.policy;
31643
+ state.policyPending = true;
31284
31644
  if (nonBlank(entry.sessionFile))
31285
31645
  state.sessionFile = entry.sessionFile;
31286
31646
  if (nonBlank(entry.piSessionId))
@@ -31594,7 +31954,7 @@ function readString2(value) {
31594
31954
  }
31595
31955
  // ../../bridges/pi-bridge/src/agent-session.ts
31596
31956
  import { randomBytes as randomBytes6 } from "node:crypto";
31597
- import { existsSync as existsSync2 } from "node:fs";
31957
+ import { existsSync as existsSync2, statSync } from "node:fs";
31598
31958
 
31599
31959
  // ../protocol/src/agent-system-instructions.ts
31600
31960
  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.";
@@ -31609,9 +31969,100 @@ function agentSystemInstructions(providerSpecific = []) {
31609
31969
  `);
31610
31970
  }
31611
31971
 
31972
+ // ../protocol/src/execution-policy-narrowing.ts
31973
+ var APPROVALS_STRICTNESS = {
31974
+ "auto-approve": 0,
31975
+ ask: 1,
31976
+ deny: 2
31977
+ };
31978
+ var SANDBOX_STRICTNESS = {
31979
+ none: 0,
31980
+ container: 1,
31981
+ provider: 2
31982
+ };
31983
+ function networkStrictness(value) {
31984
+ return value === "restricted" ? 1 : 0;
31985
+ }
31986
+ function isSubset(candidate, of) {
31987
+ const allowed = new Set(of);
31988
+ return candidate.every((item) => allowed.has(item));
31989
+ }
31990
+ function rawCapabilityDenials(policy) {
31991
+ return [
31992
+ ...policy.capabilityPolicy?.deny ?? [],
31993
+ ...policy.capabilityPolicy?.extendedDeny ?? []
31994
+ ];
31995
+ }
31996
+ function executionPolicyWidenings(current, next) {
31997
+ if (!current)
31998
+ return [];
31999
+ const widened = [];
32000
+ if (next.id !== current.id)
32001
+ widened.push("id");
32002
+ if (APPROVALS_STRICTNESS[next.approvals] < APPROVALS_STRICTNESS[current.approvals]) {
32003
+ widened.push("approvals");
32004
+ }
32005
+ if (SANDBOX_STRICTNESS[next.sandbox] < SANDBOX_STRICTNESS[current.sandbox]) {
32006
+ widened.push("sandbox");
32007
+ }
32008
+ if (next.projectResources && !current.projectResources)
32009
+ widened.push("projectResources");
32010
+ if (networkStrictness(next.networkAccess) < networkStrictness(current.networkAccess)) {
32011
+ widened.push("networkAccess");
32012
+ }
32013
+ if (networkStrictness(next.containerNetworkAccess) < networkStrictness(current.containerNetworkAccess)) {
32014
+ widened.push("containerNetworkAccess");
32015
+ }
32016
+ const currentAllow = current.toolPolicy?.allow;
32017
+ const nextAllow = next.toolPolicy?.allow;
32018
+ const allowNarrows = currentAllow === undefined ? nextAllow === undefined || nextAllow.length === 0 : nextAllow !== undefined && isSubset(nextAllow, currentAllow);
32019
+ if (!allowNarrows)
32020
+ widened.push("toolPolicy.allow");
32021
+ if (!isSubset(current.toolPolicy?.deny ?? [], next.toolPolicy?.deny ?? [])) {
32022
+ widened.push("toolPolicy.deny");
32023
+ }
32024
+ if (!isSubset(rawCapabilityDenials(current), rawCapabilityDenials(next))) {
32025
+ widened.push("capabilityPolicy.deny");
32026
+ }
32027
+ if (!isSubset(next.capabilityPolicy?.allow ?? [], current.capabilityPolicy?.allow ?? [])) {
32028
+ widened.push("capabilityPolicy.allow");
32029
+ }
32030
+ const currentServers = nativeAgentUserMcpGrant(current);
32031
+ const nextServers = nativeAgentUserMcpGrant(next);
32032
+ if (currentServers !== undefined && (nextServers === undefined || !isSubset(nextServers, currentServers))) {
32033
+ widened.push("capabilityPolicy.userMcpServers");
32034
+ }
32035
+ return widened;
32036
+ }
32037
+ var POLICY_WIDENING_REFUSED_CODE = "policy-widening-refused";
32038
+ function policyWideningRefusal(widened) {
32039
+ return {
32040
+ error: "Execution policy can only be narrowed on a live session; a wider policy applies after the agent bridge restarts.",
32041
+ code: POLICY_WIDENING_REFUSED_CODE,
32042
+ widened
32043
+ };
32044
+ }
32045
+
32046
+ class PolicyWideningRefusedError extends Error {
32047
+ widened;
32048
+ constructor(widened) {
32049
+ super(policyWideningRefusal(widened).error);
32050
+ this.widened = widened;
32051
+ this.name = "PolicyWideningRefusedError";
32052
+ }
32053
+ refusal() {
32054
+ return policyWideningRefusal(this.widened);
32055
+ }
32056
+ }
32057
+ function assertExecutionPolicyNotWidened(current, next) {
32058
+ const widened = executionPolicyWidenings(current, next);
32059
+ if (widened.length > 0)
32060
+ throw new PolicyWideningRefusedError(widened);
32061
+ }
32062
+
31612
32063
  // ../../bridges/pi-bridge/src/agent-session.ts
31613
- import { realpath, stat as stat2 } from "node:fs/promises";
31614
- import { join as join6, resolve as resolve3, sep } from "node:path";
32064
+ import { realpath, stat as stat3 } from "node:fs/promises";
32065
+ import { join as join7, resolve as resolve3, sep } from "node:path";
31615
32066
 
31616
32067
  // ../protocol/src/node/command-change-journal.ts
31617
32068
  import { appendFile, mkdir as mkdir2, readFile as readFile3, rename as rename2, rm, stat, writeFile as writeFile2 } from "node:fs/promises";
@@ -33692,7 +34143,44 @@ async function overlayCommandChanges(state, options = {}) {
33692
34143
  } catch {}
33693
34144
  }
33694
34145
 
34146
+ // ../../bridges/pi-bridge/src/session-list-cache.ts
34147
+ import { createHash as createHash4 } from "node:crypto";
34148
+ import { readdir, stat as stat2 } from "node:fs/promises";
34149
+ import { join as join6 } from "node:path";
34150
+ var SESSION_LIST_CACHE_TTL_MS = 30000;
34151
+ var MAX_CACHED_SESSION_LIST_BYTES = 2 * 1024 * 1024;
34152
+ var cached2;
34153
+ async function sessionFilesStamp(directory) {
34154
+ let names;
34155
+ try {
34156
+ names = (await readdir(directory)).filter((name) => name.endsWith(".jsonl")).sort();
34157
+ } catch {
34158
+ return;
34159
+ }
34160
+ const stats = await Promise.all(names.map((name) => stat2(join6(directory, name)).catch(() => {
34161
+ return;
34162
+ })));
34163
+ const hash = createHash4("sha256");
34164
+ for (const [index, name] of names.entries()) {
34165
+ const file = stats[index];
34166
+ hash.update(file ? `${name}\x00${file.size}\x00${file.mtimeMs}\x00${file.ctimeMs}\x00${file.ino}
34167
+ ` : `${name}\x00gone
34168
+ `);
34169
+ }
34170
+ return hash.digest("hex");
34171
+ }
34172
+ function cachedSessionList(directory, stamp) {
34173
+ if (stamp === undefined || cached2?.directory !== directory || cached2.stamp !== stamp || performance.now() >= cached2.expiresAt) {
34174
+ return;
34175
+ }
34176
+ return cached2.entries;
34177
+ }
34178
+ function rememberSessionList(directory, stamp, entries) {
34179
+ cached2 = stamp !== undefined && encodedJsonBytes(entries) <= MAX_CACHED_SESSION_LIST_BYTES ? { directory, stamp, entries, expiresAt: performance.now() + SESSION_LIST_CACHE_TTL_MS } : undefined;
34180
+ }
34181
+
33695
34182
  // ../../bridges/pi-bridge/src/agent-session.ts
34183
+ var log2 = createLogger("bridge.pi");
33696
34184
  var closingSessions = new WeakSet;
33697
34185
 
33698
34186
  class SessionClosingError extends Error {
@@ -33701,6 +34189,13 @@ class SessionClosingError extends Error {
33701
34189
  super("This Pi session is closing; retry once the close completes");
33702
34190
  }
33703
34191
  }
34192
+
34193
+ class SessionBusyError extends Error {
34194
+ name = "SessionBusyError";
34195
+ constructor() {
34196
+ super("The Pi session is already running");
34197
+ }
34198
+ }
33704
34199
  function isSessionClosed(state) {
33705
34200
  return closingSessions.has(state);
33706
34201
  }
@@ -33802,8 +34297,9 @@ async function createSession(clientSessionKey, patch, policy) {
33802
34297
  throw new SessionClosingError;
33803
34298
  if (existing) {
33804
34299
  const resolved = resolvePiExecutionPolicy(policy);
33805
- if (policy || resolved.id === "coordinator-read-only")
33806
- existing.policy = resolved;
34300
+ if (policy || resolved.id === "coordinator-read-only") {
34301
+ await applyRequestedPolicy(existing, resolved);
34302
+ }
33807
34303
  if (resolved.id === "coordinator-read-only" && existing.readOnly !== true) {
33808
34304
  await setSessionReadOnly(existing, true);
33809
34305
  }
@@ -33811,12 +34307,24 @@ async function createSession(clientSessionKey, patch, policy) {
33811
34307
  return existing;
33812
34308
  }
33813
34309
  const inFlight = sessionCreations.get(clientSessionKey);
33814
- if (inFlight)
33815
- return inFlight;
34310
+ if (inFlight) {
34311
+ const existing = await inFlight;
34312
+ if (isSessionClosed(existing))
34313
+ throw new SessionClosingError;
34314
+ const resolved = resolvePiExecutionPolicy(policy);
34315
+ if (policy || resolved.id === "coordinator-read-only") {
34316
+ await applyRequestedPolicy(existing, resolved);
34317
+ }
34318
+ if (resolved.id === "coordinator-read-only" && existing.readOnly !== true) {
34319
+ await setSessionReadOnly(existing, true);
34320
+ }
34321
+ return existing;
34322
+ }
33816
34323
  }
33817
34324
  const work = (async () => {
33818
34325
  const resolved = resolvePiExecutionPolicy(policy);
33819
34326
  const state = newSessionState(clientSessionKey, resolved);
34327
+ state.policyPending = !policy;
33820
34328
  state.promptJournalComplete = true;
33821
34329
  if (resolved.id === "coordinator-read-only")
33822
34330
  state.readOnly = true;
@@ -33837,6 +34345,8 @@ async function createSession(clientSessionKey, patch, policy) {
33837
34345
  }
33838
34346
  }
33839
34347
  async function ensureSession(state) {
34348
+ if (policyChanges.has(state))
34349
+ throw new SessionBusyError;
33840
34350
  if (closingSessions.has(state))
33841
34351
  throw new SessionClosingError;
33842
34352
  if (state.session)
@@ -34105,9 +34615,9 @@ function projectResourceDiscoveryOptions(enabled = false, readOnly = false) {
34105
34615
  }
34106
34616
  function coordinatorProjectSkillPaths(cwd = workingDirectory) {
34107
34617
  return [
34108
- join6(cwd, ".pi", "skills"),
34109
- join6(cwd, ".agents", "skills"),
34110
- join6(cwd, ".claude", "skills")
34618
+ join7(cwd, ".pi", "skills"),
34619
+ join7(cwd, ".agents", "skills"),
34620
+ join7(cwd, ".claude", "skills")
34111
34621
  ].filter((path) => existsSync2(path));
34112
34622
  }
34113
34623
  function piResourceLoaderPolicy(state, cwd = workingDirectory) {
@@ -34137,6 +34647,35 @@ function coordinatorProcessPolicy() {
34137
34647
  networkAccess: "restricted"
34138
34648
  };
34139
34649
  }
34650
+ function liveExecutionPolicy(state) {
34651
+ return state.policyPending ? undefined : state.policy;
34652
+ }
34653
+ var policyChanges = new WeakSet;
34654
+ async function applyRequestedPolicy(state, policy) {
34655
+ if (policyChanges.has(state))
34656
+ throw new SessionBusyError;
34657
+ assertExecutionPolicyNotWidened(liveExecutionPolicy(state), policy);
34658
+ if (JSON.stringify(state.policy) !== JSON.stringify(policy)) {
34659
+ if (state.status === "running" || state.dispatching)
34660
+ throw new SessionBusyError;
34661
+ policyChanges.add(state);
34662
+ state.dispatching = true;
34663
+ try {
34664
+ await state.attaching?.catch(() => {
34665
+ return;
34666
+ });
34667
+ await detachSession(state);
34668
+ if (isSessionClosed(state))
34669
+ throw new SessionClosingError;
34670
+ assertExecutionPolicyNotWidened(liveExecutionPolicy(state), policy);
34671
+ state.policy = policy;
34672
+ } finally {
34673
+ state.dispatching = false;
34674
+ policyChanges.delete(state);
34675
+ }
34676
+ }
34677
+ state.policyPending = false;
34678
+ }
34140
34679
  function resolvePiExecutionPolicy(policy) {
34141
34680
  if (process.env[BRIDGE_EXECUTION_POLICY_ENV2] === "coordinator-read-only") {
34142
34681
  return coordinatorProcessPolicy();
@@ -34169,8 +34708,17 @@ function sessionManagerFor(state) {
34169
34708
  const directory = sessionDirectory();
34170
34709
  if (state.sessionFile) {
34171
34710
  try {
34172
- return SessionManager.open(state.sessionFile, directory, workingDirectory);
34173
- } catch {
34711
+ const hasHistory = (statSync(state.sessionFile, { throwIfNoEntry: false })?.size ?? 0) > 0;
34712
+ const manager = SessionManager.open(state.sessionFile, directory, workingDirectory);
34713
+ if (!hasHistory && (state.messages.length > 0 || state.promptSequence > 0)) {
34714
+ log2.warn("session.resume-fell-back", { sessionId: state.id });
34715
+ }
34716
+ return manager;
34717
+ } catch (error) {
34718
+ log2.warn("session.resume-fell-back", {
34719
+ sessionId: state.id,
34720
+ error: formatLogError(error, { message: false })
34721
+ });
34174
34722
  state.sessionFile = undefined;
34175
34723
  }
34176
34724
  }
@@ -34275,9 +34823,31 @@ async function applyComposerToSession(state) {
34275
34823
  state.revision += 1;
34276
34824
  }
34277
34825
  }
34826
+ var SESSION_LIST_TIMEOUT_MESSAGE = "Pi took too long to read its session history";
34827
+ var sessionListTimeoutMs = CATALOG_TIMEOUT_MS;
34828
+ function setSessionListTimeoutForTests(timeoutMs) {
34829
+ sessionListTimeoutMs = timeoutMs ?? CATALOG_TIMEOUT_MS;
34830
+ }
34278
34831
  async function listResumableSessions() {
34279
- const listed = await withTimeout(SessionManager.list(workingDirectory, sessionDirectory()), CATALOG_TIMEOUT_MS, "Pi session list timed out").catch(() => []);
34280
- return listed.slice(0, MAX_RESUME_ENTRIES).map((info) => ({
34832
+ const read = new AbortController;
34833
+ try {
34834
+ return await withTimeout(readResumableSessions(read.signal), sessionListTimeoutMs, SESSION_LIST_TIMEOUT_MESSAGE);
34835
+ } catch (error) {
34836
+ read.abort();
34837
+ if (error instanceof TimeoutError)
34838
+ throw error;
34839
+ log2.warn("session-list.failed", { error: formatLogError(error, { message: false }) });
34840
+ return [];
34841
+ }
34842
+ }
34843
+ async function readResumableSessions(signal) {
34844
+ const directory = SessionManager.create(workingDirectory, sessionDirectory()).getSessionDir();
34845
+ const stamp = await sessionFilesStamp(directory);
34846
+ const cached = cachedSessionList(directory, stamp);
34847
+ if (cached)
34848
+ return cached;
34849
+ const listed = await SessionManager.list(workingDirectory, sessionDirectory(), undefined, signal);
34850
+ const entries = listed.slice(0, MAX_RESUME_ENTRIES).map((info) => ({
34281
34851
  sessionId: info.path,
34282
34852
  ...info.name?.trim() ? { title: info.name.trim() } : {},
34283
34853
  ...info.created ? { createdAt: new Date(info.created).toISOString() } : {},
@@ -34287,9 +34857,11 @@ async function listResumableSessions() {
34287
34857
  ...info.parentSessionPath ? { parentId: info.parentSessionPath } : {},
34288
34858
  ...info.parentSessionPath ? { branchLabel: info.name?.trim() || info.firstMessage.trim().slice(0, 80) || "Fork" } : {}
34289
34859
  }));
34860
+ rememberSessionList(directory, stamp, entries);
34861
+ return entries;
34290
34862
  }
34291
34863
  function resumableSessionRoot() {
34292
- return sessionDirectory() ?? join6(agentDirectory() ?? getAgentDir(), "sessions");
34864
+ return sessionDirectory() ?? join7(agentDirectory() ?? getAgentDir(), "sessions");
34293
34865
  }
34294
34866
  async function assertResumableSessionFile(sessionFile) {
34295
34867
  const root = resumableSessionRoot();
@@ -34305,7 +34877,7 @@ async function assertResumableSessionFile(sessionFile) {
34305
34877
  if (real !== rootReal && !real.startsWith(rootReal.endsWith(sep) ? rootReal : rootReal + sep)) {
34306
34878
  throw new Error("That Pi session file is outside this environment's session directory");
34307
34879
  }
34308
- const info = await stat2(real).catch(() => {
34880
+ const info = await stat3(real).catch(() => {
34309
34881
  return;
34310
34882
  });
34311
34883
  if (!info?.isFile())
@@ -34324,15 +34896,8 @@ async function resumeSession(sessionFile, patch, policy) {
34324
34896
  if (sameFile) {
34325
34897
  if (isSessionClosed(existing))
34326
34898
  throw new SessionClosingError;
34327
- if (policy && JSON.stringify(existing.policy) !== JSON.stringify(policy)) {
34328
- if (existing.status === "running" || existing.dispatching) {
34329
- throw new Error("The Pi session is already running");
34330
- }
34331
- await detachSession(existing);
34332
- if (isSessionClosed(existing))
34333
- throw new SessionClosingError;
34334
- existing.policy = resolvePiExecutionPolicy(policy);
34335
- }
34899
+ if (policy)
34900
+ await applyRequestedPolicy(existing, resolvePiExecutionPolicy(policy));
34336
34901
  applyComposerPatch(existing, patch);
34337
34902
  existing.lastAccessed = Date.now();
34338
34903
  return existing;
@@ -34343,12 +34908,15 @@ async function resumeSession(sessionFile, patch, policy) {
34343
34908
  const existing = await inFlight;
34344
34909
  if (isSessionClosed(existing))
34345
34910
  throw new SessionClosingError;
34911
+ if (policy)
34912
+ await applyRequestedPolicy(existing, resolvePiExecutionPolicy(policy));
34346
34913
  applyComposerPatch(existing, patch);
34347
34914
  existing.lastAccessed = Date.now();
34348
34915
  return existing;
34349
34916
  }
34350
34917
  const work = (async () => {
34351
34918
  const state = newSessionState(undefined, resolvePiExecutionPolicy(policy));
34919
+ state.policyPending = !policy;
34352
34920
  state.sessionFile = resolved;
34353
34921
  applyComposerPatch(state, patch);
34354
34922
  state.composer = await hydrateComposerForSession(state.composer, undefined, defaultModelIds(state));
@@ -34649,14 +35217,14 @@ function pushMessage(state, role, content, parts, createdAt, messageId = randomB
34649
35217
  chargeTranscript(state, Buffer.byteLength(JSON.stringify(message)));
34650
35218
  }
34651
35219
  // ../protocol/src/node/bridge-diagnostics.ts
34652
- import { createHash as createHash4 } from "node:crypto";
35220
+ import { createHash as createHash5 } from "node:crypto";
34653
35221
 
34654
35222
  // ../protocol/src/event-loop-stall-monitor.ts
34655
- var log2 = createLogger("event-loop");
35223
+ var log3 = createLogger("event-loop");
34656
35224
  var EVENT_LOOP_STALL_ALWAYS_LOG_MS = 1e4;
34657
35225
 
34658
35226
  // ../protocol/src/node/bridge-diagnostics.ts
34659
- var log3 = createLogger("bridge.diagnostics");
35227
+ var log4 = createLogger("bridge.diagnostics");
34660
35228
  var BRIDGE_DIAGNOSTICS_INTERVAL_MS = 60000;
34661
35229
  var INTERVAL_MS = BRIDGE_DIAGNOSTICS_INTERVAL_MS;
34662
35230
  var STALL_NO_DELTA_MS = 2 * INTERVAL_MS;
@@ -34748,7 +35316,7 @@ function sameSet(a, b) {
34748
35316
  function identity(value) {
34749
35317
  if (typeof value !== "string" || !value || value.length > MAX_ID_LENGTH)
34750
35318
  return;
34751
- return createHash4("sha256").update(value).digest("hex").slice(0, 16);
35319
+ return createHash5("sha256").update(value).digest("hex").slice(0, 16);
34752
35320
  }
34753
35321
  function readBridgeDebugFlag(value) {
34754
35322
  return value?.trim() === "1";
@@ -34821,16 +35389,16 @@ function safeDiagnosticMetrics(value) {
34821
35389
  return result;
34822
35390
  }
34823
35391
  function bridgeDiagnosticsChangesEnabled() {
34824
- return log3.isEnabled("trace");
35392
+ return log4.isEnabled("trace");
34825
35393
  }
34826
35394
  function writeBridgeDiagnostic({ bridge, event, payload }) {
34827
35395
  return tryWriteLog("info", "bridge.diagnostics", event, { bridge, payload });
34828
35396
  }
34829
35397
  function bridgeDiagnosticsActive() {
34830
- return log3.isEnabled("info");
35398
+ return log4.isEnabled("info");
34831
35399
  }
34832
35400
  function bridgeDiagnosticsStreamEnabled(bridge) {
34833
- return bridgeDebugEnabled(bridge) || log3.isEnabled("debug");
35401
+ return bridgeDebugEnabled(bridge) || log4.isEnabled("debug");
34834
35402
  }
34835
35403
  function writeDiagnostic(bridge, event, payload, write) {
34836
35404
  try {
@@ -35326,6 +35894,7 @@ var STRUCTURED_OUTPUT_FAILURE_CODES = new Set([
35326
35894
  ]);
35327
35895
 
35328
35896
  // ../../bridges/pi-bridge/src/prompt.ts
35897
+ var log5 = createLogger("bridge.pi");
35329
35898
  var STRUCTURED_PROMPT_INSTRUCTION_PREFIX = "End your turn with exactly one JSON value";
35330
35899
  function structuredPromptInstruction(schema) {
35331
35900
  return `${STRUCTURED_PROMPT_INSTRUCTION_PREFIX} matching this JSON Schema. That final message must be the JSON value alone, with no Markdown fence and no commentary around it.
@@ -35405,6 +35974,7 @@ ${structuredPromptInstruction(input.schema)}` : input.prompt;
35405
35974
  });
35406
35975
  const commandRun = input.extensionCommand ? beginCommandRun(state, input.extensionCommand) : undefined;
35407
35976
  state.turnAborted = undefined;
35977
+ state.turnCancelRequested = undefined;
35408
35978
  state.turnError = undefined;
35409
35979
  state.currentTurnApiDurationMs = undefined;
35410
35980
  let run;
@@ -35471,6 +36041,8 @@ ${structuredPromptInstruction(input.schema)}` : input.prompt;
35471
36041
  const cancelTurn = (reason = "user") => {
35472
36042
  if (cancelling)
35473
36043
  return cancelling;
36044
+ if (reason === "user")
36045
+ state.turnCancelRequested = true;
35474
36046
  const operation = (async () => {
35475
36047
  if (commandRun) {
35476
36048
  commandRun.cancelled = true;
@@ -35493,8 +36065,12 @@ ${structuredPromptInstruction(input.schema)}` : input.prompt;
35493
36065
  })();
35494
36066
  cancelling = operation;
35495
36067
  operation.catch(() => {
35496
- if (cancelling === operation)
36068
+ if (cancelling === operation) {
35497
36069
  cancelling = undefined;
36070
+ if (reason === "user" && state.cancelTurn === cancelTurn) {
36071
+ state.turnCancelRequested = undefined;
36072
+ }
36073
+ }
35498
36074
  });
35499
36075
  return operation;
35500
36076
  };
@@ -35529,6 +36105,7 @@ async function withinStartupDeadline(accepted, deadlineMs) {
35529
36105
  }
35530
36106
  }
35531
36107
  function abandonStartup(state, session, claim, accepted, settled, input, diagnostics, error, evidenceTurnId) {
36108
+ log5.warn("turn.startup-timed-out", { sessionId: state.id });
35532
36109
  state.status = "error";
35533
36110
  state.error = error.message;
35534
36111
  state.revision += 1;
@@ -35605,6 +36182,7 @@ async function followRun(state, session, run, promptSequence, input, promptTimeo
35605
36182
  }
35606
36183
  finishTurn(state, session, input);
35607
36184
  } catch (error) {
36185
+ const abortedBeforeCleanup = state.turnAborted === true;
35608
36186
  state.diagnostics?.terminalSettled("rejected");
35609
36187
  state.diagnostics?.streamSettled("rejected");
35610
36188
  state.diagnostics?.checkpoint("cancelling");
@@ -35618,7 +36196,7 @@ async function followRun(state, session, run, promptSequence, input, promptTimeo
35618
36196
  commandRun.error ??= errorText(error);
35619
36197
  settleCommandRun(state, commandRun, input.requestId);
35620
36198
  }
35621
- failTurn(state, session, error, input);
36199
+ failTurn(state, session, error, input, abortedBeforeCleanup);
35622
36200
  } finally {
35623
36201
  if (commandRun && state.commandRun === commandRun)
35624
36202
  state.commandRun = undefined;
@@ -35682,7 +36260,13 @@ function recordInterruptedOutput(state, input, message) {
35682
36260
  error: { code: "interrupted", message, provider: PROVIDER, retryable: true }
35683
36261
  });
35684
36262
  }
35685
- function failTurn(state, session, error, input) {
36263
+ function failTurn(state, session, error, input, abortedBeforeCleanup = state.turnAborted === true) {
36264
+ if (!abortedBeforeCleanup && state.turnCancelRequested !== true) {
36265
+ log5.warn("turn.failed", {
36266
+ sessionId: state.id,
36267
+ error: formatLogError(error, { message: false })
36268
+ });
36269
+ }
35686
36270
  settleTurn(state, session);
35687
36271
  recordTurnEnded(state, piRunId(state), "failed");
35688
36272
  state.status = "error";
@@ -35892,7 +36476,7 @@ function toImageContent(image) {
35892
36476
  // ../../bridges/pi-bridge/src/prompt-attachments.ts
35893
36477
  import { constants } from "node:fs";
35894
36478
  import { lstat as lstat2, open as open2, realpath as realpath2 } from "node:fs/promises";
35895
- import { isAbsolute as isAbsolute3, join as join7, relative as relative2, resolve as resolve4, sep as sep2 } from "node:path";
36479
+ import { isAbsolute as isAbsolute3, join as join8, relative as relative2, resolve as resolve4, sep as sep2 } from "node:path";
35896
36480
  class PromptAttachmentError extends Error {
35897
36481
  code;
35898
36482
  name = "PromptAttachmentError";
@@ -35995,7 +36579,7 @@ function isPathWithin(root, candidate) {
35995
36579
  async function assertNoSymlinkComponents(root, targetPath) {
35996
36580
  let currentPath = root;
35997
36581
  for (const segment of relative2(root, targetPath).split(sep2).filter(Boolean)) {
35998
- currentPath = join7(currentPath, segment);
36582
+ currentPath = join8(currentPath, segment);
35999
36583
  const stats = await lstat2(currentPath).catch((error) => {
36000
36584
  throw attachmentErrorForFsFailure(error);
36001
36585
  });
@@ -36475,7 +37059,8 @@ function configureLoggerFromEnvironment(env, options = {}) {
36475
37059
  configureLogger({
36476
37060
  ...levels.level ? { level: levels.level } : {},
36477
37061
  areaLevels: levels.areaLevels,
36478
- format
37062
+ format,
37063
+ relayEssential: options.relayToSupervisor === true
36479
37064
  });
36480
37065
  const log = createLogger("logging");
36481
37066
  if (levels.invalid.length > 0) {
@@ -36579,7 +37164,7 @@ function humanPromptObservation(messages, tasks) {
36579
37164
  }
36580
37165
 
36581
37166
  // ../../bridges/pi-bridge/src/http.ts
36582
- import { createHash as createHash6, randomBytes as randomBytes7 } from "node:crypto";
37167
+ import { createHash as createHash7, randomBytes as randomBytes7 } from "node:crypto";
36583
37168
  import { pathToFileURL } from "node:url";
36584
37169
  import { gzip } from "node:zlib";
36585
37170
 
@@ -36636,7 +37221,7 @@ var DEFAULT_MCP_MANAGEMENT_ROLLOUT = Object.freeze({
36636
37221
 
36637
37222
  // ../protocol/src/node/bridge-transcript-summary.ts
36638
37223
  import { Buffer as Buffer5 } from "node:buffer";
36639
- import { createHash as createHash5 } from "node:crypto";
37224
+ import { createHash as createHash6 } from "node:crypto";
36640
37225
 
36641
37226
  // ../protocol/src/node/progressive-transcript.ts
36642
37227
  var BRIDGE_TRANSCRIPT_MAX_MESSAGES = 100;
@@ -36802,7 +37387,7 @@ function digestPayload(payload) {
36802
37387
  const serialized = JSON.stringify(payload);
36803
37388
  return {
36804
37389
  bytes: Buffer5.byteLength(serialized),
36805
- digest: createHash5("sha256").update(serialized).digest("base64url").slice(0, 32)
37390
+ digest: createHash6("sha256").update(serialized).digest("base64url").slice(0, 32)
36806
37391
  };
36807
37392
  }
36808
37393
  function topLevelKey(part, index) {
@@ -37523,7 +38108,7 @@ async function answerSessionActivityBatch(body, read, options = {}) {
37523
38108
  }
37524
38109
 
37525
38110
  // ../../bridges/pi-bridge/src/http.ts
37526
- var log4 = createLogger("bridge.pi");
38111
+ var log6 = createLogger("bridge.pi");
37527
38112
 
37528
38113
  class HttpError extends Error {
37529
38114
  status;
@@ -37595,6 +38180,12 @@ async function route(request, response, clientSignal) {
37595
38180
  } catch (error) {
37596
38181
  if (error instanceof HttpError)
37597
38182
  return json(response, error.status, { error: error.message });
38183
+ if (error instanceof PolicyWideningRefusedError) {
38184
+ log6.warn("session.policy-widening-refused", { widened: error.widened.join(",") });
38185
+ return json(response, 403, error.refusal());
38186
+ }
38187
+ if (error instanceof SessionBusyError)
38188
+ return json(response, 409, { error: error.message });
37598
38189
  if (error instanceof CredentialError) {
37599
38190
  return json(response, 401, { error: error.message, kind: "authentication-required" });
37600
38191
  }
@@ -37607,7 +38198,7 @@ async function route(request, response, clientSignal) {
37607
38198
  if (error instanceof PromptAttachmentError) {
37608
38199
  return json(response, 400, { error: error.message });
37609
38200
  }
37610
- log4.error("http.route-failed");
38201
+ log6.error("http.route-failed");
37611
38202
  return json(response, 500, { error: "Internal bridge error" });
37612
38203
  }
37613
38204
  }
@@ -37657,7 +38248,15 @@ async function routeGlobal(request, response, url) {
37657
38248
  return true;
37658
38249
  }
37659
38250
  if (url.pathname === "/session/list" && request.method === "GET") {
37660
- const listed = await listResumableSessions();
38251
+ let listed;
38252
+ try {
38253
+ listed = await listResumableSessions();
38254
+ } catch (error) {
38255
+ if (!(error instanceof TimeoutError))
38256
+ throw error;
38257
+ json(response, 504, { error: error.message });
38258
+ return true;
38259
+ }
37661
38260
  json(response, 200, {
37662
38261
  sessions: listed.map((entry) => ({
37663
38262
  id: entry.sessionId,
@@ -37701,8 +38300,9 @@ async function routeGlobal(request, response, url) {
37701
38300
  if (!sessionFile)
37702
38301
  throw new HttpError(400, "sessionId is required");
37703
38302
  const state = await resumeSession(sessionFile, parseComposerPatch(body), isNativeAgentExecutionPolicy(body.policy) ? body.policy : undefined).catch((error) => {
37704
- if (error instanceof SessionClosingError)
38303
+ if (error instanceof SessionClosingError || error instanceof SessionBusyError || error instanceof PolicyWideningRefusedError) {
37705
38304
  throw error;
38305
+ }
37706
38306
  throw new HttpError(400, errorText(error));
37707
38307
  });
37708
38308
  storeAgentMcp(state, body.agentMcp);
@@ -37999,7 +38599,7 @@ async function handleSteer(request, response, state) {
37999
38599
  throw new HttpError(400, "requestId is required");
38000
38600
  if (!expectedRunId)
38001
38601
  throw new HttpError(400, "expectedRunId is required");
38002
- const inputDigest = createHash6("sha256").update(text).digest("hex");
38602
+ const inputDigest = createHash7("sha256").update(text).digest("hex");
38003
38603
  const previous = state.steerJournal.get(requestId);
38004
38604
  if (previous) {
38005
38605
  if (previous.inputDigest !== inputDigest || previous.expectedRunId !== expectedRunId) {
@@ -38133,6 +38733,9 @@ async function handlePrompt(request, response, state, clientSignal) {
38133
38733
  }
38134
38734
  async function handleAdmittedPrompt(request, response, state, clientSignal, admission) {
38135
38735
  const body = await readJson(request);
38736
+ if (isNativeAgentExecutionPolicy(body.policy)) {
38737
+ assertExecutionPolicyNotWidened(liveExecutionPolicy(state), resolvePiExecutionPolicy(body.policy));
38738
+ }
38136
38739
  const commandFields = readBridgePromptCommandFields(body);
38137
38740
  if (!commandFields.ok)
38138
38741
  throw new HttpError(400, commandFields.error);
@@ -38171,6 +38774,7 @@ async function handleAdmittedPrompt(request, response, state, clientSignal, admi
38171
38774
  }
38172
38775
  return json(response, 202, { accepted: true, duplicate: true });
38173
38776
  }
38777
+ state.policyPending = false;
38174
38778
  let selection;
38175
38779
  if (command) {
38176
38780
  const resolved = resolveCommandSelection(state, command);
@@ -38360,6 +38964,12 @@ async function handleAdmittedPrompt(request, response, state, clientSignal, admi
38360
38964
  ...requestId ? { requestId } : {}
38361
38965
  });
38362
38966
  }
38967
+ if (error instanceof PromptRefusedError && !cancelRequestedFor(state, claim)) {
38968
+ log6.warn("turn.refused", {
38969
+ sessionId: state.id,
38970
+ error: formatLogError(error, { message: false })
38971
+ });
38972
+ }
38363
38973
  state.messages.splice(messageStart);
38364
38974
  state.uncheckedTranscriptBytes = uncheckedBeforePrompt;
38365
38975
  state.status = "error";
@@ -38615,7 +39225,7 @@ function startParentWatchdog(options) {
38615
39225
  }
38616
39226
 
38617
39227
  // ../protocol/src/bridge-lifecycle.ts
38618
- var log5 = createLogger("bridge.lifecycle");
39228
+ var log7 = createLogger("bridge.lifecycle");
38619
39229
  var TERMINATION_SIGNALS = ["SIGTERM", "SIGINT"];
38620
39230
  function errorKind(error) {
38621
39231
  if (error instanceof Error)
@@ -38669,7 +39279,7 @@ class BridgeLifecycle {
38669
39279
  }
38670
39280
  requestExit() {
38671
39281
  this.#exit ??= this.shutdown().then(() => this.#options.exit(0), (error) => {
38672
- log5.error("shutdown.failed", {
39282
+ log7.error("shutdown.failed", {
38673
39283
  bridge: this.#options.label,
38674
39284
  errorClass: errorKind(error)
38675
39285
  });
@@ -38686,7 +39296,7 @@ class BridgeLifecycle {
38686
39296
  try {
38687
39297
  idleSweep.run();
38688
39298
  } catch (error) {
38689
- log5.warn("idle-sweep.failed", {
39299
+ log7.warn("idle-sweep.failed", {
38690
39300
  bridge: this.#options.label,
38691
39301
  errorClass: errorKind(error)
38692
39302
  });
@@ -38945,6 +39555,9 @@ function installFatalRejectionGuard(options) {
38945
39555
  try {
38946
39556
  warn(`${options.label} Unhandled promise rejection (continuing): ${describe(reason)}`);
38947
39557
  } catch {}
39558
+ try {
39559
+ options.onRejection?.(reason);
39560
+ } catch {}
38948
39561
  };
38949
39562
  target.on("unhandledRejection", handler);
38950
39563
  return () => {
@@ -38952,9 +39565,18 @@ function installFatalRejectionGuard(options) {
38952
39565
  };
38953
39566
  }
38954
39567
 
39568
+ // ../protocol/src/node/process-failure-log.ts
39569
+ var log8 = createLogger("process");
39570
+ function logUnhandledRejection(reason) {
39571
+ log8.throttled("error", "rejection.unhandled", {
39572
+ error: reason,
39573
+ fields: () => ({ error: formatLogError(reason, { message: false }) })
39574
+ });
39575
+ }
39576
+
38955
39577
  // ../../bridges/pi-bridge/src/index.ts
38956
39578
  configureBridgeLogger();
38957
- installFatalRejectionGuard({ label: "[pi-bridge]" });
39579
+ installFatalRejectionGuard({ label: "[pi-bridge]", onRejection: logUnhandledRejection });
38958
39580
  if (process.env.PI_BRIDGE_LIBRARY_ONLY !== "1") {
38959
39581
  await start();
38960
39582
  }
@@ -38996,9 +39618,11 @@ export {
38996
39618
  PromptAttachmentError,
38997
39619
  PromptRefusedError,
38998
39620
  PromptStartupTimeoutError,
39621
+ SESSION_LIST_TIMEOUT_MESSAGE,
38999
39622
  STARTUP_TIMEOUT_MS,
39000
39623
  STREAM_BOUND_INTERVAL_BYTES,
39001
39624
  STRUCTURED_PROMPT_INSTRUCTION_PREFIX,
39625
+ SessionBusyError,
39002
39626
  SessionClosingError,
39003
39627
  TODO_STATUSES,
39004
39628
  TimeoutError,
@@ -39047,6 +39671,7 @@ export {
39047
39671
  dispatchPrompt,
39048
39672
  drainPersistence,
39049
39673
  emptyComposer,
39674
+ encodeStateWithinBudget,
39050
39675
  ensureSession,
39051
39676
  errorText,
39052
39677
  expireComposerHydrationRetryForTests,
@@ -39065,6 +39690,7 @@ export {
39065
39690
  json,
39066
39691
  listModels,
39067
39692
  listResumableSessions,
39693
+ liveExecutionPolicy,
39068
39694
  loadPersistedState,
39069
39695
  markSessionClosed,
39070
39696
  markSessionDefault,
@@ -39150,6 +39776,7 @@ export {
39150
39776
  setPendingRemoval,
39151
39777
  setPersistWriteGateForTests,
39152
39778
  setPromptJournal,
39779
+ setSessionListTimeoutForTests,
39153
39780
  setSessionReadOnly,
39154
39781
  setSessionTitle,
39155
39782
  setStartupTimeoutForTests,