orkestrator 2.36.3-beta → 2.36.4-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -76,6 +76,12 @@ var BACKEND_LOG_AREAS = defineLogAreas({
76
76
  "startup.looped-review-pending": "Cleanup of the retired Looped Review stays pending.",
77
77
  "notice.failed": "A background notice after a turn or prompt failed; `step` says which.",
78
78
  "artifacts.live-unavailable": "Live interactive artifacts are unavailable.",
79
+ "previous-run": {
80
+ description: "This start read how the previous run ended: `outcome` is `clean` when it reached the end of shutdown and `crashed` when it did not, `ranForMs` its length and `lastSeenAgoMs` the time since its last health row.",
81
+ essential: true,
82
+ fields: { outcome: "label", ranForMs: "number", lastSeenAgoMs: "number" }
83
+ },
84
+ "health.write-failed": "A health summary row could not be written or read; the next sample retries.",
79
85
  "shutdown.step-failed": "One part of shutdown failed and the rest went on; `step` says which.",
80
86
  "shutdown.signal-received": {
81
87
  description: "A signal started shutdown, which tells a clean quit from the backend being killed.",
@@ -119,7 +125,8 @@ var BRIDGE_LOG_AREAS = defineLogAreas({
119
125
  description: "What every long-lived bridge does the same way: its sweep and its shutdown.",
120
126
  events: {
121
127
  "idle-sweep.failed": "An idle sweep threw; the next tick retries.",
122
- "shutdown.failed": "Releasing the bridge failed during shutdown; it still exits."
128
+ "shutdown.failed": "Releasing the bridge failed during shutdown; it still exits.",
129
+ "credential.not-hardened": "The bridge could not mark itself non-dumpable, so a same-uid process can read its memory; `reason` says why."
123
130
  }
124
131
  },
125
132
  "bridge.acp": {
@@ -253,7 +260,6 @@ var BRIDGE_LOG_AREAS = defineLogAreas({
253
260
  "parent.gone": "The backend that launched this bridge has gone; stopping turns and shutting down.",
254
261
  "queue.overflow": "The notification queue passed a bound and dropped its backlog.",
255
262
  "queue.task-failed": "A task on a per-thread queue failed.",
256
- "raw-log.write-failed": "Appending to the raw Codex log failed.",
257
263
  "recorder.notice": "The notification recorder needs attention: it is on, or was asked for without its confirmation.",
258
264
  "recorder.threw": "The notification recorder threw.",
259
265
  "recorder.write-failed": "Writing a notification recording failed; its lines were dropped.",
@@ -459,6 +465,7 @@ var ENVIRONMENT_LOG_AREAS = defineLogAreas({
459
465
  environment: {
460
466
  description: "Environment naming, setup, status, moves, deletion and cleanup afterwards.",
461
467
  events: {
468
+ "cleanup.sessions-failed": "Session metadata cleanup failed during environment deletion; deletion continues.",
462
469
  "cleanup.branch-kept": "A deleted environment's local branch was kept, as it may hold unmerged work.",
463
470
  "rename.failed": "Naming an environment from its pending prompt failed for the first time.",
464
471
  "rename.still-failing": "That rename is still failing; written at the 2nd, 4th, 8th... failure.",
@@ -532,6 +539,7 @@ var GATEWAY_LOG_AREAS = defineLogAreas({
532
539
  "websocket.upgrade-failed": "A WebSocket upgrade failed.",
533
540
  "events.client-dropped": "An event-stream client buffered too much and was dropped; it reconnects and refetches.",
534
541
  "proxy.client-disconnected": "A proxy client went away, so its upstream request was aborted.",
542
+ "traffic.burst": "Connections or requests spiked. Counts by source address, route class, client family, listener and registered invoke command; never request content.",
535
543
  "throttle.suppressed": "Repeats of the throttled `site` were counted over a window, not written.",
536
544
  "throttle.recovered": "The throttled `site` succeeded again, so its fault has cleared.",
537
545
  "throttle.evicted": "The tracked-key limit dropped the `site`, so no recovered line follows unless it fails again."
@@ -665,6 +673,7 @@ var NATIVE_AGENT_LOG_AREAS = defineLogAreas({
665
673
  "native-agent": {
666
674
  description: "Native agent sessions and what the backend reads from their bridges.",
667
675
  events: {
676
+ "session.bridge-replaced-for-policy": "An idle bridge was stopped so a resume could apply the user's wider execution policy.",
668
677
  "catalogue.outdated-bridge": "A bridge predates the command catalogue, so its commands stay unavailable.",
669
678
  "compact.instructions-ignored": "A bridge compacted without confirming the instructions sent with /compact: it predates them.",
670
679
  "handoff.summary-read-failed": "Change summaries could not be read for a handoff, so the carrier says they are unmeasured.",
@@ -730,7 +739,8 @@ var NATIVE_AGENT_LOG_AREAS = defineLogAreas({
730
739
  "coordinator-servers.unavailable": "OpenCode coordinator research servers are unavailable.",
731
740
  "monitor.reconnecting": "The request monitor lost its stream and is reconnecting. Error class only.",
732
741
  "worker-limit.reached": "The bounded request workers are full, so the stream restarts and a snapshot reconciles.",
733
- "request.failed": "Handling a request event failed, so the stream restarts. Error class only."
742
+ "request.failed": "Handling a request event failed, so the stream restarts. Error class only.",
743
+ "credential-plugin.skipped": "A host OpenCode server started without the credential plugin, so its tools inherit its password; `reason` says why."
734
744
  }
735
745
  }
736
746
  });
@@ -758,6 +768,7 @@ var PREVIEW_LOG_AREAS = defineLogAreas({
758
768
  "publication.start-failed": "Private preview publication did not start.",
759
769
  "publication.reconfigure-failed": "Preview publication could not be reconfigured.",
760
770
  "publication.listening": "Private preview origins are listening.",
771
+ "publication.same-site": "The preview domain is the same site as the application; publication runs with a warning.",
761
772
  "certificate.reloaded": "The preview certificate was reloaded.",
762
773
  "access.revoked-close-failed": "A revoked preview resource could not be closed. Error class only.",
763
774
  "registry.invalid-definition": "An invalid stored preview service definition was ignored.",
@@ -1066,10 +1077,19 @@ var STORAGE_LOG_AREAS = defineLogAreas({
1066
1077
  "retired.turn-cleanup-pending": "Cleanup of a retired Looped Review turn did not finish and stays pending.",
1067
1078
  "handoffs.prune-failed": "Pruning agent handoffs that nothing references failed; a later prune retries.",
1068
1079
  "desktop-connections.malformed": "Stored desktop connection settings were malformed, so the local connection is used.",
1080
+ "config.restrict-mode-failed": "A config file holding provider secrets could not be set to owner-only; the backend carries on.",
1069
1081
  "legacy-json.moved": "JSON store files written after the SQLite migration were archived, not imported.",
1070
1082
  "legacy-json.archive-failed": "Imported JSON store files could not be archived.",
1083
+ "lease.timed-out": "A waiter gave up on a lease; `lease` and `family` name it, `holderAgeMs` is the time since its holder's last heartbeat (null when the holder had just gone), `waitedMs` how long the waiter waited.",
1071
1084
  "lease.heartbeat-failed": "A held lease's heartbeat failed, which shortens the lease; the next one retries.",
1072
- "scrub.checkpoint-failed": "Deleted content could not be scrubbed from the WAL because the truncating checkpoint failed or was blocked; the next checkpoint retries.",
1085
+ "scrub.vacuum-failed": "Deleted-content page reclamation failed; the checkpoint is attempted independently.",
1086
+ "scrub.checkpoint-failed": "Deleted content could not be scrubbed from the WAL yet because the truncating checkpoint failed or a reader held an older snapshot; it is retried without waiting until it succeeds.",
1087
+ "upkeep.vacuum-failed": "Periodic page reclamation failed; the next upkeep pass retries.",
1088
+ "optimize.failed": "Refreshing the query planner's statistics failed; queries still run and the next check retries.",
1089
+ "ledger.moved": "The change-tracking ledger was moved out of the main database into its own file; `rows` and `durationMs` say how much and how long.",
1090
+ "snapshot.top-tables-failed": "The sampled table sizes from a finished snapshot could not be saved; the snapshot stands and the next one retries.",
1091
+ "snapshot.ledger-skipped": "The daily change-tracking ledger snapshot was skipped because the disk or the snapshot budget lacks room; `retryAt` says when it tries again.",
1092
+ "snapshot.ledger-failed": "The daily change-tracking ledger snapshot failed; `retryAt` says when it tries again, if known.",
1073
1093
  ...THROTTLE_LOG_EVENTS
1074
1094
  }
1075
1095
  }
@@ -1086,6 +1106,7 @@ var BUILD_PIPELINE_LOG_AREAS = defineLogAreas({
1086
1106
  "consolidation.consume-deferred": "Consuming a review consolidation result failed; it stays pending and is retried.",
1087
1107
  "dispatch.prepare-failed": "Attaching the agent before dispatch failed; the prompt request does the same work and answers authoritatively.",
1088
1108
  "interaction.resolved": "A human interaction on a pipeline stage resolved. Metadata only.",
1109
+ "user-message.background-send-refused": "The bridge refused a queued user message during a background wait; it stays queued and is retried.",
1089
1110
  "transcripts.migrated": "A transcript migration pass moved stage transcripts; counts only.",
1090
1111
  "transcripts.maintenance-failed": "Migrating or sweeping stage transcripts failed; the next start retries.",
1091
1112
  "restore.skipped": "A pipeline could not be restored at startup and was skipped.",
@@ -1123,6 +1144,8 @@ var CHANGE_TRACKING_LOG_AREAS = defineLogAreas({
1123
1144
  description: "Change tracking: turn capture, evidence pulls and measurements.",
1124
1145
  events: {
1125
1146
  "journal-import.failed": "Importing surviving OpenCode command journals as legacy summaries failed.",
1147
+ "measurement-drain.failed": "Draining an owner's superseded measurements failed; the retention pass retries.",
1148
+ "retention.failed": "A retention pass failed partway; what it deleted stands and the next pass goes on.",
1126
1149
  "projection.failed": "Projecting a change event onto its environment failed.",
1127
1150
  "startup.reconcile-failed": "Reconciling change tracking at startup failed.",
1128
1151
  "turn-start.capture-failed": "Capturing a turn's start failed, so the turn is untracked.",
@@ -1153,7 +1176,16 @@ var COORDINATOR_LOG_AREAS = defineLogAreas({
1153
1176
  coordinator: {
1154
1177
  description: "Coordinators: delegations, status wakes and their store.",
1155
1178
  events: {
1179
+ ...THROTTLE_LOG_EVENTS,
1156
1180
  "delegation.open-failed": "A delegation could not be opened; `source` says for what.",
1181
+ "delegation.reconcile-failed": "One delegation could not be settled; the rest of the pass still ran and the next one retries.",
1182
+ "delegation.wake-failed": "One delegation's wake could not be delivered; the rest of the pass still ran and the next one retries.",
1183
+ "delegation.wake-held": "A wake is waiting on a state the user can change (messaging off, conversation limit), and is not counted as a failure.",
1184
+ "delegation.wake-pass-failed": "A delegation wake pass could not run; the next sweep retries.",
1185
+ "delegation.wake-retire-failed": "A wake that keeps failing could not be given up on; the next pass retries.",
1186
+ "delegation.wake-retire-notice-failed": "The one notice for a wake being retired could not be sent; the wake stays owed and the next pass retries.",
1187
+ "delegation.wake-retired": "A wake kept failing and was given up on; `kind` is the last failure.",
1188
+ "mail.reconcile-failed": "One coordinator's mail could not be reconciled; the sweep carried on with the others.",
1157
1189
  "deliver-now.drain-failed": "The mail delivery pass after deliverNow failed; the next sweep delivers.",
1158
1190
  "mail.move-failed": "Mail could not move to the new main coordinator.",
1159
1191
  "work.move-failed": "Work could not move to the main coordinator.",
@@ -1278,6 +1310,8 @@ var DOCKER_LOG_AREAS = defineLogAreas({
1278
1310
  "portable-inputs.relay-missing": "Docker is rootless and the image predates the staged-input relay, so the container cannot read them until rebuilt.",
1279
1311
  "git-mirror.mount-unavailable": "A new container gets no project Git mirror, so its clone goes to the remote.",
1280
1312
  "git-mirror.refreshed": "A project's Git mirror was built or updated.",
1313
+ "git-mirror.seeded": "A project's Git mirror was built from its host checkout and only what the remote added to it.",
1314
+ "git-mirror.seed-skipped": "A project's host checkout could not seed its Git mirror, so the build downloads everything.",
1281
1315
  "git-mirror.refresh-failed": "A project's Git mirror could not be updated. New clones still work, from the mirror as it was or from the remote.",
1282
1316
  "git-mirror.low-disk": "A project's Git mirror was not updated: the disk is nearly full.",
1283
1317
  "git-mirror.oversized": "A project's repository is too large for a Git mirror, so its environments keep the blobless clone.",
@@ -1289,6 +1323,7 @@ var DOCKER_LOG_AREAS = defineLogAreas({
1289
1323
  "git-mirror.clone-fallback": "A new environment could not clone from its project's Git mirror and cloned from the remote.",
1290
1324
  "project-seed.refused": "A project .env, .env.local or opencode.json was not copied into a new container: a link, not a regular file, outside the project, too large or unreadable.",
1291
1325
  "opencode.warm-incomplete": "OpenCode did not finish loading /workspace in a container.",
1326
+ "log-driver.unbounded": "The Docker daemon offers neither the local nor the json-file log driver, so new containers keep its default driver, whose log may be uncapped. Written once per backend.",
1292
1327
  "lifecycle-event.reconcile-failed": "Reconciling an environment after a container start or stop event failed; the next status read retries.",
1293
1328
  "login-keeper.pass-failed": "A Claude login keeper pass failed; the next interval retries.",
1294
1329
  "login-keeper.refresh-failed": "Refreshing the host Claude login failed. Fixed text: CLI output can hold credentials.",
@@ -1312,6 +1347,7 @@ var DOCKER_LOG_AREAS = defineLogAreas({
1312
1347
  essential: true,
1313
1348
  fields: { staleForMs: "number" }
1314
1349
  },
1350
+ "writer-lease.listener-failed": "The callback told about a lost registry writer lease threw, so the schedules settings learn of the loss only at their next read.",
1315
1351
  "writer-lease.not-acquired": {
1316
1352
  description: "This backend started without the registry writer lease, for the fixed `reason` given. A second backend on one data directory is normal: it serves reads, runs no schedules and refuses container changes.",
1317
1353
  essential: true,
@@ -1966,6 +2002,7 @@ var WEB_SYNC_LOG_AREAS = defineLogAreas({
1966
2002
  events: {
1967
2003
  "events.disconnected": "The main event stream dropped; it reconnects and replays.",
1968
2004
  "terminal-stream.disconnected": "A terminal event stream dropped; it reconnects.",
2005
+ "relayed-stream.disconnected": "The relayed node event stream dropped; it reconnects.",
1969
2006
  "connection-listener.failed": "A main stream connection state listener threw.",
1970
2007
  "event-listener.failed": "A listener for a gateway event threw.",
1971
2008
  "stream-listener.failed": "A listener for the stream-connected notice threw."
@@ -2050,6 +2087,7 @@ var TEXT_RULES = [
2050
2087
  pattern: /\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/g,
2051
2088
  replacement: "[redacted]"
2052
2089
  },
2090
+ { pattern: /\bok[ab]_[A-Za-z0-9_-]{16,}/g, replacement: "[redacted]" },
2053
2091
  { pattern: /\bgh[pousr]_[A-Za-z0-9]{16,}/g, replacement: "[redacted]" },
2054
2092
  { pattern: /\bgithub_pat_[A-Za-z0-9_]{20,}/g, replacement: "[redacted]" },
2055
2093
  { pattern: /\b(?:sk|rk|pk)-[A-Za-z0-9_-]{12,}/g, replacement: "[redacted]" },
@@ -5226,9 +5264,6 @@ var shouldTransform = (res) => {
5226
5264
  return !cacheControl || !cacheControlNoTransformRegExp.test(cacheControl);
5227
5265
  };
5228
5266
 
5229
- // ../../bridges/claude-bridge/src/index.ts
5230
- import { randomBytes as randomBytes2, timingSafeEqual } from "node:crypto";
5231
-
5232
5267
  // ../../bridges/claude-bridge/src/routes/health.ts
5233
5268
  var health = new Hono2;
5234
5269
  health.get("/health", (c) => {
@@ -5704,6 +5739,15 @@ function claudePlanWindowFromLabel(label) {
5704
5739
  return known ? { id: known[0], ...known[1] } : claudeModelWeeklyWindow(model);
5705
5740
  }
5706
5741
 
5742
+ // ../../bridges/claude-bridge/src/services/event-message-id.ts
5743
+ function eventMessageId(event) {
5744
+ if (event.type !== "message.updated" && event.type !== "message.patched")
5745
+ return;
5746
+ const data = event.data;
5747
+ const id = event.type === "message.updated" ? data?.message?.id : data?.messageId;
5748
+ return typeof id === "string" && id.length > 0 ? id : undefined;
5749
+ }
5750
+
5707
5751
  // ../../bridges/claude-bridge/src/services/logger.ts
5708
5752
  function isDebugLoggingEnabled() {
5709
5753
  return bridgeDiagnosticsStreamEnabled("claude");
@@ -6479,11 +6523,8 @@ import { execFile } from "node:child_process";
6479
6523
  import { createHash as createHash3 } from "node:crypto";
6480
6524
  var sessions = new Map;
6481
6525
  eventEmitter.subscribe((event) => {
6482
- if (event.type !== "message.updated" && event.type !== "message.patched")
6483
- return;
6484
- const data = event.data;
6485
- const id = event.type === "message.updated" ? data?.message?.id : data?.messageId;
6486
- if (typeof id !== "string" || !event.sessionId)
6526
+ const id = eventMessageId(event);
6527
+ if (id === undefined || !event.sessionId)
6487
6528
  return;
6488
6529
  const session = sessions.get(event.sessionId);
6489
6530
  if (!session || session.messages.at(-1)?.id === id)
@@ -8111,13 +8152,11 @@ var COORDINATOR_CONTROL_TOOL_NAMES = Object.freeze([
8111
8152
  "launch_graph",
8112
8153
  "launch_job",
8113
8154
  "launch_multi_review",
8114
- "launch_node_environment",
8115
8155
  "launch_terminal",
8116
8156
  "list_agents",
8117
8157
  "list_environments",
8118
8158
  "list_graph_templates",
8119
8159
  "list_mailboxes",
8120
- "list_node_environments",
8121
8160
  "list_nodes",
8122
8161
  "list_projects",
8123
8162
  "list_provider_accounts",
@@ -8146,16 +8185,11 @@ var COORDINATOR_CONTROL_TOOL_NAMES = Object.freeze([
8146
8185
  "resume_schedule",
8147
8186
  "run_worker_command",
8148
8187
  "send_message",
8149
- "send_node_message",
8150
- "send_prompt_to_node_tab",
8151
8188
  "send_prompt_to_tab",
8152
8189
  "set_worker_goal",
8153
8190
  "start_build_pipeline",
8154
8191
  "start_environment",
8155
- "start_multi_review",
8156
- "start_node_environment",
8157
8192
  "stop_environment",
8158
- "stop_node_environment",
8159
8193
  "stop_worker_turn",
8160
8194
  "switch_provider_account",
8161
8195
  "set_account_auto_switch",
@@ -14482,6 +14516,9 @@ function claudeEvidenceTurnId(turn) {
14482
14516
 
14483
14517
  // ../../bridges/claude-bridge/src/services/command-changes.ts
14484
14518
  var commandChangeProbe = new WorkspaceChangeProbe;
14519
+ function discardCommandChangeWindow(toolUseId) {
14520
+ commandChangeProbe.discard(toolUseId);
14521
+ }
14485
14522
  var COMMAND_CHANGE_HOOK_MATCHER = "^(Bash|Edit|Write|MultiEdit|NotebookEdit)$";
14486
14523
  var COMMAND_CHANGE_HOOK_TIMEOUT_SECONDS = 60;
14487
14524
  var MAX_CACHED_JOURNALS = 64;
@@ -16579,6 +16616,7 @@ function captureTurnStartup(session) {
16579
16616
  turnStartedAt: session.turnStartedAt,
16580
16617
  abortController: session.abortController,
16581
16618
  error: session.error,
16619
+ errorCode: session.errorCode,
16582
16620
  interruption: session.interruption,
16583
16621
  interruptedRequestId: session.interruptedRequestId,
16584
16622
  lastActivity: session.lastActivity,
@@ -16638,6 +16676,7 @@ function createTurnState(session, sessionId, init) {
16638
16676
  receivedPromptResult: false,
16639
16677
  settlingResult: false,
16640
16678
  localCommandOutputSeen: false,
16679
+ rateLimitRejected: false,
16641
16680
  lastThinkingTokensEmitAt: 0,
16642
16681
  compactedTokensBefore: undefined,
16643
16682
  pendingPlanRejectionFeedback: null,
@@ -16752,6 +16791,7 @@ async function applyPromptPlanMode(admission, planMode) {
16752
16791
  session.status = beforeStartup.status;
16753
16792
  session.turnStartedAt = beforeStartup.turnStartedAt;
16754
16793
  session.error = beforeStartup.error;
16794
+ session.errorCode = beforeStartup.errorCode;
16755
16795
  session.interruption = beforeStartup.interruption;
16756
16796
  session.interruptedRequestId = beforeStartup.interruptedRequestId;
16757
16797
  session.lastActivity = beforeStartup.lastActivity;
@@ -16773,6 +16813,7 @@ async function applyPromptPlanMode(admission, planMode) {
16773
16813
  function beginPromptActivity(admission) {
16774
16814
  const { session, sessionId } = admission;
16775
16815
  session.error = undefined;
16816
+ session.errorCode = undefined;
16776
16817
  session.interruption = undefined;
16777
16818
  session.interruptedRequestId = undefined;
16778
16819
  session.lastActivity = new Date;
@@ -19338,10 +19379,178 @@ function claudeArtifactServerTools(servers) {
19338
19379
  import { open as open3, realpath as realpath3 } from "node:fs/promises";
19339
19380
  import { join as join14, relative as relative2, isAbsolute as isAbsolute4 } from "node:path";
19340
19381
 
19382
+ // ../protocol/src/rich-content-policy.ts
19383
+ var KIB = 1024;
19384
+ var MIB = 1024 * KIB;
19385
+ var CODE_BLOCK_POLICY = {
19386
+ maxHighlightBytes: 32 * KIB,
19387
+ maxHighlightLines: 2000,
19388
+ initialVisualLines: 24
19389
+ };
19390
+ var MERMAID_POLICY = {
19391
+ maxSourceBytes: 32 * KIB,
19392
+ maxEdges: 250,
19393
+ maxSvgBytes: 1 * MIB,
19394
+ maxSvgElements: 5000,
19395
+ renderTimeoutMs: 5000
19396
+ };
19397
+ var CHART_POLICY = {
19398
+ maxPayloadBytes: 256 * KIB,
19399
+ maxSeries: 6,
19400
+ maxBarCategories: 100,
19401
+ maxCartesianPoints: 2000,
19402
+ maxDonutSlices: 24,
19403
+ maxTitleCharacters: 200,
19404
+ maxLabelCharacters: 200,
19405
+ maxDescriptionCharacters: 2000,
19406
+ maxSourceNotes: 8,
19407
+ maxSourceNoteCharacters: 500,
19408
+ maxIdCharacters: 64,
19409
+ maxUnitCharacters: 32,
19410
+ maxAbsoluteValue: 1000000000000000,
19411
+ maxJsonDepth: 16
19412
+ };
19413
+ var WORKFLOW_SNAPSHOT_POLICY = {
19414
+ maxNormalizedBytes: 256 * KIB,
19415
+ maxNodes: 200,
19416
+ maxEdges: 400,
19417
+ maxIdCharacters: 128,
19418
+ maxLabelCharacters: 200,
19419
+ maxDescriptionCharacters: 2000,
19420
+ maxRawStatusCharacters: 100,
19421
+ maxLinksPerNode: 8
19422
+ };
19423
+ var STATIC_HTML_POLICY = {
19424
+ maxSourceBytes: 256 * KIB,
19425
+ maxPreparedBytes: 16 * MIB,
19426
+ maxElements: 5000
19427
+ };
19428
+ var STATIC_PRESENTATION_POLICY = {
19429
+ maxDocumentBytes: STATIC_HTML_POLICY.maxSourceBytes,
19430
+ maxElements: STATIC_HTML_POLICY.maxElements,
19431
+ maxFramesPerWindow: 4,
19432
+ renderTimeoutMs: 15000,
19433
+ maxSizeChangesPerWindow: 16,
19434
+ sizeChangeWindowMs: 5000,
19435
+ maxRefusedMessages: 100,
19436
+ maxSearchTextCharacters: 64 * KIB,
19437
+ searchTextChunkCharacters: 2 * KIB
19438
+ };
19439
+ var INTERACTIVE_HTML_POLICY = {
19440
+ maxAuthoredBytes: 512 * KIB,
19441
+ maxAssets: 32,
19442
+ maxAssetBytesTotal: 10 * MIB,
19443
+ maxDependencies: 4,
19444
+ maxPreparedBytes: 16 * MIB,
19445
+ maxRuntimeElements: 1e4,
19446
+ maxProbeSteps: 20,
19447
+ maxProbeStepMs: 2000,
19448
+ defaultWaitVisibleMs: 1000,
19449
+ maxProbeTextCharacters: 1024,
19450
+ probeTargetPattern: /^[A-Za-z][A-Za-z0-9_-]{0,63}$/
19451
+ };
19452
+ var PREVIEW_CAPTURE_POLICY = {
19453
+ maxPngBytes: 8 * MIB,
19454
+ maxPixels: 12000000,
19455
+ maxDimension: 4096,
19456
+ minDimension: 240,
19457
+ maxCapturesPerReceipt: 3,
19458
+ defaultViewport: { width: 960, height: 640, deviceScaleFactor: 1 }
19459
+ };
19460
+ var PREVIEW_ADMISSION_POLICY = {
19461
+ runningPerEnvironment: 1,
19462
+ runningGlobal: 2,
19463
+ queuedPerEnvironment: 8,
19464
+ queuedGlobal: 16,
19465
+ nonterminalPerConversation: 2,
19466
+ queuedMetadataBytesGlobal: 8 * MIB,
19467
+ queueWaitMs: 15000,
19468
+ workerWallMs: 30000,
19469
+ readinessMs: 5000,
19470
+ operationDeadlineMs: 45000,
19471
+ cleanupGraceMs: 2000,
19472
+ workerMemoryBytes: 1024 * MIB,
19473
+ workerCpus: 2,
19474
+ workerPids: 128
19475
+ };
19476
+ var FRONTEND_RENDER_POLICY = {
19477
+ highlightConcurrency: 2,
19478
+ diagramConcurrency: 1,
19479
+ maxQueuedJobs: 32,
19480
+ maxQueuedSourceBytes: 2 * MIB,
19481
+ maxSettledCacheEntries: 128,
19482
+ maxSettledCacheBytes: 16 * MIB,
19483
+ maxInactiveViewStateEntries: 500,
19484
+ maxActiveViewStateEntries: 200,
19485
+ maxPinnedViewStateEntries: 50,
19486
+ liveExecutableHostsPerWindow: 1,
19487
+ imageDecodeMaxPixels: 40000000,
19488
+ pdfPreviewMaxPages: 100,
19489
+ pdfPreviewMaxBytes: 20 * MIB
19490
+ };
19491
+ var PDF_POLICY = {
19492
+ maxPages: 100,
19493
+ maxBytes: 20 * MIB,
19494
+ thumbnailMaxDimension: 1024,
19495
+ thumbnailMaxPngBytes: 4 * MIB,
19496
+ imageDecodeMaxPixels: 40000000,
19497
+ printMarginMm: 10,
19498
+ previewCacheEntries: 32,
19499
+ previewCacheBytes: 16 * MIB
19500
+ };
19501
+ var DIAGNOSTIC_POLICY = {
19502
+ maxPersistedEntries: 50,
19503
+ maxEntryBytes: 2 * KIB,
19504
+ maxPersistedBytes: 32 * KIB,
19505
+ maxToolFieldErrors: 20,
19506
+ maxToolDiagnosticBytes: 8 * KIB
19507
+ };
19508
+ var ARTIFACT_TOOL_POLICY = {
19509
+ maxResultBytes: 16 * KIB,
19510
+ maxSourceSliceBytes: 8 * KIB,
19511
+ maxTitleCharacters: 120,
19512
+ maxSummaryCharacters: 400,
19513
+ maxRequestKeyCharacters: 128,
19514
+ maxRepairRevisions: 2,
19515
+ maxTransientRetries: 2,
19516
+ maxUnpublishedArtifactsPerConversation: 100,
19517
+ maxRevisionsPerArtifact: 100,
19518
+ assetStoreBytesPerEnvironment: 1024 * MIB,
19519
+ scopeCapabilityTtlMs: 24 * 60 * 60 * 1000
19520
+ };
19521
+ var ARTIFACT_RETENTION_POLICY = {
19522
+ cleanupIntervalMs: 60 * 60 * 1000,
19523
+ abandonedStagingMs: 60 * 60 * 1000,
19524
+ unpublishedDraftMs: 7 * 24 * 60 * 60 * 1000,
19525
+ unreferencedPreviewAssetMs: 24 * 60 * 60 * 1000
19526
+ };
19527
+ var FRAME_CHANNEL_POLICY = {
19528
+ maxMessageBytes: 8 * KIB,
19529
+ messagesPerSecond: 20,
19530
+ burst: 40,
19531
+ sizeUpdatesPerSecond: 4,
19532
+ minInlineHeight: 120,
19533
+ maxInlineHeight: 1600,
19534
+ maxLinkCharacters: 2048,
19535
+ maxLinkLabelCharacters: 200
19536
+ };
19537
+
19341
19538
  // ../protocol/src/agent-system-instructions.ts
19342
- var AGENT_IMAGE_PREVIEW_INSTRUCTION = "Orkestrator renders Markdown images inline in the transcript. When you show the user an image in your reply (a screenshot, rendered preview, or chart) using Markdown image syntax, reference it by its absolute path. In a managed worktree or container environment, save the file inside the working directory, preferably in a git-ignored folder so preview files stay out of the change set. Local image previews are limited to Orkestrator-managed workspace storage or the container's /workspace. Project-home checkouts are excluded from host preview reads, even when they are the working directory, so images saved there cannot be previewed from a local Markdown path. Paths outside previewable storage, such as /tmp, also show a placeholder.";
19539
+ var AGENT_IMAGE_PREVIEW_INSTRUCTION = "Orkestrator renders Markdown images inline in the transcript. When you show the user an image in your reply (a photograph, screenshot, rendered preview, or a requested image file) using Markdown image syntax, reference it by its absolute path. In a managed worktree or container environment, save the file inside the working directory, preferably in a git-ignored folder so preview files stay out of the change set. Local image previews are limited to Orkestrator-managed workspace storage or the container's /workspace. Project-home checkouts are excluded from host preview reads, even when they are the working directory, so images saved there cannot be previewed from a local Markdown path. Paths outside previewable storage, such as /tmp, also show a placeholder.";
19343
19540
  var AGENT_DOCUMENT_INSTRUCTION = "When the user asks for a document (a report, design doc, plan, analysis, guide, or other writing to keep), prefer writing it as a Markdown file in a `docs/` folder at the root of the working directory, and tell the user the file's path. Project instructions (such as AGENTS.md or CLAUDE.md), local skills, and the user's own request take priority over this default when they say where or how to write documents.";
19541
+ var AGENT_CHART_SPEC_SHAPES = "bar adds xAxis:{kind:'category',label}, yAxis:{label,unit?}, categories:[{id,label}], series:[{id,label,points:[{categoryId,value|null}]}] (one point per category); " + "line/area/scatter add xAxis:{kind:'number'|'utc-time',label,unit?}, yAxis:{label,unit?}, series:[{id,label,points:[{x,y|null}]}]; " + "donut adds valueLabel, unit?, slices:[{id,label,value}]";
19542
+ var AGENT_CHART_FENCE_EXAMPLE = '{"schemaVersion":1,"kind":"bar","title":"Passing tests","description":"Passing tests per suite.","xAxis":{"kind":"category","label":"Suite"},"yAxis":{"label":"Tests"},"categories":[{"id":"unit","label":"Unit"},{"id":"browser","label":"Browser"}],"series":[{"id":"passed","label":"Passed","points":[{"categoryId":"unit","value":40},{"categoryId":"browser","value":8}]}]}';
19543
+ var AGENT_VISUAL_OUTPUT_INSTRUCTION = [
19544
+ "Orkestrator displays rich visuals directly in the conversation; choose one when it helps answer the question.",
19545
+ `Flows, architecture, sequences and relationships: a \`mermaid\` code fence. Standard bar, line, area, scatter and donut charts: a \`chart\` code fence holding one ChartSpecV1 JSON object with schemaVersion 1, kind, title and description; ${AGENT_CHART_SPEC_SHAPES}. For example: ${AGENT_CHART_FENCE_EXAMPLE}.`,
19546
+ "When this session has the Orkestrator artifact tools, use them for durable visuals: create_artifact, preview_artifact, get_artifact_operation to inspect the diagnostics and capture, then publish_artifact, and respect their repair limits.",
19547
+ `A custom report, timeline or layout combining text and graphics is an html-static artifact: self-contained HTML, CSS and inline SVG, with no scripts or network resources. Its verified document is displayed in the transcript as real, selectable content, so keep it within ${STATIC_PRESENTATION_POLICY.maxDocumentBytes / 1024} KiB and ${STATIC_PRESENTATION_POLICY.maxElements} elements, use fluid widths, let content set the height (no 100vh on the root), and colour it with the --ork-foreground, --ork-muted-foreground, --ork-background, --ork-border, --ork-primary and --ork-chart-1 to --ork-chart-8 CSS variables, which follow the application theme. Always give them a fallback, such as var(--ork-foreground, #18181b), because the preview defines none of them.`,
19548
+ "Behaviour that needs authored JavaScript, such as a calculator or a filterable dashboard, is an html-interactive artifact; it runs when the reader activates it.",
19549
+ "Use ordinary images only for photographs, screenshots and requested image files.",
19550
+ "HTML, SVG and JavaScript code fences are shown as source and a file path alone publishes nothing: a visual is in the conversation only once publish_artifact succeeds. If verification is unavailable, say so and use a supported form such as a Mermaid or chart fence."
19551
+ ].join(" ");
19344
19552
  var GENERAL_AGENT_INSTRUCTIONS = [
19553
+ AGENT_VISUAL_OUTPUT_INSTRUCTION,
19345
19554
  AGENT_IMAGE_PREVIEW_INSTRUCTION,
19346
19555
  AGENT_DOCUMENT_INSTRUCTION
19347
19556
  ];
@@ -20825,6 +21034,9 @@ function handlePromptSuggestion(turn, message) {
20825
21034
  function handleRateLimitEvent(turn, message) {
20826
21035
  const { session, sessionId } = turn;
20827
21036
  const info = message.rate_limit_info;
21037
+ if (info?.status) {
21038
+ turn.rateLimitRejected = info.status === "rejected" && info.isUsingOverage !== true && info.overageInUse !== true && info.overageStatus !== "allowed" && info.overageStatus !== "allowed_warning";
21039
+ }
20828
21040
  if (info) {
20829
21041
  const nextWindows = rateLimitsFromEventInfo(info);
20830
21042
  const nextLabels = new Set(nextWindows.map((window) => window.label));
@@ -20970,6 +21182,7 @@ function classifyUsageLimitError(text) {
20970
21182
  const hint = reset?.[1]?.trim();
20971
21183
  return hint ? { resetHint: hint } : {};
20972
21184
  }
21185
+ var USAGE_LIMIT_ERROR_CODE = "usage-limit";
20973
21186
 
20974
21187
  // ../../bridges/claude-bridge/src/services/session-manager-prompt-handlers/result.ts
20975
21188
  var log12 = createLogger("bridge.claude");
@@ -21495,7 +21708,7 @@ function handlePermissionDenied(turn, message) {
21495
21708
  const denial = message;
21496
21709
  const reason = boundedNoticeText(denial.decision_reason ?? denial.message);
21497
21710
  if (typeof denial.tool_use_id === "string") {
21498
- commandChangeProbe.discard(denial.tool_use_id);
21711
+ discardCommandChangeWindow(denial.tool_use_id);
21499
21712
  recordClaudeToolDenied(sessionId, denial.tool_use_id, typeof denial.tool_name === "string" ? { toolName: denial.tool_name } : {});
21500
21713
  }
21501
21714
  const marked = typeof denial.tool_use_id === "string" && toolTracker.recordDenial(denial.tool_use_id, {
@@ -21590,7 +21803,7 @@ function handleUserMessage(turn, message) {
21590
21803
  } = parseMessageContent(message, toolTracker, turn.mcpServerNames, activeTaskIds, taskRegistry, receivedAt, recordUnknownContentBlock);
21591
21804
  const sdkUserMessage = message;
21592
21805
  for (const toolUseId of toolResultIds(sdkUserMessage)) {
21593
- commandChangeProbe.discard(toolUseId);
21806
+ discardCommandChangeWindow(toolUseId);
21594
21807
  const pending = turn.pendingCommandChanges.get(toolUseId);
21595
21808
  if (pending) {
21596
21809
  turn.pendingCommandChanges.delete(toolUseId);
@@ -22021,6 +22234,7 @@ function endClaudeRuntime(runtime, failure) {
22021
22234
  if (interruptedOutsidePrompt) {
22022
22235
  session.status = "error";
22023
22236
  session.error = claudeProcessKilledMessage(killedBy);
22237
+ session.errorCode = undefined;
22024
22238
  session.interruption = "restart";
22025
22239
  session.interruptedRequestId = session.turnInFlightRequestId;
22026
22240
  session.turnStartedAt = undefined;
@@ -22064,6 +22278,7 @@ function releaseOrphanedForeground(runtime, error) {
22064
22278
  log15.error("runtime.ended-under-resumed-turn", { sessionId });
22065
22279
  session.status = "error";
22066
22280
  session.error = error instanceof Error ? error.message : String(error);
22281
+ session.errorCode = undefined;
22067
22282
  eventEmitter.emit({ type: "session.error", sessionId, data: { error: session.error } });
22068
22283
  }
22069
22284
  function abandonJoin(turn, running) {
@@ -22331,6 +22546,7 @@ function settleFailedTurn(turn, error) {
22331
22546
  session.turnStartedAt = turn.beforeStartup.turnStartedAt;
22332
22547
  session.abortController = turn.beforeStartup.abortController;
22333
22548
  session.error = turn.beforeStartup.error;
22549
+ session.errorCode = turn.beforeStartup.errorCode;
22334
22550
  session.interruption = turn.beforeStartup.interruption;
22335
22551
  session.interruptedRequestId = turn.beforeStartup.interruptedRequestId;
22336
22552
  session.inProgressUsage = turn.beforeStartup.inProgressUsage;
@@ -22358,6 +22574,7 @@ function settleFailedTurn(turn, error) {
22358
22574
  session.status = "error";
22359
22575
  session.turnStartedAt = undefined;
22360
22576
  session.error = failure;
22577
+ session.errorCode = turn.rateLimitRejected && !killedBy ? USAGE_LIMIT_ERROR_CODE : undefined;
22361
22578
  session.interruption = killedBy ? "restart" : undefined;
22362
22579
  session.interruptedRequestId = killedBy ? turn.dispatchRequestId : undefined;
22363
22580
  session.abortController = undefined;
@@ -22617,6 +22834,18 @@ var config_default = config2;
22617
22834
 
22618
22835
  // ../protocol/src/human-prompts.ts
22619
22836
  var HUMAN_PROMPT_SCAN_BYTES = 16 * 1024;
22837
+ var HUMAN_PROMPT_KINDS = new Set([
22838
+ "sign-in",
22839
+ "device-code",
22840
+ "press-enter",
22841
+ "secret",
22842
+ "host-key"
22843
+ ]);
22844
+ var HUMAN_PROMPT_SOURCES = new Set([
22845
+ "user-command",
22846
+ "agent-tool",
22847
+ "agent-background-task"
22848
+ ]);
22620
22849
  var HUMAN_PROMPT_OBSERVATION_ROWS = 64;
22621
22850
  function humanPromptObservation(messages, tasks) {
22622
22851
  const object = (value) => !!value && typeof value === "object" && !Array.isArray(value);
@@ -23801,6 +24030,7 @@ session.get("/:id", async (c) => {
23801
24030
  createdAt: sessionData.createdAt.toISOString(),
23802
24031
  lastActivity: sessionData.lastActivity.toISOString(),
23803
24032
  error: sessionData.error,
24033
+ ...sessionData.status === "error" && sessionData.errorCode ? { errorCode: sessionData.errorCode } : {},
23804
24034
  ...sessionData.status === "error" && sessionData.interruption ? {
23805
24035
  interruption: sessionData.interruption,
23806
24036
  ...sessionData.interruptedRequestId ? { interruptedRequestId: sessionData.interruptedRequestId } : {}
@@ -24817,22 +25047,163 @@ var streamSSE = (c, cb, onError) => {
24817
25047
  return c.newResponse(stream.responseReadable);
24818
25048
  };
24819
25049
 
25050
+ // ../protocol/src/node/event-ring.ts
25051
+ var DEFAULT_RING_CAPACITY = 512;
25052
+
25053
+ class EventRing {
25054
+ capacity;
25055
+ maxBytes;
25056
+ measureBytes;
25057
+ supersede;
25058
+ buffer = [];
25059
+ revision = 0;
25060
+ droppedEvents = 0;
25061
+ retainedBytes = 0;
25062
+ constructor(capacity = DEFAULT_RING_CAPACITY, options = {}) {
25063
+ this.capacity = Math.max(1, capacity);
25064
+ if (options.maxBytes !== undefined && !options.measureBytes) {
25065
+ throw new TypeError("EventRing: maxBytes requires measureBytes");
25066
+ }
25067
+ this.maxBytes = Math.max(0, options.maxBytes ?? Number.POSITIVE_INFINITY);
25068
+ this.measureBytes = options.measureBytes ?? (() => 0);
25069
+ this.supersede = options.supersede ?? null;
25070
+ }
25071
+ get latestRevision() {
25072
+ return this.revision;
25073
+ }
25074
+ get oldestRevision() {
25075
+ return this.buffer[0]?.revision ?? 0;
25076
+ }
25077
+ getStats() {
25078
+ return {
25079
+ retained: this.buffer.length,
25080
+ capacity: this.capacity,
25081
+ latestRevision: this.revision,
25082
+ dropped: this.droppedEvents,
25083
+ retainedBytes: this.retainedBytes,
25084
+ maxBytes: Number.isFinite(this.maxBytes) ? this.maxBytes : null
25085
+ };
25086
+ }
25087
+ append(event) {
25088
+ this.revision += 1;
25089
+ this.retain(event);
25090
+ return this.revision;
25091
+ }
25092
+ appendAt(revision, event) {
25093
+ this.skipTo(revision - 1);
25094
+ this.revision = revision;
25095
+ this.retain(event);
25096
+ }
25097
+ advance() {
25098
+ this.advanceTo(this.revision + 1);
25099
+ return this.revision;
25100
+ }
25101
+ advanceTo(revision) {
25102
+ this.skipTo(revision);
25103
+ this.revision = revision;
25104
+ }
25105
+ skipTo(revision) {
25106
+ if (!Number.isSafeInteger(revision) || revision < this.revision) {
25107
+ throw new RangeError("EventRing: revisions must not go backwards");
25108
+ }
25109
+ if (revision > this.revision && this.buffer.length > 0) {
25110
+ this.droppedEvents += this.buffer.length;
25111
+ this.clear();
25112
+ }
25113
+ }
25114
+ retain(event) {
25115
+ if (this.supersede)
25116
+ this.collapseSuperseded(event);
25117
+ this.retainedBytes += Math.max(0, this.measureBytes(event));
25118
+ this.buffer.push({ revision: this.revision, event });
25119
+ while (this.buffer.length > this.capacity || this.retainedBytes > this.maxBytes) {
25120
+ const removed = this.buffer.shift();
25121
+ if (!removed)
25122
+ break;
25123
+ this.retainedBytes -= Math.max(0, this.measureBytes(removed.event));
25124
+ this.droppedEvents += 1;
25125
+ }
25126
+ }
25127
+ collapseSuperseded(incoming) {
25128
+ const supersede = this.supersede;
25129
+ if (!supersede)
25130
+ return;
25131
+ for (let index = this.buffer.length - 1;index >= 0; index -= 1) {
25132
+ const entry = this.buffer[index];
25133
+ const replacement = supersede(incoming, entry.event);
25134
+ if (replacement === null)
25135
+ continue;
25136
+ if (replacement === entry.event)
25137
+ return;
25138
+ this.retainedBytes -= Math.max(0, this.measureBytes(entry.event));
25139
+ entry.event = replacement;
25140
+ this.retainedBytes += Math.max(0, this.measureBytes(replacement));
25141
+ }
25142
+ }
25143
+ since(cursor) {
25144
+ if (!Number.isFinite(cursor) || cursor < 0) {
25145
+ return { events: [], complete: false, latestRevision: this.revision };
25146
+ }
25147
+ if (cursor > this.revision) {
25148
+ return { events: [], complete: false, latestRevision: this.revision };
25149
+ }
25150
+ if (cursor === this.revision) {
25151
+ return { events: [], complete: true, latestRevision: this.revision };
25152
+ }
25153
+ const oldest = this.oldestRevision;
25154
+ const complete = oldest !== 0 && cursor + 1 >= oldest;
25155
+ return {
25156
+ events: complete ? this.buffer.filter((entry) => entry.revision > cursor) : [],
25157
+ complete,
25158
+ latestRevision: this.revision
25159
+ };
25160
+ }
25161
+ clear() {
25162
+ this.buffer.length = 0;
25163
+ this.retainedBytes = 0;
25164
+ }
25165
+ }
25166
+
24820
25167
  // ../../bridges/claude-bridge/src/routes/events.ts
24821
25168
  var log22 = createLogger("bridge.claude");
24822
- var serializedEventData = new WeakMap;
24823
- function serializeEventData(event) {
24824
- let data = serializedEventData.get(event);
24825
- if (data === undefined) {
24826
- data = JSON.stringify({
25169
+ var serializedEvents = new WeakMap;
25170
+ function serializeEvent(event) {
25171
+ let serialized = serializedEvents.get(event);
25172
+ if (serialized === undefined) {
25173
+ const data = JSON.stringify({
24827
25174
  sessionId: event.sessionId,
24828
25175
  ...event.data
24829
25176
  });
24830
- serializedEventData.set(event, data);
25177
+ serialized = { data, dataBytes: Buffer.byteLength(data) };
25178
+ serializedEvents.set(event, serialized);
24831
25179
  }
24832
- return data;
25180
+ return serialized;
24833
25181
  }
24834
25182
  var MAX_PENDING_SSE_FRAMES = 1000;
24835
25183
  var MAX_PENDING_SSE_BYTES = 16 * 1024 * 1024;
25184
+ var SUPERSEDED_FRAME_BYTES = 64;
25185
+ function supersedeReplayFrame(incoming, retained) {
25186
+ if (incoming.event !== "message.updated" || incoming.messageId === undefined)
25187
+ return null;
25188
+ if (retained.event !== "message.updated" && retained.event !== "message.patched")
25189
+ return null;
25190
+ if (retained.messageId !== incoming.messageId || retained.sessionId !== incoming.sessionId) {
25191
+ return null;
25192
+ }
25193
+ if (retained.superseded)
25194
+ return retained;
25195
+ return {
25196
+ revision: retained.revision,
25197
+ ...retained.id === undefined ? {} : { id: retained.id },
25198
+ event: retained.event,
25199
+ data: "{}",
25200
+ dataBytes: 2,
25201
+ bytes: SUPERSEDED_FRAME_BYTES,
25202
+ ...retained.sessionId === undefined ? {} : { sessionId: retained.sessionId },
25203
+ messageId: retained.messageId,
25204
+ superseded: true
25205
+ };
25206
+ }
24836
25207
  function observationFrameData(sessionId) {
24837
25208
  return JSON.stringify(sessionId === undefined ? {} : { sessionId });
24838
25209
  }
@@ -24840,47 +25211,52 @@ var MAX_REPLAY_SSE_FRAMES = 512;
24840
25211
  var MAX_REPLAY_SSE_BYTES = 4 * 1024 * 1024;
24841
25212
  var REPLAY_IDLE_RETENTION_MS = 60000;
24842
25213
  function createReplayBuffer(limits = {}) {
24843
- const maxFrames = limits.maxFrames ?? MAX_REPLAY_SSE_FRAMES;
24844
- const maxBytes = limits.maxBytes ?? MAX_REPLAY_SSE_BYTES;
24845
- const frames = [];
24846
- let bytes = 0;
25214
+ const ring = new EventRing(limits.maxFrames ?? MAX_REPLAY_SSE_FRAMES, {
25215
+ maxBytes: limits.maxBytes ?? MAX_REPLAY_SSE_BYTES,
25216
+ measureBytes: (frame) => frame.bytes,
25217
+ supersede: supersedeReplayFrame
25218
+ });
24847
25219
  return {
24848
25220
  append(event, revision, generation) {
24849
- const data = serializeEventData(event);
24850
- const frame = {
25221
+ const { data, dataBytes } = serializeEvent(event);
25222
+ const messageId = eventMessageId(event);
25223
+ ring.appendAt(revision, {
24851
25224
  revision,
24852
25225
  id: `${generation}:${revision}`,
24853
25226
  event: event.type,
24854
25227
  data,
24855
- bytes: Buffer.byteLength(data) + Buffer.byteLength(event.type),
24856
- ...event.sessionId === undefined ? {} : { sessionId: event.sessionId }
24857
- };
24858
- frames.push(frame);
24859
- bytes += frame.bytes;
24860
- while (frames.length > maxFrames || bytes > maxBytes) {
24861
- const removed = frames.shift();
24862
- if (!removed)
24863
- break;
24864
- bytes -= removed.bytes;
24865
- }
25228
+ dataBytes,
25229
+ bytes: dataBytes + Buffer.byteLength(event.type),
25230
+ ...event.sessionId === undefined ? {} : { sessionId: event.sessionId },
25231
+ ...messageId === undefined ? {} : { messageId }
25232
+ });
25233
+ },
25234
+ skip(revision) {
25235
+ ring.advanceTo(revision);
24866
25236
  },
24867
25237
  getFrames(since, through, generation) {
24868
25238
  if (since.generation !== generation || since.revision > through) {
24869
25239
  return { frames: [], resetRequired: true };
24870
25240
  }
24871
- const oldest = frames[0]?.revision;
24872
- const resetRequired = since.revision < through && (oldest === undefined || since.revision < oldest - 1);
24873
- return {
24874
- frames: resetRequired ? [] : frames.filter((frame) => frame.revision > since.revision && frame.revision <= through),
24875
- resetRequired
24876
- };
25241
+ if (since.revision === through)
25242
+ return { frames: [], resetRequired: false };
25243
+ const replay = ring.since(since.revision);
25244
+ if (!replay.complete)
25245
+ return { frames: [], resetRequired: true };
25246
+ const frames = [];
25247
+ for (const entry of replay.events) {
25248
+ if (entry.revision > through)
25249
+ break;
25250
+ frames.push(entry.event);
25251
+ }
25252
+ return { frames, resetRequired: false };
24877
25253
  },
24878
25254
  clear() {
24879
- frames.length = 0;
24880
- bytes = 0;
25255
+ ring.clear();
24881
25256
  },
24882
25257
  stats() {
24883
- return { frames: frames.length, bytes };
25258
+ const stats = ring.getStats();
25259
+ return { frames: stats.retained, bytes: stats.retainedBytes };
24884
25260
  }
24885
25261
  };
24886
25262
  }
@@ -24933,8 +25309,10 @@ function formatReplayCursor(revision) {
24933
25309
  return `${eventEmitter.generation}:${revision}`;
24934
25310
  }
24935
25311
  eventEmitter.subscribe((event, revision) => {
24936
- if (!replayRetention.shouldRetain())
25312
+ if (!replayRetention.shouldRetain()) {
25313
+ replayBuffer.skip(revision);
24937
25314
  return;
25315
+ }
24938
25316
  replayBuffer.append(event, revision, eventEmitter.generation);
24939
25317
  });
24940
25318
  function parseReplayCursor(value) {
@@ -24964,7 +25342,7 @@ function createBoundedSseWriter(write, onOverflow, limits = {}) {
24964
25342
  return (frame) => {
24965
25343
  if (overflowed)
24966
25344
  return Promise.resolve();
24967
- const frameBytes = Buffer.byteLength(frame.data);
25345
+ const frameBytes = frame.dataBytes ?? Buffer.byteLength(frame.data);
24968
25346
  if (pendingFrames > 0 && (pendingFrames >= maxPendingFrames || pendingBytes + frameBytes > maxPendingBytes)) {
24969
25347
  overflowed = true;
24970
25348
  onOverflow();
@@ -25045,13 +25423,21 @@ function createEventsRouter(limits = {}) {
25045
25423
  unsubscribe = eventEmitter.subscribe((event, revision) => {
25046
25424
  if (!isOpen)
25047
25425
  return;
25048
- const data = observe ? observationFrameData(event.sessionId) : serializeEventData(event);
25426
+ let data;
25427
+ let dataBytes;
25428
+ if (observe) {
25429
+ data = observationFrameData(event.sessionId);
25430
+ dataBytes = Buffer.byteLength(data);
25431
+ } else {
25432
+ ({ data, dataBytes } = serializeEvent(event));
25433
+ }
25049
25434
  const frame = {
25050
25435
  revision,
25051
25436
  id: formatReplayCursor(revision),
25052
25437
  event: event.type,
25053
25438
  data,
25054
- bytes: Buffer.byteLength(data) + Buffer.byteLength(event.type)
25439
+ dataBytes,
25440
+ bytes: dataBytes + Buffer.byteLength(event.type)
25055
25441
  };
25056
25442
  if (replaying) {
25057
25443
  if (pendingLiveFrames.length >= maxPendingFrames || pendingLiveBytes + frame.bytes > maxPendingBytes) {
@@ -25094,7 +25480,17 @@ function createEventsRouter(limits = {}) {
25094
25480
  });
25095
25481
  } else {
25096
25482
  for (const frame of replay.frames) {
25097
- await writeFrame(observe ? { ...frame, data: observationFrameData(frame.sessionId) } : frame);
25483
+ if (observe) {
25484
+ await writeFrame({
25485
+ id: frame.id,
25486
+ event: frame.event,
25487
+ data: observationFrameData(frame.sessionId)
25488
+ });
25489
+ } else if (frame.superseded) {
25490
+ await writeFrame({ id: frame.id, event: "bridge.cursor", data: "{}" });
25491
+ } else {
25492
+ await writeFrame(frame);
25493
+ }
25098
25494
  }
25099
25495
  }
25100
25496
  const drained = pendingLiveFrames.splice(0);
@@ -25237,6 +25633,7 @@ function installFatalRejectionGuard(options) {
25237
25633
  const APP_PATH = /(?:^|\/)((?:apps\/(?:backend|desktop|web|web-public)|packages\/(?:protocol|cli|toolchain)|bridges\/[\w-]+|[\w-]+-bridge)\/.*)$/;
25238
25634
  const PACKAGED_PATH = /\/((?:app\.asar(?:\.unpacked)?|resources)\/.*)$/i;
25239
25635
  const CREDENTIALS = [
25636
+ { pattern: /\bok[ab]_[A-Za-z0-9_-]{16,}/g, replacement: "[redacted]" },
25240
25637
  {
25241
25638
  pattern: /([a-z][a-z0-9+.-]*:\/\/)[^/\s:@]+(?::[^/\s@]*)?@/gi,
25242
25639
  replacement: "$1[redacted]@"
@@ -26856,12 +27253,79 @@ var serve = (options, listeningListener) => {
26856
27253
  return server;
26857
27254
  };
26858
27255
 
27256
+ // ../protocol/src/node/bridge-credential.ts
27257
+ import { createHash as createHash13, randomBytes as randomBytes2, timingSafeEqual } from "node:crypto";
27258
+ import { createRequire } from "node:module";
27259
+ var BRIDGE_TOKEN_PREFIX = "okb_";
27260
+ var PR_SET_DUMPABLE = 4;
27261
+ var VERIFIER_PATTERN = /^[0-9a-f]{64}$/;
27262
+ var log26 = createLogger("bridge.lifecycle");
27263
+ function mintBridgeToken() {
27264
+ return `${BRIDGE_TOKEN_PREFIX}${randomBytes2(32).toString("base64url")}`;
27265
+ }
27266
+ function bridgeTokenVerifier(token) {
27267
+ return createHash13("sha256").update(token).digest("hex");
27268
+ }
27269
+ function bridgeTokenVerifierEnv(tokenEnv) {
27270
+ return `${tokenEnv}_SHA256`;
27271
+ }
27272
+ function credentialFromVerifier(verifier, plainToken) {
27273
+ const expected = Buffer.from(verifier, "hex");
27274
+ return {
27275
+ plainToken,
27276
+ matches(candidate) {
27277
+ if (!candidate)
27278
+ return false;
27279
+ return timingSafeEqual(expected, createHash13("sha256").update(candidate).digest());
27280
+ }
27281
+ };
27282
+ }
27283
+ function bridgeCredentialFromToken(token) {
27284
+ return credentialFromVerifier(bridgeTokenVerifier(token), token);
27285
+ }
27286
+ function markProcessNonDumpable(loadFfi = () => createRequire(import.meta.url)("bun:ffi")) {
27287
+ if (process.platform !== "linux" || !process.versions.bun)
27288
+ return false;
27289
+ try {
27290
+ const { dlopen, FFIType } = loadFfi();
27291
+ const libc = dlopen("libc.so.6", {
27292
+ prctl: {
27293
+ args: [FFIType.i32, FFIType.u64, FFIType.u64, FFIType.u64, FFIType.u64],
27294
+ returns: FFIType.i32
27295
+ }
27296
+ });
27297
+ try {
27298
+ if (libc.symbols.prctl(PR_SET_DUMPABLE, 0n, 0n, 0n, 0n) === 0)
27299
+ return true;
27300
+ } finally {
27301
+ libc.close();
27302
+ }
27303
+ log26.warn("credential.not-hardened", { reason: "prctl-refused" });
27304
+ } catch {
27305
+ log26.warn("credential.not-hardened", { reason: "ffi-unavailable" });
27306
+ }
27307
+ return false;
27308
+ }
27309
+ function loadBridgeCredential(tokenEnv, options = {}) {
27310
+ const env = options.env ?? process.env;
27311
+ const verifierEnv = bridgeTokenVerifierEnv(tokenEnv);
27312
+ const verifier = env[verifierEnv]?.trim();
27313
+ const token = env[tokenEnv]?.trim();
27314
+ delete env[verifierEnv];
27315
+ delete env[tokenEnv];
27316
+ if (verifier) {
27317
+ (options.harden ?? markProcessNonDumpable)();
27318
+ return VERIFIER_PATTERN.test(verifier) ? credentialFromVerifier(verifier, undefined) : bridgeCredentialFromToken(mintBridgeToken());
27319
+ }
27320
+ return bridgeCredentialFromToken(token || mintBridgeToken());
27321
+ }
27322
+
26859
27323
  // ../../bridges/claude-bridge/src/index.ts
26860
- var log26 = createLogger("bridge.claude");
27324
+ var log27 = createLogger("bridge.claude");
26861
27325
  configureBridgeLogger();
26862
27326
  var app = new Hono2;
26863
27327
  app.onError((error, c) => {
26864
- log26.error("http.request-failed", {
27328
+ log27.error("http.request-failed", {
26865
27329
  method: c.req.method,
26866
27330
  path: c.req.path,
26867
27331
  error: formatLogError(error)
@@ -26870,9 +27334,7 @@ app.onError((error, c) => {
26870
27334
  });
26871
27335
  var BRIDGE_TOKEN_ENV = "CLAUDE_BRIDGE_TOKEN";
26872
27336
  var BRIDGE_ALLOWED_ORIGINS_ENV = "CLAUDE_BRIDGE_ALLOWED_ORIGINS";
26873
- var configuredBridgeAuthToken = process.env[BRIDGE_TOKEN_ENV]?.trim();
26874
- var bridgeAuthToken = configuredBridgeAuthToken || randomBytes2(32).toString("base64url");
26875
- delete process.env[BRIDGE_TOKEN_ENV];
27337
+ var bridgeCredential = loadBridgeCredential(BRIDGE_TOKEN_ENV);
26876
27338
  process.env.ORKESTRATOR_NATIVE_AGENT_BRIDGE = "claude";
26877
27339
  var bridgeAuthEnabledOverrideForTesting = null;
26878
27340
  function isBridgeAuthEnabled() {
@@ -26882,11 +27344,7 @@ function isBridgeAuthEnabled() {
26882
27344
  return !(process.env.CLAUDE_BRIDGE_NO_SERVER === "1" && process.env.CLAUDE_BRIDGE_AUTH_DISABLED_FOR_TESTING === "1");
26883
27345
  }
26884
27346
  function tokenMatches(candidate) {
26885
- if (!candidate)
26886
- return false;
26887
- const expected = Buffer.from(bridgeAuthToken);
26888
- const actual = Buffer.from(candidate);
26889
- return expected.length === actual.length && timingSafeEqual(expected, actual);
27347
+ return bridgeCredential.matches(candidate);
26890
27348
  }
26891
27349
  function bearerToken(header) {
26892
27350
  if (!header)
@@ -26990,7 +27448,7 @@ if (parentPid !== null) {
26990
27448
  startParentWatchdog({
26991
27449
  parentPid,
26992
27450
  onParentExit: () => {
26993
- log26.warn("parent.gone", { parentPid });
27451
+ log27.warn("parent.gone", { parentPid });
26994
27452
  process.exit(0);
26995
27453
  }
26996
27454
  });
@@ -27001,13 +27459,13 @@ function startBridgeServer(env = process.env, start = serve) {
27001
27459
  }
27002
27460
  const port = parseInt(env.PORT || "4097", 10);
27003
27461
  const hostname = env.HOSTNAME || "0.0.0.0";
27004
- log26.debug("server.starting", { hostname, port });
27462
+ log27.debug("server.starting", { hostname, port });
27005
27463
  const server = start({
27006
27464
  fetch: app.fetch,
27007
27465
  port,
27008
27466
  hostname
27009
27467
  });
27010
- log26.info("server.listening", { hostname, port });
27468
+ log27.info("server.listening", { hostname, port });
27011
27469
  return server;
27012
27470
  }
27013
27471
  var __testing = {
@@ -27017,7 +27475,7 @@ var __testing = {
27017
27475
  bridgeAuthEnabledOverrideForTesting = null;
27018
27476
  return;
27019
27477
  }
27020
- bridgeAuthToken = token;
27478
+ bridgeCredential = bridgeCredentialFromToken(token);
27021
27479
  bridgeAuthEnabledOverrideForTesting = true;
27022
27480
  },
27023
27481
  startBridgeServerForTesting: startBridgeServer