@tangle-network/agent-app 0.63.17 → 0.63.19

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.
Files changed (128) hide show
  1. package/dist/agent-profiles/d1.js +2 -2
  2. package/dist/agent-profiles/index.js +2 -2
  3. package/dist/agent-profiles/switch.d.ts +1 -1
  4. package/dist/agent-profiles/switch.js +1 -1
  5. package/dist/app-auth/index.js.map +1 -1
  6. package/dist/chat-routes/hybrid-producer.d.ts +1 -1
  7. package/dist/chat-routes/index.js +11 -11
  8. package/dist/chat-routes/model-failover-stream.d.ts +1 -1
  9. package/dist/chat-routes/turn-prefetch.d.ts +1 -1
  10. package/dist/{chunk-Z4RD5UF7.js → chunk-2PCNHHN2.js} +2 -2
  11. package/dist/{chunk-I6BZVIRH.js → chunk-3CI35I4X.js} +1 -1
  12. package/dist/chunk-3CI35I4X.js.map +1 -0
  13. package/dist/{chunk-ISP6ZH3G.js → chunk-3Q3UEWKK.js} +1 -1
  14. package/dist/chunk-3Q3UEWKK.js.map +1 -0
  15. package/dist/{chunk-VDYEVCQQ.js → chunk-5WSSH3X5.js} +2 -2
  16. package/dist/chunk-5WSSH3X5.js.map +1 -0
  17. package/dist/{chunk-NUWSPR5O.js → chunk-G3LZITCA.js} +2 -2
  18. package/dist/{chunk-IX6UVHXY.js → chunk-JKECSYDB.js} +2 -2
  19. package/dist/{chunk-6GX3UHQW.js → chunk-K3A2YAIX.js} +6 -6
  20. package/dist/chunk-K3A2YAIX.js.map +1 -0
  21. package/dist/{chunk-5GSZGTPJ.js → chunk-KA6LD4OI.js} +3 -3
  22. package/dist/{chunk-A3BJDXPX.js → chunk-LMIP4OVR.js} +5 -5
  23. package/dist/chunk-LMIP4OVR.js.map +1 -0
  24. package/dist/{chunk-MT6ZTQGD.js → chunk-N5RWYR5N.js} +1 -1
  25. package/dist/chunk-N5RWYR5N.js.map +1 -0
  26. package/dist/{chunk-7VTGB4DM.js → chunk-OSMMEMDH.js} +1 -1
  27. package/dist/chunk-OSMMEMDH.js.map +1 -0
  28. package/dist/{chunk-5FAKBTCK.js → chunk-OYFA7BAK.js} +1 -1
  29. package/dist/chunk-OYFA7BAK.js.map +1 -0
  30. package/dist/{chunk-7EDNPQHW.js → chunk-OZDMIYES.js} +1 -1
  31. package/dist/chunk-OZDMIYES.js.map +1 -0
  32. package/dist/{chunk-ZLX4BA27.js → chunk-QUT3T2IN.js} +1 -1
  33. package/dist/chunk-QUT3T2IN.js.map +1 -0
  34. package/dist/{chunk-PK65B6HP.js → chunk-UJYEBQMS.js} +1 -1
  35. package/dist/{chunk-PK65B6HP.js.map → chunk-UJYEBQMS.js.map} +1 -1
  36. package/dist/{chunk-5UQJ7F3P.js → chunk-UULUBF5J.js} +1 -1
  37. package/dist/chunk-UULUBF5J.js.map +1 -0
  38. package/dist/{chunk-LRYY3OX7.js → chunk-VEPII3YP.js} +4 -4
  39. package/dist/chunk-VEPII3YP.js.map +1 -0
  40. package/dist/{chunk-AVBNS64P.js → chunk-W6G2HF6M.js} +1 -1
  41. package/dist/chunk-W6G2HF6M.js.map +1 -0
  42. package/dist/{chunk-4GINUJPF.js → chunk-WRCMVBUJ.js} +1 -1
  43. package/dist/{chunk-4GINUJPF.js.map → chunk-WRCMVBUJ.js.map} +1 -1
  44. package/dist/{chunk-E3AOUTIR.js → chunk-XGFGSZS5.js} +2 -2
  45. package/dist/chunk-XGFGSZS5.js.map +1 -0
  46. package/dist/{chunk-EKXG4JSN.js → chunk-YRWUJKW5.js} +2 -2
  47. package/dist/chunk-YRWUJKW5.js.map +1 -0
  48. package/dist/journeys/artifacts.d.ts +1 -0
  49. package/dist/journeys/cli.js +1 -1
  50. package/dist/journeys/index.js +55 -18
  51. package/dist/journeys/index.js.map +1 -1
  52. package/dist/journeys/journey.d.ts +1 -0
  53. package/dist/journeys/score.d.ts +1 -1
  54. package/dist/journeys/scoreboard.d.ts +1 -2
  55. package/dist/journeys/send.d.ts +1 -2
  56. package/dist/launch-invariants/auth-lookup-cache.d.ts +1 -1
  57. package/dist/launch-invariants/catalog.d.ts +3 -3
  58. package/dist/launch-invariants/cli.js +3 -3
  59. package/dist/launch-invariants/index.d.ts +1 -1
  60. package/dist/launch-invariants/index.js +3 -3
  61. package/dist/launch-invariants/index.js.map +1 -1
  62. package/dist/launch-invariants/limit-alarms.d.ts +1 -1
  63. package/dist/launch-invariants/pasted-code.d.ts +1 -1
  64. package/dist/launch-invariants/schedule.d.ts +1 -1
  65. package/dist/launch-invariants/settlement.d.ts +2 -2
  66. package/dist/launch-invariants/sized-reads.d.ts +1 -1
  67. package/dist/launch-invariants/testing.js +3 -3
  68. package/dist/model-resolution/index.js +1 -1
  69. package/dist/platform/billable-turn-admission.d.ts +1 -1
  70. package/dist/platform/delegated-keys.d.ts +2 -2
  71. package/dist/platform/delegated-turn-keys.d.ts +1 -1
  72. package/dist/platform/index.js.map +1 -1
  73. package/dist/preflight/cli.js +1 -1
  74. package/dist/preflight/index.d.ts +1 -1
  75. package/dist/preflight/index.js +1 -1
  76. package/dist/preset-cloudflare/index.js +6 -6
  77. package/dist/public-consultation/index.js +9 -9
  78. package/dist/rollout/cli.js +1 -1
  79. package/dist/rollout/d1.js +1 -1
  80. package/dist/rollout/index.d.ts +1 -1
  81. package/dist/rollout/index.js +1 -1
  82. package/dist/runtime/index.js +3 -3
  83. package/dist/runtime/router-turn.d.ts +3 -3
  84. package/dist/runtime/router-turn.js +2 -2
  85. package/dist/runtime/turn-knowledge.d.ts +1 -1
  86. package/dist/sandbox/index.js +5 -5
  87. package/dist/sandbox/model.d.ts +1 -1
  88. package/dist/sandbox/prewarm-claim-d1.d.ts +1 -1
  89. package/dist/sandbox/prewarm.d.ts +2 -2
  90. package/dist/sandbox/reuse-state.d.ts +1 -1
  91. package/dist/sandbox/terminal-connection.d.ts +4 -4
  92. package/dist/sandbox/warm-lease.d.ts +2 -2
  93. package/dist/sandbox/warm-receipts.d.ts +1 -1
  94. package/dist/signoff/app-defaults.d.ts +1 -1
  95. package/dist/signoff/cli.js +2 -2
  96. package/dist/signoff/index.js +2 -2
  97. package/dist/signoff/surface-ladder.d.ts +2 -2
  98. package/dist/signoff/workspace-surface.d.ts +1 -1
  99. package/dist/stream/index.js +2 -2
  100. package/dist/stream/turn-buffer.d.ts +1 -1
  101. package/dist/turn-health/index.js +1 -1
  102. package/dist/turn-health/index.js.map +1 -1
  103. package/dist/turn-stream/adapters.d.ts +1 -1
  104. package/dist/turn-stream/core.d.ts +1 -1
  105. package/dist/turn-stream/index.js +2 -2
  106. package/dist/turn-trace/index.js +1 -1
  107. package/dist/turn-trace/otel.d.ts +1 -1
  108. package/dist/workspace-export/index.js.map +1 -1
  109. package/package.json +1 -1
  110. package/dist/chunk-5FAKBTCK.js.map +0 -1
  111. package/dist/chunk-5UQJ7F3P.js.map +0 -1
  112. package/dist/chunk-6GX3UHQW.js.map +0 -1
  113. package/dist/chunk-7EDNPQHW.js.map +0 -1
  114. package/dist/chunk-7VTGB4DM.js.map +0 -1
  115. package/dist/chunk-A3BJDXPX.js.map +0 -1
  116. package/dist/chunk-AVBNS64P.js.map +0 -1
  117. package/dist/chunk-E3AOUTIR.js.map +0 -1
  118. package/dist/chunk-EKXG4JSN.js.map +0 -1
  119. package/dist/chunk-I6BZVIRH.js.map +0 -1
  120. package/dist/chunk-ISP6ZH3G.js.map +0 -1
  121. package/dist/chunk-LRYY3OX7.js.map +0 -1
  122. package/dist/chunk-MT6ZTQGD.js.map +0 -1
  123. package/dist/chunk-VDYEVCQQ.js.map +0 -1
  124. package/dist/chunk-ZLX4BA27.js.map +0 -1
  125. /package/dist/{chunk-Z4RD5UF7.js.map → chunk-2PCNHHN2.js.map} +0 -0
  126. /package/dist/{chunk-NUWSPR5O.js.map → chunk-G3LZITCA.js.map} +0 -0
  127. /package/dist/{chunk-IX6UVHXY.js.map → chunk-JKECSYDB.js.map} +0 -0
  128. /package/dist/{chunk-5GSZGTPJ.js.map → chunk-KA6LD4OI.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/sandbox/recovery.ts","../src/sandbox/diagnostics.ts","../src/sandbox/transient-failure.ts"],"sourcesContent":["/**\n * What an app does after the platform hands back a sandbox it cannot use.\n *\n * `replaceUnbringableBox` (see `./index`) decides whether to abandon a dead box.\n * This decides everything around that: which box key the next attempt uses,\n * whether the old box's snapshot is safe to restore from, whether an owner has\n * to confirm the loss first, and what the person waiting is told. It is\n * bookkeeping, not I/O — the app supplies storage through\n * {@link WorkspaceSandboxRecoveryStore}.\n *\n * ── Why the tables ──────────────────────────────────────────────────────────\n * Every fact about an action or a code lives in ACTIONS/CODES below, and the\n * types are DERIVED from those tables. That is deliberate, and it is the whole\n * reliability argument for this module.\n *\n * The hand-maintained alternative — a union type plus a separate `x === 'a' ||\n * x === 'b' || …` list per question — silently drops anything not on the list.\n * A recovery recorded under an unlisted action is written to storage, read\n * back, discarded as malformed, and the workspace re-provisions the box it just\n * abandoned. Nothing throws. The fix looks correct, ships, and does nothing.\n * That failure was hit twice inside one change before this module existed.\n *\n * With the tables, adding an action or code is a compile error until every\n * question about it is answered. There is no list to forget.\n */\n\n/** The box exists and still holds unsnapshotted state, so discarding it is an\n * owner's decision, not the runtime's. */\nexport const EGRESS_PROXY_RECOVERY_REQUIRED = 'EGRESS_PROXY_RECOVERY_REQUIRED'\nexport const EGRESS_PROXY_RECOVERY_PHASE = 'egress_proxy_recovery'\n/** The platform no longer has the box. Nothing to confirm, delete, or restore. */\nexport const WORKSPACE_SANDBOX_MISSING = 'WORKSPACE_SANDBOX_MISSING'\n/** The box exists but its host has no free slot, so it can never be resumed\n * where it is. A replacement can be placed on a host with room. */\nexport const WORKSPACE_SANDBOX_HOST_EXHAUSTED = 'WORKSPACE_SANDBOX_HOST_EXHAUSTED'\n/** The platform ran its own recovery, failed, and asked for a replacement.\n * Covers every way a box ends up unbringable with no more specific cause. */\nexport const WORKSPACE_SANDBOX_UNRECOVERABLE = 'WORKSPACE_SANDBOX_UNRECOVERABLE'\n\nexport const WORKSPACE_SANDBOX_SNAPSHOT_MAX_AGE_MS = 24 * 60 * 60 * 1000\n\n/**\n * Every recovery cause, and the one thing the runtime must know about each:\n * whether the box it names can still be read from.\n *\n * `snapshotUsable: false` is not a preference. A snapshot is addressed by the\n * sandbox it was taken from, so when that sandbox cannot be started the restore\n * fails exactly the way the resume did — and an app that tried it would turn a\n * recoverable workspace into a stuck one.\n */\nconst CODES = {\n [EGRESS_PROXY_RECOVERY_REQUIRED]: { snapshotUsable: true },\n [WORKSPACE_SANDBOX_MISSING]: { snapshotUsable: false },\n [WORKSPACE_SANDBOX_HOST_EXHAUSTED]: { snapshotUsable: false },\n [WORKSPACE_SANDBOX_UNRECOVERABLE]: { snapshotUsable: false },\n} as const\n\nexport type WorkspaceSandboxRecoveryCode = keyof typeof CODES\n\n/**\n * Every recovery action, and whether it means a replacement box has been\n * CHOSEN — the single question that decides which box key the next provisioning\n * attempt uses.\n *\n * `replacementChosen: false` covers the states where a key may be recorded but\n * must not be used yet: an owner has been asked and has not answered, or has\n * answered no. Handing back a key in those states replaces a box the owner\n * declined to lose.\n */\nconst ACTIONS = {\n confirmation_required: { replacementChosen: false, canDecide: true },\n deletion_declined: { replacementChosen: false, canDecide: true },\n replacement_authorized: { replacementChosen: false },\n snapshot_replacement_authorized: { replacementChosen: false },\n replacement_started: { replacementChosen: true, completedAs: 'replacement_completed' },\n replacement_completed: { replacementChosen: true },\n snapshot_replacement_started: { replacementChosen: true, completedAs: 'snapshot_replacement_completed' },\n snapshot_restore_failed: { replacementChosen: true, completedAs: 'snapshot_replacement_completed' },\n snapshot_replacement_completed: { replacementChosen: true },\n missing_replacement_started: { replacementChosen: true, completedAs: 'missing_replacement_completed' },\n missing_replacement_completed: { replacementChosen: true },\n unrecoverable_replacement_started: { replacementChosen: true, completedAs: 'unrecoverable_replacement_completed' },\n unrecoverable_replacement_completed: { replacementChosen: true },\n} as const\n\nexport type WorkspaceSandboxRecoveryAction = keyof typeof ACTIONS\n\nexport type WorkspaceSandboxSnapshotAvailability = 'available' | 'missing' | 'stale'\nexport type WorkspaceSandboxSnapshotFreshness = 'fresh' | 'stale' | 'unknown'\n\n/** A snapshot the app took of a box, addressed by the box it came from. */\nexport interface WorkspaceSandboxSnapshot {\n fromSandboxId: string\n createdAt: string\n [key: string]: unknown\n}\n\nexport interface WorkspaceSandboxSnapshotAssessment<Snapshot extends WorkspaceSandboxSnapshot = WorkspaceSandboxSnapshot> {\n availability: WorkspaceSandboxSnapshotAvailability\n freshness: WorkspaceSandboxSnapshotFreshness\n snapshot?: Snapshot\n}\n\nexport interface WorkspaceSandboxRecoveryState<Snapshot extends WorkspaceSandboxSnapshot = WorkspaceSandboxSnapshot> {\n code: WorkspaceSandboxRecoveryCode\n sandboxId: string\n detectedAt: string\n snapshot: WorkspaceSandboxSnapshotAssessment<Snapshot>\n action: WorkspaceSandboxRecoveryAction\n replacementBoxKey?: string\n replacementSandboxId?: string\n confirmedAt?: string\n}\n\nexport type WorkspaceSandboxRecoveryDecision = 'replace' | 'decline'\n\n/** Raised when chat cannot continue until an owner decides about the box. */\nexport class WorkspaceSandboxRecoveryRequiredError extends Error {\n readonly code = EGRESS_PROXY_RECOVERY_REQUIRED\n readonly status = 409\n readonly phase = EGRESS_PROXY_RECOVERY_PHASE\n readonly recovery: WorkspaceSandboxRecoveryState\n\n constructor(recovery: WorkspaceSandboxRecoveryState, cause: Error) {\n super(workspaceSandboxRecoveryMessage(recovery), { cause })\n this.name = 'WorkspaceSandboxRecoveryRequiredError'\n this.recovery = recovery\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n\nfunction asNonEmptyString(value: unknown): string | undefined {\n return typeof value === 'string' && value.trim().length > 0 ? value : undefined\n}\n\n/** Walk `cause` and `errors` breadth-first, cycle-safe. */\nfunction errorChain(error: unknown): unknown[] {\n const pending = [error]\n const visited = new Set<unknown>()\n const chain: unknown[] = []\n\n while (pending.length > 0) {\n const current = pending.shift()\n if (current === undefined || current === null || visited.has(current)) continue\n visited.add(current)\n chain.push(current)\n if (!isRecord(current)) continue\n if (current.cause !== undefined) pending.push(current.cause)\n if (Array.isArray(current.errors)) pending.push(...current.errors)\n }\n\n return chain\n}\n\nexport function isEgressProxyRecoveryRequiredError(error: unknown): boolean {\n return errorChain(error).some((current) =>\n isRecord(current) && current.code === EGRESS_PROXY_RECOVERY_REQUIRED,\n )\n}\n\nexport function isWorkspaceSandboxSnapshotRestoreError(error: unknown): boolean {\n return errorChain(error).some((current) => {\n const message = current instanceof Error\n ? current.message\n : isRecord(current) && typeof current.message === 'string'\n ? current.message\n : ''\n return /snapshot|fromSnapshot|restore/i.test(message)\n })\n}\n\n/**\n * Judge a snapshot against the box being replaced.\n *\n * Fresh means BOTH that it came from this exact sandbox and that it is inside\n * the age bound — a snapshot from a different box restores someone else's\n * filesystem, which is worse than starting empty.\n */\nexport function assessWorkspaceSandboxSnapshot<Snapshot extends WorkspaceSandboxSnapshot>(\n snapshot: Snapshot | undefined,\n sandboxId: string,\n now = Date.now(),\n): WorkspaceSandboxSnapshotAssessment<Snapshot> {\n if (!snapshot) return { availability: 'missing', freshness: 'unknown' }\n\n const createdAt = Date.parse(snapshot.createdAt)\n const ageMs = now - createdAt\n const isFresh = snapshot.fromSandboxId === sandboxId\n && Number.isFinite(createdAt)\n && ageMs >= 0\n && ageMs <= WORKSPACE_SANDBOX_SNAPSHOT_MAX_AGE_MS\n\n return isFresh\n ? { availability: 'available', freshness: 'fresh', snapshot }\n : { availability: 'stale', freshness: 'stale', snapshot }\n}\n\nfunction isSnapshotAssessment(value: unknown): value is WorkspaceSandboxSnapshotAssessment {\n if (!isRecord(value)) return false\n const availability = value.availability\n const freshness = value.freshness\n return (availability === 'available' || availability === 'missing' || availability === 'stale')\n && (freshness === 'fresh' || freshness === 'stale' || freshness === 'unknown')\n}\n\nexport function isWorkspaceSandboxRecoveryAction(\n value: unknown,\n): value is WorkspaceSandboxRecoveryAction {\n return typeof value === 'string' && Object.hasOwn(ACTIONS, value)\n}\n\nexport function isWorkspaceSandboxRecoveryCode(\n value: unknown,\n): value is WorkspaceSandboxRecoveryCode {\n return typeof value === 'string' && Object.hasOwn(CODES, value)\n}\n\nexport function isWorkspaceSandboxRecoveryState(\n value: unknown,\n): value is WorkspaceSandboxRecoveryState {\n if (!isRecord(value)) return false\n return isWorkspaceSandboxRecoveryCode(value.code)\n && !!asNonEmptyString(value.sandboxId)\n && !!asNonEmptyString(value.detectedAt)\n && isSnapshotAssessment(value.snapshot)\n && isWorkspaceSandboxRecoveryAction(value.action)\n}\n\nexport function workspaceSandboxRecoveryFromError(\n error: unknown,\n): WorkspaceSandboxRecoveryState | undefined {\n for (const current of errorChain(error)) {\n if (!isRecord(current) || !isWorkspaceSandboxRecoveryState(current.recovery)) continue\n return current.recovery\n }\n return undefined\n}\n\n/** What to tell the person waiting. Never names the product, so an app can\n * surface it verbatim. */\nexport function workspaceSandboxRecoveryMessage(recovery: WorkspaceSandboxRecoveryState): string {\n if (recovery.code === WORKSPACE_SANDBOX_MISSING) {\n return 'The sandbox behind this workspace no longer exists on the platform. A replacement is being provisioned and your saved work is restored into it.'\n }\n if (!CODES[recovery.code].snapshotUsable) {\n return 'The sandbox behind this workspace could not be started again. A replacement is being provisioned and your saved work is restored into it.'\n }\n if (recovery.action === 'deletion_declined') {\n return 'Sandbox recovery remains paused because replacement was declined. The stopped sandbox has not been deleted.'\n }\n if (recovery.action === 'confirmation_required') {\n const snapshotReason = recovery.snapshot.availability === 'missing'\n ? 'No restorable sandbox snapshot is available.'\n : 'The available sandbox snapshot is stale.'\n return `Sandbox recovery requires owner confirmation before replacement. ${snapshotReason} The stopped sandbox has not been deleted.`\n }\n if (recovery.action === 'snapshot_restore_failed') {\n return 'Sandbox replacement could not restore its verified snapshot, and an empty fallback was not created because it could lose workspace state.'\n }\n return 'Sandbox recovery is required before chat can continue. The stopped sandbox has not been deleted.'\n}\n\nexport function workspaceSandboxRecoveryRecommendedActions(\n recovery: WorkspaceSandboxRecoveryState,\n): string[] {\n if (!CODES[recovery.code].snapshotUsable) {\n return ['Retry after the replacement sandbox finishes provisioning.']\n }\n if (recovery.action === 'deletion_declined') {\n return ['Keep the stopped sandbox for support or ask a workspace owner to authorize replacement.']\n }\n if (recovery.action === 'confirmation_required') {\n return ['An owner can explicitly replace the sandbox after accepting loss of unsnapshotted sandbox-local changes.']\n }\n if (recovery.action === 'snapshot_restore_failed') {\n return ['Retry snapshot restoration or contact support. An empty replacement is not created automatically.']\n }\n return ['Retry after sandbox recovery completes.']\n}\n\n/** Flat key/value shape for a log line — no nesting, no secrets. */\nexport function workspaceSandboxRecoveryDiagnostic(\n recovery: WorkspaceSandboxRecoveryState,\n): Record<string, string | undefined> {\n return {\n sandboxId: recovery.sandboxId,\n recoveryCode: recovery.code,\n snapshotAvailability: recovery.snapshot.availability,\n snapshotFreshness: recovery.snapshot.freshness,\n selectedRecoveryAction: recovery.action,\n replacementSandboxId: recovery.replacementSandboxId,\n }\n}\n\n/**\n * The box key the next provisioning attempt should use, or undefined to keep\n * using the workspace's own key.\n *\n * Reads {@link ACTIONS} rather than a hand-kept list, because the failure mode\n * of a hand-kept list here is invisible: the key is recorded, silently ignored,\n * and provisioning goes back to the box the app just decided to abandon.\n */\nexport function preferredWorkspaceSandboxRecoveryBoxKey(\n recovery: WorkspaceSandboxRecoveryState | undefined,\n): string | undefined {\n if (!recovery?.replacementBoxKey) return undefined\n return ACTIONS[recovery.action].replacementChosen ? recovery.replacementBoxKey : undefined\n}\n\n/** Whether the replacement should be restored from the old box's snapshot. */\nexport function shouldRestoreWorkspaceSandboxRecovery(\n recovery: WorkspaceSandboxRecoveryState | undefined,\n): boolean {\n if (!recovery) return false\n if (!CODES[recovery.code].snapshotUsable) return false\n return !!preferredWorkspaceSandboxRecoveryBoxKey(recovery)\n && recovery.snapshot.availability === 'available'\n}\n\n/** One current recovery per workspace, stored by the application.\n * Concurrent writers should supply compareAndSet. Legacy write-only stores\n * remain supported but must serialize decisions and completion themselves. */\nexport interface WorkspaceSandboxRecoveryStore<Snapshot extends WorkspaceSandboxSnapshot = WorkspaceSandboxSnapshot> {\n read: (workspaceId: string) => Promise<WorkspaceSandboxRecoveryState<Snapshot> | undefined>\n write: (workspaceId: string, recovery: WorkspaceSandboxRecoveryState<Snapshot>) => Promise<void>\n /** Commit a transition only while the exact recovery read above remains current. */\n compareAndSet?: (\n workspaceId: string,\n expected: WorkspaceSandboxRecoveryState<Snapshot>,\n recovery: WorkspaceSandboxRecoveryState<Snapshot>,\n ) => Promise<boolean>\n}\n\nexport interface WorkspaceSandboxRecoveryManager<Snapshot extends WorkspaceSandboxSnapshot = WorkspaceSandboxSnapshot> {\n read: WorkspaceSandboxRecoveryStore<Snapshot>['read']\n record: WorkspaceSandboxRecoveryStore<Snapshot>['write']\n /** Only a pending/declined recovery for this sandbox accepts a new decision.\n * Replacement requires a fresh, nonblank key; decline needs no key. */\n decide: (args: {\n workspaceId: string\n sandboxId: string\n } & (\n | { decision: 'replace'; replacementBoxKey: string }\n | { decision: 'decline'; replacementBoxKey?: string }\n )) => Promise<WorkspaceSandboxRecoveryState<Snapshot> | undefined>\n /** Only a started replacement with a chosen key may be completed. */\n complete: (args: {\n workspaceId: string\n replacementSandboxId: string\n /** The key used by this provisioning attempt, not a freshly read successor. */\n replacementBoxKey?: string\n }) => Promise<WorkspaceSandboxRecoveryState<Snapshot> | undefined>\n}\n\n/** Bind canonical recovery policy to the application's existing storage. */\nexport function createWorkspaceSandboxRecoveryManager<Snapshot extends WorkspaceSandboxSnapshot>(\n store: WorkspaceSandboxRecoveryStore<Snapshot>,\n): WorkspaceSandboxRecoveryManager<Snapshot> {\n type State = WorkspaceSandboxRecoveryState<Snapshot>\n async function transition(workspaceId: string, expected: State, next: State): Promise<State> {\n if (store.compareAndSet) {\n if (!await store.compareAndSet(workspaceId, expected, next))\n throw new Error('Sandbox recovery changed; reload before retrying its transition')\n } else {\n await store.write(workspaceId, next)\n }\n return next\n }\n\n return {\n read: workspaceId => store.read(workspaceId),\n record: (workspaceId, recovery) => store.write(workspaceId, recovery),\n async decide({ workspaceId, sandboxId, decision, replacementBoxKey }) {\n const current = await store.read(workspaceId)\n if (!current || current.sandboxId !== sandboxId || !('canDecide' in ACTIONS[current.action])) return undefined\n if (decision === 'replace' && !asNonEmptyString(replacementBoxKey))\n throw new Error('Sandbox replacement authorization requires a fresh replacement box key')\n return transition(workspaceId, current, {\n ...current,\n action: decision === 'replace'\n ? (current.snapshot.availability === 'available' ? 'snapshot_replacement_authorized' : 'replacement_authorized')\n : 'deletion_declined',\n confirmedAt: new Date().toISOString(),\n ...(decision === 'replace' ? { replacementBoxKey } : {}),\n })\n },\n async complete({ workspaceId, replacementSandboxId, replacementBoxKey }) {\n const current = await store.read(workspaceId)\n if (!current || !asNonEmptyString(current.replacementBoxKey)) return undefined\n if (replacementBoxKey !== undefined && current.replacementBoxKey !== replacementBoxKey) return undefined\n const policy = ACTIONS[current.action]\n if (!('completedAs' in policy)) return undefined\n if (!asNonEmptyString(replacementSandboxId)) throw new Error('A replacement sandbox id is required')\n return transition(workspaceId, current, { ...current, action: policy.completedAs, replacementSandboxId })\n },\n }\n}\n\n/** Every declared action, for exhaustiveness tests in apps and here. */\nexport const WORKSPACE_SANDBOX_RECOVERY_ACTIONS = Object.keys(\n ACTIONS,\n) as readonly WorkspaceSandboxRecoveryAction[]\n\n/** Every declared cause. */\nexport const WORKSPACE_SANDBOX_RECOVERY_CODES = Object.keys(\n CODES,\n) as readonly WorkspaceSandboxRecoveryCode[]\n","/**\n * Read a sandbox provisioning failure without leaking what it carries.\n *\n * Provisioning errors arrive as deep `cause` chains from the sandbox API, the\n * runtime sidecar, and the app's own vault code, and they routinely carry\n * bearer tokens and signed URLs in their messages. Every app on this shell\n * needs the same three things from one: a redacted shape it can log, a\n * classification it can act on, and a sentence it can show a person. Before\n * this module each app either wrote its own or — far more often — wrote none,\n * and surfaced the raw error or a generic apology.\n *\n * The classifiers are deliberately narrow. `isSandboxApiSandboxMissingFailure`\n * does not fire on a 404 from inside a live box; `isSandboxHostCapacityFailure`\n * does not fire on capacity wording from any origin but the sandbox API. A\n * classifier that over-matches turns a transient failure into a box deletion.\n */\nimport { EGRESS_PROXY_RECOVERY_REQUIRED } from './recovery'\n\nconst SAFE_ERROR_FIELDS = [\n 'code',\n 'status',\n 'phase',\n 'endpoint',\n 'origin',\n 'retryAfterMs',\n 'sidecarVersion',\n 'containerImage',\n] as const\n\nexport interface SafeSandboxErrorCause {\n name?: string\n message?: string\n code?: string | number\n status?: string | number\n phase?: string\n endpoint?: string\n origin?: string\n retryAfterMs?: number\n sidecarVersion?: string\n containerImage?: string\n}\n\nexport interface SafeSandboxErrorDiagnostics {\n message: string\n causes: SafeSandboxErrorCause[]\n truncated: boolean\n truncatedAtDepth?: number\n cycle: boolean\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n\nfunction asSafeScalar(value: unknown): string | number | undefined {\n if (typeof value === 'string' && value.length > 0) return redactDiagnosticText(value)\n if (typeof value === 'number' && Number.isFinite(value)) return value\n return undefined\n}\n\nfunction redactDiagnosticText(value: string): string {\n const secretKeyPattern = '(?:(?:[A-Z0-9]+_)*(?:api_?key|auth_?token|access_?token|refresh_?token|key|token|password|secret|credential)|apiKey|authToken|accessToken|refreshToken)'\n return value\n .replace(/(['\"]authorization['\"]\\s*:\\s*)(['\"])[^'\"]*\\2/gi, '$1$2[REDACTED]$2')\n .replace(/\\b(authorization\\s*[:=]\\s*)(['\"])[^'\"]*\\2/gi, '$1$2[REDACTED]$2')\n .replace(/\\b(authorization\\s*[:=]\\s*)Digest\\b[^;}\\n]*(?:\\r?\\n[ \\t]+[^;}\\n]*)*/gi, '$1[REDACTED]')\n .replace(/\\b(authorization\\s*[:=]\\s*)(?:Basic|Bearer|Negotiate)\\s+[^\\s;,&}\\n]+(?:\\r?\\n[ \\t]+[^\\s;,&}\\n]+)*/gi, '$1[REDACTED]')\n .replace(new RegExp(`\\\\b(authorization\\\\s*[:=]\\\\s*)(?!(?:Basic|Bearer|Digest|Negotiate)\\\\b)([A-Za-z][A-Za-z0-9._-]+)\\\\s+(?!(?:authorization|${secretKeyPattern})\\\\s*[:=]|['\"](?:authorization|${secretKeyPattern})['\"]\\\\s*:)([^}\\\\n]*(?:\\\\r?\\\\n[ \\\\t]+[^}\\\\n]*)*)`, 'gi'), (_match, prefix: string, _scheme: string, valuePart: string) => {\n if (valuePart.includes(';') || /\\r?\\n[ \\t]+/.test(valuePart)) return `${prefix}[REDACTED]`\n const tokenMatch = valuePart.match(/^\\S+(.*)$/)\n return `${prefix}[REDACTED]${tokenMatch?.[1] ?? ''}`\n })\n .replace(/\\b(authorization\\s*[:=]\\s*)[A-Za-z][\\w.-]+\\s+[^\\s;,&}\\n]+(?=[;&}\\n]|$)/gi, '$1[REDACTED]')\n .replace(/\\b(authorization\\s*[:=]\\s*)(?!\\[REDACTED\\])[^'\"\\s&}]+(?:[;,][^'\"\\s&}]+)*/gi, '$1[REDACTED]')\n .replace(/\\bBearer\\s+[A-Za-z0-9._~+/-]+=*/gi, 'Bearer [REDACTED]')\n .replace(/\\bsk-[A-Za-z0-9_-]{6,}\\b/g, 'sk-[REDACTED]')\n .replace(\n /([?&][^=&#\\s]*(?:token|key|secret|password|authorization)[^=&#\\s]*=)[^&#\\s]+/gi,\n '$1[REDACTED]',\n )\n .replace(\n new RegExp(`(['\"])(${secretKeyPattern})\\\\1\\\\s*:\\\\s*(['\"])[^'\"]+\\\\3`, 'gi'),\n '$1$2$1:$3[REDACTED]$3',\n )\n .replace(\n new RegExp(`\\\\b(${secretKeyPattern})\\\\s*([:=])(\\\\s*)(['\"]?)(?!Bearer\\\\b)[^'\"\\\\s;,&}]+(?:[;,]\\\\s*[^'\"\\\\s;,&}]+)*`, 'gi'),\n '$1$2$3$4[REDACTED]',\n )\n}\n\nfunction readMessage(value: unknown): string | undefined {\n if (value instanceof Error) return redactDiagnosticText(value.message)\n if (typeof value === 'string' && value.length > 0) return redactDiagnosticText(value)\n if (typeof value === 'number' && Number.isFinite(value)) return String(value)\n if (typeof value === 'boolean') return String(value)\n if (!isRecord(value)) return undefined\n const message = value.message\n return typeof message === 'string' && message.length > 0 ? redactDiagnosticText(message) : undefined\n}\n\nfunction readName(value: unknown): string | undefined {\n if (value instanceof Error) return redactDiagnosticText(value.name)\n if (!isRecord(value)) return undefined\n const name = value.name\n return typeof name === 'string' && name.length > 0 ? redactDiagnosticText(name) : undefined\n}\n\nfunction readCause(value: unknown): unknown {\n if (!isRecord(value)) return undefined\n return value.cause\n}\n\nexport function serializeSandboxProvisioningError(\n error: unknown,\n options: { maxDepth?: number } = {},\n): SafeSandboxErrorDiagnostics {\n const maxDepth = options.maxDepth ?? 6\n const causes: SafeSandboxErrorCause[] = []\n const seen = new Set<unknown>()\n let truncatedAtDepth: number | undefined\n let cycle = false\n\n let current: unknown = error\n let depth = 0\n for (; depth < maxDepth && current !== undefined && current !== null; depth += 1) {\n if (seen.has(current)) {\n cycle = true\n causes.push({\n name: 'CauseChainCycle',\n message: `cause chain cycle detected after ${depth} entries`,\n })\n break\n }\n if (isRecord(current)) seen.add(current)\n\n const cause: SafeSandboxErrorCause = {}\n const name = readName(current)\n const message = readMessage(current)\n if (name) cause.name = name\n if (message) cause.message = message\n\n if (isRecord(current)) {\n for (const field of SAFE_ERROR_FIELDS) {\n const safeValue = asSafeScalar(current[field])\n if (safeValue !== undefined) {\n Object.assign(cause, { [field]: safeValue })\n }\n }\n }\n\n if (Object.keys(cause).length > 0) causes.push(cause)\n current = readCause(current)\n }\n\n if (!cycle && isRecord(current) && seen.has(current)) {\n cycle = true\n causes.push({\n name: 'CauseChainCycle',\n message: `cause chain cycle detected after ${depth} entries`,\n })\n } else if (current !== undefined && current !== null && depth >= maxDepth) {\n truncatedAtDepth = maxDepth\n causes.push({\n name: 'CauseChainTruncated',\n message: `cause chain truncated after ${maxDepth} entries`,\n })\n }\n\n return {\n message: readMessage(error) ?? 'Sandbox unavailable',\n causes,\n truncated: truncatedAtDepth !== undefined,\n truncatedAtDepth,\n cycle,\n }\n}\n\nexport function formatSandboxProvisioningSupportDetails(\n diagnostics: SafeSandboxErrorDiagnostics,\n): string {\n const actionableCause = diagnostics.causes.find((cause) =>\n cause.code !== undefined\n || cause.status !== undefined\n || cause.phase !== undefined\n || cause.endpoint !== undefined\n || cause.origin !== undefined\n || cause.retryAfterMs !== undefined\n || cause.sidecarVersion !== undefined\n || cause.containerImage !== undefined,\n ) ?? diagnostics.causes[1]\n\n if (!actionableCause) return 'Support details: no nested sandbox cause details were available.'\n\n const details = [\n typeof actionableCause.name === 'string' ? redactDiagnosticText(actionableCause.name) : undefined,\n actionableCause.code !== undefined ? `code=${actionableCause.code}` : undefined,\n actionableCause.status !== undefined ? `status=${actionableCause.status}` : undefined,\n actionableCause.phase !== undefined ? `phase=${redactDiagnosticText(actionableCause.phase)}` : undefined,\n actionableCause.endpoint !== undefined ? `endpoint=${redactDiagnosticText(actionableCause.endpoint)}` : undefined,\n actionableCause.origin !== undefined ? `origin=${redactDiagnosticText(actionableCause.origin)}` : undefined,\n actionableCause.retryAfterMs !== undefined ? `retryAfterMs=${actionableCause.retryAfterMs}` : undefined,\n actionableCause.sidecarVersion !== undefined ? `sidecarVersion=${redactDiagnosticText(actionableCause.sidecarVersion)}` : undefined,\n actionableCause.containerImage !== undefined ? `containerImage=${redactDiagnosticText(actionableCause.containerImage)}` : undefined,\n typeof actionableCause.message === 'string' ? redactDiagnosticText(actionableCause.message) : undefined,\n ].filter(Boolean)\n\n if (details.length === 0) return 'Support details: no nested sandbox cause details were available.'\n return `Support details: ${details.join('; ')}`\n}\n\nexport function isSandboxAuthFailure(diagnostics: SafeSandboxErrorDiagnostics): boolean {\n return diagnostics.causes.some((cause) => {\n const code = typeof cause.code === 'string' ? cause.code.toUpperCase() : undefined\n const status = typeof cause.status === 'number'\n ? cause.status\n : typeof cause.status === 'string'\n ? Number.parseInt(cause.status, 10)\n : undefined\n const name = typeof cause.name === 'string' ? cause.name.toLowerCase() : ''\n const message = typeof cause.message === 'string' ? cause.message.toLowerCase() : ''\n\n return code === 'AUTH_ERROR'\n || status === 401\n || name.includes('autherror')\n || message.includes('missing or invalid authentication')\n })\n}\n\n/**\n * True when the Sandbox API refused the caller's bearer: a 401 from any\n * Sandbox API route, including list and query routes such as\n * `/v1/sandboxes?status=stopped`. The caller should invalidate its cached key\n * and mint a new one once.\n *\n * Runtime routes (`/v1/sandboxes/{id}/runtime/...`) are excluded: the box's\n * runtime authentication answers those, and a new Sandbox API key does not fix\n * it. `isSandboxAuthFailure` covers them.\n */\nexport function isSandboxApiBearerAuthFailure(diagnostics: SafeSandboxErrorDiagnostics): boolean {\n return diagnostics.causes.some((cause) => {\n const status = typeof cause.status === 'number'\n ? cause.status\n : typeof cause.status === 'string'\n ? Number.parseInt(cause.status, 10)\n : undefined\n if (status !== 401) return false\n if (cause.origin !== 'sandbox-api') return false\n if (typeof cause.endpoint !== 'string') return false\n const endpointPath = sandboxApiEndpointPath(cause.endpoint)\n if (!endpointPath || !/^\\/v1(?:[/?#]|$)/.test(endpointPath)) return false\n return !/^\\/v1\\/sandboxes\\/[^/?#]+\\/runtime(?:[/?#]|$)/.test(endpointPath)\n })\n}\n\n/** Machine-readable code emitted when resume lost the physical box. */\nexport const SANDBOX_BACKING_CONTAINER_MISSING_CODE = 'BACKING_CONTAINER_MISSING' as const\n\n/**\n * Legacy fallback for Sandbox API releases that only returned the nested host\n * 404 text. New callers must use `SANDBOX_BACKING_CONTAINER_MISSING_CODE`.\n */\nexport function isLegacySandboxBackingContainerMissingMessage(message: string): boolean {\n return /host-agent startcontainer failed \\(404\\):/i.test(message)\n && /container not found/i.test(message)\n && /\"code\"\\s*:\\s*\"not_found\"/i.test(message)\n}\n\n/**\n * True when the sandbox API cannot find a sandbox resource or its backing\n * container. The latter arrives as a 500 from resume with a nested host 404.\n *\n * A sandbox id is a cache of where a workspace's box lives, not the workspace's\n * identity: the platform reaps, suspends, and loses boxes as ordinary lifecycle\n * events. Callers use this to discard the dead id and provision a replacement,\n * so the match is deliberately narrow — a 404 from the runtime sidecar\n * (`/runtime/...`, a missing file or session inside a live box) is NOT this.\n */\nexport function isSandboxApiSandboxMissingFailure(diagnostics: SafeSandboxErrorDiagnostics): boolean {\n return diagnostics.causes.some((cause) => {\n const status = typeof cause.status === 'number'\n ? cause.status\n : typeof cause.status === 'string'\n ? Number.parseInt(cause.status, 10)\n : undefined\n if (cause.origin !== 'sandbox-api') return false\n if (typeof cause.endpoint !== 'string') return false\n const endpointPath = sandboxApiEndpointPath(cause.endpoint)\n if (!endpointPath) return false\n const sandboxResource = /^\\/v1\\/sandboxes\\/[^/?#]+(?:\\/(?!runtime(?:[/?#]|$))[^?#]*)?(?:[?#].*)?$/.test(endpointPath)\n if (!sandboxResource) return false\n if (status === 404) return true\n\n if (status !== 500 || !/^\\/v1\\/sandboxes\\/[^/?#]+\\/resume(?:[?#].*)?$/.test(endpointPath)) {\n return false\n }\n const code = typeof cause.code === 'string' ? cause.code.toUpperCase() : undefined\n if (code === SANDBOX_BACKING_CONTAINER_MISSING_CODE) return true\n // Older Sandbox API releases returned only the nested host 404. The SDK\n // represented that response as SERVER_ERROR, so keep this exact fallback\n // until those releases are no longer in service.\n if (code !== undefined && code !== 'SERVER_ERROR') return false\n const message = typeof cause.message === 'string' ? cause.message : ''\n return isLegacySandboxBackingContainerMissingMessage(message)\n })\n}\n\n/**\n * True when a resume failed because the host the box is pinned to cannot seat\n * it — the host's slot budget is exhausted, not the box's fault and not\n * something waiting fixes.\n *\n * A box lives on one host. When that host fills, every future resume for every\n * box on it fails identically and permanently, so a workspace whose box landed\n * on a full host is bricked until it is placed somewhere else. Callers use this\n * the same way they use {@link isSandboxApiSandboxMissingFailure}: discard the\n * dead id and provision a replacement, which the orchestrator is free to place\n * on a host with room. The workspace itself is preserved — it lives in the\n * Vault, not in the box's filesystem.\n *\n * Matched on the message because the sandbox API returns a generic\n * `SERVER_ERROR` for it; a dedicated code upstream would replace this.\n */\nexport function isSandboxHostCapacityFailure(diagnostics: SafeSandboxErrorDiagnostics): boolean {\n return diagnostics.causes.some((cause) => {\n if (cause.origin !== 'sandbox-api') return false\n if (typeof cause.message !== 'string') return false\n return /host has no available slot|host capacity reservation failed/i.test(cause.message)\n })\n}\n\n/**\n * True when a resume failed on the box's own configuration rather than on\n * anything a retry can change.\n *\n * These are permanent facts about one box. Its egress policy can be missing,\n * or its verified Platform lineage can differ from the current caller. Neither\n * creation-time fact can change on resume, so the box must be replaced.\n *\n * Narrow on purpose. A bare 500 from the sandbox API is transient far more\n * often than not, and treating one as unbringable would delete a healthy box.\n * Matched on the specific unrecoverable phrasing, and only from `sandbox-api`.\n */\nexport function isSandboxBoxConfigFailure(diagnostics: SafeSandboxErrorDiagnostics): boolean {\n return diagnostics.causes.some((cause) => {\n if (cause.origin !== 'sandbox-api') return false\n if (cause.code === 'SANDBOX_ATTRIBUTION_MISMATCH') return true\n if (typeof cause.message !== 'string') return false\n return /has no recorded egress policy|cannot rebuild the proxy config/i.test(cause.message)\n })\n}\n\n/**\n * True when the Sandbox API answered a control-plane call with a server error\n * (500, 502, 503 or 504), such as `A sandbox backend did not answer` or\n * `Failed to resume project: fetch failed`. These clear within seconds, so a\n * caller may retry once before surfacing them.\n *\n * Runtime routes are excluded (the box answers those), and so are the narrow\n * failures that need a different action: a missing box, a box whose creation\n * facts no longer hold, and host capacity.\n */\nexport function isSandboxApiTransientFailure(diagnostics: SafeSandboxErrorDiagnostics): boolean {\n if (isSandboxApiSandboxMissingFailure(diagnostics)\n || isSandboxBoxConfigFailure(diagnostics)\n || isSandboxHostCapacityFailure(diagnostics)) return false\n return diagnostics.causes.some((cause) => {\n const status = typeof cause.status === 'number'\n ? cause.status\n : typeof cause.status === 'string'\n ? Number.parseInt(cause.status, 10)\n : undefined\n if (status !== 500 && status !== 502 && status !== 503 && status !== 504) return false\n if (cause.origin !== 'sandbox-api' || typeof cause.endpoint !== 'string') return false\n const endpointPath = sandboxApiEndpointPath(cause.endpoint)\n if (!endpointPath || !/^\\/v1(?:[/?#]|$)/.test(endpointPath)) return false\n return !/^\\/v1\\/sandboxes\\/[^/?#]+\\/runtime(?:[/?#]|$)/.test(endpointPath)\n })\n}\n\nfunction sandboxApiEndpointPath(endpoint: string): string | null {\n if (endpoint.startsWith('/')) return endpoint\n try {\n const url = new URL(endpoint)\n return `${url.pathname}${url.search}${url.hash}`\n } catch {\n return null\n }\n}\n\nexport function formatSandboxProvisioningUserMessage(\n diagnostics: SafeSandboxErrorDiagnostics,\n): string {\n if (diagnostics.causes.some((cause) => cause.code === EGRESS_PROXY_RECOVERY_REQUIRED)) {\n return 'Sandbox recovery is required before chat can continue. The stopped sandbox has not been deleted.'\n }\n\n // The sandbox itself is reachable — copying the Vault into it is what did not\n // finish. Saying \"the service is unavailable\" sends people to inspect\n // infrastructure that is healthy.\n if (diagnostics.causes.some((cause) => cause.code === 'vault.hydration_incomplete')) {\n return 'I couldn\\'t finish copying your Vault into the sandbox, so I stopped rather than work from a partial copy. The copy resumes where it left off — try again in a moment.'\n }\n\n if (isSandboxApiTransientFailure(diagnostics)) {\n return 'The sandbox service didn\\'t answer just now. Send your message again in a moment.'\n }\n\n if (isSandboxApiBearerAuthFailure(diagnostics)) {\n return 'I\\'m unable to reconnect to the sandbox because its sandbox API credential was rejected. Another request may have rotated the bearer used for this operation.'\n }\n\n if (isSandboxAuthFailure(diagnostics)) {\n return 'I\\'m unable to reconnect to the sandbox because its runtime authentication failed. This can happen when an existing sandbox is reused with stale credentials.'\n }\n\n if (diagnostics.causes.some((cause) => (\n cause.code === 'PAYLOAD_TOO_LARGE'\n || cause.code === 'FILE_TOO_LARGE'\n || cause.status === 413\n || cause.status === '413'\n ))) {\n // Profile and workspace files reach the box through writeProfileFilesToBox;\n // naming an attachment there sends people looking for one they never sent.\n if (diagnostics.causes.some((cause) => cause.message?.startsWith('writeProfileFilesToBox'))) {\n return 'A workspace file is too large to copy into the sandbox. The support details name the file.'\n }\n return 'An attachment is too large for the sandbox to accept. Use a smaller file and try again.'\n }\n\n // Matched by code, not bare 429: the sidecar's rate limiters also answer\n // 429, and those are not attachment-staging pressure.\n if (diagnostics.causes.some((cause) => cause.code === 'UPLOAD_BUDGET_EXHAUSTED')) {\n return 'Too much attachment data is staged in the sandbox at once. Retry shortly.'\n }\n\n return 'I\\'m unable to connect to the sandbox right now. Send your message again in a moment; if it keeps failing, share the support details with the team.'\n}\n","/**\n * Sandbox failures that clear on their own, and how long to wait them out.\n *\n * Both callers that meet them use this one policy: the run dispatch, which\n * resends the same execution, and the completion Workflow, which observes it.\n * A box restarting under load answers \"filesystem incarnation is not ready\"\n * for minutes (8 minutes for GTM's busiest box on 2026-10-10, 10:37 to 10:45\n * UTC), and its gateway refuses dispatches with 502 or 503 while it does.\n * Failing on the first such answer lost those turns; retrying forever would\n * hold a lock on a box that never comes back. The policy backs off from 5 s\n * to a 60 s ceiling and gives up after 15 minutes.\n */\nimport { isSandboxApiTransientFailure, serializeSandboxProvisioningError } from './diagnostics'\n\nexport type SandboxTransientFailureCode =\n /** The box is running but its filesystem incarnation is not ready yet. */\n | 'sandbox.filesystem_not_ready'\n /** The sandbox gateway answered the run dispatch with 502, 503 or 504. */\n | 'sandbox.dispatch_refused'\n /** A Sandbox API control-plane call failed with a server error. */\n | 'sandbox.control_plane_transient'\n\nexport interface SandboxTransientFailure {\n code: SandboxTransientFailureCode\n message: string\n}\n\n/** How long a transient failure may last before the caller fails. */\nexport const SANDBOX_TRANSIENT_DEADLINE_MS = 15 * 60_000\n\n/** Wait before retry `attempt` (1-based): 5 s doubling to a 60 s ceiling. */\nexport function sandboxTransientBackoffMs(attempt: number): number {\n return Math.min(60_000, 5_000 * 2 ** Math.max(0, attempt - 1))\n}\n\nfunction record(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === 'object' ? value as Record<string, unknown> : undefined\n}\n\nfunction causeChain(error: unknown): Record<string, unknown>[] {\n const chain: Record<string, unknown>[] = []\n let current = record(error)\n for (let depth = 0; current && depth < 8 && !chain.includes(current); depth += 1) {\n chain.push(current)\n current = record(current.cause)\n }\n return chain\n}\n\n/** A planned host-agent swap leaves the sandbox alive; an ordinary probe failure is not that evidence. */\nexport function plannedHostRestart(error: unknown): boolean {\n return causeChain(error).some(cause => cause.code === 'HOST_AGENT_RESTARTING' && cause.status === 503)\n}\n\n/** Wait only for the platform typed planned-restart signal, within the caller budget. */\nexport async function readDuringPlannedHostRestart<T>(\n read: () => Promise<T>,\n deadline: number,\n): Promise<{ value: T; waited: boolean }> {\n let waited = false\n for (;;) {\n try {\n return { value: await read(), waited }\n } catch (error) {\n if (!plannedHostRestart(error)) throw error\n const hint = (error as { retryAfterMs?: unknown }).retryAfterMs\n const delay = typeof hint === 'number' && Number.isFinite(hint) && hint > 0\n ? hint : sandboxTransientBackoffMs(1)\n // The existing caller budget bounds retries. Each SDK request\n // settles under its own deadline before another begins. Preserve the refusal and never start a stop on\n // expiry; its code, origin and endpoint remain available to the caller.\n if (Date.now() + delay >= deadline) throw error\n waited = true\n await new Promise(resolve => setTimeout(resolve, delay))\n }\n }\n}\n\n\nfunction status(value: unknown): number | undefined {\n if (typeof value === 'number') return value\n if (typeof value === 'string' && /^\\d{3}$/.test(value)) return Number(value)\n return undefined\n}\n\nconst FILESYSTEM_NOT_READY = /filesystem incarnation is not ready/i\nconst RUN_DISPATCH_ENDPOINT = /\\/runtime\\/agents\\/run\\/stream(?:[?#]|$)/\nconst RUN_DISPATCH_REFUSAL_MESSAGE = /\\/runtime\\/agents\\/run\\/stream: error code: (50[234])\\b/\n\n/** The typed transient failure `error` carries anywhere in its cause chain, or null. */\nexport function classifySandboxTransientFailure(error: unknown): SandboxTransientFailure | null {\n for (const cause of causeChain(error)) {\n const message = typeof cause.message === 'string' ? cause.message : ''\n if (cause.code === 'FILESYSTEM_INCARNATION_NOT_READY' || FILESYSTEM_NOT_READY.test(message)) {\n return { code: 'sandbox.filesystem_not_ready', message: 'Sandbox filesystem incarnation is not ready' }\n }\n const code = status(cause.status)\n const endpoint = typeof cause.endpoint === 'string' ? cause.endpoint : ''\n const refusal = (code === 502 || code === 503 || code === 504) && RUN_DISPATCH_ENDPOINT.test(endpoint)\n ? code\n : RUN_DISPATCH_REFUSAL_MESSAGE.exec(message)?.[1]\n if (refusal) {\n return { code: 'sandbox.dispatch_refused', message: `The sandbox gateway refused the run dispatch with ${refusal}` }\n }\n }\n if (isSandboxApiTransientFailure(serializeSandboxProvisioningError(error))) {\n return { code: 'sandbox.control_plane_transient', message: 'A Sandbox API call failed with a server error' }\n }\n return null\n}\n\n/** The error a caller raises when a transient failure outlasted the deadline. */\nexport class SandboxTransientDeadlineError extends Error {\n readonly code: SandboxTransientFailureCode\n readonly firstSeenAt: number\n readonly attempts: number\n\n constructor(failure: SandboxTransientFailure, firstSeenAt: number, attempts: number, cause?: unknown) {\n const minutes = Math.round(SANDBOX_TRANSIENT_DEADLINE_MS / 60_000)\n super(`${failure.message}; it persisted for more than ${minutes} minutes over ${attempts} attempts`, cause === undefined ? undefined : { cause })\n this.name = 'SandboxTransientDeadlineError'\n this.code = failure.code\n this.firstSeenAt = firstSeenAt\n this.attempts = attempts\n }\n}\n\nexport interface SandboxTransientRetryOptions {\n /** Defaults to {@link SANDBOX_TRANSIENT_DEADLINE_MS}. */\n deadlineMs?: number\n now?: () => number\n sleep?: (ms: number, signal?: AbortSignal) => Promise<void>\n signal?: AbortSignal\n onRetry?: (failure: SandboxTransientFailure, attempt: number, delayMs: number) => void\n}\n\nconst defaultSleep = (ms: number, signal?: AbortSignal) => new Promise<void>((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason)\n const timer = setTimeout(resolve, ms)\n signal?.addEventListener('abort', () => {\n clearTimeout(timer)\n reject(signal.reason)\n }, { once: true })\n})\n\n/**\n * Run `attempt` until it succeeds, it fails with something this policy does\n * not consider transient, or a transient failure outlasts the deadline.\n */\nexport async function retrySandboxTransient<T>(\n attempt: () => Promise<T>,\n options: SandboxTransientRetryOptions = {},\n): Promise<T> {\n const now = options.now ?? Date.now\n const sleep = options.sleep ?? defaultSleep\n const deadlineMs = options.deadlineMs ?? SANDBOX_TRANSIENT_DEADLINE_MS\n let firstSeenAt: number | undefined\n for (let attempts = 1; ; attempts += 1) {\n try {\n return await attempt()\n } catch (error) {\n const failure = classifySandboxTransientFailure(error)\n if (!failure) throw error\n const at = now()\n firstSeenAt ??= at\n const delayMs = sandboxTransientBackoffMs(attempts)\n if (at + delayMs - firstSeenAt > deadlineMs) throw new SandboxTransientDeadlineError(failure, firstSeenAt, attempts, error)\n options.onRetry?.(failure, attempts, delayMs)\n await sleep(delayMs, options.signal)\n }\n }\n}\n"],"mappings":";AA4BO,IAAM,iCAAiC;AACvC,IAAM,8BAA8B;AAEpC,IAAM,4BAA4B;AAGlC,IAAM,mCAAmC;AAGzC,IAAM,kCAAkC;AAExC,IAAM,wCAAwC,KAAK,KAAK,KAAK;AAWpE,IAAM,QAAQ;AAAA,EACZ,CAAC,8BAA8B,GAAG,EAAE,gBAAgB,KAAK;AAAA,EACzD,CAAC,yBAAyB,GAAG,EAAE,gBAAgB,MAAM;AAAA,EACrD,CAAC,gCAAgC,GAAG,EAAE,gBAAgB,MAAM;AAAA,EAC5D,CAAC,+BAA+B,GAAG,EAAE,gBAAgB,MAAM;AAC7D;AAcA,IAAM,UAAU;AAAA,EACd,uBAAuB,EAAE,mBAAmB,OAAO,WAAW,KAAK;AAAA,EACnE,mBAAmB,EAAE,mBAAmB,OAAO,WAAW,KAAK;AAAA,EAC/D,wBAAwB,EAAE,mBAAmB,MAAM;AAAA,EACnD,iCAAiC,EAAE,mBAAmB,MAAM;AAAA,EAC5D,qBAAqB,EAAE,mBAAmB,MAAM,aAAa,wBAAwB;AAAA,EACrF,uBAAuB,EAAE,mBAAmB,KAAK;AAAA,EACjD,8BAA8B,EAAE,mBAAmB,MAAM,aAAa,iCAAiC;AAAA,EACvG,yBAAyB,EAAE,mBAAmB,MAAM,aAAa,iCAAiC;AAAA,EAClG,gCAAgC,EAAE,mBA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AI,QAAc,CAAC,SAAS,WAAW;AAChG,MAAI,QAAQ,QAAS,QAAO,OAAO,OAAO,MAAM;AAChD,QAAM,QAAQ,WAAW,SAAS,EAAE;AACpC,UAAQ,iBAAiB,SAAS,MAAM;AACtC,iBAAa,KAAK;AAClB,WAAO,OAAO,MAAM;AAAA,EACtB,GAAG,EAAE,MAAM,KAAK,CAAC;AACnB,CAAC;AAMD,eAAsB,sBACpB,SACA,UAAwC,CAAC,GAC7B;AACZ,QAAM,MAAM,QAAQ,OAAO,KAAK;AAChC,QAAM,QAAQ,QAAQ,SAAS;AAC/B,QAAM,aAAa,QAAQ,cAAc;AACzC,MAAI;AACJ,WAAS,WAAW,KAAK,YAAY,GAAG;AACtC,QAAI;AACF,aAAO,MAAM,QAAQ;AAAA,IACvB,SAAS,OAAO;AACd,YAAM,UAAU,gCAAgC,KAAK;AACrD,UAAI,CAAC,QAAS,OAAM;AACpB,YAAM,KAAK,IAAI;AACf,sBAAgB;AAChB,YAAM,UAAU,0BAA0B,QAAQ;AAClD,UAAI,KAAK,UAAU,cAAc,WAAY,OAAM,IAAI,8BAA8B,SAAS,aAAa,UAAU,KAAK;AAC1H,cAAQ,UAAU,SAAS,UAAU,OAAO;AAC5C,YAAM,MAAM,SAAS,QAAQ,MAAM;AAAA,IACrC;AAAA,EACF;AACF;","names":["isRecord","status"]}
1
+ {"version":3,"sources":["../src/sandbox/recovery.ts","../src/sandbox/diagnostics.ts","../src/sandbox/transient-failure.ts"],"sourcesContent":["/**\n * What an app does after the platform hands back a sandbox it cannot use.\n *\n * `replaceUnbringableBox` (see `./index`) decides whether to abandon a dead box.\n * This decides everything around that: which box key the next attempt uses,\n * whether the old box's snapshot is safe to restore from, whether an owner has\n * to confirm the loss first, and what the person waiting is told. It is\n * bookkeeping, not I/O — the app supplies storage through\n * {@link WorkspaceSandboxRecoveryStore}.\n *\n * ── Why the tables ──────────────────────────────────────────────────────────\n * Every fact about an action or a code lives in ACTIONS/CODES below, and the\n * types are DERIVED from those tables. That is deliberate, and it is the whole\n * reliability argument for this module.\n *\n * The hand-maintained alternative — a union type plus a separate `x === 'a' ||\n * x === 'b' || …` list per question — silently drops anything not on the list.\n * A recovery recorded under an unlisted action is written to storage, read\n * back, discarded as malformed, and the workspace re-provisions the box it just\n * abandoned. Nothing throws. The fix looks correct, ships, and does nothing.\n * That failure was hit twice inside one change before this module existed.\n *\n * With the tables, adding an action or code is a compile error until every\n * question about it is answered. There is no list to forget.\n */\n\n/** The box exists and still holds unsnapshotted state, so discarding it is an\n * owner's decision, not the runtime's. */\nexport const EGRESS_PROXY_RECOVERY_REQUIRED = 'EGRESS_PROXY_RECOVERY_REQUIRED'\nexport const EGRESS_PROXY_RECOVERY_PHASE = 'egress_proxy_recovery'\n/** The platform no longer has the box. Nothing to confirm, delete, or restore. */\nexport const WORKSPACE_SANDBOX_MISSING = 'WORKSPACE_SANDBOX_MISSING'\n/** The box exists but its host has no free slot, so it can never be resumed\n * where it is. A replacement can be placed on a host with room. */\nexport const WORKSPACE_SANDBOX_HOST_EXHAUSTED = 'WORKSPACE_SANDBOX_HOST_EXHAUSTED'\n/** The platform ran its own recovery, failed, and asked for a replacement.\n * Covers every way a box ends up unbringable with no more specific cause. */\nexport const WORKSPACE_SANDBOX_UNRECOVERABLE = 'WORKSPACE_SANDBOX_UNRECOVERABLE'\n\nexport const WORKSPACE_SANDBOX_SNAPSHOT_MAX_AGE_MS = 24 * 60 * 60 * 1000\n\n/**\n * Every recovery cause, and the one thing the runtime must know about each:\n * whether the box it names can still be read from.\n *\n * `snapshotUsable: false` is not a preference. A snapshot is addressed by the\n * sandbox it was taken from, so when that sandbox cannot be started the restore\n * fails exactly the way the resume did — and an app that tried it would turn a\n * recoverable workspace into a stuck one.\n */\nconst CODES = {\n [EGRESS_PROXY_RECOVERY_REQUIRED]: { snapshotUsable: true },\n [WORKSPACE_SANDBOX_MISSING]: { snapshotUsable: false },\n [WORKSPACE_SANDBOX_HOST_EXHAUSTED]: { snapshotUsable: false },\n [WORKSPACE_SANDBOX_UNRECOVERABLE]: { snapshotUsable: false },\n} as const\n\nexport type WorkspaceSandboxRecoveryCode = keyof typeof CODES\n\n/**\n * Every recovery action, and whether it means a replacement box has been\n * CHOSEN — the single question that decides which box key the next provisioning\n * attempt uses.\n *\n * `replacementChosen: false` covers the states where a key may be recorded but\n * must not be used yet: an owner has been asked and has not answered, or has\n * answered no. Handing back a key in those states replaces a box the owner\n * declined to lose.\n */\nconst ACTIONS = {\n confirmation_required: { replacementChosen: false, canDecide: true },\n deletion_declined: { replacementChosen: false, canDecide: true },\n replacement_authorized: { replacementChosen: false },\n snapshot_replacement_authorized: { replacementChosen: false },\n replacement_started: { replacementChosen: true, completedAs: 'replacement_completed' },\n replacement_completed: { replacementChosen: true },\n snapshot_replacement_started: { replacementChosen: true, completedAs: 'snapshot_replacement_completed' },\n snapshot_restore_failed: { replacementChosen: true, completedAs: 'snapshot_replacement_completed' },\n snapshot_replacement_completed: { replacementChosen: true },\n missing_replacement_started: { replacementChosen: true, completedAs: 'missing_replacement_completed' },\n missing_replacement_completed: { replacementChosen: true },\n unrecoverable_replacement_started: { replacementChosen: true, completedAs: 'unrecoverable_replacement_completed' },\n unrecoverable_replacement_completed: { replacementChosen: true },\n} as const\n\nexport type WorkspaceSandboxRecoveryAction = keyof typeof ACTIONS\n\nexport type WorkspaceSandboxSnapshotAvailability = 'available' | 'missing' | 'stale'\nexport type WorkspaceSandboxSnapshotFreshness = 'fresh' | 'stale' | 'unknown'\n\n/** A snapshot the app took of a box, addressed by the box it came from. */\nexport interface WorkspaceSandboxSnapshot {\n fromSandboxId: string\n createdAt: string\n [key: string]: unknown\n}\n\nexport interface WorkspaceSandboxSnapshotAssessment<Snapshot extends WorkspaceSandboxSnapshot = WorkspaceSandboxSnapshot> {\n availability: WorkspaceSandboxSnapshotAvailability\n freshness: WorkspaceSandboxSnapshotFreshness\n snapshot?: Snapshot\n}\n\nexport interface WorkspaceSandboxRecoveryState<Snapshot extends WorkspaceSandboxSnapshot = WorkspaceSandboxSnapshot> {\n code: WorkspaceSandboxRecoveryCode\n sandboxId: string\n detectedAt: string\n snapshot: WorkspaceSandboxSnapshotAssessment<Snapshot>\n action: WorkspaceSandboxRecoveryAction\n replacementBoxKey?: string\n replacementSandboxId?: string\n confirmedAt?: string\n}\n\nexport type WorkspaceSandboxRecoveryDecision = 'replace' | 'decline'\n\n/** Raised when chat cannot continue until an owner decides about the box. */\nexport class WorkspaceSandboxRecoveryRequiredError extends Error {\n readonly code = EGRESS_PROXY_RECOVERY_REQUIRED\n readonly status = 409\n readonly phase = EGRESS_PROXY_RECOVERY_PHASE\n readonly recovery: WorkspaceSandboxRecoveryState\n\n constructor(recovery: WorkspaceSandboxRecoveryState, cause: Error) {\n super(workspaceSandboxRecoveryMessage(recovery), { cause })\n this.name = 'WorkspaceSandboxRecoveryRequiredError'\n this.recovery = recovery\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n\nfunction asNonEmptyString(value: unknown): string | undefined {\n return typeof value === 'string' && value.trim().length > 0 ? value : undefined\n}\n\n/** Walk `cause` and `errors` breadth-first, cycle-safe. */\nfunction errorChain(error: unknown): unknown[] {\n const pending = [error]\n const visited = new Set<unknown>()\n const chain: unknown[] = []\n\n while (pending.length > 0) {\n const current = pending.shift()\n if (current === undefined || current === null || visited.has(current)) continue\n visited.add(current)\n chain.push(current)\n if (!isRecord(current)) continue\n if (current.cause !== undefined) pending.push(current.cause)\n if (Array.isArray(current.errors)) pending.push(...current.errors)\n }\n\n return chain\n}\n\nexport function isEgressProxyRecoveryRequiredError(error: unknown): boolean {\n return errorChain(error).some((current) =>\n isRecord(current) && current.code === EGRESS_PROXY_RECOVERY_REQUIRED,\n )\n}\n\nexport function isWorkspaceSandboxSnapshotRestoreError(error: unknown): boolean {\n return errorChain(error).some((current) => {\n const message = current instanceof Error\n ? current.message\n : isRecord(current) && typeof current.message === 'string'\n ? current.message\n : ''\n return /snapshot|fromSnapshot|restore/i.test(message)\n })\n}\n\n/**\n * Judge a snapshot against the box being replaced.\n *\n * Fresh means BOTH that it came from this exact sandbox and that it is inside\n * the age bound — a snapshot from a different box restores someone else's\n * filesystem, which is worse than starting empty.\n */\nexport function assessWorkspaceSandboxSnapshot<Snapshot extends WorkspaceSandboxSnapshot>(\n snapshot: Snapshot | undefined,\n sandboxId: string,\n now = Date.now(),\n): WorkspaceSandboxSnapshotAssessment<Snapshot> {\n if (!snapshot) return { availability: 'missing', freshness: 'unknown' }\n\n const createdAt = Date.parse(snapshot.createdAt)\n const ageMs = now - createdAt\n const isFresh = snapshot.fromSandboxId === sandboxId\n && Number.isFinite(createdAt)\n && ageMs >= 0\n && ageMs <= WORKSPACE_SANDBOX_SNAPSHOT_MAX_AGE_MS\n\n return isFresh\n ? { availability: 'available', freshness: 'fresh', snapshot }\n : { availability: 'stale', freshness: 'stale', snapshot }\n}\n\nfunction isSnapshotAssessment(value: unknown): value is WorkspaceSandboxSnapshotAssessment {\n if (!isRecord(value)) return false\n const availability = value.availability\n const freshness = value.freshness\n return (availability === 'available' || availability === 'missing' || availability === 'stale')\n && (freshness === 'fresh' || freshness === 'stale' || freshness === 'unknown')\n}\n\nexport function isWorkspaceSandboxRecoveryAction(\n value: unknown,\n): value is WorkspaceSandboxRecoveryAction {\n return typeof value === 'string' && Object.hasOwn(ACTIONS, value)\n}\n\nexport function isWorkspaceSandboxRecoveryCode(\n value: unknown,\n): value is WorkspaceSandboxRecoveryCode {\n return typeof value === 'string' && Object.hasOwn(CODES, value)\n}\n\nexport function isWorkspaceSandboxRecoveryState(\n value: unknown,\n): value is WorkspaceSandboxRecoveryState {\n if (!isRecord(value)) return false\n return isWorkspaceSandboxRecoveryCode(value.code)\n && !!asNonEmptyString(value.sandboxId)\n && !!asNonEmptyString(value.detectedAt)\n && isSnapshotAssessment(value.snapshot)\n && isWorkspaceSandboxRecoveryAction(value.action)\n}\n\nexport function workspaceSandboxRecoveryFromError(\n error: unknown,\n): WorkspaceSandboxRecoveryState | undefined {\n for (const current of errorChain(error)) {\n if (!isRecord(current) || !isWorkspaceSandboxRecoveryState(current.recovery)) continue\n return current.recovery\n }\n return undefined\n}\n\n/** What to tell the person waiting. Never names the product, so an app can\n * surface it verbatim. */\nexport function workspaceSandboxRecoveryMessage(recovery: WorkspaceSandboxRecoveryState): string {\n if (recovery.code === WORKSPACE_SANDBOX_MISSING) {\n return 'The sandbox behind this workspace no longer exists on the platform. A replacement is being provisioned and your saved work is restored into it.'\n }\n if (!CODES[recovery.code].snapshotUsable) {\n return 'The sandbox behind this workspace could not be started again. A replacement is being provisioned and your saved work is restored into it.'\n }\n if (recovery.action === 'deletion_declined') {\n return 'Sandbox recovery remains paused because replacement was declined. The stopped sandbox has not been deleted.'\n }\n if (recovery.action === 'confirmation_required') {\n const snapshotReason = recovery.snapshot.availability === 'missing'\n ? 'No restorable sandbox snapshot is available.'\n : 'The available sandbox snapshot is stale.'\n return `Sandbox recovery requires owner confirmation before replacement. ${snapshotReason} The stopped sandbox has not been deleted.`\n }\n if (recovery.action === 'snapshot_restore_failed') {\n return 'Sandbox replacement could not restore its verified snapshot, and an empty fallback was not created because it could lose workspace state.'\n }\n return 'Sandbox recovery is required before chat can continue. The stopped sandbox has not been deleted.'\n}\n\nexport function workspaceSandboxRecoveryRecommendedActions(\n recovery: WorkspaceSandboxRecoveryState,\n): string[] {\n if (!CODES[recovery.code].snapshotUsable) {\n return ['Retry after the replacement sandbox finishes provisioning.']\n }\n if (recovery.action === 'deletion_declined') {\n return ['Keep the stopped sandbox for support or ask a workspace owner to authorize replacement.']\n }\n if (recovery.action === 'confirmation_required') {\n return ['An owner can explicitly replace the sandbox after accepting loss of unsnapshotted sandbox-local changes.']\n }\n if (recovery.action === 'snapshot_restore_failed') {\n return ['Retry snapshot restoration or contact support. An empty replacement is not created automatically.']\n }\n return ['Retry after sandbox recovery completes.']\n}\n\n/** Flat key/value shape for a log line — no nesting, no secrets. */\nexport function workspaceSandboxRecoveryDiagnostic(\n recovery: WorkspaceSandboxRecoveryState,\n): Record<string, string | undefined> {\n return {\n sandboxId: recovery.sandboxId,\n recoveryCode: recovery.code,\n snapshotAvailability: recovery.snapshot.availability,\n snapshotFreshness: recovery.snapshot.freshness,\n selectedRecoveryAction: recovery.action,\n replacementSandboxId: recovery.replacementSandboxId,\n }\n}\n\n/**\n * The box key the next provisioning attempt should use, or undefined to keep\n * using the workspace's own key.\n *\n * Reads {@link ACTIONS} rather than a hand-kept list, because the failure mode\n * of a hand-kept list here is invisible: the key is recorded, silently ignored,\n * and provisioning goes back to the box the app just decided to abandon.\n */\nexport function preferredWorkspaceSandboxRecoveryBoxKey(\n recovery: WorkspaceSandboxRecoveryState | undefined,\n): string | undefined {\n if (!recovery?.replacementBoxKey) return undefined\n return ACTIONS[recovery.action].replacementChosen ? recovery.replacementBoxKey : undefined\n}\n\n/** Whether the replacement should be restored from the old box's snapshot. */\nexport function shouldRestoreWorkspaceSandboxRecovery(\n recovery: WorkspaceSandboxRecoveryState | undefined,\n): boolean {\n if (!recovery) return false\n if (!CODES[recovery.code].snapshotUsable) return false\n return !!preferredWorkspaceSandboxRecoveryBoxKey(recovery)\n && recovery.snapshot.availability === 'available'\n}\n\n/** One current recovery per workspace, stored by the application.\n * Concurrent writers should supply compareAndSet. Legacy write-only stores\n * remain supported but must serialize decisions and completion themselves. */\nexport interface WorkspaceSandboxRecoveryStore<Snapshot extends WorkspaceSandboxSnapshot = WorkspaceSandboxSnapshot> {\n read: (workspaceId: string) => Promise<WorkspaceSandboxRecoveryState<Snapshot> | undefined>\n write: (workspaceId: string, recovery: WorkspaceSandboxRecoveryState<Snapshot>) => Promise<void>\n /** Commit a transition only while the exact recovery read above remains current. */\n compareAndSet?: (\n workspaceId: string,\n expected: WorkspaceSandboxRecoveryState<Snapshot>,\n recovery: WorkspaceSandboxRecoveryState<Snapshot>,\n ) => Promise<boolean>\n}\n\nexport interface WorkspaceSandboxRecoveryManager<Snapshot extends WorkspaceSandboxSnapshot = WorkspaceSandboxSnapshot> {\n read: WorkspaceSandboxRecoveryStore<Snapshot>['read']\n record: WorkspaceSandboxRecoveryStore<Snapshot>['write']\n /** Only a pending/declined recovery for this sandbox accepts a new decision.\n * Replacement requires a fresh, nonblank key; decline needs no key. */\n decide: (args: {\n workspaceId: string\n sandboxId: string\n } & (\n | { decision: 'replace'; replacementBoxKey: string }\n | { decision: 'decline'; replacementBoxKey?: string }\n )) => Promise<WorkspaceSandboxRecoveryState<Snapshot> | undefined>\n /** Only a started replacement with a chosen key may be completed. */\n complete: (args: {\n workspaceId: string\n replacementSandboxId: string\n /** The key used by this provisioning attempt, not a freshly read successor. */\n replacementBoxKey?: string\n }) => Promise<WorkspaceSandboxRecoveryState<Snapshot> | undefined>\n}\n\n/** Bind canonical recovery policy to the application's existing storage. */\nexport function createWorkspaceSandboxRecoveryManager<Snapshot extends WorkspaceSandboxSnapshot>(\n store: WorkspaceSandboxRecoveryStore<Snapshot>,\n): WorkspaceSandboxRecoveryManager<Snapshot> {\n type State = WorkspaceSandboxRecoveryState<Snapshot>\n async function transition(workspaceId: string, expected: State, next: State): Promise<State> {\n if (store.compareAndSet) {\n if (!await store.compareAndSet(workspaceId, expected, next))\n throw new Error('Sandbox recovery changed; reload before retrying its transition')\n } else {\n await store.write(workspaceId, next)\n }\n return next\n }\n\n return {\n read: workspaceId => store.read(workspaceId),\n record: (workspaceId, recovery) => store.write(workspaceId, recovery),\n async decide({ workspaceId, sandboxId, decision, replacementBoxKey }) {\n const current = await store.read(workspaceId)\n if (!current || current.sandboxId !== sandboxId || !('canDecide' in ACTIONS[current.action])) return undefined\n if (decision === 'replace' && !asNonEmptyString(replacementBoxKey))\n throw new Error('Sandbox replacement authorization requires a fresh replacement box key')\n return transition(workspaceId, current, {\n ...current,\n action: decision === 'replace'\n ? (current.snapshot.availability === 'available' ? 'snapshot_replacement_authorized' : 'replacement_authorized')\n : 'deletion_declined',\n confirmedAt: new Date().toISOString(),\n ...(decision === 'replace' ? { replacementBoxKey } : {}),\n })\n },\n async complete({ workspaceId, replacementSandboxId, replacementBoxKey }) {\n const current = await store.read(workspaceId)\n if (!current || !asNonEmptyString(current.replacementBoxKey)) return undefined\n if (replacementBoxKey !== undefined && current.replacementBoxKey !== replacementBoxKey) return undefined\n const policy = ACTIONS[current.action]\n if (!('completedAs' in policy)) return undefined\n if (!asNonEmptyString(replacementSandboxId)) throw new Error('A replacement sandbox id is required')\n return transition(workspaceId, current, { ...current, action: policy.completedAs, replacementSandboxId })\n },\n }\n}\n\n/** Every declared action, for exhaustiveness tests in apps and here. */\nexport const WORKSPACE_SANDBOX_RECOVERY_ACTIONS = Object.keys(\n ACTIONS,\n) as readonly WorkspaceSandboxRecoveryAction[]\n\n/** Every declared cause. */\nexport const WORKSPACE_SANDBOX_RECOVERY_CODES = Object.keys(\n CODES,\n) as readonly WorkspaceSandboxRecoveryCode[]\n","/**\n * Read a sandbox provisioning failure without leaking what it carries.\n *\n * Provisioning errors arrive as deep `cause` chains from the sandbox API, the\n * runtime sidecar, and the app's own vault code, and they routinely carry\n * bearer tokens and signed URLs in their messages. Every app on this shell\n * needs the same three things from one: a redacted shape it can log, a\n * classification it can act on, and a sentence it can show a person. Before\n * this module each app either wrote its own or — far more often — wrote none,\n * and surfaced the raw error or a generic apology.\n *\n * The classifiers are deliberately narrow. `isSandboxApiSandboxMissingFailure`\n * does not fire on a 404 from inside a live box; `isSandboxHostCapacityFailure`\n * does not fire on capacity wording from any origin but the sandbox API. A\n * classifier that over-matches turns a transient failure into a box deletion.\n */\nimport { EGRESS_PROXY_RECOVERY_REQUIRED } from './recovery'\n\nconst SAFE_ERROR_FIELDS = [\n 'code',\n 'status',\n 'phase',\n 'endpoint',\n 'origin',\n 'retryAfterMs',\n 'sidecarVersion',\n 'containerImage',\n] as const\n\nexport interface SafeSandboxErrorCause {\n name?: string\n message?: string\n code?: string | number\n status?: string | number\n phase?: string\n endpoint?: string\n origin?: string\n retryAfterMs?: number\n sidecarVersion?: string\n containerImage?: string\n}\n\nexport interface SafeSandboxErrorDiagnostics {\n message: string\n causes: SafeSandboxErrorCause[]\n truncated: boolean\n truncatedAtDepth?: number\n cycle: boolean\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n\nfunction asSafeScalar(value: unknown): string | number | undefined {\n if (typeof value === 'string' && value.length > 0) return redactDiagnosticText(value)\n if (typeof value === 'number' && Number.isFinite(value)) return value\n return undefined\n}\n\nfunction redactDiagnosticText(value: string): string {\n const secretKeyPattern = '(?:(?:[A-Z0-9]+_)*(?:api_?key|auth_?token|access_?token|refresh_?token|key|token|password|secret|credential)|apiKey|authToken|accessToken|refreshToken)'\n return value\n .replace(/(['\"]authorization['\"]\\s*:\\s*)(['\"])[^'\"]*\\2/gi, '$1$2[REDACTED]$2')\n .replace(/\\b(authorization\\s*[:=]\\s*)(['\"])[^'\"]*\\2/gi, '$1$2[REDACTED]$2')\n .replace(/\\b(authorization\\s*[:=]\\s*)Digest\\b[^;}\\n]*(?:\\r?\\n[ \\t]+[^;}\\n]*)*/gi, '$1[REDACTED]')\n .replace(/\\b(authorization\\s*[:=]\\s*)(?:Basic|Bearer|Negotiate)\\s+[^\\s;,&}\\n]+(?:\\r?\\n[ \\t]+[^\\s;,&}\\n]+)*/gi, '$1[REDACTED]')\n .replace(new RegExp(`\\\\b(authorization\\\\s*[:=]\\\\s*)(?!(?:Basic|Bearer|Digest|Negotiate)\\\\b)([A-Za-z][A-Za-z0-9._-]+)\\\\s+(?!(?:authorization|${secretKeyPattern})\\\\s*[:=]|['\"](?:authorization|${secretKeyPattern})['\"]\\\\s*:)([^}\\\\n]*(?:\\\\r?\\\\n[ \\\\t]+[^}\\\\n]*)*)`, 'gi'), (_match, prefix: string, _scheme: string, valuePart: string) => {\n if (valuePart.includes(';') || /\\r?\\n[ \\t]+/.test(valuePart)) return `${prefix}[REDACTED]`\n const tokenMatch = valuePart.match(/^\\S+(.*)$/)\n return `${prefix}[REDACTED]${tokenMatch?.[1] ?? ''}`\n })\n .replace(/\\b(authorization\\s*[:=]\\s*)[A-Za-z][\\w.-]+\\s+[^\\s;,&}\\n]+(?=[;&}\\n]|$)/gi, '$1[REDACTED]')\n .replace(/\\b(authorization\\s*[:=]\\s*)(?!\\[REDACTED\\])[^'\"\\s&}]+(?:[;,][^'\"\\s&}]+)*/gi, '$1[REDACTED]')\n .replace(/\\bBearer\\s+[A-Za-z0-9._~+/-]+=*/gi, 'Bearer [REDACTED]')\n .replace(/\\bsk-[A-Za-z0-9_-]{6,}\\b/g, 'sk-[REDACTED]')\n .replace(\n /([?&][^=&#\\s]*(?:token|key|secret|password|authorization)[^=&#\\s]*=)[^&#\\s]+/gi,\n '$1[REDACTED]',\n )\n .replace(\n new RegExp(`(['\"])(${secretKeyPattern})\\\\1\\\\s*:\\\\s*(['\"])[^'\"]+\\\\3`, 'gi'),\n '$1$2$1:$3[REDACTED]$3',\n )\n .replace(\n new RegExp(`\\\\b(${secretKeyPattern})\\\\s*([:=])(\\\\s*)(['\"]?)(?!Bearer\\\\b)[^'\"\\\\s;,&}]+(?:[;,]\\\\s*[^'\"\\\\s;,&}]+)*`, 'gi'),\n '$1$2$3$4[REDACTED]',\n )\n}\n\nfunction readMessage(value: unknown): string | undefined {\n if (value instanceof Error) return redactDiagnosticText(value.message)\n if (typeof value === 'string' && value.length > 0) return redactDiagnosticText(value)\n if (typeof value === 'number' && Number.isFinite(value)) return String(value)\n if (typeof value === 'boolean') return String(value)\n if (!isRecord(value)) return undefined\n const message = value.message\n return typeof message === 'string' && message.length > 0 ? redactDiagnosticText(message) : undefined\n}\n\nfunction readName(value: unknown): string | undefined {\n if (value instanceof Error) return redactDiagnosticText(value.name)\n if (!isRecord(value)) return undefined\n const name = value.name\n return typeof name === 'string' && name.length > 0 ? redactDiagnosticText(name) : undefined\n}\n\nfunction readCause(value: unknown): unknown {\n if (!isRecord(value)) return undefined\n return value.cause\n}\n\nexport function serializeSandboxProvisioningError(\n error: unknown,\n options: { maxDepth?: number } = {},\n): SafeSandboxErrorDiagnostics {\n const maxDepth = options.maxDepth ?? 6\n const causes: SafeSandboxErrorCause[] = []\n const seen = new Set<unknown>()\n let truncatedAtDepth: number | undefined\n let cycle = false\n\n let current: unknown = error\n let depth = 0\n for (; depth < maxDepth && current !== undefined && current !== null; depth += 1) {\n if (seen.has(current)) {\n cycle = true\n causes.push({\n name: 'CauseChainCycle',\n message: `cause chain cycle detected after ${depth} entries`,\n })\n break\n }\n if (isRecord(current)) seen.add(current)\n\n const cause: SafeSandboxErrorCause = {}\n const name = readName(current)\n const message = readMessage(current)\n if (name) cause.name = name\n if (message) cause.message = message\n\n if (isRecord(current)) {\n for (const field of SAFE_ERROR_FIELDS) {\n const safeValue = asSafeScalar(current[field])\n if (safeValue !== undefined) {\n Object.assign(cause, { [field]: safeValue })\n }\n }\n }\n\n if (Object.keys(cause).length > 0) causes.push(cause)\n current = readCause(current)\n }\n\n if (!cycle && isRecord(current) && seen.has(current)) {\n cycle = true\n causes.push({\n name: 'CauseChainCycle',\n message: `cause chain cycle detected after ${depth} entries`,\n })\n } else if (current !== undefined && current !== null && depth >= maxDepth) {\n truncatedAtDepth = maxDepth\n causes.push({\n name: 'CauseChainTruncated',\n message: `cause chain truncated after ${maxDepth} entries`,\n })\n }\n\n return {\n message: readMessage(error) ?? 'Sandbox unavailable',\n causes,\n truncated: truncatedAtDepth !== undefined,\n truncatedAtDepth,\n cycle,\n }\n}\n\nexport function formatSandboxProvisioningSupportDetails(\n diagnostics: SafeSandboxErrorDiagnostics,\n): string {\n const actionableCause = diagnostics.causes.find((cause) =>\n cause.code !== undefined\n || cause.status !== undefined\n || cause.phase !== undefined\n || cause.endpoint !== undefined\n || cause.origin !== undefined\n || cause.retryAfterMs !== undefined\n || cause.sidecarVersion !== undefined\n || cause.containerImage !== undefined,\n ) ?? diagnostics.causes[1]\n\n if (!actionableCause) return 'Support details: no nested sandbox cause details were available.'\n\n const details = [\n typeof actionableCause.name === 'string' ? redactDiagnosticText(actionableCause.name) : undefined,\n actionableCause.code !== undefined ? `code=${actionableCause.code}` : undefined,\n actionableCause.status !== undefined ? `status=${actionableCause.status}` : undefined,\n actionableCause.phase !== undefined ? `phase=${redactDiagnosticText(actionableCause.phase)}` : undefined,\n actionableCause.endpoint !== undefined ? `endpoint=${redactDiagnosticText(actionableCause.endpoint)}` : undefined,\n actionableCause.origin !== undefined ? `origin=${redactDiagnosticText(actionableCause.origin)}` : undefined,\n actionableCause.retryAfterMs !== undefined ? `retryAfterMs=${actionableCause.retryAfterMs}` : undefined,\n actionableCause.sidecarVersion !== undefined ? `sidecarVersion=${redactDiagnosticText(actionableCause.sidecarVersion)}` : undefined,\n actionableCause.containerImage !== undefined ? `containerImage=${redactDiagnosticText(actionableCause.containerImage)}` : undefined,\n typeof actionableCause.message === 'string' ? redactDiagnosticText(actionableCause.message) : undefined,\n ].filter(Boolean)\n\n if (details.length === 0) return 'Support details: no nested sandbox cause details were available.'\n return `Support details: ${details.join('; ')}`\n}\n\nexport function isSandboxAuthFailure(diagnostics: SafeSandboxErrorDiagnostics): boolean {\n return diagnostics.causes.some((cause) => {\n const code = typeof cause.code === 'string' ? cause.code.toUpperCase() : undefined\n const status = typeof cause.status === 'number'\n ? cause.status\n : typeof cause.status === 'string'\n ? Number.parseInt(cause.status, 10)\n : undefined\n const name = typeof cause.name === 'string' ? cause.name.toLowerCase() : ''\n const message = typeof cause.message === 'string' ? cause.message.toLowerCase() : ''\n\n return code === 'AUTH_ERROR'\n || status === 401\n || name.includes('autherror')\n || message.includes('missing or invalid authentication')\n })\n}\n\n/**\n * True when the Sandbox API refused the caller's bearer: a 401 from any\n * Sandbox API route, including list and query routes such as\n * `/v1/sandboxes?status=stopped`. The caller should invalidate its cached key\n * and mint a new one once.\n *\n * Runtime routes (`/v1/sandboxes/{id}/runtime/...`) are excluded: the box's\n * runtime authentication answers those, and a new Sandbox API key does not fix\n * it. `isSandboxAuthFailure` covers them.\n */\nexport function isSandboxApiBearerAuthFailure(diagnostics: SafeSandboxErrorDiagnostics): boolean {\n return diagnostics.causes.some((cause) => {\n const status = typeof cause.status === 'number'\n ? cause.status\n : typeof cause.status === 'string'\n ? Number.parseInt(cause.status, 10)\n : undefined\n if (status !== 401) return false\n if (cause.origin !== 'sandbox-api') return false\n if (typeof cause.endpoint !== 'string') return false\n const endpointPath = sandboxApiEndpointPath(cause.endpoint)\n if (!endpointPath || !/^\\/v1(?:[/?#]|$)/.test(endpointPath)) return false\n return !/^\\/v1\\/sandboxes\\/[^/?#]+\\/runtime(?:[/?#]|$)/.test(endpointPath)\n })\n}\n\n/** Machine-readable code emitted when resume lost the physical box. */\nexport const SANDBOX_BACKING_CONTAINER_MISSING_CODE = 'BACKING_CONTAINER_MISSING' as const\n\n/**\n * Legacy fallback for Sandbox API releases that only returned the nested host\n * 404 text. New callers must use `SANDBOX_BACKING_CONTAINER_MISSING_CODE`.\n */\nexport function isLegacySandboxBackingContainerMissingMessage(message: string): boolean {\n return /host-agent startcontainer failed \\(404\\):/i.test(message)\n && /container not found/i.test(message)\n && /\"code\"\\s*:\\s*\"not_found\"/i.test(message)\n}\n\n/**\n * True when the sandbox API cannot find a sandbox resource or its backing\n * container. The latter arrives as a 500 from resume with a nested host 404.\n *\n * A sandbox id is a cache of where a workspace's box lives, not the workspace's\n * identity: the platform reaps, suspends, and loses boxes as ordinary lifecycle\n * events. Callers use this to discard the dead id and provision a replacement,\n * so the match is deliberately narrow — a 404 from the runtime sidecar\n * (`/runtime/...`, a missing file or session inside a live box) is NOT this.\n */\nexport function isSandboxApiSandboxMissingFailure(diagnostics: SafeSandboxErrorDiagnostics): boolean {\n return diagnostics.causes.some((cause) => {\n const status = typeof cause.status === 'number'\n ? cause.status\n : typeof cause.status === 'string'\n ? Number.parseInt(cause.status, 10)\n : undefined\n if (cause.origin !== 'sandbox-api') return false\n if (typeof cause.endpoint !== 'string') return false\n const endpointPath = sandboxApiEndpointPath(cause.endpoint)\n if (!endpointPath) return false\n const sandboxResource = /^\\/v1\\/sandboxes\\/[^/?#]+(?:\\/(?!runtime(?:[/?#]|$))[^?#]*)?(?:[?#].*)?$/.test(endpointPath)\n if (!sandboxResource) return false\n if (status === 404) return true\n\n if (status !== 500 || !/^\\/v1\\/sandboxes\\/[^/?#]+\\/resume(?:[?#].*)?$/.test(endpointPath)) {\n return false\n }\n const code = typeof cause.code === 'string' ? cause.code.toUpperCase() : undefined\n if (code === SANDBOX_BACKING_CONTAINER_MISSING_CODE) return true\n // Older Sandbox API releases returned only the nested host 404. The SDK\n // represented that response as SERVER_ERROR, so keep this exact fallback\n // until those releases are no longer in service.\n if (code !== undefined && code !== 'SERVER_ERROR') return false\n const message = typeof cause.message === 'string' ? cause.message : ''\n return isLegacySandboxBackingContainerMissingMessage(message)\n })\n}\n\n/**\n * True when a resume failed because the host the box is pinned to cannot seat\n * it — the host's slot budget is exhausted, not the box's fault and not\n * something waiting fixes.\n *\n * A box lives on one host. When that host fills, every future resume for every\n * box on it fails identically and permanently, so a workspace whose box landed\n * on a full host is bricked until it is placed somewhere else. Callers use this\n * the same way they use {@link isSandboxApiSandboxMissingFailure}: discard the\n * dead id and provision a replacement, which the orchestrator is free to place\n * on a host with room. The workspace itself is preserved — it lives in the\n * Vault, not in the box's filesystem.\n *\n * Matched on the message because the sandbox API returns a generic\n * `SERVER_ERROR` for it; a dedicated code upstream would replace this.\n */\nexport function isSandboxHostCapacityFailure(diagnostics: SafeSandboxErrorDiagnostics): boolean {\n return diagnostics.causes.some((cause) => {\n if (cause.origin !== 'sandbox-api') return false\n if (typeof cause.message !== 'string') return false\n return /host has no available slot|host capacity reservation failed/i.test(cause.message)\n })\n}\n\n/**\n * True when a resume failed on the box's own configuration rather than on\n * anything a retry can change.\n *\n * These are permanent facts about one box. Its egress policy can be missing,\n * or its verified Platform lineage can differ from the current caller. Neither\n * creation-time fact can change on resume, so the box must be replaced.\n *\n * Narrow on purpose. A bare 500 from the sandbox API is transient far more\n * often than not, and treating one as unbringable would delete a healthy box.\n * Matched on the specific unrecoverable phrasing, and only from `sandbox-api`.\n */\nexport function isSandboxBoxConfigFailure(diagnostics: SafeSandboxErrorDiagnostics): boolean {\n return diagnostics.causes.some((cause) => {\n if (cause.origin !== 'sandbox-api') return false\n if (cause.code === 'SANDBOX_ATTRIBUTION_MISMATCH') return true\n if (typeof cause.message !== 'string') return false\n return /has no recorded egress policy|cannot rebuild the proxy config/i.test(cause.message)\n })\n}\n\n/**\n * True when the Sandbox API answered a control-plane call with a server error\n * (500, 502, 503 or 504), such as `A sandbox backend did not answer` or\n * `Failed to resume project: fetch failed`. These clear within seconds, so a\n * caller may retry once before surfacing them.\n *\n * Runtime routes are excluded (the box answers those), and so are the narrow\n * failures that need a different action: a missing box, a box whose creation\n * facts no longer hold, and host capacity.\n */\nexport function isSandboxApiTransientFailure(diagnostics: SafeSandboxErrorDiagnostics): boolean {\n if (isSandboxApiSandboxMissingFailure(diagnostics)\n || isSandboxBoxConfigFailure(diagnostics)\n || isSandboxHostCapacityFailure(diagnostics)) return false\n return diagnostics.causes.some((cause) => {\n const status = typeof cause.status === 'number'\n ? cause.status\n : typeof cause.status === 'string'\n ? Number.parseInt(cause.status, 10)\n : undefined\n if (status !== 500 && status !== 502 && status !== 503 && status !== 504) return false\n if (cause.origin !== 'sandbox-api' || typeof cause.endpoint !== 'string') return false\n const endpointPath = sandboxApiEndpointPath(cause.endpoint)\n if (!endpointPath || !/^\\/v1(?:[/?#]|$)/.test(endpointPath)) return false\n return !/^\\/v1\\/sandboxes\\/[^/?#]+\\/runtime(?:[/?#]|$)/.test(endpointPath)\n })\n}\n\nfunction sandboxApiEndpointPath(endpoint: string): string | null {\n if (endpoint.startsWith('/')) return endpoint\n try {\n const url = new URL(endpoint)\n return `${url.pathname}${url.search}${url.hash}`\n } catch {\n return null\n }\n}\n\nexport function formatSandboxProvisioningUserMessage(\n diagnostics: SafeSandboxErrorDiagnostics,\n): string {\n if (diagnostics.causes.some((cause) => cause.code === EGRESS_PROXY_RECOVERY_REQUIRED)) {\n return 'Sandbox recovery is required before chat can continue. The stopped sandbox has not been deleted.'\n }\n\n // The sandbox itself is reachable — copying the Vault into it is what did not\n // finish. Saying \"the service is unavailable\" sends people to inspect\n // infrastructure that is healthy.\n if (diagnostics.causes.some((cause) => cause.code === 'vault.hydration_incomplete')) {\n return 'I couldn\\'t finish copying your Vault into the sandbox, so I stopped rather than work from a partial copy. The copy resumes where it left off — try again in a moment.'\n }\n\n if (isSandboxApiTransientFailure(diagnostics)) {\n return 'The sandbox service didn\\'t answer just now. Send your message again in a moment.'\n }\n\n if (isSandboxApiBearerAuthFailure(diagnostics)) {\n return 'I\\'m unable to reconnect to the sandbox because its sandbox API credential was rejected. Another request may have rotated the bearer used for this operation.'\n }\n\n if (isSandboxAuthFailure(diagnostics)) {\n return 'I\\'m unable to reconnect to the sandbox because its runtime authentication failed. This can happen when an existing sandbox is reused with stale credentials.'\n }\n\n if (diagnostics.causes.some((cause) => (\n cause.code === 'PAYLOAD_TOO_LARGE'\n || cause.code === 'FILE_TOO_LARGE'\n || cause.status === 413\n || cause.status === '413'\n ))) {\n // Profile and workspace files reach the box through writeProfileFilesToBox;\n // naming an attachment there sends people looking for one they never sent.\n if (diagnostics.causes.some((cause) => cause.message?.startsWith('writeProfileFilesToBox'))) {\n return 'A workspace file is too large to copy into the sandbox. The support details name the file.'\n }\n return 'An attachment is too large for the sandbox to accept. Use a smaller file and try again.'\n }\n\n // Matched by code, not bare 429: the sidecar's rate limiters also answer\n // 429, and those are not attachment-staging pressure.\n if (diagnostics.causes.some((cause) => cause.code === 'UPLOAD_BUDGET_EXHAUSTED')) {\n return 'Too much attachment data is staged in the sandbox at once. Retry shortly.'\n }\n\n return 'I\\'m unable to connect to the sandbox right now. Send your message again in a moment; if it keeps failing, share the support details with the team.'\n}\n","/**\n * Sandbox failures that clear on their own, and how long to wait them out.\n *\n * Both callers that meet them use this one policy: the run dispatch, which\n * resends the same execution, and the completion Workflow, which observes it.\n * A box restarting under load answers \"filesystem incarnation is not ready\"\n * for minutes (8 minutes for GTM's busiest box, 10:37 to 10:45\n * UTC), and its gateway refuses dispatches with 502 or 503 while it does.\n * Failing on the first such answer lost those turns; retrying forever would\n * hold a lock on a box that never comes back. The policy backs off from 5 s\n * to a 60 s ceiling and gives up after 15 minutes.\n */\nimport { isSandboxApiTransientFailure, serializeSandboxProvisioningError } from './diagnostics'\n\nexport type SandboxTransientFailureCode =\n /** The box is running but its filesystem incarnation is not ready yet. */\n | 'sandbox.filesystem_not_ready'\n /** The sandbox gateway answered the run dispatch with 502, 503 or 504. */\n | 'sandbox.dispatch_refused'\n /** A Sandbox API control-plane call failed with a server error. */\n | 'sandbox.control_plane_transient'\n\nexport interface SandboxTransientFailure {\n code: SandboxTransientFailureCode\n message: string\n}\n\n/** How long a transient failure may last before the caller fails. */\nexport const SANDBOX_TRANSIENT_DEADLINE_MS = 15 * 60_000\n\n/** Wait before retry `attempt` (1-based): 5 s doubling to a 60 s ceiling. */\nexport function sandboxTransientBackoffMs(attempt: number): number {\n return Math.min(60_000, 5_000 * 2 ** Math.max(0, attempt - 1))\n}\n\nfunction record(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === 'object' ? value as Record<string, unknown> : undefined\n}\n\nfunction causeChain(error: unknown): Record<string, unknown>[] {\n const chain: Record<string, unknown>[] = []\n let current = record(error)\n for (let depth = 0; current && depth < 8 && !chain.includes(current); depth += 1) {\n chain.push(current)\n current = record(current.cause)\n }\n return chain\n}\n\n/** A planned host-agent swap leaves the sandbox alive; an ordinary probe failure is not that evidence. */\nexport function plannedHostRestart(error: unknown): boolean {\n return causeChain(error).some(cause => cause.code === 'HOST_AGENT_RESTARTING' && cause.status === 503)\n}\n\n/** Wait only for the platform typed planned-restart signal, within the caller budget. */\nexport async function readDuringPlannedHostRestart<T>(\n read: () => Promise<T>,\n deadline: number,\n): Promise<{ value: T; waited: boolean }> {\n let waited = false\n for (;;) {\n try {\n return { value: await read(), waited }\n } catch (error) {\n if (!plannedHostRestart(error)) throw error\n const hint = (error as { retryAfterMs?: unknown }).retryAfterMs\n const delay = typeof hint === 'number' && Number.isFinite(hint) && hint > 0\n ? hint : sandboxTransientBackoffMs(1)\n // The existing caller budget bounds retries. Each SDK request\n // settles under its own deadline before another begins. Preserve the refusal and never start a stop on\n // expiry; its code, origin and endpoint remain available to the caller.\n if (Date.now() + delay >= deadline) throw error\n waited = true\n await new Promise(resolve => setTimeout(resolve, delay))\n }\n }\n}\n\n\nfunction status(value: unknown): number | undefined {\n if (typeof value === 'number') return value\n if (typeof value === 'string' && /^\\d{3}$/.test(value)) return Number(value)\n return undefined\n}\n\nconst FILESYSTEM_NOT_READY = /filesystem incarnation is not ready/i\nconst RUN_DISPATCH_ENDPOINT = /\\/runtime\\/agents\\/run\\/stream(?:[?#]|$)/\nconst RUN_DISPATCH_REFUSAL_MESSAGE = /\\/runtime\\/agents\\/run\\/stream: error code: (50[234])\\b/\n\n/** The typed transient failure `error` carries anywhere in its cause chain, or null. */\nexport function classifySandboxTransientFailure(error: unknown): SandboxTransientFailure | null {\n for (const cause of causeChain(error)) {\n const message = typeof cause.message === 'string' ? cause.message : ''\n if (cause.code === 'FILESYSTEM_INCARNATION_NOT_READY' || FILESYSTEM_NOT_READY.test(message)) {\n return { code: 'sandbox.filesystem_not_ready', message: 'Sandbox filesystem incarnation is not ready' }\n }\n const code = status(cause.status)\n const endpoint = typeof cause.endpoint === 'string' ? cause.endpoint : ''\n const refusal = (code === 502 || code === 503 || code === 504) && RUN_DISPATCH_ENDPOINT.test(endpoint)\n ? code\n : RUN_DISPATCH_REFUSAL_MESSAGE.exec(message)?.[1]\n if (refusal) {\n return { code: 'sandbox.dispatch_refused', message: `The sandbox gateway refused the run dispatch with ${refusal}` }\n }\n }\n if (isSandboxApiTransientFailure(serializeSandboxProvisioningError(error))) {\n return { code: 'sandbox.control_plane_transient', message: 'A Sandbox API call failed with a server error' }\n }\n return null\n}\n\n/** The error a caller raises when a transient failure outlasted the deadline. */\nexport class SandboxTransientDeadlineError extends Error {\n readonly code: SandboxTransientFailureCode\n readonly firstSeenAt: number\n readonly attempts: number\n\n constructor(failure: SandboxTransientFailure, firstSeenAt: number, attempts: number, cause?: unknown) {\n const minutes = Math.round(SANDBOX_TRANSIENT_DEADLINE_MS / 60_000)\n super(`${failure.message}; it persisted for more than ${minutes} minutes over ${attempts} attempts`, cause === undefined ? undefined : { cause })\n this.name = 'SandboxTransientDeadlineError'\n this.code = failure.code\n this.firstSeenAt = firstSeenAt\n this.attempts = attempts\n }\n}\n\nexport interface SandboxTransientRetryOptions {\n /** Defaults to {@link SANDBOX_TRANSIENT_DEADLINE_MS}. */\n deadlineMs?: number\n now?: () => number\n sleep?: (ms: number, signal?: AbortSignal) => Promise<void>\n signal?: AbortSignal\n onRetry?: (failure: SandboxTransientFailure, attempt: number, delayMs: number) => void\n}\n\nconst defaultSleep = (ms: number, signal?: AbortSignal) => new Promise<void>((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason)\n const timer = setTimeout(resolve, ms)\n signal?.addEventListener('abort', () => {\n clearTimeout(timer)\n reject(signal.reason)\n }, { once: true })\n})\n\n/**\n * Run `attempt` until it succeeds, it fails with something this policy does\n * not consider transient, or a transient failure outlasts the deadline.\n */\nexport async function retrySandboxTransient<T>(\n attempt: () => Promise<T>,\n options: SandboxTransientRetryOptions = {},\n): Promise<T> {\n const now = options.now ?? Date.now\n const sleep = options.sleep ?? defaultSleep\n const deadlineMs = options.deadlineMs ?? SANDBOX_TRANSIENT_DEADLINE_MS\n let firstSeenAt: number | undefined\n for (let attempts = 1; ; attempts += 1) {\n try {\n return await attempt()\n } catch (error) {\n const failure = classifySandboxTransientFailure(error)\n if (!failure) throw error\n const at = now()\n firstSeenAt ??= at\n const delayMs = sandboxTransientBackoffMs(attempts)\n if (at + delayMs - firstSeenAt > deadlineMs) throw new SandboxTransientDeadlineError(failure, firstSeenAt, attempts, error)\n options.onRetry?.(failure, attempts, delayMs)\n await sleep(delayMs, options.signal)\n }\n }\n}\n"],"mappings":";AA4B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ACJ,WAAS,WAAW,KAAK,YAAY,GAAG;AACtC,QAAI;AACF,aAAO,MAAM,QAAQ;AAAA,IACvB,SAAS,OAAO;AACd,YAAM,UAAU,gCAAgC,KAAK;AACrD,UAAI,CAAC,QAAS,OAAM;AACpB,YAAM,KAAK,IAAI;AACf,sBAAgB;AAChB,YAAM,UAAU,0BAA0B,QAAQ;AAClD,UAAI,KAAK,UAAU,cAAc,WAAY,OAAM,IAAI,8BAA8B,SAAS,aAAa,UAAU,KAAK;AAC1H,cAAQ,UAAU,SAAS,UAAU,OAAO;AAC5C,YAAM,MAAM,SAAS,QAAQ,MAAM;AAAA,IACrC;AAAA,EACF;AACF;","names":["isRecord","status"]}
@@ -38,4 +38,4 @@ export {
38
38
  sizedBatches,
39
39
  readInSizedBatches
40
40
  };
41
- //# sourceMappingURL=chunk-5UQJ7F3P.js.map
41
+ //# sourceMappingURL=chunk-UULUBF5J.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/launch-invariants/sized-reads.ts"],"sourcesContent":["/**\n * Reads of a large column a bounded batch at a time.\n *\n * GTM's scheduled jobs exceeded the Worker's 128 MB by reading a\n * day of stored turns at once: the outcome sweep held about 93 MB of turn\n * events, the reliability report read 1.63 M events, and turn health read\n * 121.8 MB of message parts in one query. D1 refuses the same read on its side\n * with `D1_ERROR: Memory limit exceeded before EOF`.\n *\n * A caller lists each row's key with the stored size of its large column\n * (SQLite `length(column)`), then reads and handles one batch before it reads\n * the next, keeping only what it concluded (counts, verdicts) rather than the\n * rows. Memory then holds one batch, not the day.\n *\n * Keep what you conclude, not what you read: a value sliced or matched out of a\n * large string can pin the whole parent string in V8 (a regex match kept in a\n * Map held every tool output it came from). Copy a kept substring out, e.g.\n * `new URL(match).href` or `(' ' + text).slice(1)`, before the row goes.\n */\n\n/** Most bytes of a large column one read returns; a single larger row is read alone. */\nexport const SIZED_READ_BYTES = 4 * 1024 * 1024\n\n/** D1 binds at most 100 parameters to one query. */\nexport const D1_MAX_BOUND_PARAMETERS = 100\n\n/** Most single-column keys one read binds, leaving room for the query's own parameters. */\nexport const SIZED_READ_ROWS = 50\n\n/** Most two-column keys, such as (turnId, seq), one read binds: two parameters each. */\nexport const SIZED_READ_COMPOSITE_ROWS = 40\n\n/** A row's key and the stored size of its large column. */\nexport interface SizedRow<K> {\n key: K\n /** `length()` of the large column; null when it is NULL. */\n size: number | null | undefined\n}\n\nexport interface SizedBatchOptions {\n /** Most bytes per batch. Default {@link SIZED_READ_BYTES}. */\n bytes?: number\n /** Most keys per batch. Default {@link SIZED_READ_ROWS}; `Infinity` for a range read (`seq BETWEEN`). */\n rows?: number\n}\n\n/** Consecutive keys whose stored sizes fit one read, in their listed order. */\nexport function sizedBatches<K>(rows: Iterable<SizedRow<K>>, options: SizedBatchOptions = {}): K[][] {\n const bytes = options.bytes ?? SIZED_READ_BYTES\n const maxRows = options.rows ?? SIZED_READ_ROWS\n if (!(bytes > 0)) throw new RangeError('sized batches need a positive byte budget')\n if (!(maxRows >= 1)) throw new RangeError('sized batches need at least one row per batch')\n const batches: K[][] = []\n let batch: K[] = []\n let size = 0\n for (const row of rows) {\n const rowSize = Math.max(0, Number(row.size ?? 0) || 0)\n if (batch.length > 0 && (size + rowSize > bytes || batch.length >= maxRows)) {\n batches.push(batch)\n batch = []\n size = 0\n }\n batch.push(row.key)\n size += rowSize\n }\n if (batch.length > 0) batches.push(batch)\n return batches\n}\n\n/**\n * Read listed rows one sized batch at a time. Each batch is read only after the\n * caller has handled the previous one, so a `for await` loop that keeps its\n * conclusions and drops the rows holds one batch at most.\n */\nexport async function* readInSizedBatches<K, R>(\n rows: Iterable<SizedRow<K>>,\n read: (keys: K[]) => Promise<R>,\n options: SizedBatchOptions = {},\n): AsyncGenerator<{ keys: K[]; value: R }> {\n for (const keys of sizedBatches(rows, options)) {\n yield { keys, value: await read(keys) }\n }\n}\n"],"mappings":";AAqBO,IAAM,mBAAmB,IAAI,OAAO;AAGpC,IAAM,0BAA0B;AAGhC,IAAM,kBAAkB;AAGxB,IAAM,4BAA4B;AAiBlC,SAAS,aAAgB,MAA6B,UAA6B,CAAC,GAAU;AACnG,QAAM,QAAQ,QAAQ,SAAS;AAC/B,QAAM,UAAU,QAAQ,QAAQ;AAChC,MAAI,EAAE,QAAQ,GAAI,OAAM,IAAI,WAAW,2CAA2C;AAClF,MAAI,EAAE,WAAW,GAAI,OAAM,IAAI,WAAW,+CAA+C;AACzF,QAAM,UAAiB,CAAC;AACxB,MAAI,QAAa,CAAC;AAClB,MAAI,OAAO;AACX,aAAW,OAAO,MAAM;AACtB,UAAM,UAAU,KAAK,IAAI,GAAG,OAAO,IAAI,QAAQ,CAAC,KAAK,CAAC;AACtD,QAAI,MAAM,SAAS,MAAM,OAAO,UAAU,SAAS,MAAM,UAAU,UAAU;AAC3E,cAAQ,KAAK,KAAK;AAClB,cAAQ,CAAC;AACT,aAAO;AAAA,IACT;AACA,UAAM,KAAK,IAAI,GAAG;AAClB,YAAQ;AAAA,EACV;AACA,MAAI,MAAM,SAAS,EAAG,SAAQ,KAAK,KAAK;AACxC,SAAO;AACT;AAOA,gBAAuB,mBACrB,MACA,MACA,UAA6B,CAAC,GACW;AACzC,aAAW,QAAQ,aAAa,MAAM,OAAO,GAAG;AAC9C,UAAM,EAAE,MAAM,OAAO,MAAM,KAAK,IAAI,EAAE;AAAA,EACxC;AACF;","names":[]}
@@ -22,13 +22,13 @@ var LAUNCH_BUDGETS = {
22
22
  d1RowsPerQuery: 25e4,
23
23
  /** A workspace box's disk: the Sandbox SDK's default tier (10 GB). */
24
24
  sandboxDiskBytes: 10 * 1024 ** 3,
25
- /** Platform snapshots per box; the cap GTM hit on 2026-10-10. */
25
+ /** Platform snapshots per box; the cap GTM hit. */
26
26
  snapshotCount: 25,
27
27
  /** Operator key requests per minute. */
28
28
  keyRatePerMinute: 60,
29
29
  /** Hours one resource's limit alarm waits before it repeats. */
30
30
  alarmRepeatHours: 6,
31
- /** Cloudflare's gzip limit on a Worker's Total Upload on the paid plan, in KiB; Legal deployed 9,659 KiB (94%) on 2026-10-19. */
31
+ /** Cloudflare's gzip limit on a Worker's Total Upload on the paid plan, in KiB; Legal deployed 9,659 KiB (94%). */
32
32
  workerUploadGzipKiB: 10 * 1024,
33
33
  /** Cloudflare's raw limit on a Worker's Total Upload, in KiB. */
34
34
  workerUploadRawKiB: 64 * 1024
@@ -80,7 +80,7 @@ var LAUNCH_INVARIANTS = [
80
80
  id: "limit-alarms",
81
81
  title: "Platform-limit alarms at 80%",
82
82
  rule: "Worker memory, D1 rows per query, sandbox disk, snapshot count and key rate each have a declared limit and an alarm that fires at 80%.",
83
- incident: "19 platform-limit events on 2026-10-10, each found after it failed a customer."
83
+ incident: "19 platform-limit events, each found after it failed a customer."
84
84
  },
85
85
  {
86
86
  id: "pasted-code-reaches-chat",
@@ -102,4 +102,4 @@ export {
102
102
  LAUNCH_INVARIANT_IDS,
103
103
  describeVerdict
104
104
  };
105
- //# sourceMappingURL=chunk-LRYY3OX7.js.map
105
+ //# sourceMappingURL=chunk-VEPII3YP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/launch-invariants/catalog.ts"],"sourcesContent":["/**\n * The launch invariants every agent app holds, and the budgets they are held to.\n *\n * Each one is a failure GTM shipped to production and fixed by\n * hand. They are listed here once so every app checks the same rule with the\n * same numbers, and `agent-app-invariants` reports each by its id.\n */\n\n/** Budgets the invariants are measured against. */\nexport const LAUNCH_BUDGETS = {\n /** Most bytes one query may return in a scheduled job or report route: one sized batch with room for its listing. */\n queryBytes: 8 * 1024 * 1024,\n /** Most the live heap may grow while one scheduled job runs on a day-sized fixture. */\n heapGrowthBytes: 40 * 1024 * 1024,\n /** Most bytes of a large column one sized read returns; a single larger row is read alone. */\n sizedReadBytes: 4 * 1024 * 1024,\n /** Most stored events one long turn may write. */\n turnEvents: 5_000,\n /** A turn whose owner stopped reaches its terminal state within this long. */\n settleWithinMs: 15 * 60_000,\n /** Turn recovery and orphan settlement run at least this often. */\n recoveryEveryMs: 15 * 60_000,\n /** Longest a cached auth lookup may be served while the store cannot answer. */\n authCacheTtlMs: 60_000,\n /** A platform-limit alarm fires at this share of the limit. */\n alarmRatio: 0.8,\n /** A Worker isolate's memory. */\n workerMemoryBytes: 128 * 1024 * 1024,\n /** Rows one D1 query may read before an alarm; a sized read stays far below it (GTM's 1.63 M-event scan overloaded D1). */\n d1RowsPerQuery: 250_000,\n /** A workspace box's disk: the Sandbox SDK's default tier (10 GB). */\n sandboxDiskBytes: 10 * 1024 ** 3,\n /** Platform snapshots per box; the cap GTM hit. */\n snapshotCount: 25,\n /** Operator key requests per minute. */\n keyRatePerMinute: 60,\n /** Hours one resource's limit alarm waits before it repeats. */\n alarmRepeatHours: 6,\n /** Cloudflare's gzip limit on a Worker's Total Upload on the paid plan, in KiB; Legal deployed 9,659 KiB (94%). */\n workerUploadGzipKiB: 10 * 1024,\n /** Cloudflare's raw limit on a Worker's Total Upload, in KiB. */\n workerUploadRawKiB: 64 * 1024,\n} as const\n\nexport type LaunchInvariantId =\n | 'bounded-reads'\n | 'memory-budget'\n | 'isolated-jobs'\n | 'honest-settlement'\n | 'coalesced-events'\n | 'auth-survives-d1-stall'\n | 'authorize-before-stream'\n | 'limit-alarms'\n | 'pasted-code-reaches-chat'\n\nexport interface LaunchInvariant {\n id: LaunchInvariantId\n title: string\n /** The rule, as the conformance report states it. */\n rule: string\n /** The production failure the rule answers. */\n incident: string\n}\n\nexport const LAUNCH_INVARIANTS: readonly LaunchInvariant[] = [\n {\n id: 'bounded-reads',\n title: 'Bounded reads',\n rule: 'No query in a scheduled job or report route returns more than 8 MB; large columns are read in sized batches of at most 4 MB.',\n incident: 'GTM turn health read 500 replies with their parts (122 MB of a 128 MB Worker); the reliability report scanned 1.63 M events and overloaded D1.',\n },\n {\n id: 'memory-budget',\n title: 'Memory budget',\n rule: 'Every scheduled job runs on a day-sized fixture with live-heap growth of at most 40 MB, and every scheduled job is covered.',\n incident: 'GTM sweeps exceeded the Worker\\'s 128 MB six times; a regex slice kept in a Map pinned whole tool outputs.',\n },\n {\n id: 'isolated-jobs',\n title: 'Isolated scheduled jobs',\n rule: 'Each scheduled invocation runs exactly one job, and turn recovery and orphan settlement run at least every 15 minutes.',\n incident: 'At 21:00Z turn health ran out of memory while the hourly sweeps shared one run, and none of the eight queued after it ran.',\n },\n {\n id: 'honest-settlement',\n title: 'Honest turn settlement',\n rule: 'Every turn reaches exactly one terminal state (an answer, a typed failure with Retry, or a Stop counted on its own) within 15 minutes of its owner stopping; failures are attributed to the request time, and a completed run with an aborted tool is a failure.',\n incident: 'Stale running rows (51 settled by hand), failure notices 8–11 h late, and completions with aborted tools counted as answers.',\n },\n {\n id: 'coalesced-events',\n title: 'Coalesced turn events',\n rule: 'A recorded long turn stores at most 5,000 events: text and reasoning deltas are merged before storage.',\n incident: 'A reasoning model wrote 59,659 events in one turn and 1.63 M in a day.',\n },\n {\n id: 'auth-survives-d1-stall',\n title: 'Auth survives a D1 stall',\n rule: 'A key or session verified within 60 s keeps working while D1 errors or stalls; the cache is used only then, never past revoke or expiry, and is keyed by SHA-256.',\n incident: 'An overloaded D1 failed sign-in and API-key checks for credentials that were valid moments before.',\n },\n {\n id: 'authorize-before-stream',\n title: 'Authorization before any stream',\n rule: 'A refused request gets a plain response; no stream opens and no product state is touched before authorization resolves.',\n incident: 'agent-app 0.60.48–0.60.49 opened a progress-first stream before authorize ran.',\n },\n {\n id: 'limit-alarms',\n title: 'Platform-limit alarms at 80%',\n rule: 'Worker memory, D1 rows per query, sandbox disk, snapshot count and key rate each have a declared limit and an alarm that fires at 80%.',\n incident: '19 platform-limit events, each found after it failed a customer.',\n },\n {\n id: 'pasted-code-reaches-chat',\n title: 'Pasted code reaches the chat',\n rule: 'An authenticated chat message carrying pasted code (shell, SQL, markup) gets the route\\'s normal response; no app filter, sanitizer or edge rule refuses it.',\n incident: 'On 2026-10-11 a chat message containing `cat /etc/passwd` got Cloudflare\\'s 403 block page from gtm.tangle.tools instead of reaching the Worker.',\n },\n]\n\n/** The invariant ids in report order. */\nexport const LAUNCH_INVARIANT_IDS: readonly LaunchInvariantId[] = LAUNCH_INVARIANTS.map((invariant) => invariant.id)\n\n/** One checked outcome of one invariant, for one subject (a job, a route, a scenario). */\nexport interface InvariantVerdict {\n invariant: LaunchInvariantId\n /** What was checked: a job name, a route, a scenario. */\n subject: string\n pass: boolean\n /** Findings, one line each. On a pass, what was proven. */\n details: string[]\n /** Measurements behind the verdict, for the report. */\n data?: Record<string, unknown>\n /**\n * Set when the app recorded this failure as known, with why and who owns the\n * fix. The report counts it as not holding; it does not fail the suite.\n */\n knownFailing?: string\n}\n\n/** A verdict whose message names every finding, for a test runner's failure output. */\nexport function describeVerdict(verdict: InvariantVerdict): string {\n const head = `${verdict.pass ? 'PASS' : 'FAIL'} ${verdict.invariant} — ${verdict.subject}`\n return verdict.details.length ? `${head}\\n ${verdict.details.join('\\n ')}` : head\n}\n"],"mappings":";AASO,IAAM,iBAAiB;AAAA;AAAA,EAE5B,YAAY,IAAI,OAAO;AAAA;AAAA,EAEvB,iBAAiB,KAAK,OAAO;AAAA;AAAA,EAE7B,gBAAgB,IAAI,OAAO;AAAA;AAAA,EAE3B,YAAY;AAAA;AAAA,EAEZ,gBAAgB,KAAK;AAAA;AAAA,EAErB,iBAAiB,KAAK;AAAA;AAAA,EAEtB,gBAAgB;AAAA;AAAA,EAEhB,YAAY;AAAA;AAAA,EAEZ,mBAAmB,MAAM,OAAO;AAAA;AAAA,EAEhC,gBAAgB;AAAA;AAAA,EAEhB,kBAAkB,KAAK,QAAQ;AAAA;AAAA,EAE/B,eAAe;AAAA;AAAA,EAEf,kBAAkB;AAAA;AAAA,EAElB,kBAAkB;AAAA;AAAA,EAElB,qBAAqB,KAAK;AAAA;AAAA,EAE1B,oBAAoB,KAAK;AAC3B;AAsBO,IAAM,oBAAgD;AAAA,EAC3D;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AACF;AAGO,IAAM,uBAAqD,kBAAkB,IAAI,CAAC,cAAc,UAAU,EAAE;AAoB5G,SAAS,gBAAgB,SAAmC;AACjE,QAAM,OAAO,GAAG,QAAQ,OAAO,SAAS,MAAM,IAAI,QAAQ,SAAS,WAAM,QAAQ,OAAO;AACxF,SAAO,QAAQ,QAAQ,SAAS,GAAG,IAAI;AAAA,IAAO,QAAQ,QAAQ,KAAK,MAAM,CAAC,KAAK;AACjF;","names":[]}
@@ -651,4 +651,4 @@ export {
651
651
  nextCallIndex,
652
652
  tracedModelFetch
653
653
  };
654
- //# sourceMappingURL=chunk-AVBNS64P.js.map
654
+ //# sourceMappingURL=chunk-W6G2HF6M.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/turn-trace/phase-timing.ts","../src/turn-trace/recorder.ts","../src/turn-trace/otel.ts","../src/turn-trace/server-timing.ts","../src/turn-trace/traced-fetch.ts"],"sourcesContent":["import type { TurnSpan, TurnSpanAttrs, TurnSpanKind, TurnTrace } from './recorder'\n\n/** Domain-named phases and concurrent work over the turn's existing clock and D1 counter. */\nexport interface TurnPhaseTiming {\n readonly startedAt: number\n mark(name: string): void\n track<T>(name: string, work: Promise<T>, attrsOf?: (value: T) => TurnSpanAttrs): Promise<T>\n within(parent: TurnSpan | undefined): void\n phases(): Record<string, number>\n concurrent(): Record<string, number>\n queries(): Record<string, number>\n}\n\nexport interface TurnPhaseTimingOptions {\n prefix: string\n startedAt?: number\n kinds?: Readonly<Record<string, TurnSpanKind>>\n}\n\n/** The recorder supplies its clock/counter; this module has no host or Node dependency. */\nexport function turnPhaseTiming(trace: TurnTrace, options: TurnPhaseTimingOptions,\n now: () => number, counter?: { readonly queries: number }): TurnPhaseTiming {\n const startedAt = options.startedAt ?? trace.startedAt\n let last = startedAt, floor = startedAt, lastQuery = counter?.queries ?? 0\n let parent: TurnSpan | undefined\n const phases: Record<string, number> = {}, concurrent: Record<string, number> = {}, queries: Record<string, number> = {}\n const kind = (name: string) => options.kinds?.[name] ?? 'admission'\n const label = (name: string) => `${options.prefix}.${name}`\n return {\n startedAt,\n mark(name) {\n const at = now()\n phases[name] = (phases[name] ?? 0) + at - last\n if (counter) {\n queries[name] = (queries[name] ?? 0) + counter.queries - lastQuery\n lastQuery = counter.queries\n }\n trace.record(label(name), kind(name), parent ? Math.max(last, floor) : last, at, {}, parent)\n last = at\n },\n track(name, work, attrsOf) {\n const began = now(), span = trace.start(label(name), kind(name))\n void work.then(value => { concurrent[name] = now() - began; span.end(attrsOf?.(value)) },\n error => { concurrent[name] = now() - began; span.end(undefined, error) }).catch(() => {})\n return work\n },\n within(span) { parent = span; floor = now() },\n phases: () => ({ ...phases }), concurrent: () => ({ ...concurrent }), queries: () => counter ? { ...queries } : {},\n }\n}\n","import { turnPhaseTiming, type TurnPhaseTiming, type TurnPhaseTimingOptions } from './phase-timing'\n/**\n * One trace per agent turn: a root span for the turn's wall time and named\n * child spans for where that time went (admission, each model call, each tool\n * call, the box claim and prompt, persistence).\n *\n * This module only records. It has no imports, so the Router engine, the\n * sandbox helpers and the chat route share it from any runtime, a Worker\n * included. `./otel` turns a finished trace into OTLP spans for Tangle\n * Intelligence.\n *\n * The turn's trace id is its execution id in the charset every hop accepts\n * ({@link turnTraceId}), sent as `x-tangle-trace-id` on every Router and\n * Sandbox call, so a Router dispatch row and a sandbox record join the turn's\n * spans by one id.\n */\n\n/** What a span's time is spent on. Each instant of the turn is credited to the deepest open span's kind. */\nexport type TurnSpanKind =\n | 'admission'\n | 'router'\n | 'model'\n | 'network'\n | 'tool'\n | 'sandbox'\n | 'persist'\n | 'other'\n\nexport const TURN_SPAN_KINDS: readonly TurnSpanKind[] = ['admission', 'router', 'model', 'network', 'tool', 'sandbox', 'persist', 'other']\n\n/** Bounded primitive metadata. Never prompts, answers, tool arguments or credentials. */\nexport type TurnSpanAttrs = Record<string, string | number | boolean>\n\nexport interface TurnSpanRecord {\n spanId: string\n /** The root span's id for a top-level child. */\n parentSpanId: string\n name: string\n kind: TurnSpanKind\n startMs: number\n endMs: number\n attrs: TurnSpanAttrs\n /** Set when the span ended in failure; a short code or message, never content. */\n error?: string\n /** True when the turn finished while the span was still open. */\n unfinished?: boolean\n}\n\nexport interface TurnSpan {\n readonly id: string\n /** Merge attributes. A later value replaces an earlier one. */\n set(attrs: TurnSpanAttrs): TurnSpan\n /** End now. A second call changes nothing. `error` marks the span failed. */\n end(attrs?: TurnSpanAttrs, error?: unknown): void\n /** A child that starts now. */\n child(name: string, kind: TurnSpanKind, attrs?: TurnSpanAttrs): TurnSpan\n /** A child whose times are already known. */\n record(name: string, kind: TurnSpanKind, startMs: number, endMs: number, attrs?: TurnSpanAttrs): TurnSpan\n}\n\n/** How much of the turn's wall time is inside named spans, and what the time was spent on. */\nexport interface TurnTraceSummary {\n traceId: string\n wallMs: number\n /** Wall time inside at least one child span. */\n coveredMs: number\n /** `coveredMs / wallMs` as a percentage, one decimal. */\n coveragePct: number\n uncoveredMs: number\n /** The longest stretch with no span open: where an unnamed wait hides. */\n largestGapMs: number\n /** Wall time credited to the deepest open span's kind. Sums to `coveredMs`. */\n byKind: Record<TurnSpanKind, number>\n spans: number\n modelCalls: number\n toolCalls: number\n /** Spans refused after the per-turn cap. */\n dropped: number\n /** From the request to the first visible text the member could read (see {@link TurnTrace.markFirstText}); absent when none streamed. */\n firstTextMs?: number\n /** Headline latency: request to first reasoning, tool activity or answer output. */\n firstVisibleMs?: number\n /** D1 round trips in the turn scope, when its binding is instrumented. */\n d1Queries?: number\n /** From the request to the first model request: the wait the app owns before the model can start. */\n dispatchMs?: number\n /** Each `admission.*` span's duration by its name after `admission.`, the split of the wait before the turn opens. */\n admission?: Record<string, number>\n /** Prompt tokens over every model call, and how many of them the provider served from its prompt cache. */\n inputTokens?: number\n cachedInputTokens?: number\n}\n\nexport interface TurnTraceSnapshot {\n traceId: string\n /** The id the root span is exported under. */\n rootSpanId: string\n executionId: string\n startedAt: number\n endedAt: number\n spans: TurnSpanRecord[]\n summary: TurnTraceSummary\n /** `ok`, or the failure the turn ended with. */\n status: 'ok' | 'error'\n error?: string\n}\n\n/** Where a finished turn's trace goes. `labels` are the host's metadata for the root span (session, user, workspace). */\nexport type TurnTraceSink = (snapshot: TurnTraceSnapshot, labels: TurnSpanAttrs) => void | Promise<void>\n\nexport interface TurnTrace {\n /** The turn's execution id in the charset the Router and Sandbox accept. Send it as `x-tangle-trace-id`. */\n readonly traceId: string\n readonly executionId: string\n readonly startedAt: number\n /** The span a top-level child hangs from. */\n readonly root: TurnSpan\n /** Name the turn's execution id once it is known. Spans recorded earlier keep their times. */\n bind(executionId: string): void\n start(name: string, kind: TurnSpanKind, attrs?: TurnSpanAttrs, parent?: TurnSpan): TurnSpan\n record(name: string, kind: TurnSpanKind, startMs: number, endMs: number, attrs?: TurnSpanAttrs, parent?: TurnSpan): TurnSpan\n /** Run `work` inside a span; the span ends when it settles, failed if it throws. */\n measure<T>(name: string, kind: TurnSpanKind, work: (span: TurnSpan) => Promise<T> | T, attrs?: TurnSpanAttrs, parent?: TurnSpan): Promise<T>\n /**\n * Note that the turn's first visible text reached the member. The chat route calls it on the first text event of\n * either lane; a product that owns its turn calls it itself. Only the first call counts. The summary's\n * `firstTextMs` then reads from the request, so it holds admission, the box or the Router, and the model.\n */\n markFirstText(at?: number): void\n /** Mark the first reasoning, tool activity or answer output. Only the first call counts. */\n markFirstVisible(at?: number): void\n /** Sequential phases and concurrent work share this turn's existing clock and query counter. */\n timing(options: TurnPhaseTimingOptions): TurnPhaseTiming\n /** Read the current numbers without ending the trace. */\n summary(now?: number): TurnTraceSummary\n /** Read the spans recorded so far without ending the trace; an open span reads as ending at `now`. */\n spans(now?: number): TurnSpanRecord[]\n /** End the trace: open spans close at `endedAt`, and later spans are refused. A second call returns the first result. */\n finish(outcome?: { error?: unknown; endedAt?: number }): TurnTraceSnapshot\n}\n\nexport interface CreateTurnTraceOptions {\n /** Epoch ms the turn began (default now). A route passes its request time so admission is inside the trace. */\n startedAt?: number\n executionId?: string\n now?: () => number\n /** Most spans one turn keeps (default 1000); the rest are counted as dropped. */\n maxSpans?: number\n /** Live counter captured by the server turn owner; no Node dependency in the recorder. */\n d1QueryCounter?: { readonly queries: number }\n}\nconst MAX_ATTRS = 48\nconst MAX_ATTR_STRING = 200\n\n/**\n * The turn's execution id as a trace id. Execution ids carry `:` (`app:session:turn`),\n * which the Router drops from `x-tangle-trace-id`, so every character outside\n * `[A-Za-z0-9_-]` becomes `_`. An id already in the charset is returned as it is.\n */\nexport function turnTraceId(executionId: string): string {\n // An id in the charset is the caller's own, whatever its length (the Router drops one under 8 characters; it is not rewritten here).\n if (/^[\\w-]{1,200}$/.test(executionId)) return executionId\n const id = executionId.replace(/[^\\w-]/g, '_').slice(0, 200)\n return id.length >= 8 ? id : id.padEnd(8, '_')\n}\n\nfunction randomHex(bytes: number): string {\n const out = new Uint8Array(bytes)\n if (typeof globalThis.crypto?.getRandomValues === 'function') globalThis.crypto.getRandomValues(out)\n else for (let i = 0; i < bytes; i++) out[i] = Math.floor(Math.random() * 256)\n return Array.from(out, (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\nfunction boundedAttrs(attrs: TurnSpanAttrs): TurnSpanAttrs {\n const out: TurnSpanAttrs = {}\n let count = 0\n for (const [key, value] of Object.entries(attrs)) {\n if (count >= MAX_ATTRS) break\n if (typeof value === 'number' && !Number.isFinite(value)) continue\n out[key.slice(0, 80)] = typeof value === 'string' ? value.slice(0, MAX_ATTR_STRING) : value\n count++\n }\n return out\n}\n\nfunction errorText(error: unknown): string {\n if (error instanceof Error) return (error.name === 'Error' ? error.message : `${error.name}: ${error.message}`).slice(0, MAX_ATTR_STRING)\n return String(error).slice(0, MAX_ATTR_STRING)\n}\n\nconst zeroKinds = (): Record<TurnSpanKind, number> => ({\n admission: 0, router: 0, model: 0, network: 0, tool: 0, sandbox: 0, persist: 0, other: 0,\n})\n\nconst round1 = (value: number) => Math.round(value * 10) / 10\n\n/**\n * Coverage and the per-kind split for a set of spans over `[startMs, endMs]`.\n * Exported for a reader that holds the spans of a finished trace.\n */\nexport function summarizeTurnSpans(\n spans: readonly Pick<TurnSpanRecord, 'spanId' | 'parentSpanId' | 'kind' | 'name' | 'startMs' | 'endMs'>[],\n rootSpanId: string,\n startMs: number,\n endMs: number,\n traceId: string,\n dropped = 0,\n): TurnTraceSummary {\n const wallMs = Math.max(0, endMs - startMs)\n const parent = new Map(spans.map((span) => [span.spanId, span.parentSpanId]))\n const depthOf = (id: string): number => {\n let depth = 0\n for (let at = parent.get(id); at !== undefined && at !== rootSpanId; at = parent.get(at)) {\n depth++\n if (depth > 64) break\n }\n return depth\n }\n const clipped = spans\n .map((span) => ({ span, start: Math.max(startMs, span.startMs), end: Math.min(endMs, span.endMs), depth: depthOf(span.spanId) }))\n .filter((entry) => entry.end > entry.start)\n const points = [...new Set([startMs, endMs, ...clipped.flatMap((entry) => [entry.start, entry.end])])].sort((a, b) => a - b)\n const byKind = zeroKinds()\n let coveredMs = 0\n let largestGapMs = 0\n let gap = 0\n for (let i = 0; i + 1 < points.length; i++) {\n const from = points[i]!\n const to = points[i + 1]!\n let deepest: (typeof clipped)[number] | undefined\n for (const entry of clipped) {\n if (entry.start <= from && entry.end >= to && (!deepest || entry.depth > deepest.depth || (entry.depth === deepest.depth && entry.start > deepest.start))) deepest = entry\n }\n if (deepest) {\n byKind[deepest.span.kind] += to - from\n coveredMs += to - from\n gap = 0\n } else {\n gap += to - from\n largestGapMs = Math.max(largestGapMs, gap)\n }\n }\n for (const kind of TURN_SPAN_KINDS) byKind[kind] = round1(byKind[kind])\n return {\n traceId,\n wallMs: round1(wallMs),\n coveredMs: round1(coveredMs),\n coveragePct: wallMs > 0 ? round1((coveredMs / wallMs) * 100) : 0,\n uncoveredMs: round1(wallMs - coveredMs),\n largestGapMs: round1(largestGapMs),\n byKind,\n spans: spans.length,\n modelCalls: spans.filter((span) => span.name === 'model.call').length,\n toolCalls: spans.filter((span) => span.name === 'tool.call').length,\n dropped,\n }\n}\n\n/** The summary fields read from span names and attributes: dispatch time, the admission split and prompt-cache use. */\nfunction spanMeasurements(spans: readonly TurnSpanRecord[], startedAt: number): Partial<TurnTraceSummary> {\n const admission: Record<string, number> = {}\n let firstModelCall: number | undefined\n let inputTokens: number | undefined\n let cachedInputTokens: number | undefined\n for (const span of spans) {\n if (span.kind === 'admission' && span.name.startsWith('admission.')) {\n const step = span.name.slice('admission.'.length)\n admission[step] = round1((admission[step] ?? 0) + span.endMs - span.startMs)\n }\n if (span.name !== 'model.call') continue\n firstModelCall = Math.min(firstModelCall ?? span.startMs, span.startMs)\n const input = span.attrs['gen_ai.usage.input_tokens']\n if (typeof input === 'number') inputTokens = (inputTokens ?? 0) + input\n const cached = span.attrs['gen_ai.usage.cache_read.input_tokens']\n if (typeof cached === 'number') cachedInputTokens = (cachedInputTokens ?? 0) + cached\n }\n return {\n ...(firstModelCall === undefined ? {} : { dispatchMs: round1(Math.max(0, firstModelCall - startedAt)) }),\n ...(Object.keys(admission).length ? { admission } : {}),\n ...(inputTokens === undefined ? {} : { inputTokens }),\n ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }),\n }\n}\n\nexport function createTurnTrace(options: CreateTurnTraceOptions = {}): TurnTrace {\n const now = options.now ?? Date.now\n const startedAt = options.startedAt ?? now()\n const maxSpans = options.maxSpans ?? 1000\n const rootId = randomHex(8)\n let executionId = options.executionId ?? `pending_${randomHex(6)}`\n let traceId = turnTraceId(executionId)\n const records = new Map<string, TurnSpanRecord>()\n const open = new Set<string>()\n let dropped = 0\n let finished: TurnTraceSnapshot | undefined\n let firstVisibleAt: number | undefined\n let firstTextAt: number | undefined\n\n // A refused or late span still returns a handle, so instrumentation never branches on the trace's state.\n const inert = (id: string): TurnSpan => {\n const handle: TurnSpan = {\n id,\n set: () => handle,\n end: () => {},\n child: () => inert(rootId),\n record: () => inert(rootId),\n }\n return handle\n }\n\n const handleFor = (id: string): TurnSpan => {\n const handle: TurnSpan = {\n id,\n set(attrs) {\n const record = records.get(id)\n if (record && !finished) record.attrs = boundedAttrs({ ...record.attrs, ...attrs })\n return handle\n },\n end(attrs, error) {\n const record = records.get(id)\n if (!record || !open.has(id) || finished) return\n open.delete(id)\n record.endMs = Math.max(record.startMs, now())\n if (attrs) record.attrs = boundedAttrs({ ...record.attrs, ...attrs })\n if (error !== undefined) record.error = errorText(error)\n },\n child: (name, kind, attrs) => trace.start(name, kind, attrs, handle),\n record: (name, kind, start, end, attrs) => trace.record(name, kind, start, end, attrs, handle),\n }\n return handle\n }\n\n const add = (name: string, kind: TurnSpanKind, startMs: number, endMs: number | undefined, attrs: TurnSpanAttrs | undefined, parent: TurnSpan | undefined): TurnSpan => {\n if (finished) return inert(rootId)\n if (records.size >= maxSpans) {\n dropped++\n return inert(rootId)\n }\n const spanId = randomHex(8)\n records.set(spanId, {\n spanId,\n parentSpanId: parent && parent.id !== spanId ? parent.id : rootId,\n name: name.slice(0, 80),\n kind,\n startMs,\n endMs: endMs ?? startMs,\n attrs: attrs ? boundedAttrs(attrs) : {},\n })\n if (endMs === undefined) open.add(spanId)\n return handleFor(spanId)\n }\n\n const rootHandle: TurnSpan = {\n id: rootId,\n set: () => rootHandle,\n end: () => {},\n child: (name, kind, attrs) => trace.start(name, kind, attrs),\n record: (name, kind, start, end, attrs) => trace.record(name, kind, start, end, attrs),\n }\n\n const withMeasurements = (summary: TurnTraceSummary, spans: readonly TurnSpanRecord[]): TurnTraceSummary => ({\n ...summary,\n ...spanMeasurements(spans, startedAt),\n ...(firstVisibleAt === undefined ? {} : { firstVisibleMs: round1(firstVisibleAt - startedAt) }),\n ...(firstTextAt === undefined ? {} : { firstTextMs: round1(firstTextAt - startedAt) }),\n ...(options.d1QueryCounter === undefined ? {} : { d1Queries: options.d1QueryCounter.queries }),\n })\n\n const trace: TurnTrace = {\n get traceId() { return traceId },\n get executionId() { return executionId },\n startedAt,\n root: rootHandle,\n bind(id) {\n executionId = id\n traceId = turnTraceId(id)\n },\n start: (name, kind, attrs, parent) => add(name, kind, now(), undefined, attrs, parent),\n record: (name, kind, startMs, endMs, attrs, parent) => add(name, kind, startMs, Math.max(startMs, endMs), attrs, parent),\n async measure(name, kind, work, attrs, parent) {\n const span = trace.start(name, kind, attrs, parent)\n try {\n const result = await work(span)\n span.end()\n return result\n } catch (error) {\n span.end(undefined, error)\n throw error\n }\n },\n markFirstVisible(at) {\n if (finished || firstVisibleAt !== undefined) return\n firstVisibleAt = Math.max(startedAt, at ?? now())\n },\n markFirstText(at) {\n if (finished || firstTextAt !== undefined) return\n firstTextAt = Math.max(startedAt, at ?? now())\n firstVisibleAt ??= firstTextAt\n },\n timing: phaseOptions => turnPhaseTiming(trace, phaseOptions, now, options.d1QueryCounter),\n summary(at) {\n if (finished) return finished.summary\n const end = at ?? now()\n const spans = trace.spans(end)\n return withMeasurements(summarizeTurnSpans(spans, rootId, startedAt, end, traceId, dropped), spans)\n },\n spans(at) {\n const end = at ?? finished?.endedAt ?? now()\n return [...records.values()].map((record) => open.has(record.spanId) ? { ...record, endMs: end } : { ...record })\n },\n finish(outcome) {\n if (finished) return finished\n const endedAt = Math.max(startedAt, outcome?.endedAt ?? now())\n for (const id of open) {\n const record = records.get(id)!\n record.endMs = Math.max(record.startMs, endedAt)\n record.unfinished = true\n }\n open.clear()\n const spans = [...records.values()].sort((a, b) => a.startMs - b.startMs)\n finished = {\n traceId,\n rootSpanId: rootId,\n executionId,\n startedAt,\n endedAt,\n spans,\n summary: withMeasurements(summarizeTurnSpans(spans, rootId, startedAt, endedAt, traceId, dropped), spans),\n status: outcome?.error === undefined ? 'ok' : 'error',\n ...(outcome?.error === undefined ? {} : { error: errorText(outcome.error) }),\n }\n return finished\n },\n }\n return trace\n}\n","/**\n * A finished turn trace as OTLP spans, sent to Tangle Intelligence.\n *\n * The attribute vocabulary is the one agent-runtime's span builders write\n * (`gen_ai.operation.name`, `gen_ai.request.model`, `gen_ai.usage.*`,\n * `gen_ai.tool.name`, OpenInference's span kind, `agent.parent.confidence`), and\n * the wire shape is the one its `createOtelExporter` posts to\n * `<base>/v1/otlp/v1/traces`.\n *\n * It does not import agent-runtime. The runtime root pulls the whole sandbox\n * SDK into a Worker bundle, and the SDK's chain client imports `viem`, which a\n * Worker build cannot resolve (Hospitality's release failed on exactly that);\n * and its exporter keeps a timer a Worker refuses at module scope. One OTLP\n * POST per finished turn needs neither.\n */\nimport { TURN_SPAN_KINDS, type TurnSpanAttrs, type TurnSpanKind, type TurnTraceSink, type TurnTraceSnapshot } from './recorder'\n\n/** One OTLP/JSON span, as Intelligence's ingest reads it. */\nexport interface OtlpSpan {\n traceId: string\n spanId: string\n parentSpanId?: string\n name: string\n kind: number\n startTimeUnixNano: string\n endTimeUnixNano: string\n attributes: Array<{ key: string; value: { stringValue?: string; intValue?: string; doubleValue?: number; boolValue?: boolean } }>\n status: { code: number; message?: string }\n}\n\n/** `doubles` names measurements that stay `doubleValue` when they land on a whole number, so a reader sees one type per key. */\nfunction attributes(record: Record<string, string | number | boolean>, doubles: ReadonlySet<string> = new Set()): OtlpSpan['attributes'] {\n return Object.entries(record).flatMap(([key, value]) => {\n if (typeof value === 'number' && !Number.isFinite(value)) return []\n return [{\n key,\n value: typeof value === 'number' ? (Number.isInteger(value) && !doubles.has(key) ? { intValue: value.toString() } : { doubleValue: value })\n : typeof value === 'boolean' ? { boolValue: value } : { stringValue: value },\n }]\n })\n}\n\n/** The root span's measured numbers: one decimal, so each is always a `doubleValue`. */\nconst ROOT_MEASUREMENTS: ReadonlySet<string> = new Set([\n 'tangle.duration_ms',\n 'tangle.turn.wall_ms',\n 'tangle.turn.covered_ms',\n 'tangle.turn.coverage_pct',\n 'tangle.turn.uncovered_ms',\n 'tangle.turn.largest_gap_ms',\n 'tangle.turn.first_visible_ms',\n 'tangle.turn.first_text_ms',\n ...TURN_SPAN_KINDS.map((kind) => `tangle.turn.${kind}_ms`),\n])\n\n/**\n * A Tangle trace id as the 32-hex OTLP trace id. The mapping is the Sandbox SDK's `otelTraceIdForTangleTrace`, so a\n * Sandbox trace export of the same turn lands in the same OTLP trace. An id that is already 32 hex, or a UUID, is used as it is.\n */\nexport function otlpTraceId(traceId: string): string {\n if (/^[0-9a-f]{32}$/.test(traceId)) return traceId\n const dashless = traceId.replace(/-/g, '')\n if (/^[0-9a-f]{32}$/.test(dashless)) return dashless\n return hexId(traceId, 32)\n}\n\nfunction hexId(input: string, length: number): string {\n const hashes = [2166136261, 2654435769, 2246822507, 3266489909]\n for (const byte of new TextEncoder().encode(input)) {\n for (let lane = 0; lane < hashes.length; lane += 1) hashes[lane] = Math.imul((hashes[lane] as number) ^ (byte + lane), 16777619)\n }\n let out = hashes.map((hash) => (hash >>> 0).toString(16).padStart(8, '0')).join('')\n while (out.length < length) out += hexId(`${input}:${out.length}`, 32)\n return out.slice(0, length)\n}\n\nconst msToNs = (ms: number) => (BigInt(Math.floor(ms)) * 1_000_000n).toString()\n\n/** OpenInference span kind per turn span: model calls read as LLM, tool calls as TOOL. */\nconst SPAN_KIND: Partial<Record<string, 'LLM' | 'TOOL'>> = { 'model.call': 'LLM', 'tool.call': 'TOOL' }\n\n/**\n * The root span (`agent_app.turn`) carries the host's labels and the turn's\n * numbers: wall time, the share inside child spans, and the time credited to\n * each kind of span. Children follow under it.\n */\nexport function buildTurnTraceOtelSpans(snapshot: TurnTraceSnapshot, labels: TurnSpanAttrs = {}): OtlpSpan[] {\n const traceId = otlpTraceId(snapshot.traceId)\n const root = snapshot.rootSpanId\n const { summary } = snapshot\n const rootAttrs: Record<string, string | number | boolean> = {\n ...labels,\n 'openinference.span.kind': 'CHAIN',\n 'tangle.execution_id': snapshot.executionId,\n 'tangle.trace_id': snapshot.traceId,\n 'tangle.started_at_ms': snapshot.startedAt,\n 'tangle.completed_at_ms': snapshot.endedAt,\n 'tangle.duration_ms': summary.wallMs,\n 'tangle.turn.wall_ms': summary.wallMs,\n 'tangle.turn.covered_ms': summary.coveredMs,\n 'tangle.turn.coverage_pct': summary.coveragePct,\n 'tangle.turn.uncovered_ms': summary.uncoveredMs,\n 'tangle.turn.largest_gap_ms': summary.largestGapMs,\n 'tangle.turn.spans': summary.spans,\n 'tangle.turn.model_calls': summary.modelCalls,\n 'tangle.turn.tool_calls': summary.toolCalls,\n ...(summary.firstVisibleMs === undefined ? {} : { 'tangle.turn.first_visible_ms': summary.firstVisibleMs }),\n ...(summary.firstTextMs === undefined ? {} : { 'tangle.turn.first_text_ms': summary.firstTextMs }),\n ...(summary.d1Queries === undefined ? {} : { 'tangle.turn.d1_queries': summary.d1Queries }),\n ...(summary.dropped ? { 'tangle.turn.spans_dropped': summary.dropped } : {}),\n ...Object.fromEntries(TURN_SPAN_KINDS.map((kind: TurnSpanKind) => [`tangle.turn.${kind}_ms`, summary.byKind[kind]])),\n }\n const spans: OtlpSpan[] = [{\n traceId,\n spanId: root,\n name: 'agent_app.turn',\n kind: 1,\n startTimeUnixNano: msToNs(snapshot.startedAt),\n endTimeUnixNano: msToNs(snapshot.endedAt),\n attributes: attributes(rootAttrs, ROOT_MEASUREMENTS),\n status: snapshot.status === 'ok' ? { code: 1 } : { code: 2, ...(snapshot.error ? { message: snapshot.error } : {}) },\n }]\n for (const span of snapshot.spans) {\n const attrs: Record<string, string | number | boolean> = {\n ...span.attrs,\n 'openinference.span.kind': SPAN_KIND[span.name] ?? 'CHAIN',\n 'tangle.turn.span_kind': span.kind,\n 'agent.parent.confidence': 'explicit',\n ...(span.name === 'tool.call' ? { 'gen_ai.operation.name': 'execute_tool' } : {}),\n ...(span.unfinished ? { 'tangle.turn.unfinished': true } : {}),\n ...(span.error ? { 'error.message': span.error } : {}),\n }\n spans.push({\n traceId,\n spanId: span.spanId,\n parentSpanId: span.parentSpanId,\n name: span.name,\n kind: 1,\n startTimeUnixNano: msToNs(span.startMs),\n endTimeUnixNano: msToNs(span.endMs),\n attributes: attributes(attrs),\n status: span.error ? { code: 2, message: span.error } : { code: 1 },\n })\n }\n return spans\n}\n\nexport interface IntelligenceTurnTraceSinkOptions {\n /** The Intelligence project the spans belong to, e.g. `legal-agent`. */\n project: string\n /**\n * The tenant key the ingest requires. Omit it: the sink reads the Sandbox product key from the first of\n * `SANDBOX_PRODUCTION_API_KEY`, `TCLOUD_SANDBOX_API_KEY` and `SANDBOX_API_KEY` that is set, the platform key the\n * ingest verifies. Legal's Worker `TANGLE_API_KEY` got 401 on every export (#468), so a key is never assumed: a refusal is a console warning.\n */\n apiKey?: string\n /** Default `https://intelligence.tangle.tools`; spans go to `<base>/v1/otlp/v1/traces`. */\n baseUrl?: string\n /** Called with a short reason when a delivery fails. Never receives span content. Default: a console warning. */\n onError?: (reason: string) => void\n /** Milliseconds one POST may take (default 5000). */\n timeoutMs?: number\n}\n\nconst DEFAULT_INTELLIGENCE_BASE_URL = 'https://intelligence.tangle.tools'\n/** The Sandbox product key names, in the order the apps' sandbox lanes prefer them. Read per delivery: a Worker's env is not populated at module scope. */\nconst INGEST_KEY_ENV = ['SANDBOX_PRODUCTION_API_KEY', 'TCLOUD_SANDBOX_API_KEY', 'SANDBOX_API_KEY'] as const\n\n/** The key the ingest verifies, from the host's environment: what the sink uses when it is given none, and what an app's other Intelligence client should use too. */\nexport function resolveIngestKey(): string | undefined {\n if (typeof process === 'undefined') return undefined\n for (const name of INGEST_KEY_ENV) {\n const value = process.env?.[name]?.trim()\n if (value) return value\n }\n return undefined\n}\nconst SCOPE = { name: '@tangle-network/agent-app', version: 'turn-trace' }\n\n/**\n * The sink a chat route or a Worker turn hands each finished trace to: one OTLP POST per turn, awaited, so a host that\n * runs it under `waitUntil` keeps the isolate alive until delivery. It never throws; every failure, including a missing\n * key and a non-2xx answer, goes to `onError` (a console warning by default), because a silent sink hid Legal's 401s.\n */\nexport function createIntelligenceTurnTraceSink(options: IntelligenceTurnTraceSinkOptions): TurnTraceSink {\n const url = `${(options.baseUrl ?? DEFAULT_INTELLIGENCE_BASE_URL).replace(/\\/+$/, '')}/v1/otlp/v1/traces`\n const report = options.onError ?? ((reason: string) => console.warn(`[turn-trace] export failed: ${reason}`))\n const fail = (reason: string) => { try { report(reason.slice(0, 200)) } catch { /* telemetry only */ } }\n let missingKeyReported = false\n return async (snapshot, labels) => {\n const apiKey = options.apiKey?.trim() || resolveIngestKey()\n if (!apiKey) {\n if (!missingKeyReported) fail(`no ingest key: set ${INGEST_KEY_ENV.join(', ')} or pass apiKey`)\n missingKeyReported = true\n return\n }\n try {\n const body = {\n resourceSpans: [{\n resource: { attributes: attributes({ 'service.name': options.project, 'tangle.project': options.project }) },\n scopeSpans: [{ scope: SCOPE, spans: buildTurnTraceOtelSpans(snapshot, { project: options.project, ...labels }) }],\n }],\n }\n const response = await fetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${apiKey}` },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(options.timeoutMs ?? 5_000),\n })\n const text = await response.text()\n if (!response.ok) return fail(`HTTP ${response.status} from the OTLP ingest`)\n // A 2xx can still refuse part of a batch (`partialSuccess.rejectedSpans`).\n const rejected = Number((JSON.parse(text || '{}') as { partialSuccess?: { rejectedSpans?: unknown } }).partialSuccess?.rejectedSpans ?? 0)\n if (rejected > 0) fail(`the OTLP ingest rejected ${rejected} spans`)\n } catch (error) {\n fail(error instanceof Error ? error.message : 'turn trace export failed')\n }\n }\n}\n","/** One entry of a `Server-Timing` response header. */\nexport interface ServerTimingEntry {\n name: string\n /** Milliseconds, when the entry carries `dur`. */\n durMs?: number\n /** `desc`, unquoted: a count or a label, never a duration. */\n desc?: string\n}\n\n/** Split on commas that sit outside a quoted `desc`. */\nfunction splitEntries(header: string): string[] {\n const out: string[] = []\n let current = ''\n let quoted = false\n for (const char of header) {\n if (char === '\"') quoted = !quoted\n if (char === ',' && !quoted) {\n out.push(current)\n current = ''\n } else {\n current += char\n }\n }\n out.push(current)\n return out\n}\n\n/**\n * Parse a `Server-Timing` header, as the Router and the Sandbox orchestrator\n * send it. A malformed entry is skipped; the result never throws.\n */\nexport function parseServerTiming(header: string | null | undefined): ServerTimingEntry[] {\n if (!header) return []\n const entries: ServerTimingEntry[] = []\n for (const raw of splitEntries(header.slice(0, 4096))) {\n const [name, ...params] = raw.split(';').map((part) => part.trim())\n if (!name || !/^[\\w.!#$%&'*+^`|~-]+$/.test(name)) continue\n const entry: ServerTimingEntry = { name }\n for (const param of params) {\n const eq = param.indexOf('=')\n if (eq < 0) continue\n const key = param.slice(0, eq).trim().toLowerCase()\n const value = param.slice(eq + 1).trim()\n if (key === 'dur') {\n const dur = Number(value)\n if (Number.isFinite(dur) && dur >= 0) entry.durMs = dur\n } else if (key === 'desc') {\n entry.desc = value.replace(/^\"|\"$/g, '').slice(0, 120)\n }\n }\n entries.push(entry)\n }\n return entries\n}\n\n/** Flat span attributes for the entries: `server_timing.<name>_ms` for a duration, `server_timing.<name>` for a `desc`. */\nexport function serverTimingAttrs(entries: readonly ServerTimingEntry[]): Record<string, string | number> {\n const out: Record<string, string | number> = {}\n for (const entry of entries.slice(0, 32)) {\n const key = entry.name.replace(/[^\\w]/g, '_')\n if (entry.durMs !== undefined) out[`server_timing.${key}_ms`] = Math.round(entry.durMs * 10) / 10\n else if (entry.desc !== undefined) out[`server_timing.${key}`] = entry.desc\n }\n return out\n}\n\n/** Format entries as a `Server-Timing` header value, the inverse of {@link parseServerTiming}. Invalid names are skipped. */\nexport function formatServerTiming(entries: readonly ServerTimingEntry[]): string {\n return entries\n .filter((entry) => /^[\\w.!#$%&'*+^`|~-]+$/.test(entry.name))\n .slice(0, 32)\n .map((entry) => [\n entry.name,\n ...(entry.durMs === undefined ? [] : [`dur=${Math.round(entry.durMs * 10) / 10}`]),\n ...(entry.desc === undefined ? [] : [`desc=\"${entry.desc.replace(/[\"\\\\]/g, '').slice(0, 120)}\"`]),\n ].join(';'))\n .join(', ')\n}\n","import type { TurnSpan, TurnTrace } from './recorder'\nimport { otlpTraceId } from './otel'\nimport { parseServerTiming, serverTimingAttrs } from './server-timing'\n\nconst counters = new WeakMap<TurnTrace, Map<string, number>>()\n\n/** 1-based count of `name` spans started through {@link nextCallIndex} on this trace. */\nexport function nextCallIndex(trace: TurnTrace, name: string): number {\n const byName = counters.get(trace) ?? new Map<string, number>()\n counters.set(trace, byName)\n const next = (byName.get(name) ?? 0) + 1\n byName.set(name, next)\n return next\n}\n\n/**\n * The Router's own steps before its provider fetch, as children of `router.pre_upstream` (`origin` is the Router's\n * handler start on this clock, `end` its `upstream_start`). `t_authed` and `t_admitted` are offsets from the handler\n * start: `router.auth` runs to the first, `router.admission` (budgets, credits, routing) to the second, and\n * `router.dispatch` (body, pricing, the dispatch row, the spend hold) to the provider fetch. `dispatch_row` and\n * `spend_authorize` are durations that run back to back and end just before the fetch, so they are placed backwards\n * from `end`. A step the header does not carry is left out, and nothing is placed outside `[origin, end]`.\n */\nfunction recordRouterSteps(parent: TurnSpan, origin: number, end: number, stamp: (name: string) => number | undefined): void {\n const offset = (name: string) => {\n const ms = stamp(name)\n return ms === undefined ? undefined : Math.min(end, origin + ms)\n }\n let at = origin\n for (const [step, name] of [['t_authed', 'router.auth'], ['t_admitted', 'router.admission']] as const) {\n const until = offset(step)\n if (until === undefined || until <= at) continue\n parent.record(name, 'router', at, until)\n at = until\n }\n if (end <= at) return\n const dispatch = parent.record('router.dispatch', 'router', at, end)\n let stepEnd = end\n for (const step of ['spend_authorize', 'dispatch_row']) {\n const ms = stamp(step)\n if (ms === undefined) continue\n const start = Math.max(at, stepEnd - ms)\n dispatch.record(`router.${step}`, 'router', start, stepEnd)\n stepEnd = start\n }\n}\n\nexport interface TracedModelFetchOptions {\n /** The span a model call hangs from. Default: the trace's root. */\n parent?: TurnSpan\n /** The model the request asks for. */\n model?: string\n /** Receives each model call's span as it starts, so the engine can add the token counts when usage arrives. */\n onSpan?: (span: TurnSpan) => void\n}\n\n/**\n * `fetch` for a model request, recording one `model.call` span per send: the\n * wall time from the request to the end of its body, the time to the first\n * byte, and the Router's own `Server-Timing` so the wait before the first byte\n * splits into network and server time.\n *\n * Children partition the call:\n * - `network`: the wait for headers, less the Router's server time;\n * - `router.pre_upstream`: the Router's work before its provider fetch\n * (`upstream_start`), split by its own steps (see {@link recordRouterSteps});\n * - `router.upstream_wait`: the provider's time to response headers\n * (`upstream_headers`);\n * - `model.stream`: headers to the end of the body.\n * Without a `Server-Timing` header the first byte's wait is one `model.wait`\n * span, because the split is not known.\n *\n * The response body is passed through unchanged; the span ends when the body\n * ends, errors or is cancelled.\n */\nexport function tracedModelFetch(trace: TurnTrace, inner: typeof fetch, options: TracedModelFetchOptions = {}): typeof fetch {\n return async (input, init) => {\n const sentAt = Date.now()\n const span = trace.start('model.call', 'model', {\n 'gen_ai.operation.name': 'chat',\n 'call.index': nextCallIndex(trace, 'model.call'),\n ...(options.model ? { 'gen_ai.request.model': options.model } : {}),\n }, options.parent)\n options.onSpan?.(span)\n let response: Response\n try {\n // Fetch replaces Request headers when init.headers is supplied. Preserve\n // that precedence while parenting Router's spans to this exact send.\n const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined))\n headers.set('traceparent', `00-${otlpTraceId(trace.traceId)}-${span.id}-01`)\n response = await inner(input, { ...init, headers })\n } catch (error) {\n span.end({ 'http.failed': true }, error)\n throw error\n }\n const headersAt = Date.now()\n const timing = parseServerTiming(response.headers.get('server-timing'))\n // The last entry: a fallback chain repeats a step, and the response is the last provider's.\n const stamp = (name: string) => {\n for (let i = timing.length - 1; i >= 0; i--) if (timing[i]!.name === name && timing[i]!.durMs !== undefined) return timing[i]!.durMs\n return undefined\n }\n const preUpstreamMs = stamp('upstream_start')\n const upstreamWaitMs = stamp('upstream_headers')\n const waitMs = headersAt - sentAt\n span.set({ 'http.status_code': response.status, ttfb_ms: waitMs, ...serverTimingAttrs(timing) })\n\n let firstByteAt: number | undefined\n const finish = (endedAt: number, error?: unknown, cancelled?: boolean) => {\n const known = preUpstreamMs !== undefined || upstreamWaitMs !== undefined\n if (known) {\n const serverMs = Math.min(waitMs, (preUpstreamMs ?? 0) + (upstreamWaitMs ?? 0))\n const networkMs = waitMs - serverMs\n let at = sentAt\n span.record('network', 'network', at, at + networkMs, { 'network.ms': Math.round(networkMs) })\n at += networkMs\n if (preUpstreamMs !== undefined) {\n const end = Math.min(headersAt, at + preUpstreamMs)\n recordRouterSteps(span.record('router.pre_upstream', 'router', at, end), at, end, stamp)\n at = end\n }\n if (upstreamWaitMs !== undefined) span.record('router.upstream_wait', 'model', at, headersAt)\n span.set({ network_ms: Math.round(networkMs), router_server_ms: Math.round(serverMs) })\n } else {\n span.record('model.wait', 'model', sentAt, headersAt, { split: 'unknown' })\n }\n span.record('model.stream', 'model', headersAt, Math.max(headersAt, endedAt))\n const failure = error ?? (response.status >= 400 ? `http_${response.status}` : undefined)\n span.end({\n ...(firstByteAt !== undefined ? { ttft_ms: firstByteAt - sentAt } : {}),\n ...(cancelled ? { cancelled: true } : {}),\n }, failure)\n }\n\n if (!response.body) {\n finish(headersAt)\n return response\n }\n const reader = response.body.getReader()\n let settled = false\n const settle = (error?: unknown, cancelled?: boolean) => {\n if (settled) return\n settled = true\n finish(Date.now(), error, cancelled)\n }\n const body = new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const { done, value } = await reader.read()\n if (done) {\n settle()\n controller.close()\n return\n }\n firstByteAt ??= Date.now()\n controller.enqueue(value)\n } catch (error) {\n settle(error)\n controller.error(error)\n }\n },\n async cancel(reason) {\n settle(undefined, true)\n await reader.cancel(reason)\n },\n })\n return new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers })\n }\n}\n"],"mappings":";AAoBO,SAAS,gBAAgB,OAAkB,SAChD,KAAmB,SAAyD;AAC5E,QAAM,YAAY,QAAQ,aAAa,MAAM;AAC7C,MAAI,OAAO,WAAW,QAAQ,WAAW,YAAY,SAAS,WAAW;AACzE,MAAI;AACJ,QAAM,SAAiC,CAAC,GAAG,aAAqC,CAAC,GAAG,UAAkC,CAAC;AACvH,QAAM,OAAO,CAAC,SAAiB,QAAQ,QAAQ,IAAI,KAAK;AACxD,QAAM,QAAQ,CAAC,SAAiB,GAAG,QAAQ,MAAM,IAAI,IAAI;AACzD,SAAO;AAAA,IACL;AAAA,IACA,KAAK,MAAM;AACT,YAAM,KAAK,IAAI;AACf,aAAO,IAAI,KAAK,OAAO,IAAI,KAAK,KAAK,KAAK;AAC1C,UAAI,SAAS;AACX,gBAAQ,IAAI,KAAK,QAAQ,IAAI,KAAK,KAAK,QAAQ,UAAU;AACzD,oBAAY,QAAQ;AAAA,MACtB;AACA,YAAM,OAAO,MAAM,IAAI,GAAG,KAAK,IAAI,GAAG,SAAS,KAAK,IAAI,MAAM,KAAK,IAAI,MAAM,IAAI,CAAC,GAAG,MAAM;AAC3F,aAAO;AAAA,IACT;AAAA,IACA,MAAM,MAAM,MAAM,SAAS;AACzB,YAAM,QAAQ,IAAI,GAAG,OAAO,MAAM,MAAM,MAAM,IAAI,GAAG,KAAK,IAAI,CAAC;AAC/D,WAAK,KAAK;AAAA,QAAK,WAAS;AAA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AA,EACnH;AACF;","names":[]}
@@ -480,4 +480,4 @@ export {
480
480
  TOOL_ABORTED_ERROR,
481
481
  observeNativeCompletion
482
482
  };
483
- //# sourceMappingURL=chunk-4GINUJPF.js.map
483
+ //# sourceMappingURL=chunk-WRCMVBUJ.js.map