orkestrator 2.37.3-beta → 2.37.5-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -250,10 +250,13 @@ var BRIDGE_LOG_AREAS = defineLogAreas({
250
250
  "prompt.accepted": "The route accepted a prompt and answered 202.",
251
251
  "prompt.failed": "A prompt turn failed; the session reports the error.",
252
252
  "prompt.processing-failed": "A prompt accepted by the route failed while processing.",
253
+ "prompt.processing-usage-limited": "A prompt accepted by the route ended on a usage limit; the turn already logged prompt.usage-limited.",
253
254
  "prompt.received": "A prompt reached the bridge; only its length is logged.",
254
255
  "prompt.send-failed": "A prompt request failed; the route answered with an error.",
256
+ "prompt.usage-limited": "A prompt turn ended because the account's plan allowance is used up; the session reports the limit.",
255
257
  "query.close-failed": "Stopping the Claude query failed while closing a tab; the close stays pending.",
256
258
  "query.failed": "A Claude query ended with an error result.",
259
+ "query.usage-limited": "Claude refused a query because the account's plan allowance is used up; the turn reports the limit.",
257
260
  "question.answer-failed": "The answer-question route failed.",
258
261
  "question.answering": "Answering a parked question.",
259
262
  "question.answers-prepared": "The route prepared a question answer for the session.",
@@ -452,10 +455,10 @@ var DESKTOP_LOG_AREAS = defineLogAreas({
452
455
  "dev-mode.ignored-packaged": "A packaged app was launched with ELECTRON_DEV=1 and ignored it; it loads its bundled renderer.",
453
456
  "instance.already-running": "Another instance holds this data directory; this one will quit.",
454
457
  "main-thread.stalled": {
455
- description: "A timer fired late, so windows, IPC and the stdout reader waited.",
458
+ description: "A timer fired late, so windows, IPC and the stdout reader waited. `cpuMs` is the CPU time the process used in the window: near `lagMs` the main thread was busy, far below it the thread waited.",
456
459
  essential: true,
457
460
  minLevel: "error",
458
- fields: { lagMs: "number", intervalMs: "number" }
461
+ fields: { lagMs: "number", intervalMs: "number", cpuMs: "number" }
459
462
  },
460
463
  "process-memory": "Development only: working set per Electron process type, sampled on an interval.",
461
464
  "process-memory.failed": "Development only: one process memory sample could not be read.",
@@ -505,12 +508,22 @@ var DESKTOP_LOG_AREAS = defineLogAreas({
505
508
  denied: "A renderer asked for a permission the policy does not grant."
506
509
  }
507
510
  },
511
+ "desktop.webrequest": {
512
+ description: "Main-process webRequest listeners on Electron sessions. Listener names only; never a URL, header or error message.",
513
+ events: {
514
+ "listener.failed-closed": "A listener's decision threw or rejected, so it answered with its fail-closed response.",
515
+ "observer.failed": "A listener with no callback (a redirect observer) threw; its fallback ran.",
516
+ "callback.failed": "Electron's webRequest callback threw while a listener answered.",
517
+ ...THROTTLE_LOG_EVENTS
518
+ }
519
+ },
508
520
  "desktop.dialog": {
509
521
  description: "Native dialogs, whose modal loops hold the main thread while they are open.",
510
522
  events: {
511
523
  "attention-failed": "A dialog could not ask for the user's attention.",
512
524
  closed: "A native dialog closed.",
513
525
  "hidden-cancelled": "A hidden profile cancelled a dialog without opening native UI.",
526
+ "no-display-cancelled": "A headless Electron with no display cancelled a dialog instead of opening native UI.",
514
527
  "open-failed": "A dialog could not open; it was answered as cancelled.",
515
528
  opening: "A native dialog is opening.",
516
529
  "preview-beforeunload-ignored": "A browser preview's beforeunload handler was ignored.",
@@ -866,6 +879,7 @@ var NATIVE_AGENT_LOG_AREAS = defineLogAreas({
866
879
  "agent-tools.unavailable": "OpenCode agent tools remain unavailable for a session.",
867
880
  "coordinator-servers.unavailable": "OpenCode coordinator research servers are unavailable.",
868
881
  "monitor.reconnecting": "The request monitor lost its stream and is reconnecting. Error class only.",
882
+ "monitor.silent": "The request monitor's stream stopped heartbeating, so it is replaced. `silenceMs` only.",
869
883
  "worker-limit.reached": "The bounded request workers are full, so the stream restarts and a snapshot reconciles.",
870
884
  "request.failed": "Handling a request event failed, so the stream restarts. Error class only.",
871
885
  "credential-plugin.skipped": "A host OpenCode server started without the credential plugin, so its tools inherit its password; `reason` says why.",
@@ -888,6 +902,7 @@ var NATIVE_AGENT_LOG_AREAS = defineLogAreas({
888
902
  "host-server.terminate-failed": "A 2.x server that did not become ready could not be stopped; its process entry is kept for shutdown. Error class only.",
889
903
  "container-server.launched": "The start script of a container environment's 2.x server was run. Container port only.",
890
904
  "container-server.ready": "A container environment's 2.x server this backend started answered `/api/info` as 2.x. Environment id only.",
905
+ "container-server.cleanup-failed": "Cleanup after OpenCode startup failed; step names only, while the original startup error is preserved.",
891
906
  "container-server.warm-incomplete": "The first workspace request to a container's new 2.x server failed, so its plugins load on the next one. Error class only.",
892
907
  "resume-list.unavailable": "The 2.x sessions could not be listed for the resume picker, so it shows the 1.x list alone. Error class only.",
893
908
  "credential.mirrored": "A provider sign-in change was copied into the 2.x database. `outcome` (written, removed, unchanged, skipped) only; never a provider id or value.",
@@ -942,12 +957,13 @@ var RUNTIME_LOG_AREAS = defineLogAreas({
942
957
  description: "This process's event loop. A stall of 10 seconds or more is written at error, so no level hides it.",
943
958
  events: {
944
959
  stalled: {
945
- description: "A timer fired late, so every request in that window waited. In the backend the line also names what ran: `storageMs` and the `storage*` fields describe the slow SQLite calls in the window (`operation.slow` in `storage`), `commandsInFlight` and `commands` the commands running, and `blockingCommand` one whose synchronous part overlapped it.",
960
+ description: "A timer fired late, so every request in that window waited. In the backend the line also names what ran: `storageMs` and the `storage*` fields describe the slow SQLite calls in the window (`operation.slow` in `storage`), `commandsInFlight` and `commands` the commands running, `blockingCommand` one whose synchronous part overlapped it, and `jobsInWindow` and `jobs` the recurring jobs that ran around it. `cpuMs` is the CPU time the process used in the window: near `lagMs` its own thread was busy, far below it the thread waited.",
946
961
  essential: true,
947
962
  minLevel: "error",
948
963
  fields: {
949
964
  lagMs: "number",
950
965
  intervalMs: "number",
966
+ cpuMs: "number",
951
967
  storageMs: "number",
952
968
  storageDatabase: "label",
953
969
  storageOp: "label",
@@ -955,7 +971,8 @@ var RUNTIME_LOG_AREAS = defineLogAreas({
955
971
  storageLongestMs: "number",
956
972
  storageBusy: "boolean",
957
973
  commandsInFlight: "number",
958
- blockingCommandMs: "number"
974
+ blockingCommandMs: "number",
975
+ jobsInWindow: "number"
959
976
  }
960
977
  }
961
978
  }
@@ -995,6 +1012,8 @@ var TERMINAL_LOG_AREAS = defineLogAreas({
995
1012
  "pty.exit-notify-failed": "Notifying a terminal's exit failed.",
996
1013
  "pty.late-exit-listener-failed": "A listener added after a terminal exited threw.",
997
1014
  "setup.pty-reused": "A setup terminal reused its existing PTY.",
1015
+ "setup.pty-retired": "A setup retry ended the terminal the previous run left open, so the new run gets its own.",
1016
+ "setup.pty-retire-failed": "A setup retry could not end the previous run's process tree, so it kept that terminal and started nothing.",
998
1017
  "setup.pty-spawning": "A setup terminal is spawning its PTY. The argument count only, never the arguments.",
999
1018
  "setup.pty-spawned": "A setup terminal's PTY started.",
1000
1019
  "setup.pty-exited": "A setup terminal's PTY exited.",
@@ -1122,6 +1141,7 @@ var TMUX_LOG_AREAS = defineLogAreas({
1122
1141
  "cleanup.skipped": "Environment tmux cleanup was skipped because tmux could not be reached and nothing required it.",
1123
1142
  "cleanup.environments-load-failed": "Environments could not be loaded during tmux cleanup, so it stays incomplete.",
1124
1143
  "cleanup.kill-failed": "An environment's tmux sessions could not be killed.",
1144
+ "cleanup.kill-incomplete": "An environment's tmux sessions could not all be shown gone (a session survived, or the socket was unreachable while another tmux process might own it), so cleanup stays incomplete.",
1125
1145
  "hooks.uninstall-failed": "Workspace hooks could not be uninstalled.",
1126
1146
  "hooks.git-exclude-failed": "The git exclude for Claude's local settings could not be set.",
1127
1147
  "naming.prepare-failed": "First-prompt naming could not be prepared; the prompt still goes ahead.",
@@ -1251,6 +1271,7 @@ var STORAGE_LOG_AREAS = defineLogAreas({
1251
1271
  "config.restrict-mode-failed": "A config file holding provider secrets could not be set to owner-only; the backend carries on.",
1252
1272
  "legacy-json.moved": "JSON store files written after the SQLite migration were archived, not imported.",
1253
1273
  "legacy-json.archive-failed": "Imported JSON store files could not be archived.",
1274
+ "native-session-owners.backfill-failed": "Native-session rows could not be given their environment as owner at open; an environment delete then parses those rows instead, and the next open retries.",
1254
1275
  "lease.timed-out": "A waiter gave up on a lease; `lease` and `family` name it, `holderAgeMs` is the time since its holder's last heartbeat (null when the holder had just gone), `waitedMs` how long the waiter waited.",
1255
1276
  "lease.heartbeat-failed": "A held lease's heartbeat failed, which shortens the lease; the next one retries.",
1256
1277
  "scrub.vacuum-failed": "Deleted-content page reclamation failed; the checkpoint is attempted independently.",
@@ -1300,9 +1321,12 @@ var BUILD_PIPELINE_LOG_AREAS = defineLogAreas({
1300
1321
  "transcripts.maintenance-failed": "Migrating or sweeping stage transcripts failed; the next start retries.",
1301
1322
  "restore.skipped": "A pipeline could not be restored at startup and was skipped.",
1302
1323
  "criteria.record-failed": "Acceptance criteria results could not be recorded on the ticket.",
1324
+ "completion-notes.publish-failed": "A finished pipeline's notes tab could not be added to the layout; the run stays complete.",
1303
1325
  "workspace.waiting": "A pipeline is waiting for its workspace; written once per reason.",
1304
1326
  "rewind.pending": "A pipeline's code rewind has not finished; written once per reason.",
1305
1327
  "kanban.status-failed": "A restarted pipeline's Kanban status could not be set; it retries shortly.",
1328
+ "kanban.environment-deleted-read-failed": "The pipelines of an environment being deleted could not be read, so their tickets keep their columns.",
1329
+ "kanban.environment-deleted-update-failed": "The ticket of a pipeline whose environment was deleted could not be moved; the deletion goes on.",
1306
1330
  "usage.read-failed": "Reading a stage session's token usage failed.",
1307
1331
  "checkpoint.deferred": "A stage transcript checkpoint could not be written yet; the provider's history stands.",
1308
1332
  "checkpoint.not-committed": "A stage transcript checkpoint was reverted in the commit that should have kept it.",
@@ -1341,6 +1365,8 @@ var CHANGE_TRACKING_LOG_AREAS = defineLogAreas({
1341
1365
  "dispatch.record-failed": "Recording a turn's dispatch outcome failed.",
1342
1366
  "turn.finalize-failed": "Finalizing a turn failed.",
1343
1367
  "turn.settle-failed": "Settling a late interrupted turn failed.",
1368
+ "turn.end-recovery": "A background retry of a turn end capture that timed out finished: recovered, done (no longer eligible) or exhausted.",
1369
+ "turn.end-recovery-failed": "A background retry of a turn end capture threw; it counts as a failed attempt.",
1344
1370
  "evidence.pull-failed": "Pulling change evidence from a bridge failed; a later pull retries.",
1345
1371
  "measurement.failed": "Recomputing a tool's measurement failed."
1346
1372
  }
@@ -1351,6 +1377,7 @@ var CHANGE_TRACKING_LOG_AREAS = defineLogAreas({
1351
1377
  "baseline.update-failed": "An environment's diff baseline could not be updated.",
1352
1378
  "scan.watcher-failed": "An environment's diff watcher failed; its scans fall back to polling.",
1353
1379
  "scan.failed": "A diff scan failed; the last results stay, marked stale, and the scan is retried.",
1380
+ "scan.target-missing": "A local environment's worktree folder is missing (deleted, moved or on an unmounted drive); no scan runs, the last results stay, marked stale, and the folder is checked again on the failure backoff.",
1354
1381
  "scan.freshness-read-failed": "Reading whether an environment's remote is fresh failed.",
1355
1382
  "scan.listener-failed": "A change-tracking scan listener threw; the scan itself stands.",
1356
1383
  "emit.diff-stats-failed": "A diff stats change could not be emitted to its sink.",
@@ -1409,6 +1436,7 @@ var COORDINATOR_LOG_AREAS = defineLogAreas({
1409
1436
  "node-release.no-coordinator": "Work closed on a released node belonged to a coordinator that no longer exists, so nobody was told.",
1410
1437
  "node-offline.notice-failed": "The notice that a node has been unreachable for a day could not be sent; the next failed read retries.",
1411
1438
  "node-offline.check-failed": "Whether a long-unreachable node's coordinators were told could not be checked; the next read retries.",
1439
+ "node-reconnect.notice-failed": "The message that a node a coordinator tried while it was disconnected is back could not be sent; it is not retried, since the coordinator already holds the refusal.",
1412
1440
  "checkout.merge-followed": "After an environment's PR merged, the project checkout was fast-forwarded, or `outcome` says why not.",
1413
1441
  "checkout.merge-follow-failed": "Fast-forwarding the project checkout failed, after an environment's PR merged or before mail woke the main coordinator.",
1414
1442
  "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`).",
@@ -1461,7 +1489,8 @@ var REVIEW_LOG_AREAS = defineLogAreas({
1461
1489
  "monitor.task-store-failed": "A pull request could not be recorded on its Kanban task.",
1462
1490
  "monitor.merged-tickets-closed": "The startup sweep moved Kanban tickets whose pull request had merged to done (`count`).",
1463
1491
  "monitor.merged-tickets-close-failed": "The startup sweep closing Kanban tickets whose pull request merged failed; the next backend start retries.",
1464
- "monitor.emit-failed": "A pull request monitor event could not be emitted to its sink."
1492
+ "monitor.emit-failed": "A pull request monitor event could not be emitted to its sink.",
1493
+ "branch-cleanup.kept": "A merge or cleanup kept a pull request's head branch because it is not the branch created for the environment (`reason`)."
1465
1494
  }
1466
1495
  }
1467
1496
  });
@@ -1493,6 +1522,8 @@ var AGENT_ACCOUNTS_LOG_AREAS = defineLogAreas({
1493
1522
  "kept-note.failed": "Recording why a limit stop found no account to move to failed; the stop stands.",
1494
1523
  "container-sync.failed": "Handing a login or account to a container failed; `step` says which part.",
1495
1524
  "last-usage.save-failed": "The last plan usage reading could not be saved; the next save retries.",
1525
+ "shared-usage.save-failed": "The shared usage readings could not be saved; they stay in memory and the next reading saves them.",
1526
+ "shared-usage.record-failed": "A fresh usage reading could not be kept for sharing with other machines; the account's own reading stands.",
1496
1527
  "login-cleanup.failed": "A temporary login could not be cleaned up.",
1497
1528
  "login-renewal.failed": "Renewing an idle account's sign-in to read its usage failed; it is retried after a backoff.",
1498
1529
  "login-renewal.not-extended": "Claude Code ran to renew an idle account's sign-in, but its token is still lapsed.",
@@ -1510,6 +1541,7 @@ var DOCKER_LOG_AREAS = defineLogAreas({
1510
1541
  "git-mirror.mount-unavailable": "A new container gets no project Git mirror, so its clone goes to the remote.",
1511
1542
  "git-mirror.mount-withheld": "A new restricted container gets no project Git mirror because its firewall would not let it reach the project's remote, so it cannot read what the remote serves through the mirror either.",
1512
1543
  "git-mirror.refreshed": "A project's Git mirror was built or updated.",
1544
+ "git-mirror.access-changed": "A project's Git mirror was withdrawn because containers are now given a different credential (another access kind, or a token acting as another or an unreadable account), so no reader keeps what it could not fetch itself.",
1513
1545
  "git-mirror.seeded": "A project's Git mirror was built from its host checkout and only what the remote added to it.",
1514
1546
  "git-mirror.seed-skipped": "A project's host checkout could not seed its Git mirror, so the build downloads everything.",
1515
1547
  "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.",
@@ -1523,6 +1555,9 @@ var DOCKER_LOG_AREAS = defineLogAreas({
1523
1555
  "git-mirror.clone-fallback": "A new environment could not clone from its project's Git mirror and cloned from the remote.",
1524
1556
  "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.",
1525
1557
  "opencode.warm-incomplete": "OpenCode did not finish loading /workspace in a container.",
1558
+ "opencode.listener-replaced": "The process on a container's OpenCode port (`provider`: `opencode` or `opencode2`) is not the server the backend launched and recorded, so its password was withheld and the next start replaces it. `stage` is `request` when the re-check after a refused connection or an unexpected answer found it; that connection then sends nothing more.",
1559
+ "opencode.project-config-too-large": "A checkout's opencode.json or opencode.jsonc was larger than the limit, so a launched OpenCode server does not read it. File name only.",
1560
+ "opencode.project-config-filtered": "Values were left out of a checkout's OpenCode configuration before a launched server reads it: counts of plugin keys, `{env:}` and `{file:}` references and dropped instructions (including separate instructionGlob and instructionUrl counts), and the names of files that were not a JSONC object. Never values.",
1526
1561
  "log-driver.unbounded": "The Docker daemon offers neither the local nor the json-file log driver, so new containers keep its default driver, whose log may be uncapped. Written once per backend.",
1527
1562
  "lifecycle-event.reconcile-failed": "Reconciling an environment after a container start or stop event failed; the next status read retries.",
1528
1563
  "login-keeper.pass-failed": "A Claude login keeper pass failed; the next interval retries.",
@@ -1557,6 +1592,17 @@ var DOCKER_LOG_AREAS = defineLogAreas({
1557
1592
  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.",
1558
1593
  essential: true,
1559
1594
  fields: { provider: "label", containerPort: "number" }
1595
+ },
1596
+ "bridge.listener-refused": {
1597
+ description: "The socket listening on a container bridge's port is not the one the bridge the backend started opened, so its token is not handed out and the next start replaces it. `reason` is a fixed label: `different-socket`, `several-sockets`, `pending` (a start has not recorded its bridge yet, or failed before it did) or `scan-incomplete`.",
1598
+ essential: true,
1599
+ fields: { provider: "label", reason: "label" }
1600
+ },
1601
+ "bridge.listener-adopted": "A running container bridge had no listener record, because a backend from before the record started it, so the socket on its port was recorded as the bridge's; `provider` names it.",
1602
+ "bridge.listener-unrecorded": {
1603
+ description: "A bridge the backend just launched could not be recorded as its port's listener, for the fixed `reason` given (`no-listener`, `several-sockets`, `launch-exited` or `scan-incomplete`); what listens on the port is stopped and the start fails.",
1604
+ essential: true,
1605
+ fields: { provider: "label", reason: "label" }
1560
1606
  }
1561
1607
  }
1562
1608
  },
@@ -1611,7 +1657,8 @@ var MCP_LOG_AREAS = defineLogAreas({
1611
1657
  "listener.port-free": "The Control MCP's fixed port is free again, so it is listening.",
1612
1658
  "state-listener.failed": "A Control MCP state listener threw; the others still run.",
1613
1659
  "delegation.remote-open-failed": "A delegation could not be opened on another node.",
1614
- "delegation.open-failed": "A coordinator delegation could not be opened."
1660
+ "delegation.open-failed": "A coordinator delegation could not be opened.",
1661
+ "delegation.turn-origin-unreadable": "A coordinator's last turn origin could not be read, so its delegated prompt is marked as arising from agent mail."
1615
1662
  }
1616
1663
  },
1617
1664
  "mcp-management": {
@@ -1696,6 +1743,7 @@ var NODES_LOG_AREAS = defineLogAreas({
1696
1743
  "ticket-sync.failed": "A Kanban sync with a node failed; it is retried.",
1697
1744
  "ticket-sync.unknown-project": "A node sent ticket changes for a project that no longer exists here.",
1698
1745
  "ticket-sync.forget-failed": "A detached command node's ticket copies could not be released.",
1746
+ "usage-sync.failed": "Sharing usage readings with a node failed; the next reading or reconnect retries.",
1699
1747
  "fleet-update.requested": "The update policy asked an older leaf to install the command node's version.",
1700
1748
  "fleet-update.failed": "The update policy could not read or update a leaf; it retries later.",
1701
1749
  "fleet-update.policy-load-failed": "The stored update policy could not be read; it is off."
@@ -1787,6 +1835,20 @@ var SCHEDULER_LOG_AREAS = defineLogAreas({
1787
1835
  }
1788
1836
  });
1789
1837
 
1838
+ // ../protocol/src/log-vocabulary/self-improvement.ts
1839
+ var SELF_IMPROVEMENT_LOG_AREAS = defineLogAreas({
1840
+ "self-improvement": {
1841
+ description: "Self-improvement runs: diagnostics and conversation review turned into tickets. Counts and steps only, never conversation text.",
1842
+ events: {
1843
+ "run.started": "A run started; `trigger` is manual, daily or dry-run.",
1844
+ "run.finished": "A run finished; `created`, `verified`, `fixFailed` and `parts` count its tickets, confirmed fixes, failed fixes and conversation parts read.",
1845
+ "run.failed": "A run stopped before it finished; `reason` is a fixed label.",
1846
+ "review.call-failed": "One conversation review call failed; the run carries on and the part is read again next run.",
1847
+ "daily.check-failed": "The daily run check failed; the next check retries."
1848
+ }
1849
+ }
1850
+ });
1851
+
1790
1852
  // ../protocol/src/log-vocabulary/web-app.ts
1791
1853
  var WEB_APP_LOG_AREAS = defineLogAreas({
1792
1854
  "web.app": {
@@ -2054,6 +2116,7 @@ var WEB_KANBAN_LOG_AREAS = defineLogAreas({
2054
2116
  "task.move-failed": "A task move failed and its status was rolled back.",
2055
2117
  "comment.add-failed": "A comment could not be added to a task.",
2056
2118
  "comment.delete-failed": "A comment could not be deleted from a task.",
2119
+ "pr.merge-failed": "Merging a ticket's pull request from its Notes tab failed; the error was shown to the user.",
2057
2120
  "image.add-failed": "An image could not be added to a task.",
2058
2121
  "image.delete-failed": "An image could not be deleted from a task.",
2059
2122
  "notes.load-failed": "Project notes could not be loaded; the editor stays disabled.",
@@ -2122,6 +2185,10 @@ var WEB_SETTINGS_LOG_AREAS = defineLogAreas({
2122
2185
  "web.settings": {
2123
2186
  description: "The settings screens.",
2124
2187
  events: {
2188
+ "self-improvement.status-failed": "Settings → Self-improvement could not read the status.",
2189
+ "self-improvement.projects-failed": "Settings → Self-improvement could not list the projects.",
2190
+ "self-improvement.save-failed": "Settings → Self-improvement could not save a setting.",
2191
+ "self-improvement.run-failed": "Settings → Self-improvement could not start a run.",
2125
2192
  "config.save-failed": "Global settings could not be saved.",
2126
2193
  "config.load-failed": "The settings page could not load the config.",
2127
2194
  "config.reload-failed": "Re-reading the workspace config after a save failed.",
@@ -2291,6 +2358,7 @@ var LOG_VOCABULARY = {
2291
2358
  ...HOST_LOG_AREAS,
2292
2359
  ...TRANSCRIPT_ARTIFACTS_LOG_AREAS,
2293
2360
  ...SCHEDULER_LOG_AREAS,
2361
+ ...SELF_IMPROVEMENT_LOG_AREAS,
2294
2362
  ...WEB_APP_LOG_AREAS,
2295
2363
  ...WEB_BUILD_PIPELINE_LOG_AREAS,
2296
2364
  ...WEB_CHAT_LOG_AREAS,
@@ -2591,6 +2659,14 @@ var SIGNALS = new Set([
2591
2659
  "SIGXFSZ"
2592
2660
  ]);
2593
2661
  var PROVIDERS = new Set(["claude", "codex", "opencode", "cursor", "grok", "acp", "pi"]);
2662
+ var BRIDGE_LISTENER_REASONS = new Set([
2663
+ "different-socket",
2664
+ "several-sockets",
2665
+ "pending",
2666
+ "scan-incomplete",
2667
+ "no-listener",
2668
+ "launch-exited"
2669
+ ]);
2594
2670
  var UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
2595
2671
  var SOURCE = new RegExp(`^(?:claude|codex|opencode|cursor|grok|acp|pi):${UUID}$`, "i");
2596
2672
  var STORAGE_DATABASES = new Set(["main", "ledger", "other"]);
@@ -3337,11 +3413,10 @@ function setLiveBridgeDiagnostics(enabled) {
3337
3413
  for (const scope of Array.from(liveScopes))
3338
3414
  scope.syncActive();
3339
3415
  }
3340
- function bridgeDebugEnabled(bridge, env = process.env) {
3416
+ function bridgeDebugEnabled(_bridge, env = process.env) {
3341
3417
  if (liveDiagnostics !== undefined && env === process.env)
3342
3418
  return liveDiagnostics;
3343
- const value = env.ORKESTRATOR_BRIDGE_DEBUG ?? env[`${bridge.toUpperCase()}_BRIDGE_DEBUG`];
3344
- return readBridgeDebugFlag(value);
3419
+ return readBridgeDebugFlag(env.ORKESTRATOR_BRIDGE_DEBUG);
3345
3420
  }
3346
3421
  function safeDiagnosticMetrics(value) {
3347
3422
  const result = {};
@@ -5553,6 +5628,54 @@ health.get("/health", (c) => {
5553
5628
  });
5554
5629
  var health_default = health;
5555
5630
 
5631
+ // ../protocol/src/node/bounded-wait.ts
5632
+ function boundedWait(work, timeoutMs, options = {}) {
5633
+ return new Promise((resolve, reject) => {
5634
+ let timedOut = false;
5635
+ const timer = setTimeout(() => {
5636
+ timedOut = true;
5637
+ resolve({ settled: false });
5638
+ }, timeoutMs);
5639
+ unrefTimer(timer);
5640
+ Promise.resolve(work).then((value) => {
5641
+ if (!timedOut) {
5642
+ clearTimeout(timer);
5643
+ resolve({ settled: true, value });
5644
+ return;
5645
+ }
5646
+ disposeLate(options.onLate, value);
5647
+ }, (error) => {
5648
+ if (!timedOut) {
5649
+ clearTimeout(timer);
5650
+ reject(error);
5651
+ }
5652
+ });
5653
+ });
5654
+ }
5655
+ async function boundedWaitOrThrow(work, timeoutMs, timeoutError, options = {}) {
5656
+ const result = await boundedWait(work, timeoutMs, options);
5657
+ if (!result.settled)
5658
+ throw timeoutError();
5659
+ return result.value;
5660
+ }
5661
+ function unrefTimer(timer) {
5662
+ const handle = timer;
5663
+ if (typeof handle === "object" && typeof handle.unref === "function")
5664
+ handle.unref();
5665
+ }
5666
+ function disposeLate(onLate, value) {
5667
+ if (!onLate)
5668
+ return;
5669
+ try {
5670
+ const disposal = onLate(value);
5671
+ if (disposal && typeof disposal.then === "function") {
5672
+ Promise.resolve(disposal).catch(() => {
5673
+ return;
5674
+ });
5675
+ }
5676
+ } catch {}
5677
+ }
5678
+
5556
5679
  // ../protocol/src/agent-platforms.ts
5557
5680
  var AGENT_PLATFORMS = Object.freeze([
5558
5681
  "claude",
@@ -5745,6 +5868,58 @@ var PROTECTED_SEGMENTS = new Set([
5745
5868
  ".mcp.json"
5746
5869
  ]);
5747
5870
 
5871
+ // ../protocol/src/agent-mail.ts
5872
+ var AGENT_MAIL_MAX_BODY_BYTES = 32 * 1024;
5873
+ var AGENT_MAIL_MAX_STORE_BYTES = 32 * 1024 * 1024;
5874
+ var AGENT_MAIL_DEFAULT_RETENTION_DAYS = 14;
5875
+ var AGENT_MAIL_MAX_ATTACHMENT_BYTES = 8 * 1024 * 1024;
5876
+ var AGENT_MAIL_MAX_TOTAL_ATTACHMENT_BYTES = 32 * 1024 * 1024;
5877
+ var AGENT_MAIL_DEFAULT_AUTONOMOUS_WAKE_BUDGET = 16;
5878
+ var AGENT_MAIL_DEFAULT_HOURLY_WAKE_LIMIT = 40;
5879
+ var AGENT_MAIL_TOOL_NAMES = Object.freeze([
5880
+ "list_mailboxes",
5881
+ "send_message",
5882
+ "check_inbox",
5883
+ "read_message",
5884
+ "ack_message",
5885
+ "reply_message",
5886
+ "get_message_status"
5887
+ ]);
5888
+ var DEFAULT_AGENT_MESSAGING_SETTINGS = Object.freeze({
5889
+ enabled: true,
5890
+ allowCrossProject: false,
5891
+ defaultInjectPolicy: "off",
5892
+ wakePeers: false,
5893
+ autonomousWakeBudget: AGENT_MAIL_DEFAULT_AUTONOMOUS_WAKE_BUDGET,
5894
+ hourlyWakeLimit: AGENT_MAIL_DEFAULT_HOURLY_WAKE_LIMIT,
5895
+ coordinatorStatusWakes: "settled",
5896
+ retentionDays: AGENT_MAIL_DEFAULT_RETENTION_DAYS,
5897
+ paused: false
5898
+ });
5899
+ function agentMailCapabilities(tabType, agent, locked = true) {
5900
+ if (tabType === "agent-native") {
5901
+ if (!locked || !agent)
5902
+ return { canPull: false, canSend: false, canInject: false };
5903
+ if (agent === "claude" || agent === "codex" || agent === "opencode" || agent === "pi" || agent === "cursor" || agent === "grok") {
5904
+ return { canPull: true, canSend: true, canInject: true };
5905
+ }
5906
+ return { canPull: false, canSend: false, canInject: false };
5907
+ }
5908
+ if (tabType === "claude-tmux")
5909
+ return { canPull: true, canSend: true, canInject: true };
5910
+ if (tabType === "pipeline-worker") {
5911
+ return agent ? { canPull: true, canSend: true, canInject: true } : { canPull: false, canSend: false, canInject: false };
5912
+ }
5913
+ if (["claude", "codex", "opencode"].includes(tabType)) {
5914
+ return { canPull: true, canSend: true, canInject: false };
5915
+ }
5916
+ if (["cursor", "grok", "pi"].includes(tabType)) {
5917
+ return { canPull: false, canSend: false, canInject: false };
5918
+ }
5919
+ return { canPull: false, canSend: false, canInject: false };
5920
+ }
5921
+ var NATIVE_AGENT_MAIL_CAPABILITIES = Object.freeze(Object.fromEntries(AGENT_PLATFORMS.map((agent) => [agent, agentMailCapabilities("agent-native", agent)])));
5922
+
5748
5923
  // ../protocol/src/review-evidence-frames.ts
5749
5924
  var COORDINATOR_WORKER_NO_PR_INSTRUCTION = "Do not open a pull request, even if the prompt below asks you to: commit your work and report back. Orkestrator raises the pull request from a PR tab once the work has been reviewed.";
5750
5925
  var COORDINATOR_WORKER_VALIDATION_INSTRUCTION = "Run the focused checks your changes need and report them. When the prompt below says review follows, leave the required full test suite, typecheck, lint and build passes to review preparation unless it explicitly asks you to run them. When no review follows or the prompt does not say, follow the repository's validation requirements before handoff. Report any required full validation you did not run; do not assume a later review will run it.";
@@ -5874,6 +6049,21 @@ var MCP_TOOL_ANNOTATION_KEYS = Object.freeze({
5874
6049
  idempotent: "idempotentHint",
5875
6050
  openWorld: "openWorldHint"
5876
6051
  });
6052
+ function toolHintsFrom(value, keyFor) {
6053
+ if (typeof value !== "object" || value === null || Array.isArray(value))
6054
+ return;
6055
+ const source = value;
6056
+ const hints = {};
6057
+ for (const key of TOOL_HINT_KEYS) {
6058
+ const declared = source[keyFor(key)];
6059
+ if (typeof declared === "boolean")
6060
+ hints[key] = declared;
6061
+ }
6062
+ return Object.keys(hints).length > 0 ? hints : undefined;
6063
+ }
6064
+ function parseAgentInteractionToolHints(value) {
6065
+ return toolHintsFrom(value, (key) => key);
6066
+ }
5877
6067
  var UNATTENDED_POLICY_INSTRUCTION = "This is a non-interactive build session: no user can answer a provider input request. " + "If input is unavailable or declined, choose the safest likely assumption yourself, " + "state that assumption, and continue. Never treat the absence of a person as authorization.";
5878
6068
  var INTERACTIVE_AGENT_INTERACTION_POLICY = Object.freeze({
5879
6069
  version: AGENT_INTERACTION_POLICY_VERSION,
@@ -6389,6 +6579,11 @@ var BACKGROUND_CAPABLE_SHELL_TOOL_NAMES = new Set([
6389
6579
  "run_terminal_cmd",
6390
6580
  "execute_command"
6391
6581
  ]);
6582
+ var NATIVE_AGENT_BRANCH_LIST_LIMITS = Object.freeze({
6583
+ branches: 50,
6584
+ promptChars: 280,
6585
+ entryIdChars: 512
6586
+ });
6392
6587
  var NATIVE_AGENT_COMMAND_EXECUTION_KINDS = [
6393
6588
  "provider-prompt",
6394
6589
  "provider-command",
@@ -6658,6 +6853,7 @@ function sessionHealth(session) {
6658
6853
  }
6659
6854
 
6660
6855
  // ../protocol/src/plan-usage.ts
6856
+ var PLAN_USAGE_DISPLAY_STALE_MS = 30 * 60000;
6661
6857
  var WEEK_MINUTES = 7 * 24 * 60;
6662
6858
  var CLAUDE_PLAN_WINDOW_LABELS = {
6663
6859
  five_hour: { label: "5-hour limit", windowMinutes: 300 },
@@ -6685,26 +6881,6 @@ function claudePlanWindowFromKind(kind, modelName) {
6685
6881
  }
6686
6882
  return;
6687
6883
  }
6688
- var LEGACY_CLAUDE_WINDOW_LABELS = {
6689
- "five hour": "five_hour",
6690
- session: "five_hour",
6691
- weekly: "seven_day",
6692
- "weekly all": "seven_day",
6693
- "weekly (oauth apps)": "seven_day_oauth_apps"
6694
- };
6695
- function claudePlanWindowFromLabel(label) {
6696
- const normalized = label.trim().toLowerCase();
6697
- const legacyId = LEGACY_CLAUDE_WINDOW_LABELS[normalized];
6698
- for (const [id, meta] of Object.entries(CLAUDE_PLAN_WINDOW_LABELS)) {
6699
- if (id === legacyId || meta.label.toLowerCase() === normalized)
6700
- return { id, ...meta };
6701
- }
6702
- const model = label.trim().match(/^weekly \((.+)\)$/i)?.[1] ?? label.trim().match(/^weekly (.+) limit$/i)?.[1];
6703
- if (!model)
6704
- return;
6705
- const known = Object.entries(CLAUDE_PLAN_WINDOW_LABELS).find(([id]) => id === `seven_day_${model.trim().toLowerCase()}`);
6706
- return known ? { id: known[0], ...known[1] } : claudeModelWeeklyWindow(model);
6707
- }
6708
6884
 
6709
6885
  // ../../bridges/claude-bridge/src/services/event-message-id.ts
6710
6886
  function eventMessageId(event) {
@@ -6886,8 +7062,18 @@ function revisedRowsReconciliationToken(overflowVersion, omitted) {
6886
7062
  }
6887
7063
 
6888
7064
  // ../../bridges/claude-bridge/src/services/session-preferences.ts
6889
- import { mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
6890
- import { join as join2 } from "node:path";
7065
+ import {
7066
+ link,
7067
+ mkdir,
7068
+ open,
7069
+ readFile,
7070
+ readdir,
7071
+ rename,
7072
+ rm,
7073
+ stat,
7074
+ writeFile
7075
+ } from "node:fs/promises";
7076
+ import { basename, dirname, join as join2 } from "node:path";
6891
7077
 
6892
7078
  // ../../bridges/claude-bridge/src/services/claude-home.ts
6893
7079
  import { homedir } from "node:os";
@@ -7147,6 +7333,41 @@ function lockMetadata() {
7147
7333
  const identity = currentProcessIdentity();
7148
7334
  return JSON.stringify({ token: crypto.randomUUID(), ...identity });
7149
7335
  }
7336
+ var beforeOwnedFilePublishForTesting = null;
7337
+ var LINK_UNSUPPORTED_CODES = new Set(["ENOTSUP", "EOPNOTSUPP", "ENOSYS", "EPERM"]);
7338
+ async function createOwnedFile(path) {
7339
+ const staging = `${path}.${crypto.randomUUID()}.owner`;
7340
+ const handle = await open(staging, "wx", 384);
7341
+ try {
7342
+ await handle.writeFile(lockMetadata());
7343
+ await beforeOwnedFilePublishForTesting?.();
7344
+ try {
7345
+ await link(staging, path);
7346
+ } catch (error) {
7347
+ if (!LINK_UNSUPPORTED_CODES.has(errorCode(error) ?? ""))
7348
+ throw error;
7349
+ await handle.close().catch(() => {});
7350
+ return await createOwnedFileInPlace(path);
7351
+ }
7352
+ return handle;
7353
+ } catch (error) {
7354
+ await handle.close().catch(() => {});
7355
+ throw error;
7356
+ } finally {
7357
+ await rm(staging, { force: true }).catch(() => {});
7358
+ }
7359
+ }
7360
+ async function createOwnedFileInPlace(path) {
7361
+ const handle = await open(path, "wx", 384);
7362
+ try {
7363
+ await handle.writeFile(lockMetadata());
7364
+ return handle;
7365
+ } catch (error) {
7366
+ await handle.close().catch(() => {});
7367
+ await rm(path, { force: true }).catch(() => {});
7368
+ throw error;
7369
+ }
7370
+ }
7150
7371
  function parseLockMetadata(raw) {
7151
7372
  try {
7152
7373
  const parsed = JSON.parse(raw);
@@ -7199,15 +7420,7 @@ async function recoverStaleLock(lockPath, candidate) {
7199
7420
  const recoveryPath = `${lockPath}.recover-${candidate.dev}-${candidate.ino}`;
7200
7421
  let recoveryHandle;
7201
7422
  try {
7202
- recoveryHandle = await open(recoveryPath, "wx", 384);
7203
- try {
7204
- await recoveryHandle.writeFile(lockMetadata());
7205
- } catch (error) {
7206
- await recoveryHandle.close().catch(() => {});
7207
- recoveryHandle = undefined;
7208
- await rm(recoveryPath, { force: true }).catch(() => {});
7209
- throw error;
7210
- }
7423
+ recoveryHandle = await createOwnedFile(recoveryPath);
7211
7424
  } catch (error) {
7212
7425
  if (errorCode(error) === "EEXIST") {
7213
7426
  const abandoned = await readLockSnapshot(recoveryPath);
@@ -7239,22 +7452,31 @@ async function recoverStaleLock(lockPath, candidate) {
7239
7452
  } catch {}
7240
7453
  }
7241
7454
  }
7455
+ async function reclaimOwnerStagingFiles(lockPath) {
7456
+ const directory = dirname(lockPath);
7457
+ const prefix = `${basename(lockPath)}.`;
7458
+ for (const name of await readdir(directory)) {
7459
+ if (!name.startsWith(prefix) || !/\.[0-9a-f-]{36}\.owner$/.test(name))
7460
+ continue;
7461
+ const path = join2(directory, name);
7462
+ const candidate = await readLockSnapshot(path);
7463
+ if (!candidate || !snapshotIsRecoverable(candidate))
7464
+ continue;
7465
+ const current = await readLockSnapshot(path);
7466
+ if (current && current.dev === candidate.dev && current.ino === candidate.ino && snapshotIsRecoverable(current)) {
7467
+ await rm(path, { force: true });
7468
+ }
7469
+ }
7470
+ }
7242
7471
  async function withPreferenceFileLock(path, operation) {
7243
7472
  await mkdir(claudeSessionPreferencesDir(), { recursive: true });
7244
7473
  const lockPath = `${path}.lock`;
7474
+ await reclaimOwnerStagingFiles(lockPath);
7245
7475
  const startedAt = Date.now();
7246
7476
  let handle;
7247
7477
  while (!handle) {
7248
7478
  try {
7249
- handle = await open(lockPath, "wx", 384);
7250
- try {
7251
- await handle.writeFile(lockMetadata());
7252
- } catch (error) {
7253
- await handle.close().catch(() => {});
7254
- handle = undefined;
7255
- await rm(lockPath, { force: true }).catch(() => {});
7256
- throw error;
7257
- }
7479
+ handle = await createOwnedFile(lockPath);
7258
7480
  } catch (error) {
7259
7481
  if (errorCode(error) !== "EEXIST")
7260
7482
  throw error;
@@ -7425,6 +7647,10 @@ async function readSessionPreferences(sdkSessionId) {
7425
7647
  return parsePreferences(raw) ?? unavailablePreferences();
7426
7648
  }
7427
7649
  async function writePreferencesFile(path, preferences) {
7650
+ if (Object.values(preferences).every((value) => value === undefined)) {
7651
+ await rm(path, { force: true });
7652
+ return;
7653
+ }
7428
7654
  await mkdir(claudeSessionPreferencesDir(), { recursive: true });
7429
7655
  const tempPath = `${path}.${process.pid}.tmp`;
7430
7656
  try {
@@ -7472,21 +7698,6 @@ async function updateSessionPreferences(sdkSessionId, update) {
7472
7698
  }).catch(() => {});
7473
7699
  return write;
7474
7700
  }
7475
- async function deleteSessionPreferences(sdkSessionId) {
7476
- const writeKey = normalizedSessionId(sdkSessionId);
7477
- const path = preferencesPath(sdkSessionId);
7478
- if (!writeKey || !path)
7479
- return;
7480
- const previous = pendingWrites.get(writeKey) ?? Promise.resolve();
7481
- const deletion = previous.catch(() => {}).then(() => withPreferenceFileLock(path, () => rm(path, { force: true })));
7482
- pendingWrites.set(writeKey, deletion);
7483
- deletion.finally(() => {
7484
- if (pendingWrites.get(writeKey) === deletion) {
7485
- pendingWrites.delete(writeKey);
7486
- }
7487
- }).catch(() => {});
7488
- return deletion;
7489
- }
7490
7701
 
7491
7702
  // ../../bridges/claude-bridge/src/services/session-manager-core.ts
7492
7703
  import { execFile } from "node:child_process";
@@ -7507,7 +7718,6 @@ var pendingPromptDispatchClaims = new Map;
7507
7718
  var IDLE_TRANSCRIPT_EVICTION_MS = 30 * 60 * 1000;
7508
7719
  var IDLE_TRANSCRIPT_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
7509
7720
  var STRUCTURED_USAGE_REQUEST_TIMEOUT_MS = 1000;
7510
- var PLAN_USAGE_PROBE_TIMEOUT_MS = 1e4;
7511
7721
 
7512
7722
  class StructuredUsageRequestTimeoutError extends Error {
7513
7723
  constructor(timeoutMs = STRUCTURED_USAGE_REQUEST_TIMEOUT_MS) {
@@ -7523,18 +7733,8 @@ class ContextUsageRequestTimeoutError extends Error {
7523
7733
  this.name = "ContextUsageRequestTimeoutError";
7524
7734
  }
7525
7735
  }
7526
- async function withControlRequestTimeout(request, timeoutMs, createTimeoutError) {
7527
- let timeout;
7528
- const timeoutPromise = new Promise((_, reject) => {
7529
- timeout = setTimeout(() => reject(createTimeoutError()), timeoutMs);
7530
- timeout.unref?.();
7531
- });
7532
- try {
7533
- return await Promise.race([request, timeoutPromise]);
7534
- } finally {
7535
- if (timeout)
7536
- clearTimeout(timeout);
7537
- }
7736
+ function withControlRequestTimeout(request, timeoutMs, createTimeoutError) {
7737
+ return boundedWaitOrThrow(request, timeoutMs, createTimeoutError);
7538
7738
  }
7539
7739
  function touchSession(session) {
7540
7740
  session.lastAccessedAt = Date.now();
@@ -8276,8 +8476,6 @@ async function persistedSessionExistsOnDisk(sdkSessionId) {
8276
8476
  return true;
8277
8477
  try {
8278
8478
  const sdk = await claudeSdk();
8279
- if (typeof sdk.getSessionInfo !== "function")
8280
- return true;
8281
8479
  const info = await sdk.getSessionInfo(sdkSessionId, {
8282
8480
  dir: currentWorkingDirectory()
8283
8481
  });
@@ -8311,8 +8509,6 @@ async function persistSessionTitle(session, title) {
8311
8509
  if (!session.sdkSessionId)
8312
8510
  return;
8313
8511
  const sdk = await claudeSdk();
8314
- if (typeof sdk.renameSession !== "function")
8315
- return;
8316
8512
  await sdk.renameSession(session.sdkSessionId, title, {
8317
8513
  dir: currentWorkingDirectory()
8318
8514
  });
@@ -8568,7 +8764,7 @@ function withReadOnlyGitConfig(turnPolicy, environment) {
8568
8764
  import { createHash as createHash4, randomBytes } from "node:crypto";
8569
8765
  import {
8570
8766
  mkdir as mkdir2,
8571
- readdir,
8767
+ readdir as readdir2,
8572
8768
  readFile as readFile3,
8573
8769
  realpath,
8574
8770
  rename as rename2,
@@ -8739,7 +8935,7 @@ async function mirrorSkillSource(source, root) {
8739
8935
  return { path, names: skills.map((skill) => skill.name) };
8740
8936
  }
8741
8937
  async function readSkills(dir) {
8742
- const entries = (await readdir(dir)).filter((name) => !name.startsWith(".")).sort();
8938
+ const entries = (await readdir2(dir)).filter((name) => !name.startsWith(".")).sort();
8743
8939
  const skills = [];
8744
8940
  const names = new Set;
8745
8941
  for (const entry of entries) {
@@ -8761,7 +8957,7 @@ async function readSkills(dir) {
8761
8957
  return skills;
8762
8958
  }
8763
8959
  async function readSkill(skillDir, dirName) {
8764
- const entries = await readdir(skillDir);
8960
+ const entries = await readdir2(skillDir);
8765
8961
  const skillFile = entries.find((entry) => entry === "SKILL.md");
8766
8962
  if (!skillFile)
8767
8963
  return;
@@ -8862,7 +9058,7 @@ async function writeMirror(root, path, plugin, skills) {
8862
9058
  }
8863
9059
  async function pruneOldMirrors(root, plugin, current) {
8864
9060
  try {
8865
- const old = await Promise.all((await readdir(root)).filter((name) => name.startsWith(`${plugin}-`) && join3(root, name) !== current).map(async (name) => ({
9061
+ const old = await Promise.all((await readdir2(root)).filter((name) => name.startsWith(`${plugin}-`) && join3(root, name) !== current).map(async (name) => ({
8866
9062
  path: join3(root, name),
8867
9063
  mtimeMs: (await stat2(join3(root, name)).catch(() => {
8868
9064
  return;
@@ -8876,7 +9072,7 @@ async function pruneOldMirrors(root, plugin, current) {
8876
9072
  }
8877
9073
 
8878
9074
  // ../../bridges/claude-bridge/src/services/plugin-config.ts
8879
- import { readdir as readdir2, access } from "node:fs/promises";
9075
+ import { readdir as readdir3, access } from "node:fs/promises";
8880
9076
  import { join as join4 } from "node:path";
8881
9077
 
8882
9078
  // ../protocol/src/node/claude-plugin-set.ts
@@ -9084,7 +9280,7 @@ async function scanCliPluginsDirectory(pluginsDir) {
9084
9280
  return [];
9085
9281
  }
9086
9282
  try {
9087
- const entries = await readdir2(pluginsDir, { withFileTypes: true });
9283
+ const entries = await readdir3(pluginsDir, { withFileTypes: true });
9088
9284
  const plugins = [];
9089
9285
  for (const entry of entries) {
9090
9286
  if (!entry.isDirectory()) {
@@ -9326,7 +9522,7 @@ import { join as join6 } from "node:path";
9326
9522
  // ../protocol/src/node/coordinator-read-boundary.ts
9327
9523
  import { realpathSync } from "node:fs";
9328
9524
  import { homedir as homedir2 } from "node:os";
9329
- import { dirname, isAbsolute as isAbsolute2, join as join5, parse, resolve as resolve2, sep } from "node:path";
9525
+ import { dirname as dirname2, isAbsolute as isAbsolute2, join as join5, parse, resolve as resolve2, sep } from "node:path";
9330
9526
  function canonicalPath(path) {
9331
9527
  let existing = path;
9332
9528
  const tail = [];
@@ -9334,7 +9530,7 @@ function canonicalPath(path) {
9334
9530
  try {
9335
9531
  return join5(realpathSync.native(existing), ...tail.reverse());
9336
9532
  } catch {
9337
- const parent = dirname(existing);
9533
+ const parent = dirname2(existing);
9338
9534
  if (parent === existing)
9339
9535
  return path;
9340
9536
  tail.push(existing.slice(parent.length).replace(/^[/\\]+/, ""));
@@ -10143,17 +10339,22 @@ function probeDetail(stderr) {
10143
10339
  `).map((entry) => entry.trim()).find(Boolean) ?? "no error output";
10144
10340
  return line.length > 200 ? `${line.slice(0, 199)}…` : line;
10145
10341
  }
10146
- var UNAVAILABLE = "Claude's command sandbox cannot run commands on this host";
10342
+ function runningInContainer() {
10343
+ return existsSync("/.dockerenv") || existsSync("/run/.containerenv");
10344
+ }
10147
10345
  function probeClaudeLinuxSandbox(dependencies = {}) {
10148
10346
  const onPath = dependencies.onPath ?? ((name) => executableOnPath(name));
10149
10347
  const run = dependencies.run ?? runProbeCommand;
10150
10348
  const appArmorBwrapProfile = dependencies.appArmorBwrapProfile ?? appArmorBwrapProfileInstalled;
10349
+ const container = (dependencies.inContainer ?? runningInContainer)();
10350
+ const UNAVAILABLE = `Claude's command sandbox cannot run commands ${container ? "in this container" : "on this host"}`;
10151
10351
  const missing = CLAUDE_LINUX_SANDBOX_PROGRAMS.filter((name) => !onPath(name));
10152
10352
  if (missing.length > 0) {
10353
+ const absent = `${missing.join(" and ")} ${missing.length === 1 ? "is" : "are"}`;
10153
10354
  return {
10154
10355
  available: false,
10155
10356
  failure: "missing-programs",
10156
- reason: `${UNAVAILABLE}: the Claude CLI's Linux sandbox needs bubblewrap and socat on PATH, and ${missing.join(" and ")} ${missing.length === 1 ? "is" : "are"} missing. Install the bubblewrap and socat packages.`
10357
+ reason: container ? `${UNAVAILABLE}: the Claude CLI's Linux sandbox needs bubblewrap and socat on PATH, and ${absent} not in this container's image.` : `${UNAVAILABLE}: the Claude CLI's Linux sandbox needs bubblewrap and socat on PATH, and ${absent} missing. Install the bubblewrap and socat packages.`
10157
10358
  };
10158
10359
  }
10159
10360
  if (!onPath("unshare")) {
@@ -12719,13 +12920,18 @@ async function assertClaudeRuntimeAccepts(session, options, resources, readOnlyC
12719
12920
  }
12720
12921
  var MAX_RUNTIME_TOOL_OWNERS = 4096;
12721
12922
  var DRAINING_RUNTIME_EXIT_WAIT_MS = 5000;
12923
+ var lastClaudeRuntimeGeneration = 0;
12722
12924
  function createClaudeRuntime(input) {
12723
12925
  let markEnded;
12724
12926
  const ended = new Promise((resolve) => {
12725
12927
  markEnded = resolve;
12726
12928
  });
12929
+ lastClaudeRuntimeGeneration += 1;
12930
+ const generation = lastClaudeRuntimeGeneration;
12931
+ input.session.claudeRuntimeGeneration = generation;
12727
12932
  const runtime = {
12728
12933
  session: input.session,
12934
+ generation,
12729
12935
  control: input.control,
12730
12936
  input: input.heldInput,
12731
12937
  abortController: input.abortController,
@@ -12838,20 +13044,7 @@ async function retireDrainingClaudeRuntime(session, waitMs = DRAINING_RUNTIME_EX
12838
13044
  return;
12839
13045
  if (runtime.state === "open")
12840
13046
  drainClaudeRuntime(runtime);
12841
- const waitForEnd = async () => {
12842
- let timer;
12843
- try {
12844
- return await Promise.race([
12845
- runtime.ended.then(() => true),
12846
- new Promise((resolve) => {
12847
- timer = setTimeout(() => resolve(false), waitMs);
12848
- timer.unref?.();
12849
- })
12850
- ]);
12851
- } finally {
12852
- clearTimeout(timer);
12853
- }
12854
- };
13047
+ const waitForEnd = async () => (await boundedWait(runtime.ended, waitMs)).settled;
12855
13048
  if (await waitForEnd())
12856
13049
  return;
12857
13050
  try {
@@ -12919,7 +13112,7 @@ import { isAbsolute as isAbsolute4, join as join12, relative, resolve as resolve
12919
13112
 
12920
13113
  // ../protocol/src/node/command-change-journal.ts
12921
13114
  import { appendFile, mkdir as mkdir3, readFile as readFile5, rename as rename3, rm as rm3, stat as stat4, writeFile as writeFile3 } from "node:fs/promises";
12922
- import { dirname as dirname2 } from "node:path";
13115
+ import { dirname as dirname3 } from "node:path";
12923
13116
  var MAX_JOURNAL_ENTRIES = 1000;
12924
13117
  var MAX_JOURNAL_FILES_PER_ENTRY = 20;
12925
13118
  var MAX_JOURNAL_PATH_LENGTH = 1024;
@@ -12992,7 +13185,7 @@ class CommandChangeJournal {
12992
13185
  const line = `${JSON.stringify({ id, change: bounded })}
12993
13186
  `;
12994
13187
  this.writes = this.writes.then(async () => {
12995
- await mkdir3(dirname2(this.path), { recursive: true, mode: 448 });
13188
+ await mkdir3(dirname3(this.path), { recursive: true, mode: 448 });
12996
13189
  if (!this.sizeChecked) {
12997
13190
  this.sizeChecked = true;
12998
13191
  const existing = await stat4(this.path).catch(() => {
@@ -15852,11 +16045,6 @@ function commandChangeJournal(sdkSessionId) {
15852
16045
  }
15853
16046
  return journal;
15854
16047
  }
15855
- async function deleteCommandChangeJournal(sdkSessionId) {
15856
- const journal = commandChangeJournal(sdkSessionId);
15857
- journals.delete(sdkSessionId);
15858
- await journal?.remove();
15859
- }
15860
16048
  function isMeasuredCommand(toolName, toolInput) {
15861
16049
  if (toolName !== "Bash")
15862
16050
  return false;
@@ -16036,9 +16224,6 @@ function labelSubagentModel(row, parent, records) {
16036
16224
  }
16037
16225
  }
16038
16226
  async function rehydrateSubagentParts(sdk, sdkSessionId, dir, messages) {
16039
- if (typeof sdk.listSubagents !== "function" || typeof sdk.getSubagentMessages !== "function") {
16040
- return;
16041
- }
16042
16227
  const agentIds = (await sdk.listSubagents(sdkSessionId, { dir }).catch(() => [])).slice(0, MAX_REHYDRATED_SUBAGENTS);
16043
16228
  if (agentIds.length === 0)
16044
16229
  return;
@@ -16101,19 +16286,7 @@ function applyLocalTranscriptOverlay(session) {
16101
16286
  markTranscriptChanged(session);
16102
16287
  }
16103
16288
  var sessionDeletionTick = 0;
16104
- var DELETE_TOMBSTONE_LIMIT = 128;
16105
16289
  var deletedSdkSessionTicks = new Map;
16106
- function recordDeletedSdkSession(sdkSessionId) {
16107
- sessionDeletionTick += 1;
16108
- deletedSdkSessionTicks.delete(sdkSessionId);
16109
- deletedSdkSessionTicks.set(sdkSessionId, sessionDeletionTick);
16110
- while (deletedSdkSessionTicks.size > DELETE_TOMBSTONE_LIMIT) {
16111
- const oldest = deletedSdkSessionTicks.keys().next();
16112
- if (oldest.done)
16113
- break;
16114
- deletedSdkSessionTicks.delete(oldest.value);
16115
- }
16116
- }
16117
16290
  function deletedSinceTick(sdkSessionId, readTick) {
16118
16291
  const deletedAt = deletedSdkSessionTicks.get(sdkSessionId);
16119
16292
  return deletedAt !== undefined && deletedAt > readTick;
@@ -16127,8 +16300,6 @@ function isDefaultSessionTitle(title, bridgeId, sdkId) {
16127
16300
  }
16128
16301
  async function reconcilePersistedSessions() {
16129
16302
  const sdk = await claudeSdk();
16130
- if (typeof sdk.listSessions !== "function")
16131
- return;
16132
16303
  const cwd = currentWorkingDirectory();
16133
16304
  const listStartedAtTick = sessionDeletionTick;
16134
16305
  const infos = await sdk.listSessions({
@@ -16192,8 +16363,6 @@ async function materializePersistedSessionState(sessionId, sdkId) {
16192
16363
  const racedDuringImport = sessions.get(sessionId);
16193
16364
  if (racedDuringImport)
16194
16365
  return racedDuringImport;
16195
- if (typeof sdk.getSessionInfo !== "function")
16196
- return;
16197
16366
  const [info, preferences] = await Promise.all([
16198
16367
  sdk.getSessionInfo(sdkId, {
16199
16368
  dir: currentWorkingDirectory()
@@ -16256,8 +16425,6 @@ async function readPersistedSessionMessages(session) {
16256
16425
  if (!session.sdkSessionId)
16257
16426
  return;
16258
16427
  const sdk = await claudeSdk();
16259
- if (typeof sdk.getSessionMessages !== "function")
16260
- return;
16261
16428
  const [persisted, commandChanges, preferences] = await Promise.all([
16262
16429
  sdk.getSessionMessages(session.sdkSessionId, {
16263
16430
  dir: currentWorkingDirectory(),
@@ -16407,60 +16574,6 @@ function startIdleTranscriptSweep(intervalMs = IDLE_TRANSCRIPT_SWEEP_INTERVAL_MS
16407
16574
  return timer;
16408
16575
  }
16409
16576
  startIdleTranscriptSweep();
16410
- async function deleteSessionDurably(sessionId) {
16411
- const session = sessions.get(sessionId) ?? await ensurePersistedSession(sessionId);
16412
- if (!session) {
16413
- const sdkSessionId = sdkSessionIdFromBridgeId(sessionId);
16414
- if (sdkSessionId) {
16415
- await deleteSessionPreferences(sdkSessionId);
16416
- await deleteCommandChangeJournal(sdkSessionId);
16417
- }
16418
- return false;
16419
- }
16420
- if (session.deleting) {
16421
- throw sessionOperationError("conflict", "Session deletion is already in progress");
16422
- }
16423
- session.deleting = true;
16424
- session.status = "running";
16425
- claimedPromptDispatches.delete(sessionId);
16426
- session.abortController?.abort();
16427
- session.abortController = undefined;
16428
- cleanupPendingInteractions(sessionId);
16429
- await releaseQueryControls(session);
16430
- await waitForPendingPromptDispatchClaim(sessionId);
16431
- let rolloutDeleted = false;
16432
- try {
16433
- const preferenceSessionId = session.sdkSessionId ?? sdkSessionIdFromBridgeId(session.id);
16434
- if (session.sdkSessionId) {
16435
- const sdk = await claudeSdk();
16436
- if (typeof sdk.deleteSession === "function") {
16437
- await sdk.deleteSession(session.sdkSessionId, {
16438
- dir: currentWorkingDirectory()
16439
- });
16440
- }
16441
- rolloutDeleted = true;
16442
- recordDeletedSdkSession(session.sdkSessionId);
16443
- }
16444
- forgetPromptDispatchesForSession(sessionId);
16445
- if (preferenceSessionId) {
16446
- await deleteSessionPreferences(preferenceSessionId);
16447
- await deleteCommandChangeJournal(preferenceSessionId);
16448
- }
16449
- sessions.delete(sessionId);
16450
- return true;
16451
- } catch (error) {
16452
- if (rolloutDeleted && session.sdkSessionId) {
16453
- recordDeletedSdkSession(session.sdkSessionId);
16454
- sessions.delete(sessionId);
16455
- throw error;
16456
- }
16457
- session.deleting = false;
16458
- session.status = "idle";
16459
- session.turnStartedAt = undefined;
16460
- session.completionBlockedByBackgroundTasks = false;
16461
- throw error;
16462
- }
16463
- }
16464
16577
  async function renameSessionDurably(sessionId, title) {
16465
16578
  const session = await ensurePersistedSession(sessionId);
16466
16579
  if (!session)
@@ -16484,9 +16597,6 @@ async function forkPersistedSession(sessionId, options = {}) {
16484
16597
  throw sessionOperationError("conflict", "Cannot fork a running session");
16485
16598
  }
16486
16599
  const sdk = await claudeSdk();
16487
- if (typeof sdk.forkSession !== "function") {
16488
- throw sessionOperationError("conflict", "Installed Claude Agent SDK does not support session forking");
16489
- }
16490
16600
  const boundaryId = options.upToMessageId ? await resolvePersistedMessageId(source, options.upToMessageId) : undefined;
16491
16601
  if (options.upToMessageId && !boundaryId) {
16492
16602
  throw sessionOperationError("invalid", "The selected Claude message is not a persisted fork boundary");
@@ -16521,8 +16631,6 @@ async function resolvePersistedMessageId(session, normalizedMessageId, allowedTy
16521
16631
  if (local && !allowedTypes.has(local.role))
16522
16632
  return;
16523
16633
  const sdk = await claudeSdk();
16524
- if (typeof sdk.getSessionMessages !== "function")
16525
- return candidate;
16526
16634
  const persisted = await sdk.getSessionMessages(session.sdkSessionId, {
16527
16635
  dir: currentWorkingDirectory(),
16528
16636
  includeSystemMessages: false
@@ -16538,19 +16646,11 @@ async function closeTransientRewindQuery(control, onShutdown) {
16538
16646
  await control.return();
16539
16647
  onShutdown();
16540
16648
  });
16541
- let shutdownTimeout;
16542
16649
  try {
16543
- await Promise.race([
16544
- shutdown,
16545
- new Promise((_, reject) => {
16546
- shutdownTimeout = setTimeout(() => reject(new Error("shutdown pending")), REWIND_SHUTDOWN_TIMEOUT_MS);
16547
- })
16548
- ]);
16650
+ await boundedWaitOrThrow(shutdown, REWIND_SHUTDOWN_TIMEOUT_MS, () => new Error("shutdown pending"));
16549
16651
  } catch (error) {
16550
16652
  debugLog("[session-manager] Failed to confirm rewind query shutdown:", error);
16551
16653
  throw sessionOperationError("conflict", "Claude file rewind shutdown is pending; retry after it stops");
16552
- } finally {
16553
- clearTimeout(shutdownTimeout);
16554
16654
  }
16555
16655
  }
16556
16656
  async function rewindViaTransientQuery(sdkSessionId, persistedMessageId, dryRun, onShutdown = () => {
@@ -17470,6 +17570,29 @@ class PromptStream {
17470
17570
  }
17471
17571
  }
17472
17572
 
17573
+ // ../protocol/src/agent-usage-limits.ts
17574
+ var USAGE_LIMIT_PATTERNS = [
17575
+ /usage[\s_-]?limit/i,
17576
+ /hit your (?:usage |session |weekly )?limit/i,
17577
+ /\b(?:5|five)[\s-]?hour limit\b/i,
17578
+ /\bweekly limit\b/i,
17579
+ /\b(?:usage|quota|credits?|allowance) (?:is |has been )?(?:exhausted|exceeded|used up)\b/i,
17580
+ /\bquota exceeded\b|\binsufficient_quota\b|\bout of (?:credits|usage)\b/i,
17581
+ /\bUSAGE_EXHAUSTED\b|\bPAYMENT_REQUIRED\b/,
17582
+ /\b(?:usage|plan|session|daily|weekly|monthly|go) limit reached\b/i
17583
+ ];
17584
+ function classifyUsageLimitError(text) {
17585
+ if (typeof text !== "string" || !text.trim())
17586
+ return null;
17587
+ const bounded = text.slice(0, 2000);
17588
+ if (!USAGE_LIMIT_PATTERNS.some((pattern) => pattern.test(bounded)))
17589
+ return null;
17590
+ const reset = bounded.match(/\b(?:resets?|try again)(?:\s+(?:at|in|after))?\s+([^.\n·]{1,60})/i);
17591
+ const hint = reset?.[1]?.trim();
17592
+ return hint ? { resetHint: hint } : {};
17593
+ }
17594
+ var USAGE_LIMIT_ERROR_CODE = "usage-limit";
17595
+
17473
17596
  // ../protocol/src/structured-output-text.ts
17474
17597
  var STRUCTURED_OUTPUT_RECOVERY_CHARS = 1024 * 1024;
17475
17598
  var THINKING_TAGS = "thinking|thought|reasoning|think";
@@ -17780,6 +17903,27 @@ function diagnosticErrorClass(error) {
17780
17903
  return "Error";
17781
17904
  }
17782
17905
  }
17906
+ function isUsageLimitError(error) {
17907
+ try {
17908
+ const text = error instanceof Error ? error.message : error;
17909
+ return classifyUsageLimitError(text) !== null;
17910
+ } catch {
17911
+ return false;
17912
+ }
17913
+ }
17914
+ var USAGE_LIMITED_ERROR_PROPERTY = "usageLimited";
17915
+ function markUsageLimitError(error) {
17916
+ if (typeof error !== "object" && typeof error !== "function" || error === null)
17917
+ return;
17918
+ try {
17919
+ Object.defineProperty(error, USAGE_LIMITED_ERROR_PROPERTY, {
17920
+ value: true,
17921
+ configurable: true,
17922
+ enumerable: false,
17923
+ writable: false
17924
+ });
17925
+ } catch {}
17926
+ }
17783
17927
  function ownsActiveTurn(turn) {
17784
17928
  const { session, sessionId } = turn;
17785
17929
  return !turn.abortController.signal.aborted && sessions.get(sessionId) === session && session.abortController === turn.abortController;
@@ -18308,58 +18452,6 @@ import { query as query2 } from "@anthropic-ai/claude-agent-sdk";
18308
18452
  import { createHash as createHash9 } from "node:crypto";
18309
18453
  import { join as join13 } from "node:path";
18310
18454
 
18311
- // ../protocol/src/agent-mail.ts
18312
- var AGENT_MAIL_MAX_BODY_BYTES = 32 * 1024;
18313
- var AGENT_MAIL_MAX_STORE_BYTES = 32 * 1024 * 1024;
18314
- var AGENT_MAIL_DEFAULT_RETENTION_DAYS = 14;
18315
- var AGENT_MAIL_MAX_ATTACHMENT_BYTES = 8 * 1024 * 1024;
18316
- var AGENT_MAIL_MAX_TOTAL_ATTACHMENT_BYTES = 32 * 1024 * 1024;
18317
- var AGENT_MAIL_DEFAULT_AUTONOMOUS_WAKE_BUDGET = 16;
18318
- var AGENT_MAIL_DEFAULT_HOURLY_WAKE_LIMIT = 40;
18319
- var AGENT_MAIL_TOOL_NAMES = Object.freeze([
18320
- "list_mailboxes",
18321
- "send_message",
18322
- "check_inbox",
18323
- "read_message",
18324
- "ack_message",
18325
- "reply_message",
18326
- "get_message_status"
18327
- ]);
18328
- var DEFAULT_AGENT_MESSAGING_SETTINGS = Object.freeze({
18329
- enabled: true,
18330
- allowCrossProject: false,
18331
- defaultInjectPolicy: "off",
18332
- wakePeers: false,
18333
- autonomousWakeBudget: AGENT_MAIL_DEFAULT_AUTONOMOUS_WAKE_BUDGET,
18334
- hourlyWakeLimit: AGENT_MAIL_DEFAULT_HOURLY_WAKE_LIMIT,
18335
- coordinatorStatusWakes: "settled",
18336
- retentionDays: AGENT_MAIL_DEFAULT_RETENTION_DAYS,
18337
- paused: false
18338
- });
18339
- function agentMailCapabilities(tabType, agent, locked = true) {
18340
- if (tabType === "agent-native") {
18341
- if (!locked || !agent)
18342
- return { canPull: false, canSend: false, canInject: false };
18343
- if (agent === "claude" || agent === "codex" || agent === "opencode" || agent === "pi" || agent === "cursor" || agent === "grok") {
18344
- return { canPull: true, canSend: true, canInject: true };
18345
- }
18346
- return { canPull: false, canSend: false, canInject: false };
18347
- }
18348
- if (tabType === "claude-tmux")
18349
- return { canPull: true, canSend: true, canInject: true };
18350
- if (tabType === "pipeline-worker") {
18351
- return agent ? { canPull: true, canSend: true, canInject: true } : { canPull: false, canSend: false, canInject: false };
18352
- }
18353
- if (["claude", "codex", "opencode"].includes(tabType)) {
18354
- return { canPull: true, canSend: true, canInject: false };
18355
- }
18356
- if (["cursor", "grok", "pi"].includes(tabType)) {
18357
- return { canPull: false, canSend: false, canInject: false };
18358
- }
18359
- return { canPull: false, canSend: false, canInject: false };
18360
- }
18361
- var NATIVE_AGENT_MAIL_CAPABILITIES = Object.freeze(Object.fromEntries(AGENT_PLATFORMS.map((agent) => [agent, agentMailCapabilities("agent-native", agent)])));
18362
-
18363
18455
  // ../protocol/src/transcript-artifacts.ts
18364
18456
  var ARTIFACT_TOOL_NAMES = Object.freeze([
18365
18457
  "create_artifact",
@@ -18502,13 +18594,6 @@ async function getMcpServerInfo(cwd) {
18502
18594
  function sourceDigest(digest) {
18503
18595
  return digest === null ? "absent" : `sha256:${digest}`;
18504
18596
  }
18505
- function normalizeScope(scope) {
18506
- if (scope === true)
18507
- return "all";
18508
- if (scope === false)
18509
- return "user";
18510
- return scope;
18511
- }
18512
18597
  function mcpSourceScopeForPolicy(policy) {
18513
18598
  if (isCoordinatorReadOnlyPolicy(policy)) {
18514
18599
  return (nativeAgentUserMcpGrant(policy)?.length ?? 0) > 0 ? "user" : "none";
@@ -18580,7 +18665,7 @@ function revisionFingerprint(sources) {
18580
18665
  return createHash9("sha256").update(`user=${sources.user}\x00project=${sources.project}`).digest("base64url");
18581
18666
  }
18582
18667
  async function getMcpRuntimeConfig(cwd, env = process.env, connection, sources = "all", allowConfigured) {
18583
- const scoped = await loadScopedMcpServers(cwd, normalizeScope(sources));
18668
+ const scoped = await loadScopedMcpServers(cwd, sources);
18584
18669
  const { revision } = scoped;
18585
18670
  const configs = allowConfigured ? Object.fromEntries(Object.entries(scoped.configs).filter(([name]) => allowConfigured(name))) : scoped.configs;
18586
18671
  const servers = toSdkServers(configs);
@@ -18605,7 +18690,7 @@ async function getMcpRuntimeConfig(cwd, env = process.env, connection, sources =
18605
18690
  delete servers[ORKESTRATOR_ARTIFACT_MCP_SERVER_NAME];
18606
18691
  layers.delete(ORKESTRATOR_ARTIFACT_MCP_SERVER_NAME);
18607
18692
  }
18608
- const research = normalizeScope(sources) === "none" ? coordinatorResearchMcpServersFromEnv(env) : [];
18693
+ const research = sources === "none" ? coordinatorResearchMcpServersFromEnv(env) : [];
18609
18694
  for (const server of research)
18610
18695
  servers[server.name] = { type: "http", url: server.url };
18611
18696
  return {
@@ -18657,27 +18742,15 @@ function liveClaudeControls() {
18657
18742
  }
18658
18743
  async function readFromLiveClaude(read, timeoutMs = LIVE_CLAUDE_READ_TIMEOUT_MS) {
18659
18744
  for (const control of liveClaudeControls()) {
18660
- let timer;
18661
18745
  try {
18662
18746
  const answer = read(control);
18663
18747
  if (answer === undefined)
18664
18748
  continue;
18665
- answer.catch(() => {
18666
- return;
18667
- });
18668
- const value = await Promise.race([
18669
- answer,
18670
- new Promise((resolve) => {
18671
- timer = setTimeout(() => resolve(undefined), timeoutMs);
18672
- timer.unref?.();
18673
- })
18674
- ]);
18675
- if (value !== undefined)
18676
- return value;
18749
+ const outcome = await boundedWait(answer, timeoutMs);
18750
+ if (outcome.settled && outcome.value !== undefined)
18751
+ return outcome.value;
18677
18752
  } catch (error) {
18678
18753
  debugLog("[live-claude-control] A running CLI could not answer:", error);
18679
- } finally {
18680
- clearTimeout(timer);
18681
18754
  }
18682
18755
  }
18683
18756
  return;
@@ -18977,7 +19050,6 @@ function fallbackCatalog() {
18977
19050
  }
18978
19051
  async function probeModels(at) {
18979
19052
  let q;
18980
- let timer;
18981
19053
  try {
18982
19054
  const cwd = process.env.CWD || process.cwd();
18983
19055
  debugLog("[session-manager] Fetching supported models", { cwd });
@@ -18996,13 +19068,7 @@ async function probeModels(at) {
18996
19068
  answer.catch(() => {
18997
19069
  return;
18998
19070
  });
18999
- const [models, account] = await Promise.race([
19000
- answer,
19001
- new Promise((_resolve, reject) => {
19002
- timer = setTimeout(() => reject(new Error("The model probe did not answer in time")), CLAUDE_MODEL_PROBE_TIMEOUT_MS);
19003
- timer.unref?.();
19004
- })
19005
- ]);
19071
+ const [models, account] = await boundedWaitOrThrow(answer, CLAUDE_MODEL_PROBE_TIMEOUT_MS, () => new Error("The model probe did not answer in time"));
19006
19072
  debugLog("[session-manager] Supported models fetched", { count: models.length });
19007
19073
  await rememberModels(models, account, at);
19008
19074
  return { source: "sdk", models: catalogModels(models) };
@@ -19010,7 +19076,6 @@ async function probeModels(at) {
19010
19076
  log11.warn("models.fetch-failed", { error: formatLogError(error) });
19011
19077
  return fallbackCatalog();
19012
19078
  } finally {
19013
- clearTimeout(timer);
19014
19079
  if (q?.return) {
19015
19080
  try {
19016
19081
  await q.return();
@@ -19719,44 +19784,6 @@ async function performSessionMcpAction(sessionId, serverId, action) {
19719
19784
  });
19720
19785
  }
19721
19786
  }
19722
- function claudeWindowId(label) {
19723
- const known = claudePlanWindowFromLabel(label);
19724
- if (known)
19725
- return known.id;
19726
- const slug = label.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
19727
- return slug || "window";
19728
- }
19729
- async function planUsageFrom(control) {
19730
- const getStructuredUsage = control.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET;
19731
- if (!getStructuredUsage) {
19732
- throw new Error("Claude's plan usage API is unavailable in this CLI version");
19733
- }
19734
- const structuredUsage = await getStructuredUsageWithTimeout(getStructuredUsage, control, PLAN_USAGE_PROBE_TIMEOUT_MS);
19735
- return rateLimitsFromStructuredUsage(structuredUsage);
19736
- }
19737
- async function readClaudePlanUsage() {
19738
- let rateLimits = await readFromLiveClaude((control) => control.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET ? planUsageFrom(control) : undefined, PLAN_USAGE_PROBE_TIMEOUT_MS);
19739
- let probe;
19740
- try {
19741
- if (rateLimits === undefined) {
19742
- probe = createProbe();
19743
- rateLimits = await planUsageFrom(probe);
19744
- }
19745
- if (rateLimits === undefined) {
19746
- throw new Error("Claude did not report plan usage");
19747
- }
19748
- return rateLimits.map((window) => ({
19749
- window: claudeWindowId(window.label),
19750
- label: window.label,
19751
- ...window.usedPercent !== undefined ? { usedPercent: window.usedPercent } : {},
19752
- ...window.resetsAt !== undefined ? { resetsAt: window.resetsAt } : {}
19753
- }));
19754
- } finally {
19755
- await Promise.resolve(probe?.close()).catch(() => {
19756
- return;
19757
- });
19758
- }
19759
- }
19760
19787
  async function steerClaudeSession(sessionId, text, requestId, expectedRunId) {
19761
19788
  const capacityRefusal = {
19762
19789
  outcome: "rejected",
@@ -20181,7 +20208,6 @@ async function probeCommands(session, force) {
20181
20208
  async function runDiscoveryProbe(config) {
20182
20209
  const env = await runtimeEnvironmentForAgentQuery();
20183
20210
  let probe;
20184
- let timer;
20185
20211
  try {
20186
20212
  probe = controlOnlyQuery({
20187
20213
  cwd: config.cwd,
@@ -20195,18 +20221,12 @@ async function runDiscoveryProbe(config) {
20195
20221
  const version = typeof probe.initializationResult === "function" ? probe.initializationResult().then((result) => result?.claude_code_version).catch(() => {
20196
20222
  return;
20197
20223
  }) : Promise.resolve(undefined);
20198
- const timeout = new Promise((_, reject) => {
20199
- timer = setTimeout(() => reject(new Error("Claude command discovery timed out")), COMMAND_PROBE_TIMEOUT_MS);
20200
- timer.unref?.();
20201
- });
20202
20224
  read.catch(() => {
20203
20225
  return;
20204
20226
  });
20205
- const [commands, cliVersion] = await Promise.race([Promise.all([read, version]), timeout]);
20227
+ const [commands, cliVersion] = await boundedWaitOrThrow(Promise.all([read, version]), COMMAND_PROBE_TIMEOUT_MS, () => new Error("Claude command discovery timed out"));
20206
20228
  return { commands: sdkRows(commands), ...cliVersion ? { cliVersion } : {} };
20207
20229
  } finally {
20208
- if (timer)
20209
- clearTimeout(timer);
20210
20230
  await Promise.resolve(probe?.close()).catch(() => {
20211
20231
  return;
20212
20232
  });
@@ -21650,7 +21670,7 @@ function webFetchHost(input) {
21650
21670
  return;
21651
21671
  }
21652
21672
  }
21653
- async function requestClaudeToolApproval(sessionId, toolName, input, permissionContext) {
21673
+ async function requestClaudeToolApproval(sessionId, toolName, input, permissionContext, toolHints) {
21654
21674
  const now = Date.now();
21655
21675
  const path = bounded2(input.file_path ?? input.notebook_path);
21656
21676
  const command = bounded2(input.command);
@@ -21703,6 +21723,7 @@ async function requestClaudeToolApproval(sessionId, toolName, input, permissionC
21703
21723
  ...networkHost ? { networkHost } : {},
21704
21724
  ...ruleEligible ? { ruleEligible: true } : {},
21705
21725
  ...humanRequired ? { humanRequired: true } : {},
21726
+ ...toolHints && mcpServer && toolName.startsWith("mcp__") ? { toolHints } : {},
21706
21727
  ...proposedCommandPrefix ? { proposedCommandPrefix } : {}
21707
21728
  };
21708
21729
  const outcome = await parkInteraction(request, permissionContext?.signal);
@@ -22613,29 +22634,6 @@ var LEAF_MESSAGE_HANDLERS = {
22613
22634
  conversation_reset: handleConversationReset
22614
22635
  };
22615
22636
 
22616
- // ../protocol/src/agent-usage-limits.ts
22617
- var USAGE_LIMIT_PATTERNS = [
22618
- /usage[\s_-]?limit/i,
22619
- /hit your (?:usage |session |weekly )?limit/i,
22620
- /\b(?:5|five)[\s-]?hour limit\b/i,
22621
- /\bweekly limit\b/i,
22622
- /\b(?:usage|quota|credits?|allowance) (?:is |has been )?(?:exhausted|exceeded|used up)\b/i,
22623
- /\bquota exceeded\b|\binsufficient_quota\b|\bout of (?:credits|usage)\b/i,
22624
- /\bUSAGE_EXHAUSTED\b|\bPAYMENT_REQUIRED\b/,
22625
- /\b(?:usage|plan|session|daily|weekly|monthly|go) limit reached\b/i
22626
- ];
22627
- function classifyUsageLimitError(text) {
22628
- if (typeof text !== "string" || !text.trim())
22629
- return null;
22630
- const bounded = text.slice(0, 2000);
22631
- if (!USAGE_LIMIT_PATTERNS.some((pattern) => pattern.test(bounded)))
22632
- return null;
22633
- const reset = bounded.match(/\b(?:resets?|try again)(?:\s+(?:at|in|after))?\s+([^.\n·]{1,60})/i);
22634
- const hint = reset?.[1]?.trim();
22635
- return hint ? { resetHint: hint } : {};
22636
- }
22637
- var USAGE_LIMIT_ERROR_CODE = "usage-limit";
22638
-
22639
22637
  // ../../bridges/claude-bridge/src/services/session-manager-prompt-handlers/result.ts
22640
22638
  var log14 = createLogger("bridge.claude");
22641
22639
  function claudeStartupFailureMessage(reason) {
@@ -22842,9 +22840,13 @@ async function handleResultMessage(turn, message) {
22842
22840
  debugLog("[session-manager] Query stopped by the user", { sessionId });
22843
22841
  finishTurnInputIfSettled(turn);
22844
22842
  } else {
22845
- log14.error("query.failed", { subtype: resultMsg.subtype, sessionId, isError: resultIsError });
22846
22843
  const startupFailure = resultMsg.startup_failure_reason ? withStartupFailureDetail(claudeStartupFailureMessage(resultMsg.startup_failure_reason), resultMsg.errors) : undefined;
22847
22844
  const usageLimit = resultMsg.subtype === "success" && classifyUsageLimitError(resultMsg.result) ? resultMsg.result.trim().slice(0, MAX_USAGE_LIMIT_ERROR_CHARS) : undefined;
22845
+ if (!startupFailure && (usageLimit || turn.rateLimitRejected)) {
22846
+ log14.warn("query.usage-limited", { subtype: resultMsg.subtype, sessionId });
22847
+ } else {
22848
+ log14.error("query.failed", { subtype: resultMsg.subtype, sessionId, isError: resultIsError });
22849
+ }
22848
22850
  const resultError = startupFailure || resultMsg.errors?.filter(Boolean).join(`
22849
22851
  `) || usageLimit || (resultMsg.subtype === "success" ? "Claude ended the turn on an API error." : `Claude query failed: ${resultMsg.subtype}`);
22850
22852
  if (startupFailure) {
@@ -23398,6 +23400,46 @@ async function handleTurnMessage(turn, message) {
23398
23400
  await handled;
23399
23401
  }
23400
23402
 
23403
+ // ../../bridges/claude-bridge/src/services/claude-mcp-tool-hints.ts
23404
+ var CLAUDE_MCP_TOOL_HINTS_TIMEOUT_MS = 2000;
23405
+ function claudeMcpNameSegment(name) {
23406
+ return name.replace(/[^A-Za-z0-9_-]/g, "_");
23407
+ }
23408
+ function claudeMcpToolHintsFromStatus(statuses, serverName, toolName) {
23409
+ if (!toolName.startsWith("mcp__") || serverName.length === 0)
23410
+ return;
23411
+ const servers = statuses.filter((status) => status?.name === serverName);
23412
+ if (servers.length !== 1)
23413
+ return;
23414
+ const prefix = `mcp__${claudeMcpNameSegment(serverName)}__`;
23415
+ if (!toolName.startsWith(prefix))
23416
+ return;
23417
+ const tools = Array.isArray(servers[0].tools) ? servers[0].tools : [];
23418
+ const matches = tools.filter((tool) => typeof tool?.name === "string" && tool.name.length > 0 && prefix + claudeMcpNameSegment(tool.name) === toolName);
23419
+ if (matches.length !== 1)
23420
+ return;
23421
+ return parseAgentInteractionToolHints(matches[0].annotations);
23422
+ }
23423
+ async function readClaudeMcpToolHints(control, serverName, toolName, timeoutMs = CLAUDE_MCP_TOOL_HINTS_TIMEOUT_MS) {
23424
+ if (!control?.mcpServerStatus || !serverName || !toolName.startsWith("mcp__"))
23425
+ return;
23426
+ let timer;
23427
+ try {
23428
+ const statuses = await Promise.race([
23429
+ control.mcpServerStatus(),
23430
+ new Promise((resolve) => {
23431
+ timer = setTimeout(() => resolve(undefined), timeoutMs);
23432
+ })
23433
+ ]);
23434
+ return Array.isArray(statuses) ? claudeMcpToolHintsFromStatus(statuses, serverName, toolName) : undefined;
23435
+ } catch {
23436
+ return;
23437
+ } finally {
23438
+ if (timer)
23439
+ clearTimeout(timer);
23440
+ }
23441
+ }
23442
+
23401
23443
  // ../../bridges/claude-bridge/src/services/session-manager-prompt-can-use-tool.ts
23402
23444
  var log16 = createLogger("bridge.claude");
23403
23445
  function boundedPlan(content) {
@@ -23636,7 +23678,8 @@ async function turnCanUseTool(turn, toolName, input, permissionContext) {
23636
23678
  const approvals = turnPolicy?.approvals;
23637
23679
  if (claudeAsksForApproval(turnPolicy, turn.options)) {
23638
23680
  recordClaudeToolAwaitingApproval(sessionId, permissionContext?.toolUseID, toolName, input);
23639
- return requestClaudeToolApproval(sessionId, toolName, input, permissionContext);
23681
+ const toolHints = await readClaudeMcpToolHints(readableControl(session), permissionContext?.mcpServer?.name, toolName);
23682
+ return requestClaudeToolApproval(sessionId, toolName, input, permissionContext, toolHints);
23640
23683
  }
23641
23684
  if (approvals === "deny") {
23642
23685
  return {
@@ -24051,9 +24094,15 @@ function settleFailedTurn(turn, error) {
24051
24094
  recordInterruptedStructuredOutputIfCurrent(turn);
24052
24095
  return;
24053
24096
  }
24054
- log18.error("prompt.failed", { errorClass: diagnosticErrorClass(error) });
24097
+ const killedBy = killedClaudeProcessSignal(error);
24098
+ const usageLimited = !killedBy && (turn.rateLimitRejected || isUsageLimitError(error));
24099
+ if (usageLimited) {
24100
+ log18.warn("prompt.usage-limited", { errorClass: diagnosticErrorClass(error) });
24101
+ markUsageLimitError(error);
24102
+ } else {
24103
+ log18.error("prompt.failed", { errorClass: diagnosticErrorClass(error) });
24104
+ }
24055
24105
  if (session.abortController === abortController) {
24056
- const killedBy = killedClaudeProcessSignal(error);
24057
24106
  const failure = killedBy ? claudeProcessKilledMessage(killedBy) : error instanceof Error ? error.message : String(error);
24058
24107
  if (options?.outputSchema && structuredRequestId && !session.structuredOutput) {
24059
24108
  recordStructuredOutput(session, structuredOutputFailure("claude", "provider_error", failure, {
@@ -24288,16 +24337,7 @@ async function closeQueryControls(controls, deadline) {
24288
24337
  return failed;
24289
24338
  }
24290
24339
  async function settlesBy(work, deadline) {
24291
- let timer;
24292
- const expired = new Promise((resolve) => {
24293
- timer = setTimeout(() => resolve(false), Math.max(0, deadline - Date.now()));
24294
- timer.unref?.();
24295
- });
24296
- try {
24297
- return await Promise.race([work.then(() => true), expired]);
24298
- } finally {
24299
- clearTimeout(timer);
24300
- }
24340
+ return (await boundedWait(work, Math.max(0, deadline - Date.now()))).settled;
24301
24341
  }
24302
24342
  // ../../bridges/claude-bridge/src/routes/config.ts
24303
24343
  var log21 = createLogger("bridge.claude");
@@ -24322,6 +24362,11 @@ config2.get("/models", async (c) => {
24322
24362
  });
24323
24363
  var config_default = config2;
24324
24364
 
24365
+ // ../protocol/src/terminal-text.ts
24366
+ var MAX_STRING_LENGTH = 8 * 1024;
24367
+ var BUDGET_FLOOR = 4 * 1024;
24368
+ var MAX_MOVE = 4 * 1024;
24369
+
24325
24370
  // ../protocol/src/human-prompts.ts
24326
24371
  var HUMAN_PROMPT_SCAN_BYTES = 16 * 1024;
24327
24372
  var HUMAN_PROMPT_KINDS = new Set([
@@ -24429,6 +24474,27 @@ var bodyLimit = (options) => {
24429
24474
  };
24430
24475
  };
24431
24476
 
24477
+ // ../protocol/src/contract/ipc-error.ts
24478
+ var REGISTERED_ERROR_CODES = {
24479
+ "unknown-command": { domain: "text", command: "text" },
24480
+ "unsupported-version": { domain: "text", range: "range", command: "text" },
24481
+ "unsupported-field": { domain: "text", field: "text", command: "text" },
24482
+ "kanban-request-id-conflict": { record: "text" },
24483
+ "native-job-receipt-capacity": { limit: "count" },
24484
+ "native-agent-provider-session-missing": {},
24485
+ "container-lifecycle": { reason: "text" },
24486
+ "mcp-management": { reason: "text" },
24487
+ "pane-layout-revision-conflict": {},
24488
+ "design-revision-conflict": {},
24489
+ "prompt-queue-message-conflict": {},
24490
+ "unknown-node": {},
24491
+ "node-admin-refused": {},
24492
+ "node-scope-closed": {},
24493
+ "node-unavailable": {}
24494
+ };
24495
+ var REGISTERED_ERROR_CODE_LIST = Object.keys(REGISTERED_ERROR_CODES);
24496
+ var MAX_COUNT = 2 ** 31 - 1;
24497
+
24432
24498
  // ../protocol/src/mcp-management.ts
24433
24499
  var MCP_CONFIG_REPORTING_VERSION = 1;
24434
24500
  var MCP_MANAGEMENT_LIMITS = {
@@ -24489,10 +24555,12 @@ function sessionRuntimeHealthBody(session) {
24489
24555
  if (!session)
24490
24556
  return { ...emptyRuntimeHealth(), ...mcpConfig };
24491
24557
  const state = openClaudeRuntime(session) ? "attached" : "detached";
24558
+ const generation = session.claudeRuntimeGeneration;
24559
+ const base = { state, ...generation ? { runtimeGeneration: generation } : {} };
24492
24560
  if (!session.health)
24493
- return { ...emptyRuntimeHealth(), summary: { state }, ...mcpConfig };
24561
+ return { ...emptyRuntimeHealth(), summary: base, ...mcpConfig };
24494
24562
  const { drift, notices } = session.health.snapshot();
24495
- return { summary: { state, ...drift ? { drift } : {} }, notices, ...mcpConfig };
24563
+ return { summary: { ...base, ...drift ? { drift } : {} }, notices, ...mcpConfig };
24496
24564
  }
24497
24565
 
24498
24566
  // ../protocol/src/node/transcript-window.ts
@@ -25418,6 +25486,22 @@ function sessionErrorStatus(error) {
25418
25486
  return 503;
25419
25487
  return 500;
25420
25488
  }
25489
+ function isUsageLimitedRejection(error) {
25490
+ try {
25491
+ if (error?.usageLimited === true)
25492
+ return true;
25493
+ return classifyUsageLimitError(error instanceof Error ? error.message : error) !== null;
25494
+ } catch {
25495
+ return false;
25496
+ }
25497
+ }
25498
+ function logPromptProcessingFailure(error) {
25499
+ if (isUsageLimitedRejection(error)) {
25500
+ log23.debug("prompt.processing-usage-limited");
25501
+ return;
25502
+ }
25503
+ log23.error("prompt.processing-failed", { error: formatLogError(error) });
25504
+ }
25421
25505
  var STALE_PROMPT_STATUS = 409;
25422
25506
  function stalePrompt(message) {
25423
25507
  return { error: message, status: "stale" };
@@ -25567,35 +25651,6 @@ session.get("/:id/usage", async (c) => {
25567
25651
  return c.json({ error: "Context usage is temporarily unavailable" }, 503);
25568
25652
  }
25569
25653
  });
25570
- session.put("/:id/preferences", async (c) => {
25571
- const id = c.req.param("id");
25572
- try {
25573
- let body;
25574
- try {
25575
- body = await c.req.json();
25576
- } catch {
25577
- return c.json({ error: "Request body must be valid JSON" }, 400);
25578
- }
25579
- if (body === null || typeof body !== "object" || Array.isArray(body) || Object.getPrototypeOf(body) !== Object.prototype) {
25580
- return c.json({ error: "Request body must be a JSON object" }, 400);
25581
- }
25582
- const record = body;
25583
- const unexpectedField = Object.keys(record).find((key) => key !== "planMode");
25584
- if (unexpectedField) {
25585
- return c.json({ error: `Unexpected session preference field: ${unexpectedField}` }, 400);
25586
- }
25587
- if (!Object.hasOwn(record, "planMode")) {
25588
- return c.json({ error: "planMode is required" }, 400);
25589
- }
25590
- if (Object.hasOwn(record, "planMode") && typeof record.planMode !== "boolean") {
25591
- return c.json({ error: "planMode must be a boolean" }, 400);
25592
- }
25593
- const updated = await setSessionPreferences(id, typeof record.planMode === "boolean" ? { planMode: record.planMode } : {});
25594
- return c.json({ planMode: updated.planMode ?? false });
25595
- } catch (error) {
25596
- return c.json({ error: errorMessage(error, "Failed to update session preferences") }, sessionErrorStatus(error));
25597
- }
25598
- });
25599
25654
  function claudeApprovalMode(value) {
25600
25655
  return value === "default" || value === "acceptEdits" || value === "auto" || value === "bypassPermissions" ? value : undefined;
25601
25656
  }
@@ -25716,17 +25771,6 @@ session.get("/:id/structured-output", (c) => {
25716
25771
  requestId: sessionData.structuredOutputRequestId
25717
25772
  });
25718
25773
  });
25719
- session.get("/:id/tasks", async (c) => {
25720
- const id = c.req.param("id");
25721
- const sessionData = getSession(id) ?? await ensurePersistedSession(id);
25722
- if (!sessionData) {
25723
- return c.json({ error: "Session not found" }, 404);
25724
- }
25725
- if (sessionData.persistedMessagesLoaded === false) {
25726
- await hydratePersistedSessionMessages(id);
25727
- }
25728
- return c.json(sessionData.taskRegistry?.snapshot() ?? { items: [], complete: true });
25729
- });
25730
25774
  session.get("/:id/messages", async (c) => {
25731
25775
  const id = c.req.param("id");
25732
25776
  const resolved = await resolveSession(id, "Failed to load session messages");
@@ -25899,7 +25943,7 @@ session.post("/:id/prompt", async (c) => {
25899
25943
  rejectStarted?.(sessionOperationError("conflict", "Prompt stopped before launch"));
25900
25944
  }, (error) => {
25901
25945
  rejectStarted?.(error);
25902
- log23.error("prompt.processing-failed", { error: formatLogError(error) });
25946
+ logPromptProcessingFailure(error);
25903
25947
  });
25904
25948
  return { started, completion };
25905
25949
  });
@@ -25954,7 +25998,7 @@ session.post("/:id/prompt", async (c) => {
25954
25998
  ...workflowResultTurn ? { workflowResultTurn } : {},
25955
25999
  ...providerPrompt !== undefined ? { providerPrompt } : {}
25956
26000
  }).catch((error) => {
25957
- log23.error("prompt.processing-failed", { error: formatLogError(error) });
26001
+ logPromptProcessingFailure(error);
25958
26002
  });
25959
26003
  log23.debug("prompt.accepted", { sessionId: id });
25960
26004
  return c.json({
@@ -25998,34 +26042,7 @@ session.post("/:id/hard-abort", (c) => {
25998
26042
  return c.json({ error: "Session not found" }, 404);
25999
26043
  return c.json({ status: abortSession(id) ? "aborted" : "not_running" });
26000
26044
  });
26001
- session.delete("/:id", async (c) => {
26002
- const id = c.req.param("id");
26003
- try {
26004
- const deleted = await deleteSessionDurably(id);
26005
- if (deleted) {
26006
- return c.json({ status: "deleted" });
26007
- }
26008
- return c.json({ error: "Session not found" }, 404);
26009
- } catch (error) {
26010
- log23.error("session.delete-failed", { error: formatLogError(error) });
26011
- return c.json({ error: errorMessage(error, "Failed to delete session") }, sessionErrorStatus(error));
26012
- }
26013
- });
26014
26045
  registerSessionCloseRoute(session);
26015
- session.post("/:id/rename", async (c) => {
26016
- const id = c.req.param("id");
26017
- const body = await c.req.json().catch(() => ({}));
26018
- const title = typeof body.title === "string" ? body.title.trim() : "";
26019
- if (!title)
26020
- return c.json({ error: "Title is required" }, 400);
26021
- try {
26022
- const renamed = await renameSessionDurably(id, title);
26023
- return renamed ? c.json({ status: "renamed", title }) : c.json({ error: "Session not found" }, 404);
26024
- } catch (error) {
26025
- log23.error("session.rename-failed", { error: formatLogError(error) });
26026
- return c.json({ error: errorMessage(error, "Failed to rename session") }, sessionErrorStatus(error));
26027
- }
26028
- });
26029
26046
  session.post("/:id/title", async (c) => {
26030
26047
  const title = String((await c.req.json().catch(() => ({}))).title ?? "").trim();
26031
26048
  if (!title)
@@ -29050,7 +29067,6 @@ app.onError((error, c) => {
29050
29067
  return c.json({ error: "Internal Server Error" }, 500);
29051
29068
  });
29052
29069
  var BRIDGE_TOKEN_ENV = "CLAUDE_BRIDGE_TOKEN";
29053
- var BRIDGE_ALLOWED_ORIGINS_ENV = "CLAUDE_BRIDGE_ALLOWED_ORIGINS";
29054
29070
  var bridgeCredential = loadBridgeCredential(BRIDGE_TOKEN_ENV);
29055
29071
  process.env.ORKESTRATOR_NATIVE_AGENT_BRIDGE = "claude";
29056
29072
  var bridgeAuthEnabledOverrideForTesting = null;
@@ -29072,11 +29088,6 @@ function bearerToken(header) {
29072
29088
  function isTrustedBridgeOrigin(origin) {
29073
29089
  if (!origin)
29074
29090
  return true;
29075
- if (origin === "null" || origin === "file://")
29076
- return true;
29077
- const configured = (process.env[BRIDGE_ALLOWED_ORIGINS_ENV] ?? "").split(",").map((entry) => entry.trim().replace(/\/$/, "")).filter(Boolean);
29078
- if (configured.includes(origin.replace(/\/$/, "")))
29079
- return true;
29080
29091
  try {
29081
29092
  const parsed = new URL(origin);
29082
29093
  return (parsed.protocol === "http:" || parsed.protocol === "https:") && (parsed.hostname === "127.0.0.1" || parsed.hostname === "localhost" || parsed.hostname === "::1" || parsed.hostname === "[::1]");
@@ -29092,21 +29103,10 @@ app.use("*", async (c, next) => {
29092
29103
  if (!isTrustedBridgeOrigin(origin)) {
29093
29104
  return c.json({ error: "Origin is not allowed" }, 403);
29094
29105
  }
29095
- if (origin) {
29096
- c.header("Access-Control-Allow-Origin", origin);
29097
- c.header("Vary", "Origin");
29098
- }
29099
- if (c.req.method === "OPTIONS") {
29100
- c.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
29101
- c.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Orkestrator-Claude-Token");
29102
- c.header("Access-Control-Allow-Private-Network", "true");
29103
- return c.body(null, 204);
29104
- }
29105
29106
  if (isBridgeAuthEnabled() && !isPublicHealthRequest(c.req.method, c.req.path)) {
29106
29107
  const dedicatedHeaderToken = c.req.raw.headers.get("x-orkestrator-claude-token")?.trim();
29107
29108
  const headerToken = bearerToken(c.req.raw.headers.get("authorization") ?? undefined);
29108
- const eventToken = c.req.path === "/event/subscribe" ? c.req.query("token")?.trim() : undefined;
29109
- if (!tokenMatches(dedicatedHeaderToken) && !tokenMatches(headerToken) && !tokenMatches(eventToken)) {
29109
+ if (!tokenMatches(dedicatedHeaderToken) && !tokenMatches(headerToken)) {
29110
29110
  return c.json({ error: "Unauthorized" }, 401);
29111
29111
  }
29112
29112
  const admission = await admitFetchBridgeRequest(bridgeCredential.authority, c.req.raw);
@@ -29132,7 +29132,6 @@ app.use("/session/:id/transcript", compress({ encoding: "gzip" }));
29132
29132
  compressTranscriptReads(app);
29133
29133
  app.get("/global/auth-check", (c) => c.json({ status: "ok" }));
29134
29134
  app.get("/global/auth", async (c) => c.json(await readClaudeAuthStatus()));
29135
- app.get("/global/usage", async (c) => c.json({ account: await readClaudePlanUsage() }));
29136
29135
  app.post("/global/auth/login", (c) => c.json({ error: "Claude signs in from the sign-in card in its tab or from Settings → Claude." }, 405));
29137
29136
  app.post("/global/auth/logout", (c) => c.json({ error: "Claude sign-out is available from a terminal tab." }, 405));
29138
29137
  app.post("/global/refresh-catalog", async (c) => {