orkestrator 2.36.1 → 2.36.3-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.
@@ -2544,6 +2544,7 @@ var PROJECTION_FIELD_SET = new Set([
2544
2544
  "asyncQuestionResponses",
2545
2545
  "contextUsage",
2546
2546
  "goal",
2547
+ "suborks",
2547
2548
  "rateLimits",
2548
2549
  "runtime",
2549
2550
  "runtimeHealthAuthoritative",
@@ -2569,6 +2570,7 @@ var OPTIONAL_PROJECTION_FIELD_SET = new Set([
2569
2570
  "asyncQuestionResponses",
2570
2571
  "contextUsage",
2571
2572
  "goal",
2573
+ "suborks",
2572
2574
  "rateLimits",
2573
2575
  "runtime",
2574
2576
  "runtimeHealthAuthoritative",
@@ -4020,6 +4022,7 @@ var COORDINATOR_CONTROL_TOOL_NAMES = Object.freeze([
4020
4022
  "address_multi_review",
4021
4023
  "adopt_workflow",
4022
4024
  "answer_worker_question",
4025
+ "ask_agents",
4023
4026
  "cancel_build_pipeline",
4024
4027
  "cancel_graph_run",
4025
4028
  "cancel_multi_review",
@@ -4082,6 +4085,7 @@ var COORDINATOR_CONTROL_TOOL_NAMES = Object.freeze([
4082
4085
  "request_project_on_node",
4083
4086
  "request_root_changes",
4084
4087
  "resolve_conflicts",
4088
+ "restart_build_pipeline_step",
4085
4089
  "resume_build_pipeline",
4086
4090
  "resume_schedule",
4087
4091
  "run_worker_command",
@@ -4109,6 +4113,8 @@ var COORDINATOR_PROJECT_HOME_MESSAGE_WINDOW_MS = 3 * 60 * 60000;
4109
4113
  var AGENT_MAIL_MAX_BODY_BYTES = 32 * 1024;
4110
4114
  var AGENT_MAIL_MAX_STORE_BYTES = 32 * 1024 * 1024;
4111
4115
  var AGENT_MAIL_DEFAULT_RETENTION_DAYS = 14;
4116
+ var AGENT_MAIL_MAX_ATTACHMENT_BYTES = 8 * 1024 * 1024;
4117
+ var AGENT_MAIL_MAX_TOTAL_ATTACHMENT_BYTES = 32 * 1024 * 1024;
4112
4118
  var AGENT_MAIL_DEFAULT_AUTONOMOUS_WAKE_BUDGET = 16;
4113
4119
  var AGENT_MAIL_DEFAULT_HOURLY_WAKE_LIMIT = 40;
4114
4120
  var AGENT_MAIL_TOOL_NAMES = Object.freeze([
@@ -4155,6 +4161,24 @@ function agentMailCapabilities(tabType, agent, locked = true) {
4155
4161
  }
4156
4162
  var NATIVE_AGENT_MAIL_CAPABILITIES = Object.freeze(Object.fromEntries(AGENT_PLATFORMS.map((agent) => [agent, agentMailCapabilities("agent-native", agent)])));
4157
4163
 
4164
+ // ../protocol/src/suborks.ts
4165
+ var SUBORK_TOOL_NAME = "ask_agents";
4166
+ var AGENT_SUBORK_TOOL_NAMES = Object.freeze([SUBORK_TOOL_NAME]);
4167
+ var SUBORK_LIMITS = Object.freeze({
4168
+ targetsPerCall: 4,
4169
+ activePerSession: 8,
4170
+ totalPerSession: 64,
4171
+ retainedBatchesPerSession: 16,
4172
+ promptMaxBytes: 64 * 1024,
4173
+ nameMaxChars: 80,
4174
+ targetTextMaxChars: 200,
4175
+ storedAnswerMaxBytes: 64 * 1024,
4176
+ deliveredAnswersMaxBytes: AGENT_MAIL_MAX_BODY_BYTES - 2 * 1024,
4177
+ lineMaxChars: 240,
4178
+ errorMaxChars: 1024,
4179
+ deadlineMs: 45 * 60000
4180
+ });
4181
+
4158
4182
  // ../protocol/src/secret-redaction.ts
4159
4183
  var TEXT_RULES = [
4160
4184
  {
@@ -4217,6 +4241,7 @@ var WORKFLOW_RESULT_KINDS = [
4217
4241
  "fix-result",
4218
4242
  "verification-result",
4219
4243
  "pr-result",
4244
+ "subork-answer",
4220
4245
  "graph-output",
4221
4246
  "graph-template"
4222
4247
  ];
@@ -4232,7 +4257,8 @@ var WORKFLOW_RESULT_TOOL_NAMES = {
4232
4257
  "verification-result": "submit_verification_result",
4233
4258
  "pr-result": "submit_pr_result",
4234
4259
  "graph-output": "submit_graph_output",
4235
- "graph-template": "submit_graph_template"
4260
+ "graph-template": "submit_graph_template",
4261
+ "subork-answer": "submit_subork_answer"
4236
4262
  };
4237
4263
  var WORKFLOW_RESULT_VALIDATION_TOOL_NAME = "validate_workflow_result";
4238
4264
  var REPORT_FINDING_TOOL_NAME = "report_finding";
@@ -28231,7 +28257,7 @@ function publicPiMcpServers(state) {
28231
28257
  return runtimes.get(state)?.inventory ?? [];
28232
28258
  }
28233
28259
  function isOrkestratorMailTool(state, toolName) {
28234
- return runtimes.get(state)?.orkestratorToolNames.has(toolName) === true && (AGENT_MAIL_TOOL_NAMES.includes(toolName) || ARTIFACT_TOOL_NAMES.includes(toolName) || AGENT_GOAL_TOOL_NAMES.includes(toolName));
28260
+ return runtimes.get(state)?.orkestratorToolNames.has(toolName) === true && (AGENT_MAIL_TOOL_NAMES.includes(toolName) || ARTIFACT_TOOL_NAMES.includes(toolName) || AGENT_GOAL_TOOL_NAMES.includes(toolName) || AGENT_SUBORK_TOOL_NAMES.includes(toolName));
28235
28261
  }
28236
28262
  function isOwnWorkflowResultCall(state, toolName, input) {
28237
28263
  const turn = state.workflowResultTurn;
@@ -28907,6 +28933,16 @@ function logErrorKind(error) {
28907
28933
  }
28908
28934
 
28909
28935
  // ../protocol/src/log-vocabulary/define.ts
28936
+ var ESSENTIAL_ERROR_FIELDS = {
28937
+ "error.name": "label",
28938
+ "error.code": "label",
28939
+ "error.errno": "number",
28940
+ "error.syscall": "label",
28941
+ "error.exitCode": "number",
28942
+ "error.signal": "label",
28943
+ "error.outputOmitted": "boolean",
28944
+ "error.errorCount": "number"
28945
+ };
28910
28946
  var THROTTLE_LOG_EVENTS = {
28911
28947
  "throttle.suppressed": "Repeats of the throttled `site` were counted over a window, not written.",
28912
28948
  "throttle.recovered": "The throttled `site` succeeded again, so its fault has cleared.",
@@ -28956,7 +28992,11 @@ var BACKEND_LOG_AREAS = defineLogAreas({
28956
28992
  backend: {
28957
28993
  description: "The backend process: startup, background notices and shutdown.",
28958
28994
  events: {
28959
- starting: "The backend process is starting.",
28995
+ starting: {
28996
+ description: "The backend process is starting.",
28997
+ essential: true,
28998
+ fields: { version: "label" }
28999
+ },
28960
29000
  "ssh-socket.resolved": "An SSH agent socket was found.",
28961
29001
  "ssh-socket.missing": "No usable SSH agent socket was found.",
28962
29002
  "standalone-updater.mismatch": "--standalone-updater does not match --data-dir, so self-update is off.",
@@ -28971,8 +29011,16 @@ var BACKEND_LOG_AREAS = defineLogAreas({
28971
29011
  "notice.failed": "A background notice after a turn or prompt failed; `step` says which.",
28972
29012
  "artifacts.live-unavailable": "Live interactive artifacts are unavailable.",
28973
29013
  "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`.",
29014
+ "shutdown.signal-received": {
29015
+ description: "A signal started shutdown, which tells a clean quit from the backend being killed.",
29016
+ essential: true,
29017
+ fields: { signal: "label" }
29018
+ },
29019
+ "shutdown.finished": {
29020
+ description: "Shutdown finished, and the process exits with `code`.",
29021
+ essential: true,
29022
+ fields: { code: "number" }
29023
+ },
28976
29024
  "port-policy.second-backend": "Another backend serves the default data directory, so this one avoids its ports.",
28977
29025
  "port-policy.serve-on-free-port": "--tailscale-serve is on a free gateway port; pass --port with --strict-gateway-port to keep one."
28978
29026
  }
@@ -29015,7 +29063,10 @@ var BRIDGE_LOG_AREAS = defineLogAreas({
29015
29063
  "evidence.record-failed": "Change evidence could not be recorded; the read loop carries on.",
29016
29064
  "evidence.shell-record-failed": "A shell observation could not be recorded.",
29017
29065
  "evidence.turn-record-failed": "Turn change evidence could not be recorded.",
29066
+ "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.",
29067
+ "http.route-failed": "An HTTP route answered 500; its error message is not logged because it can hold content.",
29018
29068
  "server.listening": "The HTTP server is listening.",
29069
+ "session.policy-widening-refused": "A request tried to widen a live session's execution policy and was refused; widened names the axes.",
29019
29070
  "state.composer-reset": "A saved composer state was malformed and was reset.",
29020
29071
  "state.discarded": "Saved bridge state could not be used and was discarded.",
29021
29072
  "state.persist-failed": "Saving bridge state failed; a later write retries.",
@@ -29069,7 +29120,7 @@ var BRIDGE_LOG_AREAS = defineLogAreas({
29069
29120
  "session.created": "A session was created or recovered.",
29070
29121
  "session.delete-failed": "Deleting a session failed.",
29071
29122
  "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.",
29123
+ "session.policy-widening-refused": "A request tried to widen a live session's execution policy and was refused; widened names the axes.",
29073
29124
  "session.rename-failed": "Renaming a session failed.",
29074
29125
  "session.resolve-failed": "A session could not be found or loaded for a request; action names the request.",
29075
29126
  "session.rewind-failed": "Rewinding session files failed.",
@@ -29103,6 +29154,7 @@ var BRIDGE_LOG_AREAS = defineLogAreas({
29103
29154
  "app-server.exited": "app-server exited unexpectedly; the code and signal say how.",
29104
29155
  "app-server.invariant-violation": "app-server asked for something its configuration forbids.",
29105
29156
  "app-server.protocol-violation": "app-server wrote a line that is not valid protocol; it was ignored.",
29157
+ "app-server.overflow-restart-failed": "Replacing the child after a notification queue overflow failed; the next request tries again.",
29106
29158
  "app-server.recording": "Notification recording is on; recordings hold content.",
29107
29159
  "app-server.stale-reaped": "A stale app-server left by an earlier bridge was stopped.",
29108
29160
  "app-server.stderr": "Metadata of an app-server stderr line, never its content.",
@@ -29133,6 +29185,7 @@ var BRIDGE_LOG_AREAS = defineLogAreas({
29133
29185
  "ordered-events.publish-failed": "Publishing an ordered event failed; clients are told to rehydrate.",
29134
29186
  "ordered-events.reconcile-failed": "Reconciling ordered events failed.",
29135
29187
  "parent.gone": "The backend that launched this bridge has gone; stopping turns and shutting down.",
29188
+ "queue.overflow": "The notification queue passed a bound and dropped its backlog.",
29136
29189
  "queue.task-failed": "A task on a per-thread queue failed.",
29137
29190
  "raw-log.write-failed": "Appending to the raw Codex log failed.",
29138
29191
  "recorder.notice": "The notification recorder needs attention: it is on, or was asked for without its confirmation.",
@@ -29146,6 +29199,7 @@ var BRIDGE_LOG_AREAS = defineLogAreas({
29146
29199
  "server-request.flush-timeout": "An answer to a server request did not flush in time.",
29147
29200
  "server-request.handoff-failed": "Handing a server request to the router threw.",
29148
29201
  "session.config-apply-failed": "Applying session configuration failed; the route answers unavailable.",
29202
+ "session.policy-widening-refused": "A request tried to widen a live session's execution policy and was refused; widened names the axes.",
29149
29203
  "sse.closed": "An event stream was closed by the bridge; the client reconnects and replays.",
29150
29204
  "sse.keepalive-failed": "An event stream keepalive failed.",
29151
29205
  "sse.observer-failed": "An event stream observer failed; it reconnects.",
@@ -29174,19 +29228,39 @@ var BRIDGE_LOG_AREAS = defineLogAreas({
29174
29228
  events: {
29175
29229
  "agent.archive-failed": "Archiving or unarchiving an agent failed.",
29176
29230
  "http.route-failed": "An HTTP route failed unexpectedly; its error is not logged because it can hold content.",
29231
+ "session.policy-widening-refused": "A request tried to widen a live session's execution policy and was refused; widened names the axes.",
29177
29232
  "startup.closes-failed": "Finishing closes a previous process left behind failed at startup.",
29178
29233
  "startup.closes-incomplete": "Some closes a previous process left behind did not finish at startup; a retried close finishes them.",
29179
29234
  "state.publication-failing": "Saving bridge state is failing; new prompts and steers are refused until it recovers.",
29180
29235
  "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."
29236
+ "state.transcripts-shortened": "The state file reached its limit, so some sessions were saved with a shortened transcript copy.",
29237
+ "session.resume-fell-back": {
29238
+ description: "A saved conversation could not be resumed, so a new one started; its error message is not logged because it can hold content.",
29239
+ essential: true,
29240
+ fields: ESSENTIAL_ERROR_FIELDS
29241
+ },
29242
+ "turn.failed": "A turn failed; its error message is not logged because it can hold content. A cancelled turn is not a failure.",
29243
+ "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.",
29244
+ "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.",
29245
+ "turn.timed-out": "A turn outlived its time budget, so its run was asked to cancel; `turn.failed` follows if it never stops."
29182
29246
  }
29183
29247
  },
29184
29248
  "bridge.pi": {
29185
29249
  description: "The Pi bridge: its routes, sessions and saved state.",
29186
29250
  events: {
29187
29251
  "http.route-failed": "An HTTP route failed unexpectedly; its error is not logged because it can hold content.",
29252
+ "session.policy-widening-refused": "A request tried to widen a live session's execution policy and was refused; widened names the axes.",
29253
+ "session-list.failed": "Reading the resumable sessions failed, so none were offered; its error message is not logged because it can hold content.",
29188
29254
  "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."
29255
+ "state.transcripts-shed": "The state file was over budget, so some sessions were saved without their transcript.",
29256
+ "session.resume-fell-back": {
29257
+ description: "A saved conversation could not be reopened, so a new one started; its error message is not logged because it can hold content.",
29258
+ essential: true,
29259
+ fields: ESSENTIAL_ERROR_FIELDS
29260
+ },
29261
+ "turn.failed": "A turn failed; its error message is not logged because it can hold content. A cancelled turn is not a failure.",
29262
+ "turn.refused": "Pi refused a prompt before starting a run, so nothing ran; its error message is not logged because it can hold content.",
29263
+ "turn.startup-timed-out": "Pi did not start a turn within its startup deadline, so the prompt was abandoned."
29190
29264
  }
29191
29265
  }
29192
29266
  });
@@ -29197,14 +29271,31 @@ var DESKTOP_LOG_AREAS = defineLogAreas({
29197
29271
  description: "The Electron main process: startup, windows, quit and the Local backend's life.",
29198
29272
  events: {
29199
29273
  "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.",
29274
+ "backend.exited": {
29275
+ description: "The Local backend exited unexpectedly; Local work is unavailable. `error.exitCode` and `error.signal` say how.",
29276
+ essential: true,
29277
+ fields: ESSENTIAL_ERROR_FIELDS
29278
+ },
29279
+ "backend.exited-recovering": {
29280
+ description: "The Local backend exited just after a remote update; relaunching unattended. `error.exitCode` and `error.signal` say how.",
29281
+ essential: true,
29282
+ fields: ESSENTIAL_ERROR_FIELDS
29283
+ },
29202
29284
  "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.",
29285
+ "backend.start-failed": {
29286
+ description: "The Local backend did not start; continuing with remote machines.",
29287
+ essential: true,
29288
+ fields: ESSENTIAL_ERROR_FIELDS
29289
+ },
29204
29290
  "clipboard.write-failed": "Writing text to the system clipboard failed.",
29205
29291
  "dev-mode.ignored-packaged": "A packaged app was launched with ELECTRON_DEV=1 and ignored it; it loads its bundled renderer.",
29206
29292
  "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.",
29293
+ "main-thread.stalled": {
29294
+ description: "A timer fired late, so windows, IPC and the stdout reader waited.",
29295
+ essential: true,
29296
+ minLevel: "error",
29297
+ fields: { lagMs: "number", intervalMs: "number" }
29298
+ },
29208
29299
  "quit.stopping-backend": "The app is quitting and has asked the Local backend to stop.",
29209
29300
  "relaunch.schedule-failed": "The AppImage relaunch waiter failed; using Electron's relauncher.",
29210
29301
  "relaunch.service-register-failed": "The AppImage relaunch service was refused; using a detached waiter.",
@@ -29215,7 +29306,11 @@ var DESKTOP_LOG_AREAS = defineLogAreas({
29215
29306
  "saved-machines.attach-failed": "Saved machines were not imported into the command node yet.",
29216
29307
  "saved-machines.attached": "Saved machines were imported into the local command node.",
29217
29308
  "startup.failed": "The application failed to start.",
29218
- "uncaught-exception": "The main process hit an uncaught exception.",
29309
+ "uncaught-exception": {
29310
+ description: "The main process hit an uncaught exception.",
29311
+ essential: true,
29312
+ fields: ESSENTIAL_ERROR_FIELDS
29313
+ },
29219
29314
  "uncaught-exception.dialog-failed": "The uncaught exception sheet could not be shown.",
29220
29315
  "window.create-failed": "A menu-driven new window could not be created.",
29221
29316
  "window.recreate-failed": "The main window could not be recreated on activation.",
@@ -29238,6 +29333,12 @@ var DESKTOP_LOG_AREAS = defineLogAreas({
29238
29333
  "unhandled-rejection": "An unhandled rejection occurred while the renderer was starting."
29239
29334
  }
29240
29335
  },
29336
+ "desktop.permissions": {
29337
+ description: "Permission requests refused on the renderer and workspace realm sessions.",
29338
+ events: {
29339
+ denied: "A renderer asked for a permission the policy does not grant."
29340
+ }
29341
+ },
29241
29342
  "desktop.dialog": {
29242
29343
  description: "Native dialogs, whose modal loops hold the main thread while they are open.",
29243
29344
  events: {
@@ -29320,6 +29421,7 @@ var ENVIRONMENT_LOG_AREAS = defineLogAreas({
29320
29421
  "status.docker-error": "A transient Docker error stopped a status read, so the stored status is kept.",
29321
29422
  "setup.clear-launch-failed": "A pending agent launch could not be cleared after setup failed.",
29322
29423
  "setup.record-failure-failed": "A setup failure before its first attempt could not be recorded.",
29424
+ "setup.tab-publish-failed": "The setup terminal's tab could not be published.",
29323
29425
  "lifecycle.failed": "Starting, rebuilding or recreating an environment failed; `operation` says which.",
29324
29426
  "tab-teardown.pending": "A tab's teardown failed and stays pending; the reconcile sweep retries.",
29325
29427
  "tab-reconcile.skipped": "Orphaned tab reconciliation was skipped because pane layouts are unreadable.",
@@ -29356,6 +29458,8 @@ var GATEWAY_LOG_AREAS = defineLogAreas({
29356
29458
  "loopback.unavailable": "The loopback client listener could not start.",
29357
29459
  "auth-token.stored": "The gateway token's file was written. The path only, never the token.",
29358
29460
  "auth-token.persist-failed": "The gateway token could not be saved.",
29461
+ "auth-guess.throttled": "A listener saw enough different wrong tokens that it now pauses new ones. Never the values.",
29462
+ "host.refused": "A request named a host this gateway does not answer to. Logged once per name, up to a limit.",
29359
29463
  "port.fallback": "The preferred port was taken, so a nearby one is used.",
29360
29464
  "port.fallback-distant": "The preferred port and those nearby were taken, so another is used.",
29361
29465
  "request.failed": "A gateway request failed. Throttled: repeats are counted, not written.",
@@ -29399,6 +29503,22 @@ var LOCAL_SERVER_LOG_AREAS = defineLogAreas({
29399
29503
  "bridge-runtime.installed": "A bridge runtime finished installing.",
29400
29504
  "opencode.database-lost-retrying": "OpenCode lost its shared database at startup, so it is retried.",
29401
29505
  "server.stopping": "A local server is being stopped, for the fixed `reason` given.",
29506
+ "bridge.started": {
29507
+ description: "A local bridge process was spawned; `key` names its kind and environment.",
29508
+ essential: true,
29509
+ fields: { key: "label", pid: "number" }
29510
+ },
29511
+ "bridge.exited": {
29512
+ 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.",
29513
+ essential: true,
29514
+ fields: {
29515
+ key: "label",
29516
+ pid: "number",
29517
+ code: "number",
29518
+ signal: "label",
29519
+ requested: "boolean"
29520
+ }
29521
+ },
29402
29522
  "reaper.tmux-list-failed": "Orphaned claude-tmux sessions could not be listed.",
29403
29523
  "reaper.tmux-kill-failed": "An orphaned tmux session could not be killed.",
29404
29524
  "reaper.tmux-reaped": "Orphaned claude-tmux sessions of a deleted environment were killed.",
@@ -29432,13 +29552,29 @@ var LOGGING_LOG_AREAS = defineLogAreas({
29432
29552
  "capture.started": "Saving logs to disk began for this process.",
29433
29553
  "capture.stopped": "Saving logs to disk stopped for this process.",
29434
29554
  "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.",
29555
+ "entries.dropped": {
29556
+ 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.",
29557
+ essential: true,
29558
+ fields: { entries: "number", bytes: "number", reason: "label" }
29559
+ },
29560
+ "essential.started": {
29561
+ description: "This process began writing the essential log. One with no `essential.stopped` before it means the last writer died.",
29562
+ essential: true,
29563
+ fields: { owner: "label" }
29564
+ },
29565
+ "essential.stopped": {
29566
+ description: "This process stopped writing the essential log, in an orderly exit.",
29567
+ essential: true,
29568
+ fields: { owner: "label" }
29569
+ },
29570
+ "essential.write-failed": "Writing the essential log failed. Its entries are counted, and a marker reports them at the next write that works.",
29436
29571
  "policy.changed": "The logging settings changed: saving, retention and levels, with no content.",
29437
29572
  "policy.bridge-predates-route": "A running bridge has no logging settings route; it applies them at its next start.",
29438
29573
  "policy.push-failed": "A running bridge did not take the logging settings after retries; its next start resends them.",
29439
29574
  "prune.failed": "Removing expired log files failed; the next sweep retries.",
29440
29575
  "write.failed": "Appending to the log file failed.",
29441
- "unknown-area": "Code outside the type checker asked for an area that is not listed."
29576
+ "unknown-area": "Code outside the type checker asked for an area that is not listed.",
29577
+ ...THROTTLE_LOG_EVENTS
29442
29578
  }
29443
29579
  }
29444
29580
  });
@@ -29493,6 +29629,7 @@ var NATIVE_AGENT_LOG_AREAS = defineLogAreas({
29493
29629
  "turn-recovery.failed": "Recovering an incomplete turn failed.",
29494
29630
  "turn-recovery.exhausted": "A turn failed again after automatic recovery and is left for the user.",
29495
29631
  "turn-recovery.retrying": "An incomplete or provider-failed turn is being retried automatically.",
29632
+ "usage-limit.notice-failed": "A usage-limit stop's outcome could not be read for its notice.",
29496
29633
  "usage-limit.resend-failed": "Resending after a usage limit failed. An unknown send stays in the journal.",
29497
29634
  "title.strategy-failed": "A session title strategy failed, so the next is tried. Content-free: the error can quote the prompt.",
29498
29635
  ...THROTTLE_LOG_EVENTS
@@ -29509,6 +29646,15 @@ var NATIVE_AGENT_LOG_AREAS = defineLogAreas({
29509
29646
  "recover.failed": "Goals could not be recovered at startup."
29510
29647
  }
29511
29648
  },
29649
+ "native-agent.subork": {
29650
+ description: "Suborks: the ask_agents calls a native agent makes. Content-free.",
29651
+ events: {
29652
+ "pass.failed": "A pass over a call failed, so a later pass retries. Counts only.",
29653
+ "delivery.failed": "A call's answers could not be placed in the caller's mailbox yet. Error class only.",
29654
+ "retention.failed": "An old call could not be removed.",
29655
+ "sweep.failed": "A running call's caller could not be checked; the next sweep looks again."
29656
+ }
29657
+ },
29512
29658
  "native-agent.opencode": {
29513
29659
  description: "The OpenCode provider: its request monitor, retries and agent tools.",
29514
29660
  events: {
@@ -29563,7 +29709,28 @@ var RUNTIME_LOG_AREAS = defineLogAreas({
29563
29709
  "event-loop": {
29564
29710
  description: "This process's event loop. A stall of 10 seconds or more is written at error, so no level hides it.",
29565
29711
  events: {
29566
- stalled: "A timer fired late, so every request in that window waited."
29712
+ stalled: {
29713
+ description: "A timer fired late, so every request in that window waited.",
29714
+ essential: true,
29715
+ minLevel: "error",
29716
+ fields: { lagMs: "number", intervalMs: "number" }
29717
+ }
29718
+ }
29719
+ },
29720
+ process: {
29721
+ description: "Failures of a whole process that nothing in it handled.",
29722
+ events: {
29723
+ "rejection.unhandled": {
29724
+ description: "A promise rejection reached the fatal rejection guard, which keeps the process running.",
29725
+ essential: true,
29726
+ fields: { kind: "label", ...ESSENTIAL_ERROR_FIELDS }
29727
+ },
29728
+ "uncaught-exception": {
29729
+ 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.",
29730
+ essential: true,
29731
+ fields: { origin: "label", ...ESSENTIAL_ERROR_FIELDS }
29732
+ },
29733
+ ...THROTTLE_LOG_EVENTS
29567
29734
  }
29568
29735
  }
29569
29736
  });
@@ -29801,21 +29968,43 @@ var STORAGE_LOG_AREAS = defineLogAreas({
29801
29968
  description: "The SQLite-backed stores, their snapshots and imports from older formats.",
29802
29969
  events: {
29803
29970
  "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.",
29971
+ "migration.failed": {
29972
+ 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.",
29973
+ essential: true,
29974
+ fields: {
29975
+ fromVersion: "number",
29976
+ toVersion: "number",
29977
+ step: "label",
29978
+ ...ESSENTIAL_ERROR_FIELDS
29979
+ }
29980
+ },
29981
+ "snapshot.integrity-failed": {
29982
+ description: "A database snapshot failed its integrity check and was discarded.",
29983
+ essential: true,
29984
+ fields: {}
29985
+ },
29805
29986
  "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.",
29987
+ "snapshot.failed": {
29988
+ description: "The hourly database snapshot failed; `retryAt` says when it tries again, if known.",
29989
+ essential: true,
29990
+ fields: { retryAt: "label", ...ESSENTIAL_ERROR_FIELDS }
29991
+ },
29807
29992
  "listener.attention-failed": "An environment attention listener threw; the committed mutation stands.",
29808
29993
  "listener.change-failed": "A resource change listener threw; the committed mutation stands.",
29809
29994
  "kanban.image-cleanup-failed": "An orphaned Kanban image could not be removed after its retries; it is safe to remove later.",
29810
29995
  "nodes.entries-dropped": "Unreadable node registry entries were ignored.",
29811
29996
  "preview-identity.reminted": "The data directory moved or was copied, so previews get a new backend identity.",
29997
+ "preview-settings.invalid": "Invalid preview settings disabled transport and relay.",
29812
29998
  "machine-profile.invalid": "The stored machine profile was invalid and the default was restored.",
29813
29999
  "permission-rules.cleanup-failed": "A deleted project's permission rules could not be removed.",
29814
30000
  "retired.turn-cleanup-pending": "Cleanup of a retired Looped Review turn did not finish and stays pending.",
29815
30001
  "handoffs.prune-failed": "Pruning agent handoffs that nothing references failed; a later prune retries.",
29816
30002
  "desktop-connections.malformed": "Stored desktop connection settings were malformed, so the local connection is used.",
29817
30003
  "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."
30004
+ "legacy-json.archive-failed": "Imported JSON store files could not be archived.",
30005
+ "lease.heartbeat-failed": "A held lease's heartbeat failed, which shortens the lease; the next one retries.",
30006
+ "scrub.checkpoint-failed": "Deleted content could not be scrubbed from the WAL because the truncating checkpoint failed or was blocked; the next checkpoint retries.",
30007
+ ...THROTTLE_LOG_EVENTS
29819
30008
  }
29820
30009
  }
29821
30010
  });
@@ -29906,6 +30095,11 @@ var COORDINATOR_LOG_AREAS = defineLogAreas({
29906
30095
  "wake.observe-pull-request-failed": "A pull request could not be observed for status wakes.",
29907
30096
  "wake.observe-feature-plan-failed": "A feature plan could not be observed for status wakes.",
29908
30097
  "wake.observe-workflow-failed": "A workflow could not be observed for status wakes.",
30098
+ "notice.outbox-refused": "A leaf's outbox refused a coordinator notice, so its own coordinator takes it.",
30099
+ "notice.start-main-failed": "A coordinator notice could not start a main coordinator; it waits for one to open.",
30100
+ "notice.take-back-unread": "A notice handed back from a command node found no open coordinator here.",
30101
+ "limit-stop.own": "A coordinator's own usage-limit stop attempted to move it off the account.",
30102
+ "limit-stop.notice-failed": "A usage-limit notice could not be sent; it stays in the ledger for the next attempt.",
29909
30103
  "wake.deliver-failed": "A workflow status wake could not be delivered; the next pass retries.",
29910
30104
  "wake.waiting-check-failed": "A waiting worker could not be checked; the next pass retries.",
29911
30105
  "wake.resolve-report-failed": "A finished Resolve tab could not be reported.",
@@ -29923,8 +30117,10 @@ var COORDINATOR_LOG_AREAS = defineLogAreas({
29923
30117
  "remote-worker.settle-failed": "A remote worker could not be settled.",
29924
30118
  "checkout.merge-followed": "After an environment's PR merged, the project checkout was fast-forwarded, or `outcome` says why not.",
29925
30119
  "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."
30120
+ "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`).",
30121
+ "checkout.mail-follow-failed": "Before mail woke the main coordinator, checking whether to fast-forward the project checkout failed; the mail was delivered anyway.",
30122
+ "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`.",
30123
+ "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
30124
  }
29929
30125
  }
29930
30126
  });
@@ -29934,15 +30130,15 @@ var REVIEW_LOG_AREAS = defineLogAreas({
29934
30130
  review: {
29935
30131
  description: "Multi Review workflows: scheduling, graph runs and interactive fix sessions.",
29936
30132
  events: {
29937
- "fix-tab.publish-failed": "A fix request was delivered but its tab could not be opened; the user is told.",
30133
+ "fix-tab.publish-failed": "A Address Findings request was delivered but its tab could not be opened; the user is told.",
29938
30134
  "graph-run.not-started": "A workflow's graph run did not start.",
29939
30135
  "reconcile.scan-failed": "A reconciliation scan failed; the next scan retries.",
29940
30136
  "graph-engine.unavailable": "The graph engine is selected but unavailable, so the bespoke engine runs.",
29941
30137
  "graph-run.cancel-failed": "Cancelling a graph run failed; the next pass projects how it ended.",
29942
30138
  "delete.cleanup-failed": "A cleanup step after deleting a workflow failed; stale tabs reconcile away on hydration.",
29943
- "fix-session.read-failed": "Reading an interactive fix session's state failed.",
30139
+ "fix-session.read-failed": "Reading an interactive Address Findings session's state failed.",
29944
30140
  "fix-outcome.read-failed": "Reading an interactive fix's outcome failed; it stays pending.",
29945
- "fix-usage.read-failed": "Reading a fix session's token usage failed.",
30141
+ "fix-usage.read-failed": "Reading an Address Findings session's token usage failed.",
29946
30142
  "result.consume-deferred": "Consuming a workflow result failed; it stays staged and is retried.",
29947
30143
  "failure-triage.failed": "Classifying a review package's failing tests failed; the package is sealed without the triage and says so."
29948
30144
  }
@@ -29995,6 +30191,7 @@ var AGENT_ACCOUNTS_LOG_AREAS = defineLogAreas({
29995
30191
  "agent-accounts": {
29996
30192
  description: "Agent accounts: automatic switching, staged logins and plan usage.",
29997
30193
  events: {
30194
+ "limit-stop-notice.failed": "A session's usage-limit stop could not be reported.",
29998
30195
  "switch-notice.failed": "A notice about an automatic account switch failed; the switch stands. `audience` says whose.",
29999
30196
  "auto-switch.check-failed": "An automatic account check failed; the next nudge retries.",
30000
30197
  "container-sync.failed": "Handing a login or account to a container failed; `step` says which part.",
@@ -30013,6 +30210,17 @@ var DOCKER_LOG_AREAS = defineLogAreas({
30013
30210
  description: "Docker containers: lifecycle, starts, staged inputs and the login files they hold.",
30014
30211
  events: {
30015
30212
  "portable-inputs.relay-missing": "Docker is rootless and the image predates the staged-input relay, so the container cannot read them until rebuilt.",
30213
+ "git-mirror.mount-unavailable": "A new container gets no project Git mirror, so its clone goes to the remote.",
30214
+ "git-mirror.refreshed": "A project's Git mirror was built or updated.",
30215
+ "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.",
30216
+ "git-mirror.low-disk": "A project's Git mirror was not updated: the disk is nearly full.",
30217
+ "git-mirror.oversized": "A project's repository is too large for a Git mirror, so its environments keep the blobless clone.",
30218
+ "git-mirror.compact-failed": "A project's Git mirror could not be compacted.",
30219
+ "git-mirror.state-write-failed": "A project's Git mirror could not be marked for checking.",
30220
+ "git-mirror.remove-failed": "A project's Git mirror could not be removed; a sweep retries.",
30221
+ "git-mirror.orphans-removed": "Git mirrors of removed projects were removed.",
30222
+ "git-mirror.clone-used": "A new environment cloned from its project's Git mirror.",
30223
+ "git-mirror.clone-fallback": "A new environment could not clone from its project's Git mirror and cloned from the remote.",
30016
30224
  "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.",
30017
30225
  "opencode.warm-incomplete": "OpenCode did not finish loading /workspace in a container.",
30018
30226
  "lifecycle-event.reconcile-failed": "Reconciling an environment after a container start or stop event failed; the next status read retries.",
@@ -30027,7 +30235,27 @@ var DOCKER_LOG_AREAS = defineLogAreas({
30027
30235
  "recovery.clear-terminals-failed": "Terminal sessions could not be cleared after a recovery restore.",
30028
30236
  "github-ranges.seed-not-copied": "The GitHub ranges seed could not be copied into a container, so its firewall fetches them.",
30029
30237
  "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."
30238
+ "start.port-collision-retrying": "An automatic host port collided on start, so it is retried once with fresh ports.",
30239
+ "writer-lease.lost": {
30240
+ description: "This backend lost the registry writer lease, for the fixed `reason` given. Schedules stop and container changes are refused until it restarts.",
30241
+ essential: true,
30242
+ fields: { reason: "label" }
30243
+ },
30244
+ "writer-lease.regained": {
30245
+ 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.",
30246
+ essential: true,
30247
+ fields: { staleForMs: "number" }
30248
+ },
30249
+ "writer-lease.not-acquired": {
30250
+ 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.",
30251
+ essential: true,
30252
+ fields: { reason: "label" }
30253
+ },
30254
+ "bridge.launched": {
30255
+ 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.",
30256
+ essential: true,
30257
+ fields: { provider: "label", containerPort: "number" }
30258
+ }
30031
30259
  }
30032
30260
  },
30033
30261
  "docker.reachability": {
@@ -30141,8 +30369,12 @@ var NODES_LOG_AREAS = defineLogAreas({
30141
30369
  nodes: {
30142
30370
  description: "Command nodes: links, handovers, leaf mail, ticket sync and project copies.",
30143
30371
  events: {
30372
+ ...THROTTLE_LOG_EVENTS,
30144
30373
  "actions.resume-failed": "Approved actions could not be resumed; a later pass retries.",
30145
30374
  "project-copy.notify-failed": "The coordinator could not be told a project copy finished.",
30375
+ "mail.return-deferred": "The leaf refused returned mail; it remains queued for retry.",
30376
+ "notices.take-back-failed": "A notice for this node's coordinator stayed in the outbox.",
30377
+ "notice.collected-retired": "A detached controller owned a notice with ambiguous delivery; retired without redelivery.",
30146
30378
  "mail.delivery-deferred": "Leaf mail could not reach a coordinator yet.",
30147
30379
  "command.post-step-failed": "A step after a routed command failed.",
30148
30380
  "seed-files.incomplete": "Seed files for a leaf environment were not all copied.",
@@ -30658,6 +30890,7 @@ var WEB_SYNC_LOG_AREAS = defineLogAreas({
30658
30890
  "web.read-coordinator": {
30659
30891
  description: "The renderer's coalesced, bounded backend reads.",
30660
30892
  events: {
30893
+ "poll.read-failed": "A coordinated poll's read failed; it stays on its interval.",
30661
30894
  "listener.threw": "A read state listener threw.",
30662
30895
  "read.settle-failed": "Applying a finished read's result threw."
30663
30896
  }
@@ -30735,6 +30968,146 @@ var LOG_VOCABULARY = {
30735
30968
  ...WEB_SYNC_LOG_AREAS
30736
30969
  };
30737
30970
 
30971
+ // ../protocol/src/log-essential-labels.ts
30972
+ var ERROR_NAMES = new Set([
30973
+ "Error",
30974
+ "TypeError",
30975
+ "RangeError",
30976
+ "ReferenceError",
30977
+ "SyntaxError",
30978
+ "URIError",
30979
+ "EvalError",
30980
+ "AggregateError",
30981
+ "AbortError",
30982
+ "TimeoutError",
30983
+ "SystemError"
30984
+ ]);
30985
+ var ERROR_CODES2 = new Set([
30986
+ "EACCES",
30987
+ "EADDRINUSE",
30988
+ "EADDRNOTAVAIL",
30989
+ "EAGAIN",
30990
+ "EBADF",
30991
+ "EBUSY",
30992
+ "ECANCELED",
30993
+ "ECONNABORTED",
30994
+ "ECONNREFUSED",
30995
+ "ECONNRESET",
30996
+ "EEXIST",
30997
+ "EHOSTUNREACH",
30998
+ "EINTR",
30999
+ "EINVAL",
31000
+ "EIO",
31001
+ "EISDIR",
31002
+ "EMFILE",
31003
+ "ENETUNREACH",
31004
+ "ENFILE",
31005
+ "ENOENT",
31006
+ "ENOMEM",
31007
+ "ENOSPC",
31008
+ "ENOSYS",
31009
+ "ENOTDIR",
31010
+ "ENOTEMPTY",
31011
+ "ENOTFOUND",
31012
+ "EPERM",
31013
+ "EPIPE",
31014
+ "EROFS",
31015
+ "ETIMEDOUT",
31016
+ "EXDEV",
31017
+ "SQLITE_BUSY",
31018
+ "SQLITE_CORRUPT",
31019
+ "SQLITE_FULL",
31020
+ "SQLITE_IOERR",
31021
+ "SQLITE_NOTADB",
31022
+ "SQLITE_READONLY",
31023
+ "ERR_CANCELED",
31024
+ "ERR_STREAM_DESTROYED"
31025
+ ]);
31026
+ var SYSCALLS = new Set([
31027
+ "open",
31028
+ "read",
31029
+ "write",
31030
+ "stat",
31031
+ "lstat",
31032
+ "mkdir",
31033
+ "rmdir",
31034
+ "readdir",
31035
+ "rename",
31036
+ "unlink",
31037
+ "fsync",
31038
+ "fdatasync",
31039
+ "close",
31040
+ "access",
31041
+ "chmod",
31042
+ "copyfile",
31043
+ "connect",
31044
+ "listen",
31045
+ "bind",
31046
+ "spawn",
31047
+ "kill",
31048
+ "getaddrinfo"
31049
+ ]);
31050
+ var SIGNALS = new Set([
31051
+ "SIGABRT",
31052
+ "SIGALRM",
31053
+ "SIGBUS",
31054
+ "SIGCHLD",
31055
+ "SIGCONT",
31056
+ "SIGFPE",
31057
+ "SIGHUP",
31058
+ "SIGILL",
31059
+ "SIGINT",
31060
+ "SIGKILL",
31061
+ "SIGPIPE",
31062
+ "SIGQUIT",
31063
+ "SIGSEGV",
31064
+ "SIGSTOP",
31065
+ "SIGTERM",
31066
+ "SIGTRAP",
31067
+ "SIGTSTP",
31068
+ "SIGTTIN",
31069
+ "SIGTTOU",
31070
+ "SIGUSR1",
31071
+ "SIGUSR2",
31072
+ "SIGWINCH",
31073
+ "SIGXCPU",
31074
+ "SIGXFSZ"
31075
+ ]);
31076
+ var PROVIDERS3 = new Set(["claude", "codex", "opencode", "cursor", "grok", "acp", "pi"]);
31077
+ var UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
31078
+ var SOURCE = new RegExp(`^(?:claude|codex|opencode|cursor|grok|acp|pi):${UUID}$`, "i");
31079
+
31080
+ // ../protocol/src/log-essential.ts
31081
+ var vocabulary = LOG_VOCABULARY;
31082
+ var UNDECLARED_ERROR_LABELS = new Set([
31083
+ "site",
31084
+ "kind",
31085
+ "step",
31086
+ "reason",
31087
+ "signal",
31088
+ "code"
31089
+ ]);
31090
+ function eventSpec(area, event) {
31091
+ const spec = Object.hasOwn(vocabulary, area) ? vocabulary[area] : undefined;
31092
+ if (!spec || !Object.hasOwn(spec.events, event))
31093
+ return null;
31094
+ const definition = spec.events[event];
31095
+ return typeof definition === "object" && definition.essential ? definition : null;
31096
+ }
31097
+ function declaredEssential(area, event, level) {
31098
+ const spec = eventSpec(area, event);
31099
+ return spec && (spec.minLevel !== "error" || level === "error") ? spec : null;
31100
+ }
31101
+ function hasEssentialEvents(area) {
31102
+ const spec = Object.hasOwn(vocabulary, area) ? vocabulary[area] : undefined;
31103
+ return spec !== undefined && Object.values(spec.events).some((event) => typeof event === "object" && event.essential);
31104
+ }
31105
+ function isEssentialEntry(area, event, level) {
31106
+ if (area === "logging" && event === "essential.write-failed")
31107
+ return false;
31108
+ return level === "error" || declaredEssential(area, event, level) !== null;
31109
+ }
31110
+
30738
31111
  // ../protocol/src/logger.ts
30739
31112
  var LOG_LEVELS = ["error", "warn", "info", "debug", "trace"];
30740
31113
  var MAX_FIELD_CHARS = 2048;
@@ -30779,7 +31152,9 @@ var DEFAULT_CONFIG = {
30779
31152
  level: "info",
30780
31153
  areaLevels: {},
30781
31154
  format: "text",
30782
- sink: consoleSink
31155
+ sink: consoleSink,
31156
+ essentialSink: null,
31157
+ relayEssential: false
30783
31158
  };
30784
31159
  var config2 = DEFAULT_CONFIG;
30785
31160
  var generation = 0;
@@ -30890,17 +31265,38 @@ function renderText(record) {
30890
31265
  function renderJson(record) {
30891
31266
  return escapeLogLine(JSON.stringify(record));
30892
31267
  }
31268
+ function offerEssential(record) {
31269
+ if (!config2.essentialSink || !isEssentialEntry(record.area, record.event, record.level))
31270
+ return;
31271
+ try {
31272
+ config2.essentialSink(record);
31273
+ } catch {}
31274
+ }
30893
31275
  function deliver(record) {
31276
+ let delivered = true;
30894
31277
  try {
30895
31278
  config2.sink({
30896
31279
  method: OUTPUT_METHOD[record.level],
30897
31280
  line: config2.format === "json" ? renderJson(record) : renderText(record),
30898
31281
  record
30899
31282
  });
30900
- return true;
30901
31283
  } catch {
30902
- return false;
31284
+ delivered = false;
31285
+ }
31286
+ offerEssential(record);
31287
+ return delivered;
31288
+ }
31289
+ function deliverEssentialOnly(record) {
31290
+ if (config2.essentialSink) {
31291
+ offerEssential(record);
31292
+ return;
30903
31293
  }
31294
+ if (!config2.relayEssential)
31295
+ return;
31296
+ const marked = { ...record, essentialOnly: true };
31297
+ try {
31298
+ config2.sink({ method: OUTPUT_METHOD[record.level], line: renderJson(marked), record: marked });
31299
+ } catch {}
30904
31300
  }
30905
31301
  function buildRecord(level, area, event, fields) {
30906
31302
  const clean = fields ? sanitizeFields(fields, areaSpec(area)?.maxStringChars ?? MAX_FIELD_CHARS) : undefined;
@@ -31065,12 +31461,17 @@ function deliverEvent(level, area, event, fields) {
31065
31461
  return deliver(buildRecord(level, area, event, fields));
31066
31462
  }
31067
31463
  function tryWriteLog(level, area, event, fields) {
31068
- if (LEVEL_RANK[level] > thresholdRank(area))
31464
+ if (LEVEL_RANK[level] > thresholdRank(area)) {
31465
+ if (isEssentialEntry(area, event, level)) {
31466
+ deliverEssentialOnly(buildRecord(level, area, event, resolveFields(fields)));
31467
+ }
31069
31468
  return false;
31469
+ }
31070
31470
  return deliverEvent(level, area, event, resolveFields(fields));
31071
31471
  }
31072
31472
  function createLogger(area) {
31073
31473
  const spec = areaSpec(area);
31474
+ const mayHoldEssential = hasEssentialEvents(area);
31074
31475
  let seenGeneration = -1;
31075
31476
  let rank = 0;
31076
31477
  const enabled = (level) => {
@@ -31083,9 +31484,16 @@ function createLogger(area) {
31083
31484
  const writeResolved = (level, event, resolved) => {
31084
31485
  deliverEvent(level, area, event, resolved);
31085
31486
  };
31487
+ const writeFiltered = (level, event, fields) => {
31488
+ if (!mayHoldEssential || !isEssentialEntry(area, event, level))
31489
+ return;
31490
+ deliverEssentialOnly(buildRecord(level, area, event, resolveFields(fields)));
31491
+ };
31086
31492
  const write = (level, event, fields) => {
31087
- if (!enabled(level))
31493
+ if (!enabled(level)) {
31494
+ writeFiltered(level, event, fields);
31088
31495
  return;
31496
+ }
31089
31497
  writeResolved(level, event, resolveFields(fields));
31090
31498
  };
31091
31499
  return {
@@ -31096,8 +31504,10 @@ function createLogger(area) {
31096
31504
  trace: (event, fields) => write("trace", event, fields),
31097
31505
  throttled: (level, event, options) => {
31098
31506
  syncThrottleLevels();
31099
- if (!enabled(level))
31507
+ if (!enabled(level)) {
31508
+ writeFiltered(level, event, options.fields);
31100
31509
  return;
31510
+ }
31101
31511
  if (!spec || !Object.hasOwn(spec.events, event) || event.startsWith("throttle.") || !Object.hasOwn(spec.events, "throttle.recovered")) {
31102
31512
  deliver(buildRecord(level, spec ? area : "logging", spec ? "invalid-event" : "unknown-area", undefined));
31103
31513
  return;
@@ -31171,41 +31581,46 @@ async function drainPersistence() {
31171
31581
  return;
31172
31582
  });
31173
31583
  }
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;
31584
+ function encodeStateWithinBudget(payload, lastAccessedById, budget) {
31585
+ const envelope = JSON.stringify({ ...payload, sessions: [] });
31586
+ const head = envelope.slice(0, -2);
31587
+ const records = payload.sessions.map((session) => JSON.stringify(session));
31588
+ const separators = Math.max(0, records.length - 1);
31589
+ let total = Buffer.byteLength(envelope) + separators;
31590
+ for (const record of records)
31591
+ total += Buffer.byteLength(record);
31592
+ if (total > budget) {
31593
+ const oldestFirst = payload.sessions.map((session, index) => ({ session, index })).sort((left, right) => (lastAccessedById.get(left.session.id) ?? 0) - (lastAccessedById.get(right.session.id) ?? 0));
31594
+ let shed = 0;
31595
+ for (const { session, index } of oldestFirst) {
31596
+ if (total <= budget)
31597
+ break;
31598
+ if (session.messages.length === 0)
31599
+ continue;
31600
+ session.droppedMessages = (session.droppedMessages ?? 0) + session.messages.length;
31601
+ session.messages = [];
31602
+ session.transcriptTruncated = true;
31603
+ shed += 1;
31604
+ const trimmed = JSON.stringify(session);
31605
+ total += Buffer.byteLength(trimmed) - Buffer.byteLength(records[index]);
31606
+ records[index] = trimmed;
31607
+ }
31608
+ if (total > budget) {
31609
+ log.warn("state.over-budget", { sessions: shed });
31610
+ return;
31187
31611
  }
31612
+ log.warn("state.transcripts-shed", { sessions: shed });
31188
31613
  }
31189
- log.warn("state.over-budget", { sessions: shed });
31190
- return false;
31614
+ return `${head}${records.join(",")}]}`;
31191
31615
  }
31192
31616
  async function persistNow(write = { barrier: false }) {
31193
31617
  const stateFile = stateFilePath();
31194
31618
  if (!stateFile)
31195
31619
  return;
31196
31620
  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);
31621
+ const serialized = encodeStateWithinBudget({ version: 1, provider: "pi", sessions: live.map(toPersisted) }, new Map(live.map((state) => [state.id, state.lastAccessed])), MAX_STATE_FILE_BYTES);
31622
+ if (serialized === undefined) {
31623
+ throw new Error("Pi bridge state exceeds its persistence budget");
31209
31624
  }
31210
31625
  await mkdir(dirname(stateFile), { recursive: true, mode: 448 });
31211
31626
  if (writeGateForTests)
@@ -31281,6 +31696,7 @@ function restoreSession(entry) {
31281
31696
  state.id = entry.id;
31282
31697
  if (isNativeAgentExecutionPolicy(entry.policy))
31283
31698
  state.policy = entry.policy;
31699
+ state.policyPending = true;
31284
31700
  if (nonBlank(entry.sessionFile))
31285
31701
  state.sessionFile = entry.sessionFile;
31286
31702
  if (nonBlank(entry.piSessionId))
@@ -31594,7 +32010,7 @@ function readString2(value) {
31594
32010
  }
31595
32011
  // ../../bridges/pi-bridge/src/agent-session.ts
31596
32012
  import { randomBytes as randomBytes6 } from "node:crypto";
31597
- import { existsSync as existsSync2 } from "node:fs";
32013
+ import { existsSync as existsSync2, statSync } from "node:fs";
31598
32014
 
31599
32015
  // ../protocol/src/agent-system-instructions.ts
31600
32016
  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 +32025,100 @@ function agentSystemInstructions(providerSpecific = []) {
31609
32025
  `);
31610
32026
  }
31611
32027
 
32028
+ // ../protocol/src/execution-policy-narrowing.ts
32029
+ var APPROVALS_STRICTNESS = {
32030
+ "auto-approve": 0,
32031
+ ask: 1,
32032
+ deny: 2
32033
+ };
32034
+ var SANDBOX_STRICTNESS = {
32035
+ none: 0,
32036
+ container: 1,
32037
+ provider: 2
32038
+ };
32039
+ function networkStrictness(value) {
32040
+ return value === "restricted" ? 1 : 0;
32041
+ }
32042
+ function isSubset(candidate, of) {
32043
+ const allowed = new Set(of);
32044
+ return candidate.every((item) => allowed.has(item));
32045
+ }
32046
+ function rawCapabilityDenials(policy) {
32047
+ return [
32048
+ ...policy.capabilityPolicy?.deny ?? [],
32049
+ ...policy.capabilityPolicy?.extendedDeny ?? []
32050
+ ];
32051
+ }
32052
+ function executionPolicyWidenings(current, next) {
32053
+ if (!current)
32054
+ return [];
32055
+ const widened = [];
32056
+ if (next.id !== current.id)
32057
+ widened.push("id");
32058
+ if (APPROVALS_STRICTNESS[next.approvals] < APPROVALS_STRICTNESS[current.approvals]) {
32059
+ widened.push("approvals");
32060
+ }
32061
+ if (SANDBOX_STRICTNESS[next.sandbox] < SANDBOX_STRICTNESS[current.sandbox]) {
32062
+ widened.push("sandbox");
32063
+ }
32064
+ if (next.projectResources && !current.projectResources)
32065
+ widened.push("projectResources");
32066
+ if (networkStrictness(next.networkAccess) < networkStrictness(current.networkAccess)) {
32067
+ widened.push("networkAccess");
32068
+ }
32069
+ if (networkStrictness(next.containerNetworkAccess) < networkStrictness(current.containerNetworkAccess)) {
32070
+ widened.push("containerNetworkAccess");
32071
+ }
32072
+ const currentAllow = current.toolPolicy?.allow;
32073
+ const nextAllow = next.toolPolicy?.allow;
32074
+ const allowNarrows = currentAllow === undefined ? nextAllow === undefined || nextAllow.length === 0 : nextAllow !== undefined && isSubset(nextAllow, currentAllow);
32075
+ if (!allowNarrows)
32076
+ widened.push("toolPolicy.allow");
32077
+ if (!isSubset(current.toolPolicy?.deny ?? [], next.toolPolicy?.deny ?? [])) {
32078
+ widened.push("toolPolicy.deny");
32079
+ }
32080
+ if (!isSubset(rawCapabilityDenials(current), rawCapabilityDenials(next))) {
32081
+ widened.push("capabilityPolicy.deny");
32082
+ }
32083
+ if (!isSubset(next.capabilityPolicy?.allow ?? [], current.capabilityPolicy?.allow ?? [])) {
32084
+ widened.push("capabilityPolicy.allow");
32085
+ }
32086
+ const currentServers = nativeAgentUserMcpGrant(current);
32087
+ const nextServers = nativeAgentUserMcpGrant(next);
32088
+ if (currentServers !== undefined && (nextServers === undefined || !isSubset(nextServers, currentServers))) {
32089
+ widened.push("capabilityPolicy.userMcpServers");
32090
+ }
32091
+ return widened;
32092
+ }
32093
+ var POLICY_WIDENING_REFUSED_CODE = "policy-widening-refused";
32094
+ function policyWideningRefusal(widened) {
32095
+ return {
32096
+ error: "Execution policy can only be narrowed on a live session; a wider policy applies after the agent bridge restarts.",
32097
+ code: POLICY_WIDENING_REFUSED_CODE,
32098
+ widened
32099
+ };
32100
+ }
32101
+
32102
+ class PolicyWideningRefusedError extends Error {
32103
+ widened;
32104
+ constructor(widened) {
32105
+ super(policyWideningRefusal(widened).error);
32106
+ this.widened = widened;
32107
+ this.name = "PolicyWideningRefusedError";
32108
+ }
32109
+ refusal() {
32110
+ return policyWideningRefusal(this.widened);
32111
+ }
32112
+ }
32113
+ function assertExecutionPolicyNotWidened(current, next) {
32114
+ const widened = executionPolicyWidenings(current, next);
32115
+ if (widened.length > 0)
32116
+ throw new PolicyWideningRefusedError(widened);
32117
+ }
32118
+
31612
32119
  // ../../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";
32120
+ import { realpath, stat as stat3 } from "node:fs/promises";
32121
+ import { join as join7, resolve as resolve3, sep } from "node:path";
31615
32122
 
31616
32123
  // ../protocol/src/node/command-change-journal.ts
31617
32124
  import { appendFile, mkdir as mkdir2, readFile as readFile3, rename as rename2, rm, stat, writeFile as writeFile2 } from "node:fs/promises";
@@ -33692,7 +34199,44 @@ async function overlayCommandChanges(state, options = {}) {
33692
34199
  } catch {}
33693
34200
  }
33694
34201
 
34202
+ // ../../bridges/pi-bridge/src/session-list-cache.ts
34203
+ import { createHash as createHash4 } from "node:crypto";
34204
+ import { readdir, stat as stat2 } from "node:fs/promises";
34205
+ import { join as join6 } from "node:path";
34206
+ var SESSION_LIST_CACHE_TTL_MS = 30000;
34207
+ var MAX_CACHED_SESSION_LIST_BYTES = 2 * 1024 * 1024;
34208
+ var cached2;
34209
+ async function sessionFilesStamp(directory) {
34210
+ let names;
34211
+ try {
34212
+ names = (await readdir(directory)).filter((name) => name.endsWith(".jsonl")).sort();
34213
+ } catch {
34214
+ return;
34215
+ }
34216
+ const stats = await Promise.all(names.map((name) => stat2(join6(directory, name)).catch(() => {
34217
+ return;
34218
+ })));
34219
+ const hash = createHash4("sha256");
34220
+ for (const [index, name] of names.entries()) {
34221
+ const file = stats[index];
34222
+ hash.update(file ? `${name}\x00${file.size}\x00${file.mtimeMs}\x00${file.ctimeMs}\x00${file.ino}
34223
+ ` : `${name}\x00gone
34224
+ `);
34225
+ }
34226
+ return hash.digest("hex");
34227
+ }
34228
+ function cachedSessionList(directory, stamp) {
34229
+ if (stamp === undefined || cached2?.directory !== directory || cached2.stamp !== stamp || performance.now() >= cached2.expiresAt) {
34230
+ return;
34231
+ }
34232
+ return cached2.entries;
34233
+ }
34234
+ function rememberSessionList(directory, stamp, entries) {
34235
+ cached2 = stamp !== undefined && encodedJsonBytes(entries) <= MAX_CACHED_SESSION_LIST_BYTES ? { directory, stamp, entries, expiresAt: performance.now() + SESSION_LIST_CACHE_TTL_MS } : undefined;
34236
+ }
34237
+
33695
34238
  // ../../bridges/pi-bridge/src/agent-session.ts
34239
+ var log2 = createLogger("bridge.pi");
33696
34240
  var closingSessions = new WeakSet;
33697
34241
 
33698
34242
  class SessionClosingError extends Error {
@@ -33701,6 +34245,13 @@ class SessionClosingError extends Error {
33701
34245
  super("This Pi session is closing; retry once the close completes");
33702
34246
  }
33703
34247
  }
34248
+
34249
+ class SessionBusyError extends Error {
34250
+ name = "SessionBusyError";
34251
+ constructor() {
34252
+ super("The Pi session is already running");
34253
+ }
34254
+ }
33704
34255
  function isSessionClosed(state) {
33705
34256
  return closingSessions.has(state);
33706
34257
  }
@@ -33802,8 +34353,9 @@ async function createSession(clientSessionKey, patch, policy) {
33802
34353
  throw new SessionClosingError;
33803
34354
  if (existing) {
33804
34355
  const resolved = resolvePiExecutionPolicy(policy);
33805
- if (policy || resolved.id === "coordinator-read-only")
33806
- existing.policy = resolved;
34356
+ if (policy || resolved.id === "coordinator-read-only") {
34357
+ await applyRequestedPolicy(existing, resolved);
34358
+ }
33807
34359
  if (resolved.id === "coordinator-read-only" && existing.readOnly !== true) {
33808
34360
  await setSessionReadOnly(existing, true);
33809
34361
  }
@@ -33811,12 +34363,24 @@ async function createSession(clientSessionKey, patch, policy) {
33811
34363
  return existing;
33812
34364
  }
33813
34365
  const inFlight = sessionCreations.get(clientSessionKey);
33814
- if (inFlight)
33815
- return inFlight;
34366
+ if (inFlight) {
34367
+ const existing = await inFlight;
34368
+ if (isSessionClosed(existing))
34369
+ throw new SessionClosingError;
34370
+ const resolved = resolvePiExecutionPolicy(policy);
34371
+ if (policy || resolved.id === "coordinator-read-only") {
34372
+ await applyRequestedPolicy(existing, resolved);
34373
+ }
34374
+ if (resolved.id === "coordinator-read-only" && existing.readOnly !== true) {
34375
+ await setSessionReadOnly(existing, true);
34376
+ }
34377
+ return existing;
34378
+ }
33816
34379
  }
33817
34380
  const work = (async () => {
33818
34381
  const resolved = resolvePiExecutionPolicy(policy);
33819
34382
  const state = newSessionState(clientSessionKey, resolved);
34383
+ state.policyPending = !policy;
33820
34384
  state.promptJournalComplete = true;
33821
34385
  if (resolved.id === "coordinator-read-only")
33822
34386
  state.readOnly = true;
@@ -33837,6 +34401,8 @@ async function createSession(clientSessionKey, patch, policy) {
33837
34401
  }
33838
34402
  }
33839
34403
  async function ensureSession(state) {
34404
+ if (policyChanges.has(state))
34405
+ throw new SessionBusyError;
33840
34406
  if (closingSessions.has(state))
33841
34407
  throw new SessionClosingError;
33842
34408
  if (state.session)
@@ -34105,9 +34671,9 @@ function projectResourceDiscoveryOptions(enabled = false, readOnly = false) {
34105
34671
  }
34106
34672
  function coordinatorProjectSkillPaths(cwd = workingDirectory) {
34107
34673
  return [
34108
- join6(cwd, ".pi", "skills"),
34109
- join6(cwd, ".agents", "skills"),
34110
- join6(cwd, ".claude", "skills")
34674
+ join7(cwd, ".pi", "skills"),
34675
+ join7(cwd, ".agents", "skills"),
34676
+ join7(cwd, ".claude", "skills")
34111
34677
  ].filter((path) => existsSync2(path));
34112
34678
  }
34113
34679
  function piResourceLoaderPolicy(state, cwd = workingDirectory) {
@@ -34137,6 +34703,35 @@ function coordinatorProcessPolicy() {
34137
34703
  networkAccess: "restricted"
34138
34704
  };
34139
34705
  }
34706
+ function liveExecutionPolicy(state) {
34707
+ return state.policyPending ? undefined : state.policy;
34708
+ }
34709
+ var policyChanges = new WeakSet;
34710
+ async function applyRequestedPolicy(state, policy) {
34711
+ if (policyChanges.has(state))
34712
+ throw new SessionBusyError;
34713
+ assertExecutionPolicyNotWidened(liveExecutionPolicy(state), policy);
34714
+ if (JSON.stringify(state.policy) !== JSON.stringify(policy)) {
34715
+ if (state.status === "running" || state.dispatching)
34716
+ throw new SessionBusyError;
34717
+ policyChanges.add(state);
34718
+ state.dispatching = true;
34719
+ try {
34720
+ await state.attaching?.catch(() => {
34721
+ return;
34722
+ });
34723
+ await detachSession(state);
34724
+ if (isSessionClosed(state))
34725
+ throw new SessionClosingError;
34726
+ assertExecutionPolicyNotWidened(liveExecutionPolicy(state), policy);
34727
+ state.policy = policy;
34728
+ } finally {
34729
+ state.dispatching = false;
34730
+ policyChanges.delete(state);
34731
+ }
34732
+ }
34733
+ state.policyPending = false;
34734
+ }
34140
34735
  function resolvePiExecutionPolicy(policy) {
34141
34736
  if (process.env[BRIDGE_EXECUTION_POLICY_ENV2] === "coordinator-read-only") {
34142
34737
  return coordinatorProcessPolicy();
@@ -34169,8 +34764,17 @@ function sessionManagerFor(state) {
34169
34764
  const directory = sessionDirectory();
34170
34765
  if (state.sessionFile) {
34171
34766
  try {
34172
- return SessionManager.open(state.sessionFile, directory, workingDirectory);
34173
- } catch {
34767
+ const hasHistory = (statSync(state.sessionFile, { throwIfNoEntry: false })?.size ?? 0) > 0;
34768
+ const manager = SessionManager.open(state.sessionFile, directory, workingDirectory);
34769
+ if (!hasHistory && (state.messages.length > 0 || state.promptSequence > 0)) {
34770
+ log2.warn("session.resume-fell-back", { sessionId: state.id });
34771
+ }
34772
+ return manager;
34773
+ } catch (error) {
34774
+ log2.warn("session.resume-fell-back", {
34775
+ sessionId: state.id,
34776
+ error: formatLogError(error, { message: false })
34777
+ });
34174
34778
  state.sessionFile = undefined;
34175
34779
  }
34176
34780
  }
@@ -34275,9 +34879,31 @@ async function applyComposerToSession(state) {
34275
34879
  state.revision += 1;
34276
34880
  }
34277
34881
  }
34882
+ var SESSION_LIST_TIMEOUT_MESSAGE = "Pi took too long to read its session history";
34883
+ var sessionListTimeoutMs = CATALOG_TIMEOUT_MS;
34884
+ function setSessionListTimeoutForTests(timeoutMs) {
34885
+ sessionListTimeoutMs = timeoutMs ?? CATALOG_TIMEOUT_MS;
34886
+ }
34278
34887
  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) => ({
34888
+ const read = new AbortController;
34889
+ try {
34890
+ return await withTimeout(readResumableSessions(read.signal), sessionListTimeoutMs, SESSION_LIST_TIMEOUT_MESSAGE);
34891
+ } catch (error) {
34892
+ read.abort();
34893
+ if (error instanceof TimeoutError)
34894
+ throw error;
34895
+ log2.warn("session-list.failed", { error: formatLogError(error, { message: false }) });
34896
+ return [];
34897
+ }
34898
+ }
34899
+ async function readResumableSessions(signal) {
34900
+ const directory = SessionManager.create(workingDirectory, sessionDirectory()).getSessionDir();
34901
+ const stamp = await sessionFilesStamp(directory);
34902
+ const cached = cachedSessionList(directory, stamp);
34903
+ if (cached)
34904
+ return cached;
34905
+ const listed = await SessionManager.list(workingDirectory, sessionDirectory(), undefined, signal);
34906
+ const entries = listed.slice(0, MAX_RESUME_ENTRIES).map((info) => ({
34281
34907
  sessionId: info.path,
34282
34908
  ...info.name?.trim() ? { title: info.name.trim() } : {},
34283
34909
  ...info.created ? { createdAt: new Date(info.created).toISOString() } : {},
@@ -34287,9 +34913,11 @@ async function listResumableSessions() {
34287
34913
  ...info.parentSessionPath ? { parentId: info.parentSessionPath } : {},
34288
34914
  ...info.parentSessionPath ? { branchLabel: info.name?.trim() || info.firstMessage.trim().slice(0, 80) || "Fork" } : {}
34289
34915
  }));
34916
+ rememberSessionList(directory, stamp, entries);
34917
+ return entries;
34290
34918
  }
34291
34919
  function resumableSessionRoot() {
34292
- return sessionDirectory() ?? join6(agentDirectory() ?? getAgentDir(), "sessions");
34920
+ return sessionDirectory() ?? join7(agentDirectory() ?? getAgentDir(), "sessions");
34293
34921
  }
34294
34922
  async function assertResumableSessionFile(sessionFile) {
34295
34923
  const root = resumableSessionRoot();
@@ -34305,7 +34933,7 @@ async function assertResumableSessionFile(sessionFile) {
34305
34933
  if (real !== rootReal && !real.startsWith(rootReal.endsWith(sep) ? rootReal : rootReal + sep)) {
34306
34934
  throw new Error("That Pi session file is outside this environment's session directory");
34307
34935
  }
34308
- const info = await stat2(real).catch(() => {
34936
+ const info = await stat3(real).catch(() => {
34309
34937
  return;
34310
34938
  });
34311
34939
  if (!info?.isFile())
@@ -34324,15 +34952,8 @@ async function resumeSession(sessionFile, patch, policy) {
34324
34952
  if (sameFile) {
34325
34953
  if (isSessionClosed(existing))
34326
34954
  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
- }
34955
+ if (policy)
34956
+ await applyRequestedPolicy(existing, resolvePiExecutionPolicy(policy));
34336
34957
  applyComposerPatch(existing, patch);
34337
34958
  existing.lastAccessed = Date.now();
34338
34959
  return existing;
@@ -34343,12 +34964,15 @@ async function resumeSession(sessionFile, patch, policy) {
34343
34964
  const existing = await inFlight;
34344
34965
  if (isSessionClosed(existing))
34345
34966
  throw new SessionClosingError;
34967
+ if (policy)
34968
+ await applyRequestedPolicy(existing, resolvePiExecutionPolicy(policy));
34346
34969
  applyComposerPatch(existing, patch);
34347
34970
  existing.lastAccessed = Date.now();
34348
34971
  return existing;
34349
34972
  }
34350
34973
  const work = (async () => {
34351
34974
  const state = newSessionState(undefined, resolvePiExecutionPolicy(policy));
34975
+ state.policyPending = !policy;
34352
34976
  state.sessionFile = resolved;
34353
34977
  applyComposerPatch(state, patch);
34354
34978
  state.composer = await hydrateComposerForSession(state.composer, undefined, defaultModelIds(state));
@@ -34649,14 +35273,14 @@ function pushMessage(state, role, content, parts, createdAt, messageId = randomB
34649
35273
  chargeTranscript(state, Buffer.byteLength(JSON.stringify(message)));
34650
35274
  }
34651
35275
  // ../protocol/src/node/bridge-diagnostics.ts
34652
- import { createHash as createHash4 } from "node:crypto";
35276
+ import { createHash as createHash5 } from "node:crypto";
34653
35277
 
34654
35278
  // ../protocol/src/event-loop-stall-monitor.ts
34655
- var log2 = createLogger("event-loop");
35279
+ var log3 = createLogger("event-loop");
34656
35280
  var EVENT_LOOP_STALL_ALWAYS_LOG_MS = 1e4;
34657
35281
 
34658
35282
  // ../protocol/src/node/bridge-diagnostics.ts
34659
- var log3 = createLogger("bridge.diagnostics");
35283
+ var log4 = createLogger("bridge.diagnostics");
34660
35284
  var BRIDGE_DIAGNOSTICS_INTERVAL_MS = 60000;
34661
35285
  var INTERVAL_MS = BRIDGE_DIAGNOSTICS_INTERVAL_MS;
34662
35286
  var STALL_NO_DELTA_MS = 2 * INTERVAL_MS;
@@ -34748,7 +35372,7 @@ function sameSet(a, b) {
34748
35372
  function identity(value) {
34749
35373
  if (typeof value !== "string" || !value || value.length > MAX_ID_LENGTH)
34750
35374
  return;
34751
- return createHash4("sha256").update(value).digest("hex").slice(0, 16);
35375
+ return createHash5("sha256").update(value).digest("hex").slice(0, 16);
34752
35376
  }
34753
35377
  function readBridgeDebugFlag(value) {
34754
35378
  return value?.trim() === "1";
@@ -34821,16 +35445,16 @@ function safeDiagnosticMetrics(value) {
34821
35445
  return result;
34822
35446
  }
34823
35447
  function bridgeDiagnosticsChangesEnabled() {
34824
- return log3.isEnabled("trace");
35448
+ return log4.isEnabled("trace");
34825
35449
  }
34826
35450
  function writeBridgeDiagnostic({ bridge, event, payload }) {
34827
35451
  return tryWriteLog("info", "bridge.diagnostics", event, { bridge, payload });
34828
35452
  }
34829
35453
  function bridgeDiagnosticsActive() {
34830
- return log3.isEnabled("info");
35454
+ return log4.isEnabled("info");
34831
35455
  }
34832
35456
  function bridgeDiagnosticsStreamEnabled(bridge) {
34833
- return bridgeDebugEnabled(bridge) || log3.isEnabled("debug");
35457
+ return bridgeDebugEnabled(bridge) || log4.isEnabled("debug");
34834
35458
  }
34835
35459
  function writeDiagnostic(bridge, event, payload, write) {
34836
35460
  try {
@@ -35326,6 +35950,7 @@ var STRUCTURED_OUTPUT_FAILURE_CODES = new Set([
35326
35950
  ]);
35327
35951
 
35328
35952
  // ../../bridges/pi-bridge/src/prompt.ts
35953
+ var log5 = createLogger("bridge.pi");
35329
35954
  var STRUCTURED_PROMPT_INSTRUCTION_PREFIX = "End your turn with exactly one JSON value";
35330
35955
  function structuredPromptInstruction(schema) {
35331
35956
  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 +36030,7 @@ ${structuredPromptInstruction(input.schema)}` : input.prompt;
35405
36030
  });
35406
36031
  const commandRun = input.extensionCommand ? beginCommandRun(state, input.extensionCommand) : undefined;
35407
36032
  state.turnAborted = undefined;
36033
+ state.turnCancelRequested = undefined;
35408
36034
  state.turnError = undefined;
35409
36035
  state.currentTurnApiDurationMs = undefined;
35410
36036
  let run;
@@ -35471,6 +36097,8 @@ ${structuredPromptInstruction(input.schema)}` : input.prompt;
35471
36097
  const cancelTurn = (reason = "user") => {
35472
36098
  if (cancelling)
35473
36099
  return cancelling;
36100
+ if (reason === "user")
36101
+ state.turnCancelRequested = true;
35474
36102
  const operation = (async () => {
35475
36103
  if (commandRun) {
35476
36104
  commandRun.cancelled = true;
@@ -35493,8 +36121,12 @@ ${structuredPromptInstruction(input.schema)}` : input.prompt;
35493
36121
  })();
35494
36122
  cancelling = operation;
35495
36123
  operation.catch(() => {
35496
- if (cancelling === operation)
36124
+ if (cancelling === operation) {
35497
36125
  cancelling = undefined;
36126
+ if (reason === "user" && state.cancelTurn === cancelTurn) {
36127
+ state.turnCancelRequested = undefined;
36128
+ }
36129
+ }
35498
36130
  });
35499
36131
  return operation;
35500
36132
  };
@@ -35529,6 +36161,7 @@ async function withinStartupDeadline(accepted, deadlineMs) {
35529
36161
  }
35530
36162
  }
35531
36163
  function abandonStartup(state, session, claim, accepted, settled, input, diagnostics, error, evidenceTurnId) {
36164
+ log5.warn("turn.startup-timed-out", { sessionId: state.id });
35532
36165
  state.status = "error";
35533
36166
  state.error = error.message;
35534
36167
  state.revision += 1;
@@ -35605,6 +36238,7 @@ async function followRun(state, session, run, promptSequence, input, promptTimeo
35605
36238
  }
35606
36239
  finishTurn(state, session, input);
35607
36240
  } catch (error) {
36241
+ const abortedBeforeCleanup = state.turnAborted === true;
35608
36242
  state.diagnostics?.terminalSettled("rejected");
35609
36243
  state.diagnostics?.streamSettled("rejected");
35610
36244
  state.diagnostics?.checkpoint("cancelling");
@@ -35618,7 +36252,7 @@ async function followRun(state, session, run, promptSequence, input, promptTimeo
35618
36252
  commandRun.error ??= errorText(error);
35619
36253
  settleCommandRun(state, commandRun, input.requestId);
35620
36254
  }
35621
- failTurn(state, session, error, input);
36255
+ failTurn(state, session, error, input, abortedBeforeCleanup);
35622
36256
  } finally {
35623
36257
  if (commandRun && state.commandRun === commandRun)
35624
36258
  state.commandRun = undefined;
@@ -35682,7 +36316,13 @@ function recordInterruptedOutput(state, input, message) {
35682
36316
  error: { code: "interrupted", message, provider: PROVIDER, retryable: true }
35683
36317
  });
35684
36318
  }
35685
- function failTurn(state, session, error, input) {
36319
+ function failTurn(state, session, error, input, abortedBeforeCleanup = state.turnAborted === true) {
36320
+ if (!abortedBeforeCleanup && state.turnCancelRequested !== true) {
36321
+ log5.warn("turn.failed", {
36322
+ sessionId: state.id,
36323
+ error: formatLogError(error, { message: false })
36324
+ });
36325
+ }
35686
36326
  settleTurn(state, session);
35687
36327
  recordTurnEnded(state, piRunId(state), "failed");
35688
36328
  state.status = "error";
@@ -35892,7 +36532,7 @@ function toImageContent(image) {
35892
36532
  // ../../bridges/pi-bridge/src/prompt-attachments.ts
35893
36533
  import { constants } from "node:fs";
35894
36534
  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";
36535
+ import { isAbsolute as isAbsolute3, join as join8, relative as relative2, resolve as resolve4, sep as sep2 } from "node:path";
35896
36536
  class PromptAttachmentError extends Error {
35897
36537
  code;
35898
36538
  name = "PromptAttachmentError";
@@ -35995,7 +36635,7 @@ function isPathWithin(root, candidate) {
35995
36635
  async function assertNoSymlinkComponents(root, targetPath) {
35996
36636
  let currentPath = root;
35997
36637
  for (const segment of relative2(root, targetPath).split(sep2).filter(Boolean)) {
35998
- currentPath = join7(currentPath, segment);
36638
+ currentPath = join8(currentPath, segment);
35999
36639
  const stats = await lstat2(currentPath).catch((error) => {
36000
36640
  throw attachmentErrorForFsFailure(error);
36001
36641
  });
@@ -36475,7 +37115,8 @@ function configureLoggerFromEnvironment(env, options = {}) {
36475
37115
  configureLogger({
36476
37116
  ...levels.level ? { level: levels.level } : {},
36477
37117
  areaLevels: levels.areaLevels,
36478
- format
37118
+ format,
37119
+ relayEssential: options.relayToSupervisor === true
36479
37120
  });
36480
37121
  const log = createLogger("logging");
36481
37122
  if (levels.invalid.length > 0) {
@@ -36579,7 +37220,7 @@ function humanPromptObservation(messages, tasks) {
36579
37220
  }
36580
37221
 
36581
37222
  // ../../bridges/pi-bridge/src/http.ts
36582
- import { createHash as createHash6, randomBytes as randomBytes7 } from "node:crypto";
37223
+ import { createHash as createHash7, randomBytes as randomBytes7 } from "node:crypto";
36583
37224
  import { pathToFileURL } from "node:url";
36584
37225
  import { gzip } from "node:zlib";
36585
37226
 
@@ -36636,7 +37277,7 @@ var DEFAULT_MCP_MANAGEMENT_ROLLOUT = Object.freeze({
36636
37277
 
36637
37278
  // ../protocol/src/node/bridge-transcript-summary.ts
36638
37279
  import { Buffer as Buffer5 } from "node:buffer";
36639
- import { createHash as createHash5 } from "node:crypto";
37280
+ import { createHash as createHash6 } from "node:crypto";
36640
37281
 
36641
37282
  // ../protocol/src/node/progressive-transcript.ts
36642
37283
  var BRIDGE_TRANSCRIPT_MAX_MESSAGES = 100;
@@ -36802,7 +37443,7 @@ function digestPayload(payload) {
36802
37443
  const serialized = JSON.stringify(payload);
36803
37444
  return {
36804
37445
  bytes: Buffer5.byteLength(serialized),
36805
- digest: createHash5("sha256").update(serialized).digest("base64url").slice(0, 32)
37446
+ digest: createHash6("sha256").update(serialized).digest("base64url").slice(0, 32)
36806
37447
  };
36807
37448
  }
36808
37449
  function topLevelKey(part, index) {
@@ -37523,7 +38164,7 @@ async function answerSessionActivityBatch(body, read, options = {}) {
37523
38164
  }
37524
38165
 
37525
38166
  // ../../bridges/pi-bridge/src/http.ts
37526
- var log4 = createLogger("bridge.pi");
38167
+ var log6 = createLogger("bridge.pi");
37527
38168
 
37528
38169
  class HttpError extends Error {
37529
38170
  status;
@@ -37595,6 +38236,12 @@ async function route(request, response, clientSignal) {
37595
38236
  } catch (error) {
37596
38237
  if (error instanceof HttpError)
37597
38238
  return json(response, error.status, { error: error.message });
38239
+ if (error instanceof PolicyWideningRefusedError) {
38240
+ log6.warn("session.policy-widening-refused", { widened: error.widened.join(",") });
38241
+ return json(response, 403, error.refusal());
38242
+ }
38243
+ if (error instanceof SessionBusyError)
38244
+ return json(response, 409, { error: error.message });
37598
38245
  if (error instanceof CredentialError) {
37599
38246
  return json(response, 401, { error: error.message, kind: "authentication-required" });
37600
38247
  }
@@ -37607,7 +38254,7 @@ async function route(request, response, clientSignal) {
37607
38254
  if (error instanceof PromptAttachmentError) {
37608
38255
  return json(response, 400, { error: error.message });
37609
38256
  }
37610
- log4.error("http.route-failed");
38257
+ log6.error("http.route-failed");
37611
38258
  return json(response, 500, { error: "Internal bridge error" });
37612
38259
  }
37613
38260
  }
@@ -37657,7 +38304,15 @@ async function routeGlobal(request, response, url) {
37657
38304
  return true;
37658
38305
  }
37659
38306
  if (url.pathname === "/session/list" && request.method === "GET") {
37660
- const listed = await listResumableSessions();
38307
+ let listed;
38308
+ try {
38309
+ listed = await listResumableSessions();
38310
+ } catch (error) {
38311
+ if (!(error instanceof TimeoutError))
38312
+ throw error;
38313
+ json(response, 504, { error: error.message });
38314
+ return true;
38315
+ }
37661
38316
  json(response, 200, {
37662
38317
  sessions: listed.map((entry) => ({
37663
38318
  id: entry.sessionId,
@@ -37701,8 +38356,9 @@ async function routeGlobal(request, response, url) {
37701
38356
  if (!sessionFile)
37702
38357
  throw new HttpError(400, "sessionId is required");
37703
38358
  const state = await resumeSession(sessionFile, parseComposerPatch(body), isNativeAgentExecutionPolicy(body.policy) ? body.policy : undefined).catch((error) => {
37704
- if (error instanceof SessionClosingError)
38359
+ if (error instanceof SessionClosingError || error instanceof SessionBusyError || error instanceof PolicyWideningRefusedError) {
37705
38360
  throw error;
38361
+ }
37706
38362
  throw new HttpError(400, errorText(error));
37707
38363
  });
37708
38364
  storeAgentMcp(state, body.agentMcp);
@@ -37999,7 +38655,7 @@ async function handleSteer(request, response, state) {
37999
38655
  throw new HttpError(400, "requestId is required");
38000
38656
  if (!expectedRunId)
38001
38657
  throw new HttpError(400, "expectedRunId is required");
38002
- const inputDigest = createHash6("sha256").update(text).digest("hex");
38658
+ const inputDigest = createHash7("sha256").update(text).digest("hex");
38003
38659
  const previous = state.steerJournal.get(requestId);
38004
38660
  if (previous) {
38005
38661
  if (previous.inputDigest !== inputDigest || previous.expectedRunId !== expectedRunId) {
@@ -38133,6 +38789,9 @@ async function handlePrompt(request, response, state, clientSignal) {
38133
38789
  }
38134
38790
  async function handleAdmittedPrompt(request, response, state, clientSignal, admission) {
38135
38791
  const body = await readJson(request);
38792
+ if (isNativeAgentExecutionPolicy(body.policy)) {
38793
+ assertExecutionPolicyNotWidened(liveExecutionPolicy(state), resolvePiExecutionPolicy(body.policy));
38794
+ }
38136
38795
  const commandFields = readBridgePromptCommandFields(body);
38137
38796
  if (!commandFields.ok)
38138
38797
  throw new HttpError(400, commandFields.error);
@@ -38171,6 +38830,7 @@ async function handleAdmittedPrompt(request, response, state, clientSignal, admi
38171
38830
  }
38172
38831
  return json(response, 202, { accepted: true, duplicate: true });
38173
38832
  }
38833
+ state.policyPending = false;
38174
38834
  let selection;
38175
38835
  if (command) {
38176
38836
  const resolved = resolveCommandSelection(state, command);
@@ -38360,6 +39020,12 @@ async function handleAdmittedPrompt(request, response, state, clientSignal, admi
38360
39020
  ...requestId ? { requestId } : {}
38361
39021
  });
38362
39022
  }
39023
+ if (error instanceof PromptRefusedError && !cancelRequestedFor(state, claim)) {
39024
+ log6.warn("turn.refused", {
39025
+ sessionId: state.id,
39026
+ error: formatLogError(error, { message: false })
39027
+ });
39028
+ }
38363
39029
  state.messages.splice(messageStart);
38364
39030
  state.uncheckedTranscriptBytes = uncheckedBeforePrompt;
38365
39031
  state.status = "error";
@@ -38615,7 +39281,7 @@ function startParentWatchdog(options) {
38615
39281
  }
38616
39282
 
38617
39283
  // ../protocol/src/bridge-lifecycle.ts
38618
- var log5 = createLogger("bridge.lifecycle");
39284
+ var log7 = createLogger("bridge.lifecycle");
38619
39285
  var TERMINATION_SIGNALS = ["SIGTERM", "SIGINT"];
38620
39286
  function errorKind(error) {
38621
39287
  if (error instanceof Error)
@@ -38669,7 +39335,7 @@ class BridgeLifecycle {
38669
39335
  }
38670
39336
  requestExit() {
38671
39337
  this.#exit ??= this.shutdown().then(() => this.#options.exit(0), (error) => {
38672
- log5.error("shutdown.failed", {
39338
+ log7.error("shutdown.failed", {
38673
39339
  bridge: this.#options.label,
38674
39340
  errorClass: errorKind(error)
38675
39341
  });
@@ -38686,7 +39352,7 @@ class BridgeLifecycle {
38686
39352
  try {
38687
39353
  idleSweep.run();
38688
39354
  } catch (error) {
38689
- log5.warn("idle-sweep.failed", {
39355
+ log7.warn("idle-sweep.failed", {
38690
39356
  bridge: this.#options.label,
38691
39357
  errorClass: errorKind(error)
38692
39358
  });
@@ -38945,6 +39611,9 @@ function installFatalRejectionGuard(options) {
38945
39611
  try {
38946
39612
  warn(`${options.label} Unhandled promise rejection (continuing): ${describe(reason)}`);
38947
39613
  } catch {}
39614
+ try {
39615
+ options.onRejection?.(reason);
39616
+ } catch {}
38948
39617
  };
38949
39618
  target.on("unhandledRejection", handler);
38950
39619
  return () => {
@@ -38952,9 +39621,18 @@ function installFatalRejectionGuard(options) {
38952
39621
  };
38953
39622
  }
38954
39623
 
39624
+ // ../protocol/src/node/process-failure-log.ts
39625
+ var log8 = createLogger("process");
39626
+ function logUnhandledRejection(reason) {
39627
+ log8.throttled("error", "rejection.unhandled", {
39628
+ error: reason,
39629
+ fields: () => ({ error: formatLogError(reason, { message: false }) })
39630
+ });
39631
+ }
39632
+
38955
39633
  // ../../bridges/pi-bridge/src/index.ts
38956
39634
  configureBridgeLogger();
38957
- installFatalRejectionGuard({ label: "[pi-bridge]" });
39635
+ installFatalRejectionGuard({ label: "[pi-bridge]", onRejection: logUnhandledRejection });
38958
39636
  if (process.env.PI_BRIDGE_LIBRARY_ONLY !== "1") {
38959
39637
  await start();
38960
39638
  }
@@ -38996,9 +39674,11 @@ export {
38996
39674
  PromptAttachmentError,
38997
39675
  PromptRefusedError,
38998
39676
  PromptStartupTimeoutError,
39677
+ SESSION_LIST_TIMEOUT_MESSAGE,
38999
39678
  STARTUP_TIMEOUT_MS,
39000
39679
  STREAM_BOUND_INTERVAL_BYTES,
39001
39680
  STRUCTURED_PROMPT_INSTRUCTION_PREFIX,
39681
+ SessionBusyError,
39002
39682
  SessionClosingError,
39003
39683
  TODO_STATUSES,
39004
39684
  TimeoutError,
@@ -39047,6 +39727,7 @@ export {
39047
39727
  dispatchPrompt,
39048
39728
  drainPersistence,
39049
39729
  emptyComposer,
39730
+ encodeStateWithinBudget,
39050
39731
  ensureSession,
39051
39732
  errorText,
39052
39733
  expireComposerHydrationRetryForTests,
@@ -39065,6 +39746,7 @@ export {
39065
39746
  json,
39066
39747
  listModels,
39067
39748
  listResumableSessions,
39749
+ liveExecutionPolicy,
39068
39750
  loadPersistedState,
39069
39751
  markSessionClosed,
39070
39752
  markSessionDefault,
@@ -39150,6 +39832,7 @@ export {
39150
39832
  setPendingRemoval,
39151
39833
  setPersistWriteGateForTests,
39152
39834
  setPromptJournal,
39835
+ setSessionListTimeoutForTests,
39153
39836
  setSessionReadOnly,
39154
39837
  setSessionTitle,
39155
39838
  setStartupTimeoutForTests,