@tangle-network/agent-app 0.61.4 → 0.62.1
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.
- package/dist/{DesignCanvas-L6J72JQ2.js → DesignCanvas-IQKYAEC4.js} +3 -2
- package/dist/{DesignCanvasEditor-QFQD63MR.js → DesignCanvasEditor-O7OCZTGC.js} +5 -4
- package/dist/{TimelineEditor-7KBPJQLT.js → TimelineEditor-VB2UJ34D.js} +4 -2
- package/dist/VaultPane-AYW7CO33.js +8 -0
- package/dist/agent-profiles/d1.js +1 -1
- package/dist/agent-profiles/index.d.ts +0 -82
- package/dist/agent-profiles/index.js +1 -21
- package/dist/agent-profiles/self-management.d.ts +0 -55
- package/dist/alerting/index.d.ts +1 -1
- package/dist/alerting/index.js +1 -3
- package/dist/alerting/slack.d.ts +6 -79
- package/dist/app-auth/drizzle.d.ts +17 -271
- package/dist/app-auth/drizzle.js +6 -2
- package/dist/app-auth/drizzle.js.map +1 -1
- package/dist/app-auth/index.js +3 -3
- package/dist/assets/types.d.ts +2 -1
- package/dist/assistant/AssistantPanel.d.ts +1 -1
- package/dist/assistant/index.js +635 -392
- package/dist/assistant/index.js.map +1 -1
- package/dist/billing/identity-locks.d.ts +5 -0
- package/dist/billing/index.js +1 -1
- package/dist/brand-extraction/index.js.map +1 -1
- package/dist/brand-extraction/types.d.ts +2 -1
- package/dist/chat-react/index.js +6 -5
- package/dist/chat-routes/attachment-write-safety.d.ts +4 -0
- package/dist/chat-routes/draft-persistence.d.ts +2 -14
- package/dist/chat-routes/index.d.ts +1 -0
- package/dist/chat-routes/index.js +853 -773
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/chat-routes/sandbox-model-source.d.ts +20 -0
- package/dist/chat-routes/stored-attachments.d.ts +18 -0
- package/dist/chat-routes/turn-admission.d.ts +1 -1
- package/dist/chat-routes/turn-execution.d.ts +2 -2
- package/dist/chat-routes/turn-route-contracts.d.ts +3 -29
- package/dist/chat-store/core.d.ts +19 -1
- package/dist/chat-store/index.js.map +1 -1
- package/dist/chat-store/store.d.ts +3 -29
- package/dist/{chunk-ATQQCG4I.js → chunk-2VJLLRVV.js} +2 -2
- package/dist/{chunk-4LBCTFBP.js → chunk-4MD5PS4F.js} +5 -1
- package/dist/{chunk-4LBCTFBP.js.map → chunk-4MD5PS4F.js.map} +1 -1
- package/dist/{chunk-R4X5474U.js → chunk-52SDU43B.js} +12 -27
- package/dist/chunk-52SDU43B.js.map +1 -0
- package/dist/{chunk-MDRH3SDA.js → chunk-54YIL7WM.js} +3 -3
- package/dist/{chunk-6QJ3GB3A.js → chunk-5GSZGTPJ.js} +2 -2
- package/dist/{chunk-5IM2CLYX.js → chunk-6JEDSKFH.js} +232 -218
- package/dist/chunk-6JEDSKFH.js.map +1 -0
- package/dist/{chunk-6PRQ45QE.js → chunk-6OG4244Y.js} +1 -1
- package/dist/chunk-6OG4244Y.js.map +1 -0
- package/dist/{chunk-ZDPUC6CM.js → chunk-6ZVSMA4T.js} +3 -3
- package/dist/{chunk-TXUAGSFR.js → chunk-76MPX7JQ.js} +47 -1
- package/dist/chunk-76MPX7JQ.js.map +1 -0
- package/dist/{chunk-BOQ4HVVH.js → chunk-7ISHKBAD.js} +61 -52
- package/dist/chunk-7ISHKBAD.js.map +1 -0
- package/dist/chunk-7PULOECS.js +22 -0
- package/dist/chunk-7PULOECS.js.map +1 -0
- package/dist/{chunk-KJODHPWM.js → chunk-CPVGRQ43.js} +511 -339
- package/dist/chunk-CPVGRQ43.js.map +1 -0
- package/dist/{chunk-LO6VQ35O.js → chunk-CQZVJVME.js} +2 -2
- package/dist/{chunk-Y43PXON2.js → chunk-EFQUAWWF.js} +577 -546
- package/dist/chunk-EFQUAWWF.js.map +1 -0
- package/dist/{chunk-FPNZMIAW.js → chunk-ELX5YITO.js} +1 -1
- package/dist/chunk-ELX5YITO.js.map +1 -0
- package/dist/chunk-FGAROAUF.js +19 -0
- package/dist/chunk-FGAROAUF.js.map +1 -0
- package/dist/{chunk-HN6MZ2XL.js → chunk-FTNGGR37.js} +641 -466
- package/dist/chunk-FTNGGR37.js.map +1 -0
- package/dist/{chunk-G4F2NWZH.js → chunk-FZ3ZFVAC.js} +4 -4
- package/dist/{chunk-UCCSJX64.js → chunk-GIEUZBQQ.js} +1112 -644
- package/dist/chunk-GIEUZBQQ.js.map +1 -0
- package/dist/{chunk-MEKOWH5E.js → chunk-IVBREL7A.js} +785 -526
- package/dist/chunk-IVBREL7A.js.map +1 -0
- package/dist/{chunk-WSEXFTN4.js → chunk-JBXNU5WD.js} +26 -26
- package/dist/chunk-JBXNU5WD.js.map +1 -0
- package/dist/{chunk-F2VX6TTJ.js → chunk-JRCZHDRG.js} +2 -41
- package/dist/chunk-JRCZHDRG.js.map +1 -0
- package/dist/{chunk-LXYQOOXU.js → chunk-JRW6LCIA.js} +552 -302
- package/dist/chunk-JRW6LCIA.js.map +1 -0
- package/dist/{chunk-TVPH5T4F.js → chunk-KS4I7KVC.js} +16 -22
- package/dist/{chunk-TVPH5T4F.js.map → chunk-KS4I7KVC.js.map} +1 -1
- package/dist/{chunk-J2BBYVGF.js → chunk-MRZP65DZ.js} +1 -117
- package/dist/chunk-MRZP65DZ.js.map +1 -0
- package/dist/{chunk-L7LQRJGD.js → chunk-MVKMDROU.js} +48 -48
- package/dist/{chunk-L7LQRJGD.js.map → chunk-MVKMDROU.js.map} +1 -1
- package/dist/{chunk-4ZSLX3LY.js → chunk-OODZCBSM.js} +1 -1
- package/dist/chunk-OODZCBSM.js.map +1 -0
- package/dist/chunk-P4RRC4AO.js +47 -0
- package/dist/chunk-P4RRC4AO.js.map +1 -0
- package/dist/{chunk-ORQD4AUO.js → chunk-PCAY23GS.js} +1 -6
- package/dist/chunk-PCAY23GS.js.map +1 -0
- package/dist/{chunk-NMZUW6VJ.js → chunk-PEJ5OP5B.js} +3 -3
- package/dist/chunk-PEJ5OP5B.js.map +1 -0
- package/dist/{chunk-NHYRIM4I.js → chunk-PIPNDZ6H.js} +304 -194
- package/dist/chunk-PIPNDZ6H.js.map +1 -0
- package/dist/chunk-UHSUY6H6.js +79 -0
- package/dist/chunk-UHSUY6H6.js.map +1 -0
- package/dist/{chunk-PDD5A43Y.js → chunk-UTL6TEN6.js} +3 -3
- package/dist/{chunk-VJBFCNAU.js → chunk-UW2DKTEM.js} +123 -130
- package/dist/chunk-UW2DKTEM.js.map +1 -0
- package/dist/{chunk-S27DKRI6.js → chunk-VDYEVCQQ.js} +2 -2
- package/dist/{chunk-UFQM46NV.js → chunk-VK3F4N4U.js} +2 -2
- package/dist/{chunk-6ZIC6OG5.js → chunk-VYBTQK25.js} +126 -122
- package/dist/chunk-VYBTQK25.js.map +1 -0
- package/dist/{chunk-RL3Z747H.js → chunk-W2BV2XOC.js} +1491 -700
- package/dist/chunk-W2BV2XOC.js.map +1 -0
- package/dist/{chunk-FUZETA6Z.js → chunk-X6SZGQTK.js} +2 -2
- package/dist/{chunk-CD2LQXY6.js → chunk-XOHE6SKU.js} +14 -16
- package/dist/{chunk-CD2LQXY6.js.map → chunk-XOHE6SKU.js.map} +1 -1
- package/dist/{chunk-ZBB5KQ6B.js → chunk-Y3GO6SG3.js} +73 -66
- package/dist/chunk-Y3GO6SG3.js.map +1 -0
- package/dist/chunk-ZAMHLXNS.js +56 -0
- package/dist/chunk-ZAMHLXNS.js.map +1 -0
- package/dist/{chunk-RHFN7TUV.js → chunk-ZDHCV462.js} +47 -44
- package/dist/{chunk-RHFN7TUV.js.map → chunk-ZDHCV462.js.map} +1 -1
- package/dist/chunk-ZOS3D26Z.js +72 -0
- package/dist/chunk-ZOS3D26Z.js.map +1 -0
- package/dist/design-canvas/index.js +32 -32
- package/dist/design-canvas/index.js.map +1 -1
- package/dist/design-canvas-react/components/DesignCanvas.d.ts +1 -1
- package/dist/design-canvas-react/components/Workspace.d.ts +1 -1
- package/dist/design-canvas-react/components/glyphs.d.ts +31 -40
- package/dist/design-canvas-react/components/transform-math.d.ts +0 -8
- package/dist/design-canvas-react/components/use-workspace-keyboard.d.ts +2 -2
- package/dist/design-canvas-react/contracts.d.ts +2 -2
- package/dist/design-canvas-react/engine.js +1 -1
- package/dist/design-canvas-react/index.js +9 -7
- package/dist/design-canvas-react/index.js.map +1 -1
- package/dist/design-canvas-react/lazy.js +1 -1
- package/dist/eval/calibration.d.ts +1 -38
- package/dist/eval/index.d.ts +2 -4
- package/dist/eval/index.js +0 -84
- package/dist/eval/index.js.map +1 -1
- package/dist/harness/index.d.ts +1 -1
- package/dist/harness/index.js +1 -1
- package/dist/harness/session-selection.d.ts +2 -2
- package/dist/hub-approvals/index.js +1 -1
- package/dist/hub-approvals/result.d.ts +1 -1
- package/dist/hub-approvals-react/index.js +4 -4
- package/dist/hub-approvals-react/index.js.map +1 -1
- package/dist/hub-approvals-react/parts.d.ts +1 -1
- package/dist/launch-invariants/cli.js +4 -4
- package/dist/launch-invariants/index.js +3 -3
- package/dist/launch-invariants/testing.js +4 -4
- package/dist/legibility/cli.js +1 -1
- package/dist/legibility/index.js +1 -1
- package/dist/{mention-editor-B23OMFT2.js → mention-editor-4BKBMWIK.js} +83 -57
- package/dist/mention-editor-4BKBMWIK.js.map +1 -0
- package/dist/missions/index.js +144 -137
- package/dist/missions/index.js.map +1 -1
- package/dist/operator/index.js +1 -1
- package/dist/peer-floors/check.js +1 -1
- package/dist/peer-floors/cli.js +6 -14
- package/dist/peer-floors/cli.js.map +1 -1
- package/dist/peer-floors/source-entries.d.ts +6 -0
- package/dist/platform/index.js +10 -10
- package/dist/preset-cloudflare/index.js +2 -2
- package/dist/profile/index.d.ts +0 -1
- package/dist/profile/index.js +1 -422
- package/dist/profile/index.js.map +1 -1
- package/dist/profile-editor/server.d.ts +0 -1
- package/dist/profile-editor/server.js +0 -1
- package/dist/profile-editor/server.js.map +1 -1
- package/dist/public-consultation/index.d.ts +2 -2
- package/dist/public-consultation/index.js +6 -6
- package/dist/record/drizzle.js +156 -148
- package/dist/record/drizzle.js.map +1 -1
- package/dist/runtime/index.js +4 -4
- package/dist/runtime/router-turn.js +3 -3
- package/dist/sandbox/index.js +8 -6
- package/dist/sandbox/transient-failure.d.ts +2 -0
- package/dist/sequences/drizzle.js +5 -15
- package/dist/sequences/drizzle.js.map +1 -1
- package/dist/sequences/index.d.ts +1 -0
- package/dist/sequences/index.js +18 -14
- package/dist/sequences/index.js.map +1 -1
- package/dist/sequences/row-mapping.d.ts +7 -0
- package/dist/sequences-react/components/TimelineEditor.d.ts +0 -40
- package/dist/sequences-react/components/TimelineHistory.d.ts +31 -0
- package/dist/sequences-react/components/glyphs.d.ts +12 -21
- package/dist/sequences-react/components/index.d.ts +0 -2
- package/dist/sequences-react/components/interaction-math.d.ts +3 -3
- package/dist/sequences-react/contracts.d.ts +1 -1
- package/dist/sequences-react/engine/snap.d.ts +2 -2
- package/dist/sequences-react/index.js +4 -4
- package/dist/sequences-react/index.js.map +1 -1
- package/dist/settings-react/index.js +13 -30
- package/dist/settings-react/index.js.map +1 -1
- package/dist/settings-react/timezone-picker.d.ts +0 -6
- package/dist/signoff/browser-budget.d.ts +6 -1
- package/dist/signoff/cli.d.ts +0 -7
- package/dist/signoff/cli.js +1 -2
- package/dist/signoff/cli.js.map +1 -1
- package/dist/signoff/index.js +1 -1
- package/dist/skills/index.d.ts +1 -1
- package/dist/skills/index.js +5 -25
- package/dist/skills/marketplace.d.ts +1 -75
- package/dist/skills-placement/box.js +3 -4
- package/dist/skills-placement/box.js.map +1 -1
- package/dist/skills-placement/index.js +3 -4
- package/dist/spend/cli-args.d.ts +1 -1
- package/dist/spend/cli.js +3 -3
- package/dist/spend/cli.js.map +1 -1
- package/dist/spend/index.js +1 -1
- package/dist/stories/design-canvas/fixtures.d.ts +1 -14
- package/dist/stream/index.js +17 -17
- package/dist/studio/generation.d.ts +1 -1
- package/dist/studio/index.js +1 -1
- package/dist/studio-react/index.js +353 -184
- package/dist/studio-react/index.js.map +1 -1
- package/dist/studio-react/studio-composer.d.ts +1 -5
- package/dist/studio-react/studio-history-screen.d.ts +1 -1
- package/dist/teams/invitations-api.d.ts +3 -3
- package/dist/teams/invitations-api.js +74 -72
- package/dist/teams/invitations-api.js.map +1 -1
- package/dist/teams/member-sync.d.ts +2 -0
- package/dist/teams/members-api.d.ts +2 -2
- package/dist/teams/members-api.js +1 -1
- package/dist/teams-react/index.js +28 -45
- package/dist/teams-react/index.js.map +1 -1
- package/dist/tools/index.js +1 -1
- package/dist/tools/mcp-arguments.d.ts +1 -1
- package/dist/trace/index.d.ts +1 -18
- package/dist/trace/index.js +1 -36
- package/dist/trace/index.js.map +1 -1
- package/dist/trace/mission-flow.d.ts +1 -59
- package/dist/turn-health/index.d.ts +1 -1
- package/dist/turn-health/index.js +2 -2
- package/dist/turn-health/sink.d.ts +2 -1
- package/dist/turn-trace/index.js +2 -4
- package/dist/turn-trace/recorder.d.ts +0 -2
- package/dist/vault/VaultPane.d.ts +0 -20
- package/dist/vault/VaultPaneOperations.d.ts +318 -0
- package/dist/vault/index.js +2 -1
- package/dist/vault/index.js.map +1 -1
- package/dist/vault/lazy.js +1 -1
- package/dist/web-react/agent-profile-editor.d.ts +1 -2
- package/dist/web-react/agent-profile-editor.js +6 -5
- package/dist/web-react/chat-composer.d.ts +1 -1
- package/dist/web-react/durable-plan-flow.d.ts +6 -1
- package/dist/web-react/editor-glyphs.d.ts +12 -0
- package/dist/web-react/focus-navigation.d.ts +12 -0
- package/dist/web-react/history-controls.d.ts +37 -0
- package/dist/web-react/index.js +36 -34
- package/dist/web-react/interaction-question-card.d.ts +1 -1
- package/dist/web-react/record-grid-writes.d.ts +31 -0
- package/dist/web-react/record-grid.d.ts +1 -48
- package/dist/web-react/session-history-panel.d.ts +1 -9
- package/dist/web-react/use-document-dark.d.ts +1 -0
- package/dist/workspace-export/engine.d.ts +1 -6
- package/dist/workspace-export/index.js +198 -185
- package/dist/workspace-export/index.js.map +1 -1
- package/dist/workspace-export/routes.d.ts +1 -1
- package/dist/workspace-react/index.js +9 -8
- package/dist/workspace-react/index.js.map +1 -1
- package/package.json +1 -11
- package/dist/VaultPane-RXL3WLA2.js +0 -7
- package/dist/agent-profiles/reaper.d.ts +0 -31
- package/dist/agent-profiles/reaper.js +0 -29
- package/dist/agent-profiles/reaper.js.map +0 -1
- package/dist/chunk-4ZSLX3LY.js.map +0 -1
- package/dist/chunk-5IM2CLYX.js.map +0 -1
- package/dist/chunk-6OSJNJA2.js +0 -251
- package/dist/chunk-6OSJNJA2.js.map +0 -1
- package/dist/chunk-6PRQ45QE.js.map +0 -1
- package/dist/chunk-6ZIC6OG5.js.map +0 -1
- package/dist/chunk-BDEBQ4WO.js +0 -38
- package/dist/chunk-BDEBQ4WO.js.map +0 -1
- package/dist/chunk-BOQ4HVVH.js.map +0 -1
- package/dist/chunk-F2VX6TTJ.js.map +0 -1
- package/dist/chunk-FPNZMIAW.js.map +0 -1
- package/dist/chunk-HN6MZ2XL.js.map +0 -1
- package/dist/chunk-J2BBYVGF.js.map +0 -1
- package/dist/chunk-KJODHPWM.js.map +0 -1
- package/dist/chunk-LTWJYNEC.js +0 -100
- package/dist/chunk-LTWJYNEC.js.map +0 -1
- package/dist/chunk-LXYQOOXU.js.map +0 -1
- package/dist/chunk-MEKOWH5E.js.map +0 -1
- package/dist/chunk-NHYRIM4I.js.map +0 -1
- package/dist/chunk-NMZUW6VJ.js.map +0 -1
- package/dist/chunk-ORQD4AUO.js.map +0 -1
- package/dist/chunk-R4X5474U.js.map +0 -1
- package/dist/chunk-RL3Z747H.js.map +0 -1
- package/dist/chunk-TXUAGSFR.js.map +0 -1
- package/dist/chunk-UCCSJX64.js.map +0 -1
- package/dist/chunk-VJBFCNAU.js.map +0 -1
- package/dist/chunk-WSEXFTN4.js.map +0 -1
- package/dist/chunk-Y43PXON2.js.map +0 -1
- package/dist/chunk-ZBB5KQ6B.js.map +0 -1
- package/dist/eval/parity.d.ts +0 -74
- package/dist/mention-editor-B23OMFT2.js.map +0 -1
- package/dist/profile/humanizer-skill.d.ts +0 -23
- package/dist/profile/humanizer-skill.vendored.d.ts +0 -4
- package/dist/sequences-react/components/BrandMark.d.ts +0 -10
- package/dist/skills/marketplace-drizzle.d.ts +0 -121
- package/dist/skills/marketplace-drizzle.js +0 -34
- package/dist/skills/marketplace-drizzle.js.map +0 -1
- package/dist/teams-react/components/BrandMark.d.ts +0 -10
- /package/dist/{DesignCanvas-L6J72JQ2.js.map → DesignCanvas-IQKYAEC4.js.map} +0 -0
- /package/dist/{DesignCanvasEditor-QFQD63MR.js.map → DesignCanvasEditor-O7OCZTGC.js.map} +0 -0
- /package/dist/{TimelineEditor-7KBPJQLT.js.map → TimelineEditor-VB2UJ34D.js.map} +0 -0
- /package/dist/{VaultPane-RXL3WLA2.js.map → VaultPane-AYW7CO33.js.map} +0 -0
- /package/dist/{chunk-ATQQCG4I.js.map → chunk-2VJLLRVV.js.map} +0 -0
- /package/dist/{chunk-MDRH3SDA.js.map → chunk-54YIL7WM.js.map} +0 -0
- /package/dist/{chunk-6QJ3GB3A.js.map → chunk-5GSZGTPJ.js.map} +0 -0
- /package/dist/{chunk-ZDPUC6CM.js.map → chunk-6ZVSMA4T.js.map} +0 -0
- /package/dist/{chunk-LO6VQ35O.js.map → chunk-CQZVJVME.js.map} +0 -0
- /package/dist/{chunk-G4F2NWZH.js.map → chunk-FZ3ZFVAC.js.map} +0 -0
- /package/dist/{chunk-PDD5A43Y.js.map → chunk-UTL6TEN6.js.map} +0 -0
- /package/dist/{chunk-S27DKRI6.js.map → chunk-VDYEVCQQ.js.map} +0 -0
- /package/dist/{chunk-UFQM46NV.js.map → chunk-VK3F4N4U.js.map} +0 -0
- /package/dist/{chunk-FUZETA6Z.js.map → chunk-X6SZGQTK.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\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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,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 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\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,EA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AAA,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,3 +1,6 @@
|
|
|
1
|
+
import {
|
|
2
|
+
bindSearchPickerNavigation
|
|
3
|
+
} from "./chunk-ZAMHLXNS.js";
|
|
1
4
|
import {
|
|
2
5
|
ProviderLogo
|
|
3
6
|
} from "./chunk-RASGKEAL.js";
|
|
@@ -372,32 +375,14 @@ function ModelPicker({
|
|
|
372
375
|
useEffect3(() => {
|
|
373
376
|
const panel = panelRef.current;
|
|
374
377
|
if (!expanded || !panel) return;
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
if (event.shiftKey && index === 0 || !event.shiftKey && index === controls.length - 1) {
|
|
384
|
-
changeOpen(false);
|
|
385
|
-
triggerRef.current?.focus();
|
|
386
|
-
if (event.shiftKey) event.preventDefault();
|
|
387
|
-
}
|
|
388
|
-
return;
|
|
389
|
-
}
|
|
390
|
-
let next;
|
|
391
|
-
if (event.key === "ArrowDown") next = (index + 1) % controls.length;
|
|
392
|
-
else if (event.key === "ArrowUp") next = (index - 1 + controls.length) % controls.length;
|
|
393
|
-
else if (event.key === "Home" && index > 0) next = 1;
|
|
394
|
-
else if (event.key === "End" && index > 0) next = controls.length - 1;
|
|
395
|
-
else return;
|
|
396
|
-
event.preventDefault();
|
|
397
|
-
controls[next]?.focus();
|
|
398
|
-
}
|
|
399
|
-
panel.addEventListener("keydown", onKeyDown);
|
|
400
|
-
return () => panel.removeEventListener("keydown", onKeyDown);
|
|
378
|
+
return bindSearchPickerNavigation({
|
|
379
|
+
panel,
|
|
380
|
+
input: () => inputRef.current,
|
|
381
|
+
trigger: () => triggerRef.current,
|
|
382
|
+
onClose: () => changeOpen(false),
|
|
383
|
+
buttonSelector: "button:not(:disabled)",
|
|
384
|
+
homeEnd: true
|
|
385
|
+
});
|
|
401
386
|
}, [expanded, changeOpen, panelRef, triggerRef]);
|
|
402
387
|
const selected = sortedModels.find((m) => m.id === value);
|
|
403
388
|
const selectedLabel = selected?.name ?? value;
|
|
@@ -739,4 +724,4 @@ export {
|
|
|
739
724
|
EffortMeter,
|
|
740
725
|
EffortPicker
|
|
741
726
|
};
|
|
742
|
-
//# sourceMappingURL=chunk-
|
|
727
|
+
//# sourceMappingURL=chunk-52SDU43B.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/web-react/popover-surface.tsx","../src/web-react/picker-presentation.ts","../src/web-react/use-pending.ts","../src/web-react/model-picker.tsx","../src/web-react/control-glyphs.tsx","../src/web-react/effort-picker.tsx"],"sourcesContent":["/** Portaled popover placement, nested focus, and outside-click ownership. */\nimport { useCallback, useEffect, useId, useLayoutEffect, useRef, useState, type CSSProperties, type ReactNode, type RefObject } from 'react'\nimport { createPortal } from 'react-dom'\n\n/**\n * Keyboard + pointer model for a trigger-and-popover pair, dependency-free.\n * Outside-mousedown and Escape both close; Escape also returns focus to the\n * trigger so keyboard users aren't dropped at the top of the document. The\n * returned `triggerProps` carry the ARIA contract (`aria-haspopup`/\n * `aria-expanded`); spread them onto the trigger button.\n *\n * `panelRef` belongs to the popover panel and MUST be wired when the panel is\n * rendered through {@link PopoverSurface}: a portaled panel is not inside\n * `containerRef`, so a container-only outside test reads every click on the\n * menu's own rows as an outside click and closes before the row's handler runs.\n */\nexport function usePopover(open: boolean, setOpen: (open: boolean) => void) {\n const containerRef = useRef<HTMLDivElement>(null)\n const triggerRef = useRef<HTMLButtonElement>(null)\n const panelRef = useRef<HTMLDivElement>(null)\n\n useEffect(() => {\n if (!open) return\n function onMouseDown(e: MouseEvent) {\n const target = e.target as Node\n if (containerRef.current?.contains(target)) return\n const panel = panelRef.current\n if (panel?.contains(target)) return\n // A popover opened FROM this one portals as a SIBLING at body level, so\n // `contains` cannot see it and a click on its rows would read as outside.\n // Surfaces stamp their ancestor chain, so descendancy survives the portal.\n const ownPath = panel?.getAttribute(POPOVER_SURFACE_ATTR)\n const hitPath =\n target instanceof Element\n ? target.closest(`[${POPOVER_SURFACE_ATTR}]`)?.getAttribute(POPOVER_SURFACE_ATTR)\n : null\n if (ownPath && hitPath && (hitPath === ownPath || hitPath.startsWith(`${ownPath}${POPOVER_PATH_SEPARATOR}`))) return\n setOpen(false)\n }\n function onKeyDown(e: KeyboardEvent) {\n if (e.key === 'Escape' && !e.defaultPrevented) {\n const ownPath = panelRef.current?.getAttribute(POPOVER_SURFACE_ATTR)\n const focusedPath = document.activeElement?.closest(`[${POPOVER_SURFACE_ATTR}]`)?.getAttribute(POPOVER_SURFACE_ATTR)\n if (ownPath && focusedPath?.startsWith(`${ownPath}${POPOVER_PATH_SEPARATOR}`)) return\n e.preventDefault()\n setOpen(false)\n triggerRef.current?.focus()\n }\n }\n document.addEventListener('mousedown', onMouseDown)\n document.addEventListener('keydown', onKeyDown)\n return () => {\n document.removeEventListener('mousedown', onMouseDown)\n document.removeEventListener('keydown', onKeyDown)\n }\n }, [open, setOpen])\n\n return {\n containerRef,\n triggerRef,\n panelRef,\n triggerProps: {\n ref: triggerRef,\n 'aria-haspopup': true as const,\n 'aria-expanded': open,\n },\n }\n}\n\n// ── PopoverSurface ────────────────────────────────────────────────────────\n\n/** Distance between the trigger and the panel it opens. */\nconst POPOVER_GAP = 8\n/** Minimum distance the panel keeps from every viewport edge. */\nconst POPOVER_VIEWPORT_MARGIN = 16\n/** Floor for the computed max-height, so a cramped side still shows rows\n * rather than collapsing to a sliver the user cannot read. */\nconst POPOVER_MIN_HEIGHT = 120\n\n/**\n * Marks the portaled panel in the DOM. Products and audits (see\n * `playground/scripts/popover-hit-test.mjs`) select on this rather than on a\n * Tailwind class, which is presentation and free to change.\n *\n * Its VALUE is the surface's ancestor path (`outer/inner`), which is what\n * restores \"is this click inside my popover\" after the portal flattens two\n * nested panels into two siblings of `<body>`.\n */\nexport const POPOVER_SURFACE_ATTR = 'data-agent-app-popover'\nconst POPOVER_PATH_SEPARATOR = '/'\n\n/**\n * `PopoverSurface` is now mounted (closed) inside every server-rendered\n * composer, so its hooks run on the server once per composer per request.\n * React 18 logs \"useLayoutEffect does nothing on the server\" for that; React 19\n * does not (measured silent on react-dom 19.2.8). The peer floor is `react >=18`,\n * so bind the synchronous hook only where there is a DOM and the effect hook\n * elsewhere — placement never runs on the server either way.\n */\nexport const useBrowserLayoutEffect = typeof document !== 'undefined' ? useLayoutEffect : useEffect\n\nexport interface PopoverSurfaceProps {\n open: boolean\n /** The trigger the panel anchors to — `usePopover`'s `triggerRef`. */\n triggerRef: RefObject<HTMLElement | null>\n /** `usePopover`'s `panelRef`; also what the outside-click test consults. */\n panelRef: RefObject<HTMLDivElement | null>\n /** Presentation classes. Placement and elevation are owned here — a caller\n * must not pass `absolute`/`fixed`/`top-*`/`bottom-*`/`z-*`. */\n className?: string\n role?: string\n id?: string\n 'aria-label'?: string\n /** Make the panel at least as wide as its trigger. A portaled panel has no\n * `w-full` to inherit — the trigger is no longer its offset parent — so a\n * menu that used to stretch to a full-width trigger declares it here. */\n matchTriggerWidth?: boolean\n /** Preferred side. `above` suits controls docked at the bottom of a composer;\n * `below` suits headers, rows, and rails. Either flips when the other side has more room. */\n side?: 'above' | 'below'\n /** Which trigger edge the panel lines up with. `end` keeps a row's trailing menu over the row. */\n align?: 'start' | 'end'\n /** Opt in to remeasurement when asynchronous or filtered content changes. */\n contentKey?: unknown\n children: ReactNode\n}\n\n/**\n * The floating panel every canonical picker opens.\n *\n * It renders through a PORTAL to `document.body` and anchors itself to the\n * trigger in viewport coordinates, because an in-place `absolute` panel's\n * visibility is decided by markup this package does not own. Measured in\n * production: the shipped chat composer docks these controls inside a\n * horizontally scrolling rail (`overflow-x-auto`), and a scroll container\n * clips every positioned descendant whose containing block sits inside it —\n * so a correct 420x457 menu with correct coordinates painted zero pixels and\n * could not be clicked. An ancestor `transform`/`filter`/`contain` would trap\n * it the same way through the stacking context instead of the clip. Leaving\n * the DOM subtree is the only placement a host cannot re-break.\n *\n * Placement prefers ABOVE the trigger (these controls dock at the bottom of a\n * composer), flips below when there is more room there, clamps horizontally\n * into the viewport, and caps its own height to the space on the chosen side.\n * The panel is `visibility: hidden` for the measure pass so it never paints at\n * the pre-placement origin.\n */\nexport function PopoverSurface({\n open,\n triggerRef,\n panelRef,\n className,\n role,\n id,\n 'aria-label': ariaLabel,\n matchTriggerWidth,\n side = 'above',\n align = 'start',\n contentKey,\n children,\n}: PopoverSurfaceProps) {\n const surfaceId = useId()\n const [style, setStyle] = useState<CSSProperties>(() => ({\n position: 'fixed',\n top: 0,\n left: 0,\n visibility: 'hidden',\n }))\n\n const place = useCallback(() => {\n const trigger = triggerRef.current\n const panel = panelRef.current\n if (!trigger || !panel) return\n const anchor = trigger.getBoundingClientRect()\n const viewportWidth = window.innerWidth\n const viewportHeight = window.innerHeight\n\n // `scrollHeight` is the panel's CONTENT height, so it does not feed back\n // on the `maxHeight` this function just applied — reading `offsetHeight`\n // here would measure the previous pass's clamp and ratchet the panel\n // smaller on every scroll event.\n const contentHeight = panel.scrollHeight\n const panelWidth = panel.offsetWidth\n\n const roomAbove = anchor.top - POPOVER_GAP - POPOVER_VIEWPORT_MARGIN\n const roomBelow = viewportHeight - anchor.bottom - POPOVER_GAP - POPOVER_VIEWPORT_MARGIN\n const above = side === 'above'\n ? contentHeight <= roomAbove || roomAbove >= roomBelow\n : !(contentHeight <= roomBelow || roomBelow >= roomAbove)\n const maxHeight = Math.max(POPOVER_MIN_HEIGHT, above ? roomAbove : roomBelow)\n const height = Math.min(contentHeight, maxHeight)\n\n const top = above ? Math.max(POPOVER_VIEWPORT_MARGIN, anchor.top - POPOVER_GAP - height) : anchor.bottom + POPOVER_GAP\n const rightBound = Math.max(POPOVER_VIEWPORT_MARGIN, viewportWidth - panelWidth - POPOVER_VIEWPORT_MARGIN)\n const preferredLeft = align === 'end' ? anchor.right - panelWidth : anchor.left\n const left = Math.min(Math.max(POPOVER_VIEWPORT_MARGIN, preferredLeft), rightBound)\n\n setStyle({\n position: 'fixed',\n top,\n left,\n maxHeight,\n visibility: 'visible',\n ...(matchTriggerWidth ? { minWidth: anchor.width } : {}),\n })\n }, [align, matchTriggerWidth, panelRef, side, triggerRef])\n\n // Layout effect: placement is resolved before the browser paints, so the\n // panel is never seen at the origin it mounts at.\n useBrowserLayoutEffect(() => {\n if (!open) {\n setStyle({ position: 'fixed', top: 0, left: 0, visibility: 'hidden' })\n return\n }\n place()\n }, [open, place, contentKey])\n\n useEffect(() => {\n if (!open) return\n const onViewportChange = () => place()\n // `capture` so the rail's OWN scroll re-anchors the panel — a scroll inside\n // an ancestor does not bubble to window.\n window.addEventListener('scroll', onViewportChange, true)\n window.addEventListener('resize', onViewportChange)\n return () => {\n window.removeEventListener('scroll', onViewportChange, true)\n window.removeEventListener('resize', onViewportChange)\n }\n }, [open, place])\n\n if (!open || typeof document === 'undefined') return null\n\n const ownerPath = triggerRef.current?.closest?.(`[${POPOVER_SURFACE_ATTR}]`)?.getAttribute(POPOVER_SURFACE_ATTR)\n const path = ownerPath ? `${ownerPath}${POPOVER_PATH_SEPARATOR}${surfaceId}` : surfaceId\n\n return createPortal(\n <div\n ref={panelRef}\n id={id}\n role={role}\n aria-label={ariaLabel}\n style={style}\n {...{ [POPOVER_SURFACE_ATTR]: path }}\n className={`z-[1000] ${className ?? ''}`}\n >\n {children}\n </div>,\n document.body,\n )\n}\n","/** Shared picker geometry, focus, and theme presentation. */\nimport { fieldPresentation, fieldSizes, fieldTouchText } from '@tangle-network/ui/presentation'\n\n/**\n * Focus treatment for a row inside a popover panel.\n *\n * The ring itself now comes from the `:focus-visible` floor in tokens.css, so\n * this no longer restates a width or a colour. What it still has to say is\n * WHERE the ring is drawn: a popover option is a full-width row inside a panel\n * that clips its own corners (`overflow-hidden rounded-xl`), and an outward\n * ring on the first or last row is clipped away by that panel. Pulling the\n * offset negative draws the same ring just inside the row instead.\n */\nexport const POPOVER_OPTION_FOCUS = 'focus-visible:[outline-offset:-2px]'\n\n/**\n * The one overlay elevation for floating surfaces — picker menus, popovers,\n * drawers, modals. Reads the theme's `--shadow-overlay` token, so every overlay\n * lifts with the same shadow and re-themes from one source. The floating\n * composer uses the quieter `shadow-raised` rung instead.\n *\n * Written as an arbitrary value rather than the preset's `shadow-overlay`\n * utility, because that utility only exists where the preset is part of the\n * Tailwind build. A host that gets its tokens through a precompiled bundle —\n * `@tangle-network/sandbox-ui` ships brand's tokens inlined, with no `@theme`\n * block surviving the compile — receives `--shadow-overlay` as a plain custom\n * property, from which no `shadow-overlay` utility can be generated, and these\n * surfaces render flat. The arbitrary form emits from the class alone and works\n * either way.\n */\nexport const OVERLAY_SHADOW = 'shadow-[var(--shadow-overlay)]'\n\n/**\n * Root geometry for a picker — the box that holds the trigger — in one place\n * because every picker in this family has to agree on it.\n *\n * Shrink-wrapping (`inline-flex`) is the default: these controls dock on a\n * composer row where an expanding pill shoves its neighbours around. A STACKED\n * panel wants the opposite — the compact `AgentSessionControls` gear popover\n * lays its controls out in a column, and a shrink-wrapped root there makes a\n * trigger's own `w-full` a no-op, since it fills a box the trigger itself\n * sized. That is what left Agent backend short of the panel edge and Thinking\n * narrower still.\n *\n * The panel is portaled ({@link PopoverSurface}), so widening the root widens\n * the TRIGGER only. A menu that should follow it declares `matchTriggerWidth`.\n */\nexport function pickerRootClass(fullWidth: boolean): string {\n return `relative ${fullWidth ? 'flex w-full' : 'inline-flex'}`\n}\n\n/**\n * How a picker's TRIGGER is drawn. The menu it opens is the same either way.\n *\n * - `chip` (default): the 32px bordered pill — `rounded-full border\n * border-border bg-card font-medium`, on the composer row's height.\n * - `quiet`: a 32px borderless text button (the control scale's sm, the\n * composer row's one height) — muted label, small glyph, a\n * surface fill on hover and while the menu is open, nothing else. For a\n * composer whose card already draws the border: three pills docked under\n * the input there read as three more cards, not as the input's controls.\n * - `field`: a full-width form field — the same height, radius, border,\n * well, and focus treatment as a text input at `--control-height`. For a\n * settings form, where a pill among inputs reads as a different control.\n */\nexport type PickerVariant = 'chip' | 'quiet' | 'field'\n\n/**\n * Trigger classes for a `field` picker: `@tangle-network/ui`'s own field\n * presentation and `md` field size, the classes its `Input` and `SelectTrigger`\n * draw, so a model, harness or timezone selector sits in a form as one more\n * field — the same well on every plane, the same border, hover and focus halo.\n */\nexport function fieldPickerTriggerClass({ interactive = true }: { interactive?: boolean } = {}): string {\n return `${fieldPresentation} ${fieldSizes.md} ${fieldTouchText} inline-flex w-full min-w-0 items-center justify-between gap-2 whitespace-nowrap border text-left font-normal text-foreground disabled:cursor-not-allowed disabled:opacity-50 ${\n interactive ? 'data-[state=open]:border-[var(--ix-hover-border)] data-[state=open]:shadow-[var(--ix-after)]' : 'cursor-default'}`\n}\n\n/** The chip trigger: a fixed 32px height (no vertical padding, so the 20px\n * line and the border cannot push it to 34px). A full-width EffortPicker in a\n * settings panel keeps the 36px field row instead. */\nexport const CHIP_PICKER_TRIGGER =\n 'inline-flex h-[var(--control-height-sm,2rem)] items-center gap-1.5 whitespace-nowrap rounded-full border border-border bg-card px-3 text-sm font-medium text-foreground transition'\n\n/** The quiet trigger at rest: geometry, type, and keyboard focus. */\nconst QUIET_PICKER_TRIGGER_BASE =\n 'inline-flex h-[var(--control-height-sm,2rem)] shrink-0 items-center gap-1.5 whitespace-nowrap rounded-md bg-transparent px-2 text-sm font-normal text-muted-foreground transition focus:outline-none focus-visible:ring-2 focus-visible:ring-ring'\n\n/** The fills a quiet trigger shows on hover and while its menu is open — the\n * only two states it draws. Reads `data-state`, which every picker trigger\n * in this family stamps. */\nconst QUIET_PICKER_TRIGGER_INTERACTIVE =\n 'hover:bg-accent hover:text-foreground data-[state=open]:bg-accent data-[state=open]:text-foreground'\n\n/**\n * Trigger classes for a `quiet` picker. Height, padding, radius, and type are\n * fixed here so the triggers on one composer row agree; a caller adds only\n * width (`w-full`) and alignment (`justify-between`).\n *\n * The focus ring is drawn on the element rather than left to the tokens.css\n * `:focus-visible` floor: a quiet trigger sits beside the composer's own action\n * buttons (attach, dictate, send), which draw `focus-visible:ring-2\n * focus-visible:ring-ring`, and a row whose controls answer keyboard focus two\n * different ways reads as two families.\n *\n * `interactive: false` is for a PINNED control (see `HarnessPicker`'s\n * `lockReason`): it keeps the resting treatment and draws no hover or open\n * fill, because a fill promises a menu the control will not open.\n */\nexport function quietPickerTriggerClass({ interactive = true }: { interactive?: boolean } = {}): string {\n return interactive\n ? `${QUIET_PICKER_TRIGGER_BASE} ${QUIET_PICKER_TRIGGER_INTERACTIVE}`\n : `${QUIET_PICKER_TRIGGER_BASE} cursor-default`\n}\n","import { useEffect, useRef, useState } from 'react'\n\n/**\n * Guard an async action against double-submit. `run` ignores re-entrant calls\n * while a promise is in flight and flips `pending` so the caller can disable\n * the control — the fix for double-charge / double-approve on a slow network.\n * Settles (success or throw) before clearing, and no-ops state updates after\n * unmount.\n */\nexport function usePending(): { pending: boolean; run: (action: () => void | Promise<void>) => void } {\n const [pending, setPending] = useState(false)\n const inFlight = useRef(false)\n const mounted = useRef(true)\n useEffect(() => {\n mounted.current = true\n return () => {\n mounted.current = false\n }\n }, [])\n const run = (action: () => void | Promise<void>) => {\n if (inFlight.current) return\n let result: void | Promise<void>\n try {\n result = action()\n } catch {\n return\n }\n if (!(result instanceof Promise)) return\n inFlight.current = true\n setPending(true)\n void result.finally(() => {\n inFlight.current = false\n if (mounted.current) setPending(false)\n })\n }\n return { pending, run }\n}\n","import { bindSearchPickerNavigation } from './focus-navigation'\n/** Searchable catalog selection and truthful model price presentation. */\nimport { useCallback, useEffect, useId, useMemo, useRef, useState, type ReactNode } from 'react'\nimport { ProviderLogo } from './provider-logo'\nimport { StatusPill } from '@tangle-network/ui/primitives'\nimport { MAX_RECOMMENDED_MODELS, sortModelsByFreshness, type CatalogModel } from '../runtime/model-catalog'\nimport { ChevronDown, CheckGlyph, SearchGlyph, SparkleGlyph } from './control-glyphs'\nimport { usePopover, PopoverSurface } from './popover-surface'\nimport { CHIP_PICKER_TRIGGER, OVERLAY_SHADOW, POPOVER_OPTION_FOCUS, pickerRootClass, fieldPickerTriggerClass, quietPickerTriggerClass, type PickerVariant } from './picker-presentation'\n\nexport interface ModelPickerProps {\n /** Controlled, opaque saved id. Never replaced merely because the catalogue omits it. */\n value: string\n onChange: (id: string) => void\n /** Catalogue models — from `GET`ing the app's catalogue route (see\n * `runtime/model-catalog`), plus any product-specific entries appended. */\n models: CatalogModel[]\n /** Host-owned request state. Loading takes precedence over error and results. */\n loading?: boolean\n /** Host-safe failure message. null/undefined means no failure; even '' is an error. */\n error?: string | null\n /** Ask the host to retry. The host owns fetching, loading, errors and cancellation. */\n onRetry?: () => void\n /** Disable the trigger and close an open picker; does not change the saved value. */\n disabled?: boolean\n /** Associations belong to the trigger button, not its surrounding div. */\n id?: string\n 'aria-label'?: string\n 'aria-labelledby'?: string\n 'aria-describedby'?: string\n /** Render a provider logo/badge; default is ProviderLogo. */\n renderProviderBadge?: (provider: string) => ReactNode\n /** Section label for `featured` models. */\n recommendedLabel?: string\n /** Pin a labeled section to the TOP of the list (above Recommended) for the\n * models a product wants surfaced first — e.g. a tuner app's own fine-tuned\n * models (`{ label: 'Your Fine-Tuned Models', match: (m) => m.provider === 'tuner' }`).\n * Matching models are shown only in this section, not duplicated below. */\n priorityGroup?: {\n label: string\n match: (model: CatalogModel) => boolean\n }\n /** Trigger treatment — see {@link PickerVariant}. Default `chip`. */\n variant?: PickerVariant\n /** Optional accessible trigger content for a picker docked beside an editable model field. */\n triggerContent?: ReactNode\n /**\n * Offer \"no selection\" as the first row, for a setting that may defer to a\n * default chosen elsewhere. Choosing it calls `onChange('')`, and the trigger\n * shows this label while `value` is empty.\n */\n defaultOption?: { label: string }\n}\n\nfunction formatPrice(p?: string): string | undefined {\n if (!p) return undefined\n const n = Number(p)\n if (isNaN(n) || n === 0) return undefined\n const perM = n * 1_000_000\n const amount = Number.isInteger(perM) ? perM.toFixed(0) : perM.toFixed(2)\n return `$${amount}/M`\n}\n\nconst OUTPUT_UNIT_LABEL: Record<NonNullable<CatalogModel['outputPrice']>['unit'], string> = {\n image: 'image',\n second: 'sec',\n minute: 'min',\n '1k_chars': '1K chars',\n}\n\n/**\n * The price a person pays per output, in the unit that output comes in: per\n * million prompt tokens for text, per image, per second of video, per minute of\n * audio, per 1,000 characters of speech. Undefined when the catalogue has no\n * price, so a row never shows a made-up number.\n */\nexport function formatModelPrice(model: Pick<CatalogModel, 'pricing' | 'outputPrice'>): string | undefined {\n const media = model.outputPrice\n if (media && Number.isFinite(media.usd) && media.usd > 0) {\n const amount = media.usd >= 1 ? media.usd.toFixed(2) : media.usd >= 0.01 ? String(Number(media.usd.toFixed(3))) : media.usd.toPrecision(2)\n return `$${amount}/${OUTPUT_UNIT_LABEL[media.unit]}`\n }\n return formatPrice(model.pricing?.prompt)\n}\n\nfunction formatContext(len?: number): string | undefined {\n if (!len) return undefined\n if (len >= 1_000_000) return `${(len / 1_000_000).toFixed(1)}M ctx`\n if (len >= 1_000) return `${Math.round(len / 1_000)}K ctx`\n return `${len} ctx`\n}\n\n/** The brand whose logo a row shows: its maker when the catalogue names one,\n * else its host. A fal-hosted Veo row shows Google, not fal. */\nfunction logoBrand(model: Pick<CatalogModel, 'provider' | 'maker'>): string {\n return model.maker?.trim() || model.provider\n}\n\nfunction SectionHeader({ children }: { children: ReactNode }) {\n return (\n <div className=\"px-3 pb-1 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground\">\n {children}\n </div>\n )\n}\n\nfunction ModelRow({\n model,\n selected,\n onSelect,\n renderProviderBadge,\n}: {\n model: CatalogModel\n selected: boolean\n onSelect: () => void\n renderProviderBadge?: (provider: string) => ReactNode\n}) {\n const price = formatModelPrice(model)\n const ctx = formatContext(model.contextLength)\n const media = model.output && model.output !== 'text'\n const thumb = media && (model.output === 'image' || model.output === 'video') ? model.previewUrl : undefined\n const unavailable = model.status === 'unavailable'\n const flagged = unavailable || model.status === 'limited'\n // A flagged model keeps its row and stays selectable; the warning tone, not a\n // grey sentence, says it cannot run as asked.\n const capability = model.capability ?? (flagged ? model.statusReason : undefined)\n return (\n <button\n type=\"button\"\n onClick={onSelect}\n aria-pressed={selected}\n title={`${model.name} (${model.id})`}\n className={`flex w-full items-center gap-2.5 rounded-md px-3 py-2.5 text-left text-sm transition ${POPOVER_OPTION_FOCUS} ${\n selected ? 'bg-primary/10 font-medium' : 'hover:bg-accent'\n }`}\n >\n {thumb ? (\n // A media model shows what it makes: a 40px example beside its name.\n <img src={thumb} alt=\"\" loading=\"lazy\" decoding=\"async\" data-model-preview\n className={`size-10 shrink-0 rounded-md border border-border object-cover${unavailable ? ' opacity-50' : ''}`} />\n ) : (\n <span className=\"shrink-0\" aria-hidden>\n {renderProviderBadge ? renderProviderBadge(logoBrand(model)) : <ProviderLogo provider={logoBrand(model)} size={16} />}\n </span>\n )}\n <span className=\"min-w-0 flex-1\">\n <span className=\"flex min-w-0 items-center gap-1.5\">\n {thumb && (\n <span className=\"shrink-0\" aria-hidden>\n {renderProviderBadge ? renderProviderBadge(logoBrand(model)) : <ProviderLogo provider={logoBrand(model)} size={14} />}\n </span>\n )}\n <span className={`min-w-0 break-words [overflow-wrap:anywhere]${unavailable ? ' text-muted-foreground' : ''}`}>{model.name}</span>\n {flagged && (\n <StatusPill tone=\"warning\" size=\"sm\" className=\"shrink-0\" title={model.statusReason} data-model-status={model.status}>\n {unavailable ? 'Unavailable' : 'Limited'}\n </StatusPill>\n )}\n </span>\n {capability && (\n <span className=\"mt-0.5 block truncate text-xs font-normal text-muted-foreground\" data-model-capability>{capability}</span>\n )}\n {(ctx || price || (!media && !model.supportsTools)) && (\n <span className=\"mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs font-normal text-muted-foreground\">\n {!media && !model.supportsTools && <span className=\"rounded bg-secondary px-1.5 py-0.5\">no tools</span>}\n {!media && ctx && <span>{ctx}</span>}\n {price && <span data-model-price>{price}</span>}\n </span>\n )}\n </span>\n {selected && <CheckGlyph className=\"h-3.5 w-3.5 shrink-0 text-primary\" />}\n </button>\n )\n}\n\n/**\n * Searchable model picker pill + popover. A featured model is recommended\n * when the catalog marks it as a current choice. The first view stays short;\n * search and the browse action retain every routeable legacy model.\n *\n * This is the CANONICAL ecosystem model picker (see docs/ui-picker-canon.md).\n * Catalogue requests, retry outcomes and persisted selections belong to the host.\n * The non-modal dialog uses native buttons, not a partial combobox/listbox:\n * Tab and Enter/Space work normally; arrow keys also move through its controls.\n */\nexport function ModelPicker({\n value, onChange, models, loading = false, error, onRetry, disabled = false,\n id, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledBy, 'aria-describedby': ariaDescribedBy,\n renderProviderBadge, recommendedLabel = 'Recommended', priorityGroup,\n variant = 'chip', triggerContent, defaultOption,\n}: ModelPickerProps) {\n const [open, setOpen] = useState(false)\n const [query, setQuery] = useState('')\n const [showAll, setShowAll] = useState(false)\n const changeOpen = useCallback((next: boolean) => {\n setOpen(next && !disabled)\n if (!next) {\n setQuery('')\n setShowAll(false)\n }\n }, [disabled])\n const expanded = open && !disabled\n const { containerRef, triggerRef, panelRef, triggerProps } = usePopover(expanded, changeOpen)\n const inputRef = useRef<HTMLInputElement>(null)\n const panelId = useId()\n const valueId = useId()\n const unavailable = error != null\n const sortedModels = useMemo(() => sortModelsByFreshness(models), [models])\n const contentKey = useMemo(() => ({ query, showAll, loading, error, models, value, priorityGroup }),\n [query, showAll, loading, error, models, value, priorityGroup])\n\n useEffect(() => {\n if (disabled) changeOpen(false)\n }, [disabled, changeOpen])\n\n useEffect(() => {\n if (!expanded) return\n // The portal's placement may commit a second render. Focus after that too.\n const focus = () => inputRef.current?.focus()\n focus()\n if (typeof requestAnimationFrame !== 'function') return\n const frame = requestAnimationFrame(focus)\n return () => cancelAnimationFrame(frame)\n }, [expanded])\n\n useEffect(() => {\n const panel = panelRef.current\n if (!expanded || !panel) return\n return bindSearchPickerNavigation({\n panel, input: () => inputRef.current, trigger: () => triggerRef.current,\n onClose: () => changeOpen(false), buttonSelector: 'button:not(:disabled)',\n homeEnd: true,\n })\n }, [expanded, changeOpen, panelRef, triggerRef])\n\n const selected = sortedModels.find((m) => m.id === value)\n const selectedLabel = selected?.name ?? value\n const describeValue = triggerContent != null || Boolean(id || ariaLabel || ariaLabelledBy)\n const filtered = useMemo(() => {\n const q = query.trim().toLowerCase()\n if (!q) return null\n return sortedModels.filter(\n (m) =>\n m.id.toLowerCase().includes(q) ||\n m.name.toLowerCase().includes(q) ||\n (m.description?.toLowerCase() ?? '').includes(q) ||\n m.provider.toLowerCase().includes(q) ||\n (m.maker?.toLowerCase() ?? '').includes(q),\n )\n }, [sortedModels, query])\n\n const sections = useMemo(() => {\n const isPriority = priorityGroup ? (m: CatalogModel) => priorityGroup.match(m) : () => false\n const priority = priorityGroup ? sortedModels.filter(isPriority) : []\n const featured = sortedModels.filter((model) => model.featured && !isPriority(model))\n const recommended = featured.slice(0, MAX_RECOMMENDED_MODELS)\n const visibleIds = new Set([...priority, ...recommended].map((model) => model.id))\n const currentSelection = sortedModels.find((model) => model.id === value && !visibleIds.has(model.id))\n const byProvider: Array<{ provider: string; items: CatalogModel[] }> = []\n for (const model of sortedModels) {\n if (visibleIds.has(model.id)) continue\n const last = byProvider[byProvider.length - 1]\n if (last && last.provider === model.provider) last.items.push(model)\n else byProvider.push({ provider: model.provider, items: [model] })\n }\n return { priority, recommended, currentSelection, byProvider }\n }, [sortedModels, priorityGroup, value])\n\n const select = (modelId: string) => {\n if (disabled || (modelId && (loading || unavailable))) return\n changeOpen(false)\n triggerRef.current?.focus()\n onChange(modelId)\n }\n const row = (model: CatalogModel) => (\n <ModelRow key={model.id} model={model} selected={model.id === value} onSelect={() => select(model.id)} renderProviderBadge={renderProviderBadge} />\n )\n\n return (\n <div ref={containerRef} className={variant === 'field' ? 'relative flex w-full min-w-0' : 'relative inline-flex min-w-0 max-w-full'}>\n <button\n type=\"button\"\n {...triggerProps}\n id={id}\n disabled={disabled}\n aria-label={ariaLabel}\n aria-labelledby={ariaLabelledBy}\n aria-describedby={[ariaDescribedBy, describeValue && value ? valueId : undefined].filter(Boolean).join(' ') || undefined}\n aria-haspopup=\"dialog\"\n aria-controls={expanded ? panelId : undefined}\n onClick={() => changeOpen(!expanded)}\n onKeyDown={(event) => {\n if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {\n event.preventDefault()\n changeOpen(true)\n }\n }}\n title={selectedLabel || defaultOption?.label || 'Select model'}\n data-state={expanded ? 'open' : 'closed'}\n className={`${\n variant === 'field'\n ? fieldPickerTriggerClass({ interactive: !disabled })\n : variant === 'quiet'\n ? quietPickerTriggerClass({ interactive: !disabled })\n : `${CHIP_PICKER_TRIGGER} ${disabled ? '' : 'hover:bg-accent'}`\n } max-w-full disabled:cursor-not-allowed disabled:opacity-50`}\n >\n {triggerContent ?? <span className={variant === 'field' ? 'flex min-w-0 flex-1 items-center gap-2' : 'contents'}>\n <span className=\"shrink-0\" aria-hidden>\n {selected ? (renderProviderBadge ? renderProviderBadge(logoBrand(selected)) : <ProviderLogo provider={logoBrand(selected)} size={16} />) : <SparkleGlyph className=\"h-3.5 w-3.5 text-muted-foreground\" />}\n </span>\n <span className={variant === 'field' ? `min-w-0 flex-1 truncate ${value ? '' : 'text-muted-foreground'}` : 'max-w-[160px] truncate'}>\n {selectedLabel || defaultOption?.label || 'Select model'}</span>\n </span>}\n <ChevronDown className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n </button>\n {describeValue && value && <span id={valueId} className=\"sr-only\">Selected model: {selectedLabel}</span>}\n\n <PopoverSurface\n open={expanded}\n id={panelId}\n role=\"dialog\"\n aria-label=\"Choose a model\"\n contentKey={contentKey}\n triggerRef={triggerRef}\n panelRef={panelRef}\n matchTriggerWidth={variant === 'field'}\n side={variant === 'field' ? 'below' : undefined}\n className={`flex w-[420px] max-w-[calc(100vw-2rem)] flex-col overflow-hidden rounded-xl border border-card-edge bg-popover text-foreground ${OVERLAY_SHADOW}`}\n >\n <div className=\"shrink-0 border-b border-border px-3 py-2\">\n <div className=\"flex items-center gap-2 rounded-lg border border-strong bg-background px-3 py-2 focus-within:ring-2 focus-within:ring-ring\">\n <SearchGlyph className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n <input\n ref={inputRef}\n type=\"text\"\n value={query}\n onChange={(event) => setQuery(event.target.value)}\n placeholder=\"Search models...\"\n aria-label=\"Search all models\"\n className=\"min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground\"\n />\n </div>\n </div>\n {/* min-h-0 lets results absorb the surface's viewport height limit. */}\n <div className=\"max-h-[520px] min-h-0 overflow-y-auto p-1 pb-2\">\n {defaultOption && !query.trim() && (\n <button\n type=\"button\"\n onClick={() => select('')}\n aria-pressed={!value}\n className={`flex w-full items-center gap-2.5 rounded-md px-3 py-2.5 text-left text-sm transition ${POPOVER_OPTION_FOCUS} ${\n value ? 'hover:bg-accent' : 'bg-primary/10 font-medium'\n }`}\n >\n <SparkleGlyph className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n <span className=\"min-w-0 flex-1\">{defaultOption.label}</span>\n {!value && <CheckGlyph className=\"h-3.5 w-3.5 shrink-0 text-primary\" />}\n </button>\n )}\n {value && !selected && (\n <div className=\"mx-2 mb-1 mt-2 rounded-lg bg-secondary px-3 py-2 text-sm\">\n <p className=\"text-xs font-medium text-muted-foreground\">Saved model</p>\n <p className=\"break-words [overflow-wrap:anywhere]\">{value}</p>\n <p className=\"mt-1 text-xs text-muted-foreground\">\n {loading || unavailable ? 'Your saved selection is unchanged.' : 'Not in this catalogue. Your saved selection is unchanged.'}\n </p>\n </div>\n )}\n {loading ? (\n <div role=\"status\" className=\"px-3 py-4 text-center text-sm text-muted-foreground\">Loading models...</div>\n ) : unavailable ? (\n <div className=\"px-3 py-4 text-sm\">\n <div role=\"alert\">\n <p className=\"font-medium\">Model catalogue unavailable</p>\n <p className=\"mt-1 break-words text-muted-foreground [overflow-wrap:anywhere]\">{error || 'The catalogue could not be loaded.'}</p>\n </div>\n {onRetry && <button type=\"button\" className={`mt-3 rounded-md border border-border bg-card px-3 py-2 font-medium hover:bg-accent ${POPOVER_OPTION_FOCUS}`}\n onClick={() => {\n // Retry may remove this button synchronously. Keep focus on\n // the stable search input while the host updates its state.\n inputRef.current?.focus()\n onRetry()\n }}>Retry</button>}\n </div>\n ) : models.length === 0 ? (\n <div role=\"status\" className=\"px-3 py-4 text-center text-sm text-muted-foreground\">No models available</div>\n ) : filtered ? (\n <>\n {filtered.length === 0 && <div role=\"status\" className=\"px-3 py-4 text-center text-sm text-muted-foreground\">No models match your search</div>}\n {filtered.map(row)}\n </>\n ) : (\n <>\n {priorityGroup && sections.priority.length > 0 && <>\n <SectionHeader>{priorityGroup.label}</SectionHeader>\n {sections.priority.map(row)}\n </>}\n {sections.currentSelection && !showAll && <>\n <SectionHeader>Selected model</SectionHeader>\n {row(sections.currentSelection)}\n </>}\n {sections.recommended.length > 0 && <>\n <SectionHeader>{recommendedLabel}</SectionHeader>\n {sections.recommended.map(row)}\n </>}\n {sections.recommended.length === 0 && sections.priority.length === 0 && !sections.currentSelection && (\n <div className=\"px-3 py-3 text-sm text-muted-foreground\">Search or browse all models</div>\n )}\n {sections.byProvider.length > 0 && <button\n type=\"button\"\n aria-expanded={showAll}\n onClick={() => setShowAll(!showAll)}\n className={`mt-2 w-full rounded-md px-3 py-2 text-left text-sm text-muted-foreground hover:bg-accent hover:text-foreground ${POPOVER_OPTION_FOCUS}`}\n >{showAll ? 'Hide older models' : 'Browse all models'}</button>}\n {showAll && sections.byProvider.map((group) => (\n <div key={group.provider}>\n <SectionHeader>{group.provider}</SectionHeader>\n {group.items.map(row)}\n </div>\n ))}\n </>\n )}\n </div>\n </PopoverSurface>\n </div>\n )\n}\n","/** Inline glyphs shared by chat-shell pickers. */\nexport function ChevronDown({ className }: { className?: string }) {\n return (\n <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d=\"m6 9 6 6 6-6\" />\n </svg>\n )\n}\n\nexport function SearchGlyph({ className }: { className?: string }) {\n return (\n <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <circle cx=\"11\" cy=\"11\" r=\"8\" />\n <path d=\"m21 21-4.3-4.3\" />\n </svg>\n )\n}\n\nexport function SparkleGlyph({ className }: { className?: string }) {\n return (\n <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d=\"M12 3v3m0 12v3M3 12h3m12 0h3M5.6 5.6l2.1 2.1m8.6 8.6 2.1 2.1m0-12.8-2.1 2.1M7.7 16.3l-2.1 2.1\" />\n </svg>\n )\n}\n\n/** lucide `brain` (v1.27) inlined — `/web-react` ships no icon-library\n * dependency, so the thinking glyph follows the same pattern as the rest of\n * this set. */\nexport function BrainGlyph({ className }: { className?: string }) {\n return (\n <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d=\"M12 18V5\" />\n <path d=\"M15 13a4.17 4.17 0 0 1-3-4 4.17 4.17 0 0 1-3 4\" />\n <path d=\"M17.598 6.5A3 3 0 1 0 12 5a3 3 0 1 0-5.598 1.5\" />\n <path d=\"M17.997 5.125a4 4 0 0 1 2.526 5.77\" />\n <path d=\"M18 18a4 4 0 0 0 2-7.464\" />\n <path d=\"M19.967 17.483A4 4 0 1 1 12 18a4 4 0 1 1-7.967-.517\" />\n <path d=\"M6 18a4 4 0 0 1-2-7.464\" />\n <path d=\"M6.003 5.125a4 4 0 0 0-2.526 5.77\" />\n </svg>\n )\n}\n\n/** lucide `check` — the selected-row mark in the picker menus. */\nexport function CheckGlyph({ className }: { className?: string }) {\n return (\n <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d=\"M20 6 9 17l-5-5\" />\n </svg>\n )\n}\n","/** Reasoning-level selection and effort-meter presentation. */\nimport { useId, useState } from 'react'\nimport { BrainGlyph, ChevronDown, CheckGlyph } from './control-glyphs'\nimport { usePopover, PopoverSurface } from './popover-surface'\nimport { CHIP_PICKER_TRIGGER, OVERLAY_SHADOW, POPOVER_OPTION_FOCUS, pickerRootClass, fieldPickerTriggerClass, quietPickerTriggerClass, type PickerVariant } from './picker-presentation'\n\n/** One reasoning-budget level: the engine `id` is unchanged (the value the\n * product sends to the loop); only the user-facing `label` is renamed to the\n * plainer \"how hard should it think\" vocabulary from docs/product-surfaces.md.\n * `low`→Quick, `medium`→Standard, `high`→Extended. The mapping is overridable\n * via `EffortPickerProps.levels`, so a product can relabel without losing the\n * ids the runtime expects. */\nexport interface EffortLevel {\n id: string\n label: string\n}\n\n/**\n * The engine ids this package NAMES, and the word each one reads as.\n *\n * Deliberately WIDER than {@link DEFAULT_EFFORT_LEVELS}: the default list is\n * what a picker OFFERS when a product declares nothing, while this is the\n * vocabulary — the labels a named id keeps wherever it appears. The two are\n * different questions, and folding them together is what made a real engine\n * rung read as its own id: `xhigh` and `ultracode` are rungs claude-code\n * applies above `high`, so a product declaring them got \"Xhigh\" while every\n * neighbouring rung had a plain English word. Naming them here is what stops\n * each product inventing its own — the drift `effortLevelsFromIds` exists to\n * prevent. They stay OUT of the offered default because most backends do not\n * apply them, and offering a rung the backend ignores is the defect\n * `effortLevels` was added to close.\n */\nconst KNOWN_EFFORT_LABELS = {\n off: 'Off',\n low: 'Quick',\n medium: 'Standard',\n high: 'Extended',\n xhigh: 'Extra',\n ultracode: 'Ultra',\n} as const\n\nexport const DEFAULT_EFFORT_LEVELS: readonly EffortLevel[] = [\n { id: 'off', label: KNOWN_EFFORT_LABELS.off },\n { id: 'low', label: KNOWN_EFFORT_LABELS.low },\n { id: 'medium', label: KNOWN_EFFORT_LABELS.medium },\n { id: 'high', label: KNOWN_EFFORT_LABELS.high },\n]\n\n/**\n * The user-facing label for an engine level id: the canonical vocabulary when\n * the id is one this package names, otherwise the id itself made readable\n * (`auto` -> \"Auto\", `ultra-code` -> \"Ultra code\"). Never invents a depth word,\n * so an id nobody declared a label for still reads as ITSELF and never as some\n * other level.\n */\nexport function effortLevelLabel(id: string): string {\n const known = (KNOWN_EFFORT_LABELS as Record<string, string | undefined>)[id]\n if (known) return known\n const words = id.replace(/[-_]+/g, ' ').trim()\n return words ? words.charAt(0).toUpperCase() + words.slice(1) : id\n}\n\n/**\n * Build a levels list from the engine ids a backend applies — the shape the\n * removed `ComposerAgentControls` took as `reasoning.available`, so a product\n * migrating that list has one call to make instead of a hand-written label map\n * per product (which is how \"Quick\" and \"Low\" drift apart across surfaces).\n */\nexport function effortLevelsFromIds(ids: readonly string[]): readonly EffortLevel[] {\n return ids.map((id) => ({ id, label: effortLevelLabel(id) }))\n}\n\n/**\n * The list {@link EffortPicker} RENDERS for `value` — the declared levels, plus\n * `value` itself when the declaration omits it.\n *\n * A picker cannot honestly resolve a selected value it was not given, and the\n * failure it used to take instead — fall back to the middle entry — renders the\n * session's real depth as a DIFFERENT level's name. That is exactly the defect\n * `levels` was added to prevent: the legacy adapter's `available` list excluded\n * the `auto` sentinel because the old picker injected it, so a product mapping\n * that list straight across ships a session running on `auto` labelled\n * \"Extended\". Admitting the value is not offering a new choice — it is\n * reporting the state the session is already in, and it disappears from the\n * list as soon as the user picks a declared level.\n *\n * A blank value is not admitted (there is no honest label for it); the picker\n * renders no selection instead.\n */\nexport function reconcileEffortLevels(\n value: string,\n levels: readonly EffortLevel[] = DEFAULT_EFFORT_LEVELS,\n): readonly EffortLevel[] {\n if (!value || levels.some((l) => l.id === value)) return levels\n return [{ id: value, label: effortLevelLabel(value) }, ...levels]\n}\n\n// ── effort strength meter ─────────────────────────────────────────────────\n\n/** Segments the meter draws — fixed geometry so the ladder stays tabular\n * across levels (and across the trigger and its menu rows). */\nexport const EFFORT_METER_SEGMENTS = 4\n\n/** Filled-segment opacity ladder: translucent on the left, heavy on the\n * right — the ramp carries strength even at a glance, the count carries it\n * exactly. Unfilled segments sit at a fixed ghost opacity. */\nconst EFFORT_METER_FILL_OPACITY = [0.25, 0.5, 0.75, 1] as const\nconst EFFORT_METER_GHOST_OPACITY = 0.15\n\n/** Level ids that mean \"no reasoning\" — the meter renders all-ghost. */\nconst OFF_LEVEL_IDS: ReadonlySet<string> = new Set(['off', 'none'])\n\n/**\n * Ids that name a POLICY rather than a depth: `auto` means \"let the harness and\n * model decide\", so it has no position on a strength ladder.\n *\n * Without this it lands wherever the declaration puts it and draws a filled\n * meter — measured on a product that offers `auto` first: every harness read\n * `Auto` at a FULL four bars, including `cli-base`, which has no agent to think\n * at all. A meter is a claim about how hard the run will think, and a sentinel\n * cannot make that claim.\n */\nconst UNPLACEABLE_LEVEL_IDS: ReadonlySet<string> = new Set(['auto'])\n\n/**\n * Filled-segment count for a level: 0 for off/none (or an id the levels list\n * does not carry); otherwise the level's position among the non-off choices\n * scaled onto the meter, so the ladder reads low < medium < high and the top\n * level fills the whole scale. The canonical four levels land 0 / 1 / 2 / 4.\n */\nexport function effortMeterFill(\n levelId: string,\n levels: readonly EffortLevel[] = DEFAULT_EFFORT_LEVELS,\n): number {\n if (OFF_LEVEL_IDS.has(levelId) || UNPLACEABLE_LEVEL_IDS.has(levelId)) return 0\n const active = levels.filter((l) => !OFF_LEVEL_IDS.has(l.id) && !UNPLACEABLE_LEVEL_IDS.has(l.id))\n const index = active.findIndex((l) => l.id === levelId)\n if (index < 0 || active.length === 0) return 0\n return Math.max(1, Math.floor(((index + 1) * EFFORT_METER_SEGMENTS) / active.length))\n}\n\n/**\n * The thinking-strength meter: four 12px bars, filled count = level, filled\n * opacity ramping 25→100% left to right (unfilled at a faint ghost). Purely\n * decorative — the level name is always rendered as text beside it, so the\n * meter is `aria-hidden` and adds no second accessible name.\n */\nexport function EffortMeter({ fill, className }: { fill: number; className?: string }) {\n return (\n <span aria-hidden className={`inline-flex items-center gap-[2px] ${className ?? ''}`}>\n {Array.from({ length: EFFORT_METER_SEGMENTS }, (_, i) => (\n <span\n key={i}\n className=\"h-3 w-[3px] rounded-full bg-current\"\n style={{ opacity: i < fill ? EFFORT_METER_FILL_OPACITY[i] : EFFORT_METER_GHOST_OPACITY }}\n />\n ))}\n </span>\n )\n}\n\nexport interface EffortPickerProps {\n value: string\n onChange: (id: string) => void\n /** Selectable levels (engine id + user-facing label). Defaults to the plain\n * \"Thinking\" vocabulary; override to relabel without changing the ids the\n * runtime receives.\n *\n * A list that omits the current `value` is not a rendering error the picker\n * papers over: `value` is reconciled INTO the rendered list under its own\n * name (see {@link reconcileEffortLevels}), because a control must report\n * the depth the session is running at and never some other list entry. */\n levels?: readonly EffortLevel[]\n /** Prefix shown before the active level on the pill — the \"what is this\"\n * context the bare value lacked. Default \"Thinking\". Pass '' to hide it. */\n label?: string\n /** Fill the container instead of shrink-wrapping — opt-in, default `false`;\n * see {@link pickerRootClass} for when and why. */\n fullWidth?: boolean\n /** Trigger treatment — see {@link PickerVariant}. Default `chip`. */\n variant?: PickerVariant\n /** Disable the trigger and close an open menu; does not change the value. */\n disabled?: boolean\n /** Associations belong to the trigger button, for a picker labelled by a form field. */\n id?: string\n 'aria-describedby'?: string\n}\n\n/** Thinking-budget selector pill, styled to match {@link ModelPicker}. Show\n * it only when the selected model `supportsReasoning`. \"Thinking\" is the\n * plain-English name for what was internally called \"effort\".\n *\n * The CANONICAL ecosystem effort picker — sandbox-ui's reasoning menu (inside\n * its `chat/AgentSessionControls`) is legacy and frozen. */\nexport function EffortPicker({ value, onChange, levels = DEFAULT_EFFORT_LEVELS, label = 'Thinking', fullWidth = false, variant = 'chip',\n disabled = false, id, 'aria-describedby': ariaDescribedBy }: EffortPickerProps) {\n const [requestedOpen, setOpen] = useState(false)\n const open = requestedOpen && !disabled\n const { containerRef, triggerRef, panelRef, triggerProps } = usePopover(open, setOpen)\n const field = variant === 'field'\n const panelId = useId()\n const rendered = reconcileEffortLevels(value, levels)\n // The strength ladder is computed over the DECLARED levels only, so admitting\n // the selected value cannot shift where the declared ones sit on the meter.\n // A level the declaration does not carry has no position on that ladder, so\n // it renders with NO meter — an all-ghost meter is what `off` looks like, and\n // \"we cannot place this\" is not \"no thinking\".\n const isDeclared = (id: string) => levels.some((l) => l.id === id) && !UNPLACEABLE_LEVEL_IDS.has(id)\n const selected = rendered.find((l) => l.id === value)\n\n return (\n <div ref={containerRef} className={pickerRootClass(fullWidth || field)}>\n <button\n type=\"button\"\n {...triggerProps}\n id={id}\n disabled={disabled}\n aria-describedby={ariaDescribedBy}\n aria-controls={open ? panelId : undefined}\n onClick={() => setOpen(!open)}\n title={label ? `${label} — how hard the agent reasons before answering` : 'Reasoning effort'}\n data-state={open ? 'open' : 'closed'}\n className={`${\n field\n ? fieldPickerTriggerClass({ interactive: !disabled })\n : variant === 'quiet'\n ? quietPickerTriggerClass()\n : fullWidth\n ? 'inline-flex min-h-[36px] shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full border border-border bg-card px-3 py-1.5 text-sm font-medium text-foreground transition hover:bg-accent'\n : `${CHIP_PICKER_TRIGGER} shrink-0 hover:bg-accent`\n } ${fullWidth ? 'w-full' : ''}`}\n >\n <BrainGlyph className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n {/* Full width gives the label the slack, so the meter and chevron park\n on the trailing edge and the glyph stays against the text. */}\n <span className={fullWidth || field ? 'flex-1 truncate text-left' : undefined}>\n {label ? <span className=\"text-muted-foreground\">{label}: </span> : null}\n {selected ? selected.label : '—'}\n </span>\n {/* Quiet inherits the trigger's tone, so the meter is muted at rest\n and lifts with the label on hover instead of staying at full foreground. */}\n {selected && isDeclared(selected.id) && (\n <EffortMeter\n fill={effortMeterFill(selected.id, levels)}\n className={variant === 'quiet' ? 'shrink-0' : 'shrink-0 text-foreground'}\n />\n )}\n <ChevronDown className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n </button>\n <PopoverSurface\n open={open}\n id={panelId}\n role=\"menu\"\n triggerRef={triggerRef}\n panelRef={panelRef}\n // A portaled panel has no `w-full` to inherit, so a full-width trigger\n // hands its measured width to the panel instead.\n matchTriggerWidth={fullWidth || field}\n side={field ? 'below' : undefined}\n className={`w-44 overflow-y-auto rounded-xl border border-card-edge bg-popover p-1 ${OVERLAY_SHADOW}`}\n >\n {rendered.map((l) => (\n <button\n key={l.id}\n type=\"button\"\n role=\"menuitemradio\"\n aria-checked={l.id === value}\n onClick={() => {\n onChange(l.id)\n setOpen(false)\n }}\n className={`flex min-h-[40px] w-full items-center gap-2 rounded-md px-3 py-2 text-left text-sm transition ${POPOVER_OPTION_FOCUS} ${\n l.id === value ? 'bg-primary/10 font-medium' : 'hover:bg-accent'\n }`}\n >\n <BrainGlyph className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n <span className=\"truncate\">{l.label}</span>\n {isDeclared(l.id) && (\n <EffortMeter fill={effortMeterFill(l.id, levels)} className=\"ml-auto text-foreground\" />\n )}\n {l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AA;AAAA,UAlB9F,EAAE;AAAA,QAoBT,CACD;AAAA;AAAA,IACL;AAAA,KACF;AAEJ;","names":["useEffect","useRef","useState","useCallback","useEffect","useId","useRef","useState","jsx","jsx","jsxs","useState","useCallback","useRef","useId","useEffect","useId","useState","jsx","jsxs","useState","useId","id"]}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
2
|
KNOWN_HARNESSES
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-ELX5YITO.js";
|
|
4
4
|
import {
|
|
5
5
|
composeSkills,
|
|
6
6
|
renderInlineSkills
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-76MPX7JQ.js";
|
|
8
8
|
|
|
9
9
|
// src/skills-placement/index.ts
|
|
10
10
|
import {
|
|
@@ -103,4 +103,4 @@ export {
|
|
|
103
103
|
skillSupportFileMounts,
|
|
104
104
|
withSkillSupportFiles
|
|
105
105
|
};
|
|
106
|
-
//# sourceMappingURL=chunk-
|
|
106
|
+
//# sourceMappingURL=chunk-54YIL7WM.js.map
|
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
PASTED_CODE_SAMPLES,
|
|
4
4
|
isEdgeBlock,
|
|
5
5
|
parseWranglerCrons
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-VDYEVCQQ.js";
|
|
7
7
|
import {
|
|
8
8
|
LAUNCH_BUDGETS,
|
|
9
9
|
LAUNCH_INVARIANTS,
|
|
@@ -547,4 +547,4 @@ export {
|
|
|
547
547
|
PLATFORM_LIMITS,
|
|
548
548
|
checkLimitAlarms
|
|
549
549
|
};
|
|
550
|
-
//# sourceMappingURL=chunk-
|
|
550
|
+
//# sourceMappingURL=chunk-5GSZGTPJ.js.map
|