@tangle-network/agent-app 0.61.4 → 0.62.0
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-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-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-L7LQRJGD.js → chunk-TCJ4TMOW.js} +37 -33
- package/dist/{chunk-L7LQRJGD.js.map → chunk-TCJ4TMOW.js.map} +1 -1
- 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 +1 -1
- 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 +5 -5
- 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
|
@@ -34,37 +34,40 @@ import {
|
|
|
34
34
|
reconcileStaleTurnLock
|
|
35
35
|
} from "../chunk-CCVWR33L.js";
|
|
36
36
|
import {
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
isUpstreamUnavailable,
|
|
40
|
-
readHttpStatusHint,
|
|
41
|
-
readUpstreamUnavailableCode,
|
|
42
|
-
runWithModelFailover
|
|
43
|
-
} from "../chunk-ZLX4BA27.js";
|
|
37
|
+
assertSafeKeySegment
|
|
38
|
+
} from "../chunk-6DOQ6T2O.js";
|
|
44
39
|
import {
|
|
45
40
|
createEscalationSpeculator,
|
|
46
41
|
createSandboxRunTool,
|
|
47
42
|
escalationHints,
|
|
48
43
|
flattenHistory
|
|
49
|
-
} from "../chunk-
|
|
44
|
+
} from "../chunk-TCJ4TMOW.js";
|
|
50
45
|
import "../chunk-F4TUZYMX.js";
|
|
51
46
|
import "../chunk-4LBCTFBP.js";
|
|
47
|
+
import {
|
|
48
|
+
ModelFailoverExhaustedError,
|
|
49
|
+
buildModelChain,
|
|
50
|
+
isUpstreamUnavailable,
|
|
51
|
+
readHttpStatusHint,
|
|
52
|
+
readUpstreamUnavailableCode,
|
|
53
|
+
runWithModelFailover
|
|
54
|
+
} from "../chunk-ZLX4BA27.js";
|
|
52
55
|
import "../chunk-DSMGS4IV.js";
|
|
53
56
|
import "../chunk-5BJHKQ33.js";
|
|
54
57
|
import "../chunk-6A7MYOUI.js";
|
|
55
58
|
import "../chunk-O7UX55EU.js";
|
|
56
|
-
import "../chunk-XEAZWJ3W.js";
|
|
57
59
|
import "../chunk-S5SRJJQG.js";
|
|
60
|
+
import "../chunk-XEAZWJ3W.js";
|
|
58
61
|
import "../chunk-7TZA2TAM.js";
|
|
59
62
|
import "../chunk-UGWQLQDS.js";
|
|
60
63
|
import "../chunk-WSQFNMIA.js";
|
|
61
64
|
import {
|
|
62
65
|
runProtectedRouterTurn
|
|
63
|
-
} from "../chunk-
|
|
66
|
+
} from "../chunk-CQZVJVME.js";
|
|
64
67
|
import {
|
|
65
68
|
runRouterTurn
|
|
66
|
-
} from "../chunk-
|
|
67
|
-
import "../chunk-
|
|
69
|
+
} from "../chunk-UW2DKTEM.js";
|
|
70
|
+
import "../chunk-VK3F4N4U.js";
|
|
68
71
|
import "../chunk-D6UJEOZQ.js";
|
|
69
72
|
import "../chunk-AMUXRAUO.js";
|
|
70
73
|
import {
|
|
@@ -78,7 +81,7 @@ import {
|
|
|
78
81
|
rowIdOf,
|
|
79
82
|
storeSupportsDraftPersistence,
|
|
80
83
|
streamChatRouteAsSandboxEvents
|
|
81
|
-
} from "../chunk-
|
|
84
|
+
} from "../chunk-EFQUAWWF.js";
|
|
82
85
|
import {
|
|
83
86
|
redactErrorMessage
|
|
84
87
|
} from "../chunk-MH74DY2I.js";
|
|
@@ -89,6 +92,13 @@ import {
|
|
|
89
92
|
import "../chunk-RN4WPTBH.js";
|
|
90
93
|
import "../chunk-WP2GYFZ4.js";
|
|
91
94
|
import "../chunk-6R73V3Y5.js";
|
|
95
|
+
import "../chunk-Z4RD5UF7.js";
|
|
96
|
+
import "../chunk-YG66IHDU.js";
|
|
97
|
+
import {
|
|
98
|
+
coalesceDeltas,
|
|
99
|
+
createBufferedTurnTap
|
|
100
|
+
} from "../chunk-ISP6ZH3G.js";
|
|
101
|
+
import "../chunk-MM6RLOXF.js";
|
|
92
102
|
import {
|
|
93
103
|
attachmentInputToPart,
|
|
94
104
|
attachmentKindForMime,
|
|
@@ -129,8 +139,6 @@ import {
|
|
|
129
139
|
turnResponseEventFor,
|
|
130
140
|
validateSandboxMentionPath
|
|
131
141
|
} from "../chunk-G7M2C72Q.js";
|
|
132
|
-
import "../chunk-Z4RD5UF7.js";
|
|
133
|
-
import "../chunk-YG66IHDU.js";
|
|
134
142
|
import {
|
|
135
143
|
asRecord,
|
|
136
144
|
asString,
|
|
@@ -154,18 +162,13 @@ import {
|
|
|
154
162
|
parseInteractionCancel,
|
|
155
163
|
parseInteractionRequest
|
|
156
164
|
} from "../chunk-6VQCFJWP.js";
|
|
157
|
-
import {
|
|
158
|
-
coalesceDeltas,
|
|
159
|
-
createBufferedTurnTap
|
|
160
|
-
} from "../chunk-ISP6ZH3G.js";
|
|
161
|
-
import "../chunk-MM6RLOXF.js";
|
|
162
165
|
import "../chunk-XELWWXJJ.js";
|
|
163
|
-
import "../chunk-
|
|
166
|
+
import "../chunk-PCAY23GS.js";
|
|
164
167
|
import {
|
|
165
168
|
readSandboxBinaryBytes,
|
|
166
169
|
statSandboxFileSize
|
|
167
170
|
} from "../chunk-CTREXL3O.js";
|
|
168
|
-
import "../chunk-
|
|
171
|
+
import "../chunk-ELX5YITO.js";
|
|
169
172
|
import "../chunk-HY57QRRW.js";
|
|
170
173
|
import {
|
|
171
174
|
isWorkspaceFileExportable
|
|
@@ -313,17 +316,139 @@ function streamWithModelFailover(options) {
|
|
|
313
316
|
let serving;
|
|
314
317
|
let trail = [];
|
|
315
318
|
let fellBack = false;
|
|
316
|
-
|
|
319
|
+
const attemptState = { index: 0 };
|
|
317
320
|
let finalTimeout;
|
|
321
|
+
const { drainOnce } = createModelAttemptDrainer(attemptState, options, openTimeoutMs, firstResponseTimeoutMs, committing, liveLifecycle, progress);
|
|
322
|
+
const probe = async (model) => {
|
|
323
|
+
finalTimeout = void 0;
|
|
324
|
+
for (let retry = 0; ; retry += 1) {
|
|
325
|
+
const pass = await drainOnce(model);
|
|
326
|
+
if (!pass.empty || retry >= emptyTurnRetries) {
|
|
327
|
+
if (!pass.outcome.committed && pass.outcome.timeoutCode) {
|
|
328
|
+
finalTimeout = {
|
|
329
|
+
code: pass.outcome.timeoutCode,
|
|
330
|
+
model,
|
|
331
|
+
timeoutMs: pass.outcome.timeoutCode === "model_stream_open_timeout" ? openTimeoutMs : firstResponseTimeoutMs
|
|
332
|
+
};
|
|
333
|
+
} else {
|
|
334
|
+
finalTimeout = void 0;
|
|
335
|
+
}
|
|
336
|
+
return pass.outcome;
|
|
337
|
+
}
|
|
338
|
+
const iterator = pass.outcome.committed ? pass.outcome.iterator : null;
|
|
339
|
+
if (pass.outcome.committed) pass.outcome.abort();
|
|
340
|
+
if (iterator) void closeIterator(iterator, options.log);
|
|
341
|
+
const info = { model, retry: retry + 1, remaining: emptyTurnRetries - retry - 1 };
|
|
342
|
+
options.log?.("[chat-routes] turn completed with no assistant text; re-running the same model", {
|
|
343
|
+
...info
|
|
344
|
+
});
|
|
345
|
+
options.onEmptyTurnRetry?.(info);
|
|
346
|
+
}
|
|
347
|
+
};
|
|
348
|
+
const events = (async function* () {
|
|
349
|
+
let handle;
|
|
350
|
+
const settled = runWithModelFailover({
|
|
351
|
+
models: options.models,
|
|
352
|
+
run: probe,
|
|
353
|
+
...options.policy ? { policy: options.policy } : {},
|
|
354
|
+
// The probe has already classified the raw payload with
|
|
355
|
+
// `isUpstreamUnavailable`; this reads its verdict rather than
|
|
356
|
+
// re-classifying a wrapper object, so the two can never disagree.
|
|
357
|
+
isUnavailableResult: (result) => result.committed === false,
|
|
358
|
+
onFallback: (attempt, nextModel) => {
|
|
359
|
+
const info = {
|
|
360
|
+
from: attempt.model,
|
|
361
|
+
to: nextModel,
|
|
362
|
+
reason: attempt.reason ?? "upstream unavailable"
|
|
363
|
+
};
|
|
364
|
+
options.log?.("[chat-routes] model upstream unavailable; falling over", { ...info });
|
|
365
|
+
options.onFallback?.(info);
|
|
366
|
+
}
|
|
367
|
+
}).finally(() => progress.close());
|
|
368
|
+
settled.catch(() => void 0);
|
|
369
|
+
for (; ; ) {
|
|
370
|
+
const item = await progress.pull();
|
|
371
|
+
if (item === PROGRESS_CLOSED) break;
|
|
372
|
+
yield item;
|
|
373
|
+
}
|
|
374
|
+
try {
|
|
375
|
+
const outcome = await settled;
|
|
376
|
+
serving = outcome.model;
|
|
377
|
+
trail = outcome.attempts;
|
|
378
|
+
fellBack = outcome.usedFallback;
|
|
379
|
+
handle = outcome.value;
|
|
380
|
+
} catch (err) {
|
|
381
|
+
const attempts = err?.attempts;
|
|
382
|
+
if (Array.isArray(attempts)) trail = attempts;
|
|
383
|
+
if (err instanceof ModelFailoverExhaustedError && finalTimeout) {
|
|
384
|
+
throw new ModelFailoverTimeoutError({
|
|
385
|
+
attempts: trail,
|
|
386
|
+
...finalTimeout
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
throw err;
|
|
390
|
+
}
|
|
391
|
+
for (const event of handle.buffered) yield event;
|
|
392
|
+
const live = handle.iterator;
|
|
393
|
+
if (!live) {
|
|
394
|
+
handle.abort();
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
try {
|
|
398
|
+
for (; ; ) {
|
|
399
|
+
const next = await live.next();
|
|
400
|
+
if (next.done) return;
|
|
401
|
+
yield next.value;
|
|
402
|
+
}
|
|
403
|
+
} finally {
|
|
404
|
+
handle.abort();
|
|
405
|
+
await closeIterator(live, options.log);
|
|
406
|
+
}
|
|
407
|
+
})();
|
|
408
|
+
return {
|
|
409
|
+
events,
|
|
410
|
+
servingModel: () => serving,
|
|
411
|
+
attempts: () => trail,
|
|
412
|
+
usedFallback: () => fellBack
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
var PROGRESS_CLOSED = /* @__PURE__ */ Symbol("progress-closed");
|
|
416
|
+
function createProgressQueue() {
|
|
417
|
+
const items = [];
|
|
418
|
+
const waiters = [];
|
|
419
|
+
let closed = false;
|
|
420
|
+
const deliver = (value) => {
|
|
421
|
+
const waiter = waiters.shift();
|
|
422
|
+
if (waiter) waiter(value);
|
|
423
|
+
else items.push(value);
|
|
424
|
+
};
|
|
425
|
+
return {
|
|
426
|
+
push(event) {
|
|
427
|
+
if (closed) return;
|
|
428
|
+
deliver(event);
|
|
429
|
+
},
|
|
430
|
+
close() {
|
|
431
|
+
if (closed) return;
|
|
432
|
+
closed = true;
|
|
433
|
+
deliver(PROGRESS_CLOSED);
|
|
434
|
+
},
|
|
435
|
+
pull() {
|
|
436
|
+
if (items.length > 0) return Promise.resolve(items.shift());
|
|
437
|
+
if (closed) return Promise.resolve(PROGRESS_CLOSED);
|
|
438
|
+
return new Promise((resolve) => waiters.push(resolve));
|
|
439
|
+
}
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
function createModelAttemptDrainer(attemptState, options, openTimeoutMs, firstResponseTimeoutMs, committing, liveLifecycle, progress) {
|
|
318
443
|
const drainOnce = async (model) => {
|
|
319
|
-
|
|
444
|
+
attemptState.index += 1;
|
|
320
445
|
const controller = new AbortController();
|
|
321
446
|
const abort = () => {
|
|
322
447
|
if (!controller.signal.aborted) controller.abort();
|
|
323
448
|
};
|
|
324
449
|
const opening = Promise.resolve().then(() => options.open({
|
|
325
450
|
model,
|
|
326
|
-
attempt:
|
|
451
|
+
attempt: attemptState.index,
|
|
327
452
|
signal: controller.signal
|
|
328
453
|
}));
|
|
329
454
|
const openDeadline = deadlineAfter(openTimeoutMs);
|
|
@@ -476,125 +601,91 @@ function streamWithModelFailover(options) {
|
|
|
476
601
|
}
|
|
477
602
|
}
|
|
478
603
|
};
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
finalTimeout = void 0;
|
|
492
|
-
}
|
|
493
|
-
return pass.outcome;
|
|
494
|
-
}
|
|
495
|
-
const iterator = pass.outcome.committed ? pass.outcome.iterator : null;
|
|
496
|
-
if (pass.outcome.committed) pass.outcome.abort();
|
|
497
|
-
if (iterator) void closeIterator(iterator, options.log);
|
|
498
|
-
const info = { model, retry: retry + 1, remaining: emptyTurnRetries - retry - 1 };
|
|
499
|
-
options.log?.("[chat-routes] turn completed with no assistant text; re-running the same model", {
|
|
500
|
-
...info
|
|
501
|
-
});
|
|
502
|
-
options.onEmptyTurnRetry?.(info);
|
|
503
|
-
}
|
|
504
|
-
};
|
|
505
|
-
const events = (async function* () {
|
|
506
|
-
let handle;
|
|
507
|
-
const settled = runWithModelFailover({
|
|
508
|
-
models: options.models,
|
|
509
|
-
run: probe,
|
|
510
|
-
...options.policy ? { policy: options.policy } : {},
|
|
511
|
-
// The probe has already classified the raw payload with
|
|
512
|
-
// `isUpstreamUnavailable`; this reads its verdict rather than
|
|
513
|
-
// re-classifying a wrapper object, so the two can never disagree.
|
|
514
|
-
isUnavailableResult: (result) => result.committed === false,
|
|
515
|
-
onFallback: (attempt, nextModel) => {
|
|
516
|
-
const info = {
|
|
517
|
-
from: attempt.model,
|
|
518
|
-
to: nextModel,
|
|
519
|
-
reason: attempt.reason ?? "upstream unavailable"
|
|
520
|
-
};
|
|
521
|
-
options.log?.("[chat-routes] model upstream unavailable; falling over", { ...info });
|
|
522
|
-
options.onFallback?.(info);
|
|
523
|
-
}
|
|
524
|
-
}).finally(() => progress.close());
|
|
525
|
-
settled.catch(() => void 0);
|
|
526
|
-
for (; ; ) {
|
|
527
|
-
const item = await progress.pull();
|
|
528
|
-
if (item === PROGRESS_CLOSED) break;
|
|
529
|
-
yield item;
|
|
530
|
-
}
|
|
531
|
-
try {
|
|
532
|
-
const outcome = await settled;
|
|
533
|
-
serving = outcome.model;
|
|
534
|
-
trail = outcome.attempts;
|
|
535
|
-
fellBack = outcome.usedFallback;
|
|
536
|
-
handle = outcome.value;
|
|
537
|
-
} catch (err) {
|
|
538
|
-
const attempts = err?.attempts;
|
|
539
|
-
if (Array.isArray(attempts)) trail = attempts;
|
|
540
|
-
if (err instanceof ModelFailoverExhaustedError && finalTimeout) {
|
|
541
|
-
throw new ModelFailoverTimeoutError({
|
|
542
|
-
attempts: trail,
|
|
543
|
-
...finalTimeout
|
|
544
|
-
});
|
|
545
|
-
}
|
|
546
|
-
throw err;
|
|
547
|
-
}
|
|
548
|
-
for (const event of handle.buffered) yield event;
|
|
549
|
-
const live = handle.iterator;
|
|
550
|
-
if (!live) {
|
|
551
|
-
handle.abort();
|
|
552
|
-
return;
|
|
553
|
-
}
|
|
554
|
-
try {
|
|
555
|
-
for (; ; ) {
|
|
556
|
-
const next = await live.next();
|
|
557
|
-
if (next.done) return;
|
|
558
|
-
yield next.value;
|
|
559
|
-
}
|
|
560
|
-
} finally {
|
|
561
|
-
handle.abort();
|
|
562
|
-
await closeIterator(live, options.log);
|
|
563
|
-
}
|
|
564
|
-
})();
|
|
604
|
+
return { drainOnce };
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
// src/chat-routes/sandbox-model-source.ts
|
|
608
|
+
function parseEffectiveBackend(data) {
|
|
609
|
+
const backend = asRecord(data.effectiveBackend);
|
|
610
|
+
if (!backend) return void 0;
|
|
611
|
+
const provider = asString(backend.provider);
|
|
612
|
+
const model = asString(backend.model);
|
|
613
|
+
const rawSource = asString(backend.source);
|
|
614
|
+
const source = rawSource === "request" || rawSource === "environment" || rawSource === "profile" ? rawSource : void 0;
|
|
615
|
+
if (!provider && !model && !source) return void 0;
|
|
565
616
|
return {
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
usedFallback: () => fellBack
|
|
617
|
+
...model ? { servedModel: model } : {},
|
|
618
|
+
...provider ? { servedProvider: provider } : {},
|
|
619
|
+
...source ? { servedSource: source } : {}
|
|
570
620
|
};
|
|
571
621
|
}
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
622
|
+
function createSandboxModelSource(options, log) {
|
|
623
|
+
if (options.openEvents && !options.model) {
|
|
624
|
+
throw new Error(
|
|
625
|
+
"createSandboxChatProducer: `openEvents` requires `model` \u2014 failover must know which model it is running"
|
|
626
|
+
);
|
|
627
|
+
}
|
|
628
|
+
if (!options.openEvents && !options.events) {
|
|
629
|
+
throw new Error("createSandboxChatProducer: pass `openEvents` (failover-capable) or `events`");
|
|
630
|
+
}
|
|
631
|
+
if (!options.openEvents && resolveEmptyTurnRetries(options.emptyTurnRetries) > 0) {
|
|
632
|
+
throw new Error(
|
|
633
|
+
"createSandboxChatProducer: `emptyTurnRetries` requires `openEvents` \u2014 a fixed `events` stream cannot be re-opened"
|
|
634
|
+
);
|
|
635
|
+
}
|
|
636
|
+
const chain = options.model ? buildModelChain(options.model, options.modelFailover === false ? [] : options.fallbackModels ?? []) : [];
|
|
637
|
+
const pendingModelNotices = [];
|
|
638
|
+
let modelNoticeCount = 0;
|
|
639
|
+
let failover;
|
|
640
|
+
let source;
|
|
641
|
+
if (options.openEvents) {
|
|
642
|
+
failover = streamWithModelFailover({
|
|
643
|
+
models: chain,
|
|
644
|
+
open: options.openEvents,
|
|
645
|
+
log,
|
|
646
|
+
...options.modelPolicy ? { policy: options.modelPolicy } : {},
|
|
647
|
+
...options.openTimeoutMs !== void 0 ? { openTimeoutMs: options.openTimeoutMs } : {},
|
|
648
|
+
...options.firstResponseTimeoutMs !== void 0 ? { firstResponseTimeoutMs: options.firstResponseTimeoutMs } : {},
|
|
649
|
+
...options.emptyTurnRetries !== void 0 ? { emptyTurnRetries: options.emptyTurnRetries } : {},
|
|
650
|
+
...options.onEmptyTurnRetry ? { onEmptyTurnRetry: options.onEmptyTurnRetry } : {},
|
|
651
|
+
...options.liveLifecycleEvents !== void 0 ? { liveLifecycleEvents: options.liveLifecycleEvents } : {},
|
|
652
|
+
onFallback: (info) => {
|
|
653
|
+
modelNoticeCount += 1;
|
|
654
|
+
pendingModelNotices.push({
|
|
655
|
+
id: `model-fallback-${modelNoticeCount}`,
|
|
656
|
+
// Named models on both sides: a quality regression after a downgrade
|
|
657
|
+
// must be attributable to the model that actually answered. The
|
|
658
|
+
// REASON is condensed — a real edge 5xx arrives as Cloudflare's HTML
|
|
659
|
+
// error page, and the raw text put `<!DOCTYPE html><!--[if lt IE 7]>…`
|
|
660
|
+
// into the customer's transcript. The verbatim text is still on
|
|
661
|
+
// `modelFailover.attempts[].reason` for the operator.
|
|
662
|
+
text: `${info.from} was unavailable (${summarizeFailoverReason(info.reason)}) \u2014 answered with ${info.to} instead.`
|
|
663
|
+
});
|
|
664
|
+
options.onModelFallback?.(info);
|
|
665
|
+
}
|
|
666
|
+
});
|
|
667
|
+
source = failover.events;
|
|
668
|
+
} else {
|
|
669
|
+
source = options.events;
|
|
670
|
+
}
|
|
671
|
+
const servingModel = () => failover?.servingModel() ?? options.model;
|
|
672
|
+
const modelState = { effectiveBackend: void 0 };
|
|
673
|
+
let substitutionNoticeQueued = false;
|
|
674
|
+
const servedModel = () => modelState.effectiveBackend?.servedModel ?? servingModel();
|
|
675
|
+
const captureEffectiveBackend = (data) => {
|
|
676
|
+
if (!data) return;
|
|
677
|
+
const parsed = parseEffectiveBackend(data);
|
|
678
|
+
if (!parsed) return;
|
|
679
|
+
modelState.effectiveBackend = parsed;
|
|
680
|
+
const sentModel = servingModel();
|
|
681
|
+
if (substitutionNoticeQueued || !options.model || !sentModel || !parsed.servedModel || parsed.servedModel === sentModel) return;
|
|
682
|
+
substitutionNoticeQueued = true;
|
|
683
|
+
pendingModelNotices.push({
|
|
684
|
+
id: "model-substitution-1",
|
|
685
|
+
text: `Requested ${sentModel} \u2014 the sandbox answered with ${parsed.servedModel} instead.`
|
|
686
|
+
});
|
|
597
687
|
};
|
|
688
|
+
return { pendingModelNotices, source, captureEffectiveBackend, servedModel, servingModel, failover, modelState };
|
|
598
689
|
}
|
|
599
690
|
|
|
600
691
|
// src/chat-routes/reasoning-clock.ts
|
|
@@ -666,245 +757,106 @@ function textDelta(tracker, key, part, rawDelta) {
|
|
|
666
757
|
tracker.seen.set(key, snapshot);
|
|
667
758
|
return snapshot;
|
|
668
759
|
}
|
|
669
|
-
function parseEffectiveBackend(data) {
|
|
670
|
-
const backend = asRecord(data.effectiveBackend);
|
|
671
|
-
if (!backend) return void 0;
|
|
672
|
-
const provider = asString(backend.provider);
|
|
673
|
-
const model = asString(backend.model);
|
|
674
|
-
const rawSource = asString(backend.source);
|
|
675
|
-
const source = rawSource === "request" || rawSource === "environment" || rawSource === "profile" ? rawSource : void 0;
|
|
676
|
-
if (!provider && !model && !source) return void 0;
|
|
677
|
-
return {
|
|
678
|
-
...model ? { servedModel: model } : {},
|
|
679
|
-
...provider ? { servedProvider: provider } : {},
|
|
680
|
-
...source ? { servedSource: source } : {}
|
|
681
|
-
};
|
|
682
|
-
}
|
|
683
760
|
function toFiniteNumber(value) {
|
|
684
761
|
if (typeof value === "number") return Number.isFinite(value) ? value : null;
|
|
685
762
|
if (typeof value === "string" && value.trim() !== "") {
|
|
686
763
|
const parsed = Number(value);
|
|
687
|
-
return Number.isFinite(parsed) ? parsed : null;
|
|
688
|
-
}
|
|
689
|
-
return null;
|
|
690
|
-
}
|
|
691
|
-
function extractReportedTurnUsage(data) {
|
|
692
|
-
const tokenUsage = asRecord(data?.tokenUsage);
|
|
693
|
-
if (!tokenUsage) return null;
|
|
694
|
-
const inputTokens = toFiniteNumber(tokenUsage.inputTokens);
|
|
695
|
-
const outputTokens = toFiniteNumber(tokenUsage.outputTokens);
|
|
696
|
-
if (inputTokens === null || outputTokens === null) return null;
|
|
697
|
-
const reported = { inputTokens, outputTokens };
|
|
698
|
-
const reasoningTokens = toFiniteNumber(tokenUsage.reasoningTokens);
|
|
699
|
-
if (reasoningTokens !== null) reported.reasoningTokens = reasoningTokens;
|
|
700
|
-
const cacheReadTokens = toFiniteNumber(tokenUsage.cacheReadInputTokens);
|
|
701
|
-
if (cacheReadTokens !== null) reported.cacheReadTokens = cacheReadTokens;
|
|
702
|
-
const cacheWriteTokens = toFiniteNumber(tokenUsage.cacheCreationInputTokens);
|
|
703
|
-
if (cacheWriteTokens !== null) reported.cacheWriteTokens = cacheWriteTokens;
|
|
704
|
-
const costUsd = toFiniteNumber(data?.totalCostUsd) ?? toFiniteNumber(tokenUsage.cost);
|
|
705
|
-
if (costUsd !== null) reported.costUsd = costUsd;
|
|
706
|
-
return reported;
|
|
707
|
-
}
|
|
708
|
-
function extractUsageSnapshot(value) {
|
|
709
|
-
const inputTokens = toFiniteNumber(value?.promptTokens);
|
|
710
|
-
const outputTokens = toFiniteNumber(value?.completionTokens);
|
|
711
|
-
if (inputTokens === null || outputTokens === null || inputTokens < 0 || outputTokens < 0) return null;
|
|
712
|
-
const reported = { inputTokens, outputTokens };
|
|
713
|
-
const reasoningTokens = toFiniteNumber(value?.reasoningTokens);
|
|
714
|
-
if (reasoningTokens !== null && reasoningTokens >= 0) reported.reasoningTokens = reasoningTokens;
|
|
715
|
-
const costUsd = toFiniteNumber(value?.providerCostUsd);
|
|
716
|
-
if (costUsd !== null && costUsd >= 0) reported.costUsd = costUsd;
|
|
717
|
-
return reported;
|
|
718
|
-
}
|
|
719
|
-
function applyTerminalUsage(reported, usage) {
|
|
720
|
-
usage.inputTokens = reported.inputTokens;
|
|
721
|
-
usage.outputTokens = reported.outputTokens;
|
|
722
|
-
if (reported.reasoningTokens !== void 0) usage.reasoningTokens = reported.reasoningTokens;
|
|
723
|
-
if (reported.cacheReadTokens !== void 0) usage.cacheReadTokens = reported.cacheReadTokens;
|
|
724
|
-
if (reported.cacheWriteTokens !== void 0) usage.cacheWriteTokens = reported.cacheWriteTokens;
|
|
725
|
-
if (reported.costUsd !== void 0) usage.costUsd = reported.costUsd;
|
|
726
|
-
}
|
|
727
|
-
function sandboxStreamErrorMessage(data) {
|
|
728
|
-
const record2 = asRecord(data);
|
|
729
|
-
const message = asString(record2?.message) ?? asString(record2?.error);
|
|
730
|
-
if (message) return message;
|
|
731
|
-
try {
|
|
732
|
-
return JSON.stringify(data) || "Sandbox stream returned an error event without details.";
|
|
733
|
-
} catch {
|
|
734
|
-
return "Sandbox stream returned an error event without details.";
|
|
735
|
-
}
|
|
736
|
-
}
|
|
737
|
-
function sandboxStreamErrorCode(data) {
|
|
738
|
-
return asString(asRecord(data)?.code) ?? "sandbox.stream_error";
|
|
739
|
-
}
|
|
740
|
-
function toProducerWireEvent(event) {
|
|
741
|
-
return event;
|
|
742
|
-
}
|
|
743
|
-
function sandboxStreamFailureDiagnostic(error) {
|
|
744
|
-
const streamMessage = error?.streamMessage;
|
|
745
|
-
const message = typeof streamMessage === "string" ? streamMessage : error instanceof Error ? error.message : "Sandbox stream failed";
|
|
746
|
-
const diagnostics = asRecord(error?.diagnostics);
|
|
747
|
-
let diagnosticText;
|
|
748
|
-
if (diagnostics) {
|
|
749
|
-
try {
|
|
750
|
-
diagnosticText = JSON.stringify(diagnostics);
|
|
751
|
-
} catch {
|
|
752
|
-
diagnosticText = "[unserializable diagnostics]";
|
|
753
|
-
}
|
|
754
|
-
}
|
|
755
|
-
const userMessage = [
|
|
756
|
-
"The sandbox model stream stopped before a clean completion.",
|
|
757
|
-
`Error: ${message}`,
|
|
758
|
-
"Please retry. If it repeats, send these support details to the team."
|
|
759
|
-
].join("\n\n");
|
|
760
|
-
const failureNote = diagnosticText ? `sandbox-stream: ${message}; ${diagnosticText}` : `sandbox-stream: ${message}`;
|
|
761
|
-
let code = "sandbox.stream_failed";
|
|
762
|
-
if (error instanceof ModelFailoverTimeoutError) {
|
|
763
|
-
code = error.code;
|
|
764
|
-
} else if (error instanceof ModelFailoverExhaustedError) {
|
|
765
|
-
code = error.upstreamCode ?? code;
|
|
766
|
-
}
|
|
767
|
-
return { userMessage, failureNote, code };
|
|
768
|
-
}
|
|
769
|
-
function createSandboxChatProducer(options) {
|
|
770
|
-
const log = options.log ?? ((message, meta) => console.error(message, meta ?? ""));
|
|
771
|
-
const renderable = options.isRenderableInteraction ?? isRenderableInteractionKind;
|
|
772
|
-
if (options.openEvents && !options.model) {
|
|
773
|
-
throw new Error(
|
|
774
|
-
"createSandboxChatProducer: `openEvents` requires `model` \u2014 failover must know which model it is running"
|
|
775
|
-
);
|
|
776
|
-
}
|
|
777
|
-
if (!options.openEvents && !options.events) {
|
|
778
|
-
throw new Error("createSandboxChatProducer: pass `openEvents` (failover-capable) or `events`");
|
|
779
|
-
}
|
|
780
|
-
if (!options.openEvents && resolveEmptyTurnRetries(options.emptyTurnRetries) > 0) {
|
|
781
|
-
throw new Error(
|
|
782
|
-
"createSandboxChatProducer: `emptyTurnRetries` requires `openEvents` \u2014 a fixed `events` stream cannot be re-opened"
|
|
783
|
-
);
|
|
784
|
-
}
|
|
785
|
-
const chain = options.model ? buildModelChain(options.model, options.modelFailover === false ? [] : options.fallbackModels ?? []) : [];
|
|
786
|
-
const pendingModelNotices = [];
|
|
787
|
-
let modelNoticeCount = 0;
|
|
788
|
-
let failover;
|
|
789
|
-
let source;
|
|
790
|
-
if (options.openEvents) {
|
|
791
|
-
failover = streamWithModelFailover({
|
|
792
|
-
models: chain,
|
|
793
|
-
open: options.openEvents,
|
|
794
|
-
log,
|
|
795
|
-
...options.modelPolicy ? { policy: options.modelPolicy } : {},
|
|
796
|
-
...options.openTimeoutMs !== void 0 ? { openTimeoutMs: options.openTimeoutMs } : {},
|
|
797
|
-
...options.firstResponseTimeoutMs !== void 0 ? { firstResponseTimeoutMs: options.firstResponseTimeoutMs } : {},
|
|
798
|
-
...options.emptyTurnRetries !== void 0 ? { emptyTurnRetries: options.emptyTurnRetries } : {},
|
|
799
|
-
...options.onEmptyTurnRetry ? { onEmptyTurnRetry: options.onEmptyTurnRetry } : {},
|
|
800
|
-
...options.liveLifecycleEvents !== void 0 ? { liveLifecycleEvents: options.liveLifecycleEvents } : {},
|
|
801
|
-
onFallback: (info) => {
|
|
802
|
-
modelNoticeCount += 1;
|
|
803
|
-
pendingModelNotices.push({
|
|
804
|
-
id: `model-fallback-${modelNoticeCount}`,
|
|
805
|
-
// Named models on both sides: a quality regression after a downgrade
|
|
806
|
-
// must be attributable to the model that actually answered. The
|
|
807
|
-
// REASON is condensed — a real edge 5xx arrives as Cloudflare's HTML
|
|
808
|
-
// error page, and the raw text put `<!DOCTYPE html><!--[if lt IE 7]>…`
|
|
809
|
-
// into the customer's transcript. The verbatim text is still on
|
|
810
|
-
// `modelFailover.attempts[].reason` for the operator.
|
|
811
|
-
text: `${info.from} was unavailable (${summarizeFailoverReason(info.reason)}) \u2014 answered with ${info.to} instead.`
|
|
812
|
-
});
|
|
813
|
-
options.onModelFallback?.(info);
|
|
814
|
-
}
|
|
815
|
-
});
|
|
816
|
-
source = failover.events;
|
|
817
|
-
} else {
|
|
818
|
-
source = options.events;
|
|
819
|
-
}
|
|
820
|
-
const servingModel = () => failover?.servingModel() ?? options.model;
|
|
821
|
-
let effectiveBackend;
|
|
822
|
-
let substitutionNoticeQueued = false;
|
|
823
|
-
const servedModel = () => effectiveBackend?.servedModel ?? servingModel();
|
|
824
|
-
const captureEffectiveBackend = (data) => {
|
|
825
|
-
if (!data) return;
|
|
826
|
-
const parsed = parseEffectiveBackend(data);
|
|
827
|
-
if (!parsed) return;
|
|
828
|
-
effectiveBackend = parsed;
|
|
829
|
-
const sentModel = servingModel();
|
|
830
|
-
if (substitutionNoticeQueued || !options.model || !sentModel || !parsed.servedModel || parsed.servedModel === sentModel) return;
|
|
831
|
-
substitutionNoticeQueued = true;
|
|
832
|
-
pendingModelNotices.push({
|
|
833
|
-
id: "model-substitution-1",
|
|
834
|
-
text: `Requested ${sentModel} \u2014 the sandbox answered with ${parsed.servedModel} instead.`
|
|
835
|
-
});
|
|
836
|
-
};
|
|
837
|
-
let fullText = "";
|
|
838
|
-
let terminalObserved = false;
|
|
839
|
-
const partOrder = [];
|
|
840
|
-
const partMap = /* @__PURE__ */ new Map();
|
|
841
|
-
const tracker = { seen: /* @__PURE__ */ new Map() };
|
|
842
|
-
const reasoningClock = createReasoningClock();
|
|
843
|
-
const usage = {};
|
|
844
|
-
const announcedToolArgs = /* @__PURE__ */ new Map();
|
|
845
|
-
const settledTools = /* @__PURE__ */ new Set();
|
|
846
|
-
let stepCounter = 0;
|
|
847
|
-
let danglingToolsTerminalized = false;
|
|
848
|
-
let interactionOutcome = "answered";
|
|
849
|
-
let warningCount = 0;
|
|
850
|
-
const promotedFileParts = /* @__PURE__ */ new Map();
|
|
851
|
-
function recordPersistedPart(part, delta, keyOverride) {
|
|
852
|
-
const persisted = normalizePersistedPart(part);
|
|
853
|
-
if (!persisted) return;
|
|
854
|
-
const key = keyOverride ?? getPartKey(persisted);
|
|
855
|
-
if (!partMap.has(key)) partOrder.push(key);
|
|
856
|
-
partMap.set(key, mergePersistedPart(partMap.get(key), persisted, delta));
|
|
857
|
-
}
|
|
858
|
-
function* emitTerminalizedTools() {
|
|
859
|
-
if (danglingToolsTerminalized) return;
|
|
860
|
-
danglingToolsTerminalized = true;
|
|
861
|
-
const updates = terminalizeDanglingAssistantToolUpdates(partOrder, partMap, fullText);
|
|
862
|
-
for (const part of updates) {
|
|
863
|
-
const toolId = asString(part.id);
|
|
864
|
-
if (!toolId || settledTools.has(toolId)) continue;
|
|
865
|
-
settledTools.add(toolId);
|
|
866
|
-
const state = asRecord(part.state);
|
|
867
|
-
yield {
|
|
868
|
-
type: "tool_result",
|
|
869
|
-
toolCallId: toolId,
|
|
870
|
-
toolName: asString(part.tool) ?? "tool",
|
|
871
|
-
outcome: {
|
|
872
|
-
ok: false,
|
|
873
|
-
...asString(state?.error) ? { message: asString(state?.error) } : {}
|
|
874
|
-
}
|
|
875
|
-
};
|
|
876
|
-
}
|
|
877
|
-
}
|
|
878
|
-
function* emitFinalUsage() {
|
|
879
|
-
const promptTokens = usage.inputTokens ?? 0;
|
|
880
|
-
const completionTokens = usage.outputTokens ?? 0;
|
|
881
|
-
if (promptTokens || completionTokens) {
|
|
882
|
-
yield {
|
|
883
|
-
type: "usage",
|
|
884
|
-
usage: {
|
|
885
|
-
promptTokens,
|
|
886
|
-
completionTokens,
|
|
887
|
-
...usage.reasoningTokens !== void 0 ? { reasoningTokens: usage.reasoningTokens } : {},
|
|
888
|
-
...usage.costUsd !== void 0 ? { providerCostUsd: usage.costUsd } : {}
|
|
889
|
-
}
|
|
890
|
-
};
|
|
891
|
-
}
|
|
764
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
892
765
|
}
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
766
|
+
return null;
|
|
767
|
+
}
|
|
768
|
+
function extractReportedTurnUsage(data) {
|
|
769
|
+
const tokenUsage = asRecord(data?.tokenUsage);
|
|
770
|
+
if (!tokenUsage) return null;
|
|
771
|
+
const inputTokens = toFiniteNumber(tokenUsage.inputTokens);
|
|
772
|
+
const outputTokens = toFiniteNumber(tokenUsage.outputTokens);
|
|
773
|
+
if (inputTokens === null || outputTokens === null) return null;
|
|
774
|
+
const reported = { inputTokens, outputTokens };
|
|
775
|
+
const reasoningTokens = toFiniteNumber(tokenUsage.reasoningTokens);
|
|
776
|
+
if (reasoningTokens !== null) reported.reasoningTokens = reasoningTokens;
|
|
777
|
+
const cacheReadTokens = toFiniteNumber(tokenUsage.cacheReadInputTokens);
|
|
778
|
+
if (cacheReadTokens !== null) reported.cacheReadTokens = cacheReadTokens;
|
|
779
|
+
const cacheWriteTokens = toFiniteNumber(tokenUsage.cacheCreationInputTokens);
|
|
780
|
+
if (cacheWriteTokens !== null) reported.cacheWriteTokens = cacheWriteTokens;
|
|
781
|
+
const costUsd = toFiniteNumber(data?.totalCostUsd) ?? toFiniteNumber(tokenUsage.cost);
|
|
782
|
+
if (costUsd !== null) reported.costUsd = costUsd;
|
|
783
|
+
return reported;
|
|
784
|
+
}
|
|
785
|
+
function extractUsageSnapshot(value) {
|
|
786
|
+
const inputTokens = toFiniteNumber(value?.promptTokens);
|
|
787
|
+
const outputTokens = toFiniteNumber(value?.completionTokens);
|
|
788
|
+
if (inputTokens === null || outputTokens === null || inputTokens < 0 || outputTokens < 0) return null;
|
|
789
|
+
const reported = { inputTokens, outputTokens };
|
|
790
|
+
const reasoningTokens = toFiniteNumber(value?.reasoningTokens);
|
|
791
|
+
if (reasoningTokens !== null && reasoningTokens >= 0) reported.reasoningTokens = reasoningTokens;
|
|
792
|
+
const costUsd = toFiniteNumber(value?.providerCostUsd);
|
|
793
|
+
if (costUsd !== null && costUsd >= 0) reported.costUsd = costUsd;
|
|
794
|
+
return reported;
|
|
795
|
+
}
|
|
796
|
+
function applyTerminalUsage(reported, usage) {
|
|
797
|
+
usage.inputTokens = reported.inputTokens;
|
|
798
|
+
usage.outputTokens = reported.outputTokens;
|
|
799
|
+
if (reported.reasoningTokens !== void 0) usage.reasoningTokens = reported.reasoningTokens;
|
|
800
|
+
if (reported.cacheReadTokens !== void 0) usage.cacheReadTokens = reported.cacheReadTokens;
|
|
801
|
+
if (reported.cacheWriteTokens !== void 0) usage.cacheWriteTokens = reported.cacheWriteTokens;
|
|
802
|
+
if (reported.costUsd !== void 0) usage.costUsd = reported.costUsd;
|
|
803
|
+
}
|
|
804
|
+
function sandboxStreamErrorMessage(data) {
|
|
805
|
+
const record2 = asRecord(data);
|
|
806
|
+
const message = asString(record2?.message) ?? asString(record2?.error);
|
|
807
|
+
if (message) return message;
|
|
808
|
+
try {
|
|
809
|
+
return JSON.stringify(data) || "Sandbox stream returned an error event without details.";
|
|
810
|
+
} catch {
|
|
811
|
+
return "Sandbox stream returned an error event without details.";
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
function sandboxStreamErrorCode(data) {
|
|
815
|
+
return asString(asRecord(data)?.code) ?? "sandbox.stream_error";
|
|
816
|
+
}
|
|
817
|
+
function toProducerWireEvent(event) {
|
|
818
|
+
return event;
|
|
819
|
+
}
|
|
820
|
+
function sandboxStreamFailureDiagnostic(error) {
|
|
821
|
+
const streamMessage = error?.streamMessage;
|
|
822
|
+
const message = typeof streamMessage === "string" ? streamMessage : error instanceof Error ? error.message : "Sandbox stream failed";
|
|
823
|
+
const diagnostics = asRecord(error?.diagnostics);
|
|
824
|
+
let diagnosticText;
|
|
825
|
+
if (diagnostics) {
|
|
826
|
+
try {
|
|
827
|
+
diagnosticText = JSON.stringify(diagnostics);
|
|
828
|
+
} catch {
|
|
829
|
+
diagnosticText = "[unserializable diagnostics]";
|
|
899
830
|
}
|
|
900
831
|
}
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
832
|
+
const userMessage = [
|
|
833
|
+
"The sandbox model stream stopped before a clean completion.",
|
|
834
|
+
`Error: ${message}`,
|
|
835
|
+
"Please retry. If it repeats, send these support details to the team."
|
|
836
|
+
].join("\n\n");
|
|
837
|
+
const failureNote = diagnosticText ? `sandbox-stream: ${message}; ${diagnosticText}` : `sandbox-stream: ${message}`;
|
|
838
|
+
let code = "sandbox.stream_failed";
|
|
839
|
+
if (error instanceof ModelFailoverTimeoutError) {
|
|
840
|
+
code = error.code;
|
|
841
|
+
} else if (error instanceof ModelFailoverExhaustedError) {
|
|
842
|
+
code = error.upstreamCode ?? code;
|
|
907
843
|
}
|
|
844
|
+
return { userMessage, failureNote, code };
|
|
845
|
+
}
|
|
846
|
+
function createSandboxChatProducer(options) {
|
|
847
|
+
const log = options.log ?? ((message, meta) => console.error(message, meta ?? ""));
|
|
848
|
+
const renderable = options.isRenderableInteraction ?? isRenderableInteractionKind;
|
|
849
|
+
const { pendingModelNotices, source, captureEffectiveBackend, servedModel, servingModel, failover, modelState } = createSandboxModelSource(options, log);
|
|
850
|
+
const projectionState = {
|
|
851
|
+
fullText: "",
|
|
852
|
+
terminalObserved: false,
|
|
853
|
+
stepCounter: 0,
|
|
854
|
+
danglingToolsTerminalized: false,
|
|
855
|
+
interactionOutcome: "answered",
|
|
856
|
+
warningCount: 0,
|
|
857
|
+
errorNoticeCount: 0
|
|
858
|
+
};
|
|
859
|
+
const { timedParts, drainModelNotices, tracker, recordPersistedPart, reasoningClock, partMap, announcedToolArgs, settledTools, usage, promotedFileParts, emitFinalUsage, emitTerminalizedTools, emitErrorNotice, partOrder } = createSandboxProjection(projectionState, pendingModelNotices);
|
|
908
860
|
async function* stream() {
|
|
909
861
|
try {
|
|
910
862
|
for await (const raw of source) {
|
|
@@ -915,105 +867,7 @@ function createSandboxChatProducer(options) {
|
|
|
915
867
|
const normalized = normalizeToolEvent({ type: record2.type, data: asRecord(record2.data) });
|
|
916
868
|
const event = normalized.type === "message.part.updated" ? normalized : { type: record2.type, data: asRecord(record2.data) };
|
|
917
869
|
if (event.type === "message.part.updated") {
|
|
918
|
-
|
|
919
|
-
if (!part) continue;
|
|
920
|
-
const rawDelta = event.data?.delta;
|
|
921
|
-
const partType = String(part.type ?? "");
|
|
922
|
-
if (partType === "text" || partType === "reasoning") {
|
|
923
|
-
const key = getPartKey(part);
|
|
924
|
-
const delta = textDelta(tracker, key, part, rawDelta);
|
|
925
|
-
recordPersistedPart(part, delta || void 0);
|
|
926
|
-
if (delta) {
|
|
927
|
-
if (partType === "reasoning") reasoningClock.reasoning(key);
|
|
928
|
-
else reasoningClock.settle();
|
|
929
|
-
if (partType === "text") fullText += delta;
|
|
930
|
-
yield { type: partType, text: delta };
|
|
931
|
-
}
|
|
932
|
-
continue;
|
|
933
|
-
}
|
|
934
|
-
if (partType === "tool") {
|
|
935
|
-
reasoningClock.settle();
|
|
936
|
-
recordPersistedPart(part, void 0);
|
|
937
|
-
const persisted = partMap.get(getPartKey(part));
|
|
938
|
-
const state = asRecord(persisted?.state);
|
|
939
|
-
const toolId = String(persisted?.id ?? "");
|
|
940
|
-
const toolName = String(persisted?.tool ?? "tool");
|
|
941
|
-
const args = asRecord(state?.input) ?? {};
|
|
942
|
-
const hasPopulatedArgs = Object.keys(args).length > 0;
|
|
943
|
-
const announcedWithPopulatedArgs = announcedToolArgs.get(toolId);
|
|
944
|
-
if (toolId && (announcedWithPopulatedArgs === void 0 || !announcedWithPopulatedArgs && hasPopulatedArgs && !settledTools.has(toolId))) {
|
|
945
|
-
announcedToolArgs.set(toolId, hasPopulatedArgs);
|
|
946
|
-
yield {
|
|
947
|
-
type: "tool_call",
|
|
948
|
-
call: { toolCallId: toolId, toolName, args }
|
|
949
|
-
};
|
|
950
|
-
}
|
|
951
|
-
const status = String(state?.status ?? "");
|
|
952
|
-
if (toolId && (status === "completed" || status === "error") && !settledTools.has(toolId)) {
|
|
953
|
-
settledTools.add(toolId);
|
|
954
|
-
yield {
|
|
955
|
-
type: "tool_result",
|
|
956
|
-
toolCallId: toolId,
|
|
957
|
-
toolName,
|
|
958
|
-
outcome: {
|
|
959
|
-
ok: status === "completed",
|
|
960
|
-
...state?.output !== void 0 ? { result: state.output } : {},
|
|
961
|
-
...asString(state?.error) ? { message: asString(state?.error) } : {}
|
|
962
|
-
}
|
|
963
|
-
};
|
|
964
|
-
}
|
|
965
|
-
continue;
|
|
966
|
-
}
|
|
967
|
-
if (partType === "step-finish") {
|
|
968
|
-
addStepFinishUsage(part, usage);
|
|
969
|
-
recordPersistedPart(part, void 0, `step-finish:#${stepCounter++}`);
|
|
970
|
-
const promptTokens = usage.inputTokens ?? 0;
|
|
971
|
-
const completionTokens = usage.outputTokens ?? 0;
|
|
972
|
-
if (promptTokens || completionTokens) {
|
|
973
|
-
yield {
|
|
974
|
-
type: "usage",
|
|
975
|
-
usage: {
|
|
976
|
-
promptTokens,
|
|
977
|
-
completionTokens,
|
|
978
|
-
...usage.reasoningTokens !== void 0 ? { reasoningTokens: usage.reasoningTokens } : {},
|
|
979
|
-
...usage.costUsd !== void 0 ? { providerCostUsd: usage.costUsd } : {}
|
|
980
|
-
}
|
|
981
|
-
};
|
|
982
|
-
}
|
|
983
|
-
continue;
|
|
984
|
-
}
|
|
985
|
-
if (partType === "step-start") {
|
|
986
|
-
recordPersistedPart(part, void 0, `step-start:#${stepCounter}`);
|
|
987
|
-
continue;
|
|
988
|
-
}
|
|
989
|
-
if (partType === "file" && options.promoteFilePart) {
|
|
990
|
-
const promote = options.promoteFilePart;
|
|
991
|
-
const rawId = asString(part.id);
|
|
992
|
-
const rawUrl = asString(part.url);
|
|
993
|
-
const memoKey = rawId ? `id:${rawId}` : rawUrl ? `url:${rawUrl}` : void 0;
|
|
994
|
-
const attempt = () => Promise.resolve().then(() => promote(part)).catch((err) => {
|
|
995
|
-
const reason = err instanceof Error ? err.message : String(err);
|
|
996
|
-
log("[chat-routes] file part promotion threw", { key: memoKey ?? "(keyless)", error: reason });
|
|
997
|
-
return { succeeded: false, reason };
|
|
998
|
-
});
|
|
999
|
-
let pending;
|
|
1000
|
-
if (memoKey) {
|
|
1001
|
-
pending = promotedFileParts.get(memoKey) ?? attempt();
|
|
1002
|
-
promotedFileParts.set(memoKey, pending);
|
|
1003
|
-
} else {
|
|
1004
|
-
pending = attempt();
|
|
1005
|
-
}
|
|
1006
|
-
const outcome = await pending;
|
|
1007
|
-
if (outcome.succeeded) {
|
|
1008
|
-
recordPersistedPart(outcome.part, void 0, outcome.key);
|
|
1009
|
-
} else if (outcome.part) {
|
|
1010
|
-
recordPersistedPart(outcome.part, void 0, outcome.key);
|
|
1011
|
-
} else {
|
|
1012
|
-
recordPersistedPart(part, void 0);
|
|
1013
|
-
}
|
|
1014
|
-
continue;
|
|
1015
|
-
}
|
|
1016
|
-
recordPersistedPart(part, void 0);
|
|
870
|
+
yield* projectSandboxMessagePart(event, tracker, recordPersistedPart, reasoningClock, projectionState, partMap, announcedToolArgs, settledTools, usage, options, log, promotedFileParts);
|
|
1017
871
|
continue;
|
|
1018
872
|
}
|
|
1019
873
|
if (event.type === "interaction") {
|
|
@@ -1086,10 +940,10 @@ function createSandboxChatProducer(options) {
|
|
|
1086
940
|
if (event.type === "warning") {
|
|
1087
941
|
const message = asString(event.data?.message);
|
|
1088
942
|
if (message) {
|
|
1089
|
-
warningCount += 1;
|
|
943
|
+
projectionState.warningCount += 1;
|
|
1090
944
|
const code = asString(event.data?.code);
|
|
1091
945
|
const text = code ? `${code}: ${message}` : message;
|
|
1092
|
-
const notice = noticePart("warning", `warning-${warningCount}`, text);
|
|
946
|
+
const notice = noticePart("warning", `warning-${projectionState.warningCount}`, text);
|
|
1093
947
|
recordPersistedPart(notice, void 0, noticePartKey(notice.id));
|
|
1094
948
|
yield { type: "notice", id: notice.id, noticeKind: "warning", text };
|
|
1095
949
|
}
|
|
@@ -1103,9 +957,9 @@ function createSandboxChatProducer(options) {
|
|
|
1103
957
|
continue;
|
|
1104
958
|
}
|
|
1105
959
|
if (event.type === "result") {
|
|
1106
|
-
terminalObserved = true;
|
|
960
|
+
projectionState.terminalObserved = true;
|
|
1107
961
|
const finalText = asString(event.data?.finalText);
|
|
1108
|
-
if (finalText) fullText = finalText;
|
|
962
|
+
if (finalText) projectionState.fullText = finalText;
|
|
1109
963
|
const reported = extractReportedTurnUsage(asRecord(event.data));
|
|
1110
964
|
if (reported) {
|
|
1111
965
|
applyTerminalUsage(reported, usage);
|
|
@@ -1123,7 +977,7 @@ function createSandboxChatProducer(options) {
|
|
|
1123
977
|
continue;
|
|
1124
978
|
}
|
|
1125
979
|
if (event.type === "done") {
|
|
1126
|
-
terminalObserved = true;
|
|
980
|
+
projectionState.terminalObserved = true;
|
|
1127
981
|
const reported = extractReportedTurnUsage(asRecord(event.data));
|
|
1128
982
|
if (reported) {
|
|
1129
983
|
applyTerminalUsage(reported, usage);
|
|
@@ -1135,7 +989,7 @@ function createSandboxChatProducer(options) {
|
|
|
1135
989
|
}
|
|
1136
990
|
if (event.type === "error") {
|
|
1137
991
|
const message = sandboxStreamErrorMessage(event.data);
|
|
1138
|
-
const errorContent = fullText.trim() ? `The sandbox model stream stopped before a clean completion.
|
|
992
|
+
const errorContent = projectionState.fullText.trim() ? `The sandbox model stream stopped before a clean completion.
|
|
1139
993
|
|
|
1140
994
|
Error: ${message}` : `The sandbox agent returned an error before producing a visible answer.
|
|
1141
995
|
|
|
@@ -1143,14 +997,14 @@ Error: ${message}`;
|
|
|
1143
997
|
if (options.errorNotice) {
|
|
1144
998
|
yield* emitErrorNotice(errorContent, sandboxStreamErrorCode(event.data));
|
|
1145
999
|
} else if (options.includeErrorText !== false) {
|
|
1146
|
-
const errorDelta = fullText ? `
|
|
1000
|
+
const errorDelta = projectionState.fullText ? `
|
|
1147
1001
|
|
|
1148
1002
|
---
|
|
1149
1003
|
${errorContent}` : errorContent;
|
|
1150
|
-
fullText += errorDelta;
|
|
1004
|
+
projectionState.fullText += errorDelta;
|
|
1151
1005
|
yield { type: "text", text: errorDelta };
|
|
1152
1006
|
}
|
|
1153
|
-
interactionOutcome = "expired";
|
|
1007
|
+
projectionState.interactionOutcome = "expired";
|
|
1154
1008
|
yield* emitTerminalizedTools();
|
|
1155
1009
|
yield toProducerWireEvent(record2);
|
|
1156
1010
|
continue;
|
|
@@ -1167,14 +1021,14 @@ ${errorContent}` : errorContent;
|
|
|
1167
1021
|
if (options.errorNotice) {
|
|
1168
1022
|
yield* emitErrorNotice(diagnostic.userMessage, diagnostic.code);
|
|
1169
1023
|
} else if (options.includeErrorText !== false) {
|
|
1170
|
-
const errorDelta = fullText ? `
|
|
1024
|
+
const errorDelta = projectionState.fullText ? `
|
|
1171
1025
|
|
|
1172
1026
|
---
|
|
1173
1027
|
${diagnostic.userMessage}` : diagnostic.userMessage;
|
|
1174
|
-
fullText += errorDelta;
|
|
1028
|
+
projectionState.fullText += errorDelta;
|
|
1175
1029
|
yield { type: "text", text: errorDelta };
|
|
1176
1030
|
}
|
|
1177
|
-
interactionOutcome = "expired";
|
|
1031
|
+
projectionState.interactionOutcome = "expired";
|
|
1178
1032
|
yield* emitTerminalizedTools();
|
|
1179
1033
|
yield {
|
|
1180
1034
|
type: "error",
|
|
@@ -1188,29 +1042,20 @@ ${diagnostic.userMessage}` : diagnostic.userMessage;
|
|
|
1188
1042
|
reasoningClock.settle();
|
|
1189
1043
|
}
|
|
1190
1044
|
}
|
|
1191
|
-
const timedParts = () => {
|
|
1192
|
-
const timed = new Map(partMap);
|
|
1193
|
-
for (const [key, part] of partMap) {
|
|
1194
|
-
if (part.type !== "reasoning") continue;
|
|
1195
|
-
const time = reasoningClock.time(key, asRecord(part.time));
|
|
1196
|
-
if (time) timed.set(key, { ...part, time });
|
|
1197
|
-
}
|
|
1198
|
-
return timed;
|
|
1199
|
-
};
|
|
1200
1045
|
return {
|
|
1201
1046
|
stream: stream(),
|
|
1202
|
-
finalText: () => fullText,
|
|
1203
|
-
terminalObserved: () => terminalObserved,
|
|
1047
|
+
finalText: () => projectionState.fullText,
|
|
1048
|
+
terminalObserved: () => projectionState.terminalObserved,
|
|
1204
1049
|
assistantParts: () => finalizePendingInteractionParts(
|
|
1205
|
-
finalizeAssistantParts(partOrder, timedParts(), fullText),
|
|
1206
|
-
interactionOutcome
|
|
1050
|
+
finalizeAssistantParts(partOrder, timedParts(), projectionState.fullText),
|
|
1051
|
+
projectionState.interactionOutcome
|
|
1207
1052
|
),
|
|
1208
1053
|
// Mid-stream snapshot for incremental persistence: the same accumulators,
|
|
1209
1054
|
// WITHOUT the two completion-time settlements (`terminalizeDanglingTool*`
|
|
1210
1055
|
// and `finalizePendingInteractionParts`). A running tool and an unanswered
|
|
1211
1056
|
// ask are the correct live state; settling them early would persist
|
|
1212
1057
|
// phantom failures the final write then reverses.
|
|
1213
|
-
draftParts: () => draftAssistantParts(partOrder, timedParts(), fullText),
|
|
1058
|
+
draftParts: () => draftAssistantParts(partOrder, timedParts(), projectionState.fullText),
|
|
1214
1059
|
usage: () => usage,
|
|
1215
1060
|
// A GETTER, not a captured value: `turn-routes` reads `producer.model` at
|
|
1216
1061
|
// draft-snapshot and persist time, both of which happen after the stream
|
|
@@ -1227,11 +1072,191 @@ ${diagnostic.userMessage}` : diagnostic.userMessage;
|
|
|
1227
1072
|
}),
|
|
1228
1073
|
modelAttribution: () => ({
|
|
1229
1074
|
...options.model ? { requestedModel: options.model } : {},
|
|
1230
|
-
...effectiveBackend ?? {},
|
|
1231
|
-
echoReceived: effectiveBackend !== void 0
|
|
1075
|
+
...modelState.effectiveBackend ?? {},
|
|
1076
|
+
echoReceived: modelState.effectiveBackend !== void 0
|
|
1232
1077
|
})
|
|
1233
1078
|
};
|
|
1234
1079
|
}
|
|
1080
|
+
function createSandboxProjection(projectionState, pendingModelNotices) {
|
|
1081
|
+
const partOrder = [];
|
|
1082
|
+
const partMap = /* @__PURE__ */ new Map();
|
|
1083
|
+
const tracker = { seen: /* @__PURE__ */ new Map() };
|
|
1084
|
+
const reasoningClock = createReasoningClock();
|
|
1085
|
+
const usage = {};
|
|
1086
|
+
const announcedToolArgs = /* @__PURE__ */ new Map();
|
|
1087
|
+
const settledTools = /* @__PURE__ */ new Set();
|
|
1088
|
+
const promotedFileParts = /* @__PURE__ */ new Map();
|
|
1089
|
+
function recordPersistedPart(part, delta, keyOverride) {
|
|
1090
|
+
const persisted = normalizePersistedPart(part);
|
|
1091
|
+
if (!persisted) return;
|
|
1092
|
+
const key = keyOverride ?? getPartKey(persisted);
|
|
1093
|
+
if (!partMap.has(key)) partOrder.push(key);
|
|
1094
|
+
partMap.set(key, mergePersistedPart(partMap.get(key), persisted, delta));
|
|
1095
|
+
}
|
|
1096
|
+
function* emitTerminalizedTools() {
|
|
1097
|
+
if (projectionState.danglingToolsTerminalized) return;
|
|
1098
|
+
projectionState.danglingToolsTerminalized = true;
|
|
1099
|
+
const updates = terminalizeDanglingAssistantToolUpdates(partOrder, partMap, projectionState.fullText);
|
|
1100
|
+
for (const part of updates) {
|
|
1101
|
+
const toolId = asString(part.id);
|
|
1102
|
+
if (!toolId || settledTools.has(toolId)) continue;
|
|
1103
|
+
settledTools.add(toolId);
|
|
1104
|
+
const state = asRecord(part.state);
|
|
1105
|
+
yield {
|
|
1106
|
+
type: "tool_result",
|
|
1107
|
+
toolCallId: toolId,
|
|
1108
|
+
toolName: asString(part.tool) ?? "tool",
|
|
1109
|
+
outcome: {
|
|
1110
|
+
ok: false,
|
|
1111
|
+
...asString(state?.error) ? { message: asString(state?.error) } : {}
|
|
1112
|
+
}
|
|
1113
|
+
};
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
function* emitFinalUsage() {
|
|
1117
|
+
const promptTokens = usage.inputTokens ?? 0;
|
|
1118
|
+
const completionTokens = usage.outputTokens ?? 0;
|
|
1119
|
+
if (promptTokens || completionTokens) {
|
|
1120
|
+
yield {
|
|
1121
|
+
type: "usage",
|
|
1122
|
+
usage: {
|
|
1123
|
+
promptTokens,
|
|
1124
|
+
completionTokens,
|
|
1125
|
+
...usage.reasoningTokens !== void 0 ? { reasoningTokens: usage.reasoningTokens } : {},
|
|
1126
|
+
...usage.costUsd !== void 0 ? { providerCostUsd: usage.costUsd } : {}
|
|
1127
|
+
}
|
|
1128
|
+
};
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
function* drainModelNotices() {
|
|
1132
|
+
while (pendingModelNotices.length > 0) {
|
|
1133
|
+
const queued = pendingModelNotices.shift();
|
|
1134
|
+
const notice = noticePart("warning", queued.id, queued.text);
|
|
1135
|
+
recordPersistedPart(notice, void 0, noticePartKey(notice.id));
|
|
1136
|
+
yield { type: "notice", id: notice.id, noticeKind: "warning", text: queued.text };
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
function* emitErrorNotice(text, code) {
|
|
1140
|
+
projectionState.errorNoticeCount += 1;
|
|
1141
|
+
const notice = noticePart("error", `error-${projectionState.errorNoticeCount}`, text, code);
|
|
1142
|
+
recordPersistedPart(notice, void 0, noticePartKey(notice.id));
|
|
1143
|
+
yield { type: "notice", id: notice.id, noticeKind: "error", text, code };
|
|
1144
|
+
}
|
|
1145
|
+
const timedParts = () => {
|
|
1146
|
+
const timed = new Map(partMap);
|
|
1147
|
+
for (const [key, part] of partMap) {
|
|
1148
|
+
if (part.type !== "reasoning") continue;
|
|
1149
|
+
const time = reasoningClock.time(key, asRecord(part.time));
|
|
1150
|
+
if (time) timed.set(key, { ...part, time });
|
|
1151
|
+
}
|
|
1152
|
+
return timed;
|
|
1153
|
+
};
|
|
1154
|
+
return { timedParts, drainModelNotices, tracker, recordPersistedPart, reasoningClock, partMap, announcedToolArgs, settledTools, usage, promotedFileParts, emitFinalUsage, emitTerminalizedTools, emitErrorNotice, partOrder };
|
|
1155
|
+
}
|
|
1156
|
+
async function* projectSandboxMessagePart(event, tracker, recordPersistedPart, reasoningClock, projectionState, partMap, announcedToolArgs, settledTools, usage, options, log, promotedFileParts) {
|
|
1157
|
+
if (event.type === "message.part.updated") {
|
|
1158
|
+
const part = asRecord(event.data?.part);
|
|
1159
|
+
if (!part) return;
|
|
1160
|
+
const rawDelta = event.data?.delta;
|
|
1161
|
+
const partType = String(part.type ?? "");
|
|
1162
|
+
if (partType === "text" || partType === "reasoning") {
|
|
1163
|
+
const key = getPartKey(part);
|
|
1164
|
+
const delta = textDelta(tracker, key, part, rawDelta);
|
|
1165
|
+
recordPersistedPart(part, delta || void 0);
|
|
1166
|
+
if (delta) {
|
|
1167
|
+
if (partType === "reasoning") reasoningClock.reasoning(key);
|
|
1168
|
+
else reasoningClock.settle();
|
|
1169
|
+
if (partType === "text") projectionState.fullText += delta;
|
|
1170
|
+
yield { type: partType, text: delta };
|
|
1171
|
+
}
|
|
1172
|
+
return;
|
|
1173
|
+
}
|
|
1174
|
+
if (partType === "tool") {
|
|
1175
|
+
reasoningClock.settle();
|
|
1176
|
+
recordPersistedPart(part, void 0);
|
|
1177
|
+
const persisted = partMap.get(getPartKey(part));
|
|
1178
|
+
const state = asRecord(persisted?.state);
|
|
1179
|
+
const toolId = String(persisted?.id ?? "");
|
|
1180
|
+
const toolName = String(persisted?.tool ?? "tool");
|
|
1181
|
+
const args = asRecord(state?.input) ?? {};
|
|
1182
|
+
const hasPopulatedArgs = Object.keys(args).length > 0;
|
|
1183
|
+
const announcedWithPopulatedArgs = announcedToolArgs.get(toolId);
|
|
1184
|
+
if (toolId && (announcedWithPopulatedArgs === void 0 || !announcedWithPopulatedArgs && hasPopulatedArgs && !settledTools.has(toolId))) {
|
|
1185
|
+
announcedToolArgs.set(toolId, hasPopulatedArgs);
|
|
1186
|
+
yield {
|
|
1187
|
+
type: "tool_call",
|
|
1188
|
+
call: { toolCallId: toolId, toolName, args }
|
|
1189
|
+
};
|
|
1190
|
+
}
|
|
1191
|
+
const status = String(state?.status ?? "");
|
|
1192
|
+
if (toolId && (status === "completed" || status === "error") && !settledTools.has(toolId)) {
|
|
1193
|
+
settledTools.add(toolId);
|
|
1194
|
+
yield {
|
|
1195
|
+
type: "tool_result",
|
|
1196
|
+
toolCallId: toolId,
|
|
1197
|
+
toolName,
|
|
1198
|
+
outcome: {
|
|
1199
|
+
ok: status === "completed",
|
|
1200
|
+
...state?.output !== void 0 ? { result: state.output } : {},
|
|
1201
|
+
...asString(state?.error) ? { message: asString(state?.error) } : {}
|
|
1202
|
+
}
|
|
1203
|
+
};
|
|
1204
|
+
}
|
|
1205
|
+
return;
|
|
1206
|
+
}
|
|
1207
|
+
if (partType === "step-finish") {
|
|
1208
|
+
addStepFinishUsage(part, usage);
|
|
1209
|
+
recordPersistedPart(part, void 0, `step-finish:#${projectionState.stepCounter++}`);
|
|
1210
|
+
const promptTokens = usage.inputTokens ?? 0;
|
|
1211
|
+
const completionTokens = usage.outputTokens ?? 0;
|
|
1212
|
+
if (promptTokens || completionTokens) {
|
|
1213
|
+
yield {
|
|
1214
|
+
type: "usage",
|
|
1215
|
+
usage: {
|
|
1216
|
+
promptTokens,
|
|
1217
|
+
completionTokens,
|
|
1218
|
+
...usage.reasoningTokens !== void 0 ? { reasoningTokens: usage.reasoningTokens } : {},
|
|
1219
|
+
...usage.costUsd !== void 0 ? { providerCostUsd: usage.costUsd } : {}
|
|
1220
|
+
}
|
|
1221
|
+
};
|
|
1222
|
+
}
|
|
1223
|
+
return;
|
|
1224
|
+
}
|
|
1225
|
+
if (partType === "step-start") {
|
|
1226
|
+
recordPersistedPart(part, void 0, `step-start:#${projectionState.stepCounter}`);
|
|
1227
|
+
return;
|
|
1228
|
+
}
|
|
1229
|
+
if (partType === "file" && options.promoteFilePart) {
|
|
1230
|
+
const promote = options.promoteFilePart;
|
|
1231
|
+
const rawId = asString(part.id);
|
|
1232
|
+
const rawUrl = asString(part.url);
|
|
1233
|
+
const memoKey = rawId ? `id:${rawId}` : rawUrl ? `url:${rawUrl}` : void 0;
|
|
1234
|
+
const attempt = () => Promise.resolve().then(() => promote(part)).catch((err) => {
|
|
1235
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
1236
|
+
log("[chat-routes] file part promotion threw", { key: memoKey ?? "(keyless)", error: reason });
|
|
1237
|
+
return { succeeded: false, reason };
|
|
1238
|
+
});
|
|
1239
|
+
let pending;
|
|
1240
|
+
if (memoKey) {
|
|
1241
|
+
pending = promotedFileParts.get(memoKey) ?? attempt();
|
|
1242
|
+
promotedFileParts.set(memoKey, pending);
|
|
1243
|
+
} else {
|
|
1244
|
+
pending = attempt();
|
|
1245
|
+
}
|
|
1246
|
+
const outcome = await pending;
|
|
1247
|
+
if (outcome.succeeded) {
|
|
1248
|
+
recordPersistedPart(outcome.part, void 0, outcome.key);
|
|
1249
|
+
} else if (outcome.part) {
|
|
1250
|
+
recordPersistedPart(outcome.part, void 0, outcome.key);
|
|
1251
|
+
} else {
|
|
1252
|
+
recordPersistedPart(part, void 0);
|
|
1253
|
+
}
|
|
1254
|
+
return;
|
|
1255
|
+
}
|
|
1256
|
+
recordPersistedPart(part, void 0);
|
|
1257
|
+
return;
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1235
1260
|
|
|
1236
1261
|
// src/chat-routes/router-producer.ts
|
|
1237
1262
|
function createRouterTurnProducer(options) {
|
|
@@ -2741,6 +2766,18 @@ function inspectAtomicAttachmentWriteResult(value, ownership) {
|
|
|
2741
2766
|
}
|
|
2742
2767
|
return void 0;
|
|
2743
2768
|
}
|
|
2769
|
+
function logAttachmentStorageError(logger, message, fields) {
|
|
2770
|
+
try {
|
|
2771
|
+
const safeFields = Object.fromEntries(
|
|
2772
|
+
Object.entries(fields).map(([key, value]) => [
|
|
2773
|
+
key,
|
|
2774
|
+
typeof value === "string" ? redactErrorMessage(value) : value
|
|
2775
|
+
])
|
|
2776
|
+
);
|
|
2777
|
+
logger.error(message, safeFields);
|
|
2778
|
+
} catch {
|
|
2779
|
+
}
|
|
2780
|
+
}
|
|
2744
2781
|
|
|
2745
2782
|
// src/chat-routes/promote-file-part.ts
|
|
2746
2783
|
var PROMOTE_MAX_FILE_BYTES = 10 * 1024 * 1024;
|
|
@@ -2835,18 +2872,6 @@ function defaultBuildAttachmentPath(args) {
|
|
|
2835
2872
|
const base = extension ? args.filename.slice(0, -extension.length) : args.filename;
|
|
2836
2873
|
return `uploads/agent/${args.date}/${base}-${args.hash8}${extension}`;
|
|
2837
2874
|
}
|
|
2838
|
-
function logPromotionStorageError(logger, message, fields) {
|
|
2839
|
-
try {
|
|
2840
|
-
const safeFields = Object.fromEntries(
|
|
2841
|
-
Object.entries(fields).map(([key, value]) => [
|
|
2842
|
-
key,
|
|
2843
|
-
typeof value === "string" ? redactErrorMessage(value) : value
|
|
2844
|
-
])
|
|
2845
|
-
);
|
|
2846
|
-
logger.error(message, safeFields);
|
|
2847
|
-
} catch {
|
|
2848
|
-
}
|
|
2849
|
-
}
|
|
2850
2875
|
async function compensatePromotionWrite(writer, scopeId, ownership, receipt) {
|
|
2851
2876
|
try {
|
|
2852
2877
|
await receipt.rollback();
|
|
@@ -2897,7 +2922,7 @@ async function promoteAgentFilePart(options) {
|
|
|
2897
2922
|
const date = now().toISOString().split("T")[0] ?? "";
|
|
2898
2923
|
logicalPath = buildAttachmentPath({ filename, hash8: digest, date, mediaType, kind });
|
|
2899
2924
|
} catch (error) {
|
|
2900
|
-
|
|
2925
|
+
logAttachmentStorageError(logger, "[promote-file-part] path planning failed", {
|
|
2901
2926
|
error: redactErrorMessage(error)
|
|
2902
2927
|
});
|
|
2903
2928
|
return { succeeded: false, filename, reason: ATTACHMENT_STORAGE_FAILURE_MESSAGE };
|
|
@@ -2913,7 +2938,7 @@ async function promoteAgentFilePart(options) {
|
|
|
2913
2938
|
});
|
|
2914
2939
|
} catch (error) {
|
|
2915
2940
|
const reason = redactErrorMessage(error);
|
|
2916
|
-
|
|
2941
|
+
logAttachmentStorageError(logger, "[promote-file-part] legacy writer failed", {
|
|
2917
2942
|
path: logicalPath,
|
|
2918
2943
|
error: reason
|
|
2919
2944
|
});
|
|
@@ -2921,14 +2946,14 @@ async function promoteAgentFilePart(options) {
|
|
|
2921
2946
|
}
|
|
2922
2947
|
const result2 = inspectLegacyAttachmentWriteResult(written2);
|
|
2923
2948
|
if (!result2) {
|
|
2924
|
-
|
|
2949
|
+
logAttachmentStorageError(logger, "[promote-file-part] legacy writer returned an invalid result", {
|
|
2925
2950
|
path: logicalPath
|
|
2926
2951
|
});
|
|
2927
2952
|
return { succeeded: false, filename, reason: ATTACHMENT_STORAGE_FAILURE_MESSAGE };
|
|
2928
2953
|
}
|
|
2929
2954
|
if (!result2.ok) {
|
|
2930
2955
|
const reason = redactErrorMessage(result2.reason);
|
|
2931
|
-
|
|
2956
|
+
logAttachmentStorageError(logger, "[promote-file-part] legacy write rejected", {
|
|
2932
2957
|
path: logicalPath,
|
|
2933
2958
|
error: reason
|
|
2934
2959
|
});
|
|
@@ -2951,7 +2976,7 @@ async function promoteAgentFilePart(options) {
|
|
|
2951
2976
|
ownershipId = createWriteId();
|
|
2952
2977
|
path = immutableAttachmentPath(logicalPath, ownershipId);
|
|
2953
2978
|
} catch (error) {
|
|
2954
|
-
|
|
2979
|
+
logAttachmentStorageError(logger, "[promote-file-part] could not allocate ownership key", {
|
|
2955
2980
|
path: logicalPath,
|
|
2956
2981
|
error: redactErrorMessage(error)
|
|
2957
2982
|
});
|
|
@@ -2974,7 +2999,7 @@ async function promoteAgentFilePart(options) {
|
|
|
2974
2999
|
} catch (error) {
|
|
2975
3000
|
abortError = error;
|
|
2976
3001
|
}
|
|
2977
|
-
|
|
3002
|
+
logAttachmentStorageError(logger, "[promote-file-part] write failed", {
|
|
2978
3003
|
path,
|
|
2979
3004
|
ownershipId: ownership.id,
|
|
2980
3005
|
error: redactErrorMessage(err),
|
|
@@ -2990,7 +3015,7 @@ async function promoteAgentFilePart(options) {
|
|
|
2990
3015
|
} catch (error) {
|
|
2991
3016
|
abortError = error;
|
|
2992
3017
|
}
|
|
2993
|
-
|
|
3018
|
+
logAttachmentStorageError(logger, "[promote-file-part] writer returned a mismatched ownership receipt", {
|
|
2994
3019
|
path,
|
|
2995
3020
|
ownershipId: ownership.id,
|
|
2996
3021
|
...abortError === void 0 ? {} : { abortError: redactErrorMessage(abortError) }
|
|
@@ -3004,7 +3029,7 @@ async function promoteAgentFilePart(options) {
|
|
|
3004
3029
|
ownership,
|
|
3005
3030
|
result.receipt
|
|
3006
3031
|
);
|
|
3007
|
-
|
|
3032
|
+
logAttachmentStorageError(logger, "[promote-file-part] write rejected", {
|
|
3008
3033
|
path,
|
|
3009
3034
|
ownershipId: ownership.id,
|
|
3010
3035
|
error: redactErrorMessage(result.reason),
|
|
@@ -3016,28 +3041,16 @@ async function promoteAgentFilePart(options) {
|
|
|
3016
3041
|
return {
|
|
3017
3042
|
succeeded: true,
|
|
3018
3043
|
part: {
|
|
3019
|
-
type: kind,
|
|
3020
|
-
path,
|
|
3021
|
-
name: filename,
|
|
3022
|
-
size: resolved.bytes.byteLength,
|
|
3023
|
-
mediaType
|
|
3024
|
-
}
|
|
3025
|
-
};
|
|
3026
|
-
}
|
|
3027
|
-
|
|
3028
|
-
// src/chat-routes/attachment-upload.ts
|
|
3029
|
-
function logAttachmentUploadError(logger, message, fields) {
|
|
3030
|
-
try {
|
|
3031
|
-
const safeFields = Object.fromEntries(
|
|
3032
|
-
Object.entries(fields).map(([key, value]) => [
|
|
3033
|
-
key,
|
|
3034
|
-
typeof value === "string" ? redactErrorMessage(value) : value
|
|
3035
|
-
])
|
|
3036
|
-
);
|
|
3037
|
-
logger.error(message, safeFields);
|
|
3038
|
-
} catch {
|
|
3039
|
-
}
|
|
3044
|
+
type: kind,
|
|
3045
|
+
path,
|
|
3046
|
+
name: filename,
|
|
3047
|
+
size: resolved.bytes.byteLength,
|
|
3048
|
+
mediaType
|
|
3049
|
+
}
|
|
3050
|
+
};
|
|
3040
3051
|
}
|
|
3052
|
+
|
|
3053
|
+
// src/chat-routes/attachment-upload.ts
|
|
3041
3054
|
function attachmentUploadError(status, code, message, path) {
|
|
3042
3055
|
return Response.json(
|
|
3043
3056
|
{ error: path === void 0 ? { code, message } : { code, message, path } },
|
|
@@ -3148,7 +3161,7 @@ async function rollbackSuccessfulWrites(writes, scopeId, writer, logger) {
|
|
|
3148
3161
|
await write.receipt.rollback();
|
|
3149
3162
|
} catch (error) {
|
|
3150
3163
|
failures += 1;
|
|
3151
|
-
|
|
3164
|
+
logAttachmentStorageError(logger, "[attachment-upload] cleanup failed", {
|
|
3152
3165
|
path: write.path,
|
|
3153
3166
|
ownershipId: write.ownership.id,
|
|
3154
3167
|
error: redactErrorMessage(error)
|
|
@@ -3163,7 +3176,7 @@ async function abortOwnership(writer, scopeId, ownership, logger) {
|
|
|
3163
3176
|
await writer.abort(scopeId, ownership);
|
|
3164
3177
|
return 0;
|
|
3165
3178
|
} catch (error) {
|
|
3166
|
-
|
|
3179
|
+
logAttachmentStorageError(logger, "[attachment-upload] ambiguous write cleanup failed", {
|
|
3167
3180
|
path: ownership.path,
|
|
3168
3181
|
ownershipId: ownership.id,
|
|
3169
3182
|
error: redactErrorMessage(error)
|
|
@@ -3200,6 +3213,89 @@ function createAttachmentUploadRoute(options) {
|
|
|
3200
3213
|
return sniff.mime === null ? maxBinaryBytes : maxBytesBySniffedMime?.get(sniff.mime) ?? maxBinaryBytes;
|
|
3201
3214
|
};
|
|
3202
3215
|
const largestFileBytes = Math.max(maxTextBytes, maxBinaryBytes, ...maxBytesBySniffedMime?.values() ?? []);
|
|
3216
|
+
const { streamRawUpload } = createRawUploadStream(sniffMime, allowedSniffedMimes, allowedKinds, limitFor, logger);
|
|
3217
|
+
return async function attachmentUpload(request) {
|
|
3218
|
+
const auth = await options.authorize({ request });
|
|
3219
|
+
if (!auth.ok) return auth.response;
|
|
3220
|
+
const atomicWriter = atomic ? auth.attachmentWriter ?? options.attachmentWriter : void 0;
|
|
3221
|
+
const legacyWriter = atomic ? void 0 : auth.writeAttachment ?? options.writeAttachment;
|
|
3222
|
+
if (atomic && !atomicWriter) {
|
|
3223
|
+
return attachmentUploadError(503, "attachment_store_unavailable", ATTACHMENT_STORAGE_FAILURE_MESSAGE);
|
|
3224
|
+
}
|
|
3225
|
+
const files = [];
|
|
3226
|
+
const contentType = request.headers.get("Content-Type")?.toLowerCase() ?? "";
|
|
3227
|
+
if (!contentType.startsWith("multipart/form-data")) {
|
|
3228
|
+
const target = rawUploadTarget(request);
|
|
3229
|
+
if (!target.succeeded) return target.response;
|
|
3230
|
+
const { filename, declaredBytes } = target;
|
|
3231
|
+
const name = sanitizeAttachmentFileName(filename);
|
|
3232
|
+
if (declaredBytes > largestFileBytes) {
|
|
3233
|
+
return attachmentUploadError(413, "attachment_too_large", attachmentSizeErrorMessage(name, declaredBytes, largestFileBytes));
|
|
3234
|
+
}
|
|
3235
|
+
if (declaredBytes > maxTotalBytes) {
|
|
3236
|
+
return attachmentUploadError(413, "attachments_total_too_large", attachmentTotalSizeErrorMessage(declaredBytes, maxTotalBytes));
|
|
3237
|
+
}
|
|
3238
|
+
if (streamWriter && declaredBytes > STREAM_SNIFF_HEAD_BYTES) {
|
|
3239
|
+
const path = pathFor(name);
|
|
3240
|
+
const pathCheck = validatePath(path);
|
|
3241
|
+
if (!pathCheck.succeeded) return attachmentUploadError(400, "invalid_attachment_path", pathCheck.error, path);
|
|
3242
|
+
const writer = auth.writeAttachmentStream ?? streamWriter;
|
|
3243
|
+
return streamRawUpload({ request, scopeId: auth.scopeId, writer, filename, name, path, declaredBytes });
|
|
3244
|
+
}
|
|
3245
|
+
const body = await readRawBody(request, declaredBytes);
|
|
3246
|
+
if (!body.succeeded) return body.response;
|
|
3247
|
+
files.push(new File([body.value], filename));
|
|
3248
|
+
} else {
|
|
3249
|
+
let formSource = request;
|
|
3250
|
+
if (maxFormBytes !== void 0) {
|
|
3251
|
+
const bounded = await readBodyUpTo(request, maxFormBytes);
|
|
3252
|
+
if (!bounded.succeeded && !bounded.tooLarge) {
|
|
3253
|
+
return attachmentUploadError(400, "invalid_upload", "The upload body ended early");
|
|
3254
|
+
}
|
|
3255
|
+
if (!bounded.succeeded) {
|
|
3256
|
+
return attachmentUploadError(
|
|
3257
|
+
413,
|
|
3258
|
+
"form_upload_too_large",
|
|
3259
|
+
`Form uploads are limited to ${formatBytes(maxFormBytes)}; send a larger file as a raw request body named by the filename query parameter`
|
|
3260
|
+
);
|
|
3261
|
+
}
|
|
3262
|
+
formSource = new Response(bounded.value, { headers: { "Content-Type": request.headers.get("Content-Type") ?? "" } });
|
|
3263
|
+
}
|
|
3264
|
+
let form;
|
|
3265
|
+
try {
|
|
3266
|
+
form = await formSource.formData();
|
|
3267
|
+
} catch {
|
|
3268
|
+
return attachmentUploadError(400, "invalid_upload", "Expected a multipart/form-data body with file fields");
|
|
3269
|
+
}
|
|
3270
|
+
form.forEach((value) => {
|
|
3271
|
+
if (value instanceof File) files.push(value);
|
|
3272
|
+
});
|
|
3273
|
+
}
|
|
3274
|
+
if (files.length === 0) {
|
|
3275
|
+
return attachmentUploadError(400, "invalid_upload", "No files in the upload body");
|
|
3276
|
+
}
|
|
3277
|
+
if (files.length > maxCount) {
|
|
3278
|
+
return attachmentUploadError(
|
|
3279
|
+
400,
|
|
3280
|
+
"attachment_count_exceeded",
|
|
3281
|
+
`Too many files \u2014 the ${maxCount}-file limit was exceeded`
|
|
3282
|
+
);
|
|
3283
|
+
}
|
|
3284
|
+
const advisoryTotal = files.reduce((sum2, file) => sum2 + file.size, 0);
|
|
3285
|
+
if (advisoryTotal > maxTotalBytes) {
|
|
3286
|
+
return attachmentUploadError(
|
|
3287
|
+
413,
|
|
3288
|
+
"attachments_total_too_large",
|
|
3289
|
+
attachmentTotalSizeErrorMessage(advisoryTotal, maxTotalBytes)
|
|
3290
|
+
);
|
|
3291
|
+
}
|
|
3292
|
+
const preparedBatch = await prepareUploadBatch(files, allowedSniffedMimes, allowedKinds, limitFor, pathFor, atomic, createWriteId, logger, validatePath, maxTotalBytes, sniffMime);
|
|
3293
|
+
if (preparedBatch instanceof Response) return preparedBatch;
|
|
3294
|
+
const { prepared } = preparedBatch;
|
|
3295
|
+
return await commitUploadBatch(prepared, legacyWriter, auth, atomicWriter, atomic, logger);
|
|
3296
|
+
};
|
|
3297
|
+
}
|
|
3298
|
+
function createRawUploadStream(sniffMime, allowedSniffedMimes, allowedKinds, limitFor, logger) {
|
|
3203
3299
|
async function streamRawUpload(input) {
|
|
3204
3300
|
const { request, declaredBytes, name, path } = input;
|
|
3205
3301
|
if (!request.body) return attachmentUploadError(400, "invalid_length", LENGTH_MISMATCH_MESSAGE);
|
|
@@ -3300,19 +3396,19 @@ function createAttachmentUploadRoute(options) {
|
|
|
3300
3396
|
} catch (error) {
|
|
3301
3397
|
if (!finalSniff) await reader.cancel().catch(() => void 0);
|
|
3302
3398
|
if (refusal) return refusal;
|
|
3303
|
-
|
|
3399
|
+
logAttachmentStorageError(logger, "[attachment-upload] stream writer failed", { path, error: redactErrorMessage(error) });
|
|
3304
3400
|
return attachmentUploadError(503, "attachment_store_unavailable", ATTACHMENT_STORAGE_FAILURE_MESSAGE, path);
|
|
3305
3401
|
}
|
|
3306
3402
|
if (!finalSniff) await reader.cancel().catch(() => void 0);
|
|
3307
3403
|
if (refusal) return refusal;
|
|
3308
3404
|
const result = inspectLegacyAttachmentWriteResult(written);
|
|
3309
3405
|
if (!result || result.ok && !finalSniff) {
|
|
3310
|
-
|
|
3406
|
+
logAttachmentStorageError(logger, "[attachment-upload] stream writer returned without a checked file", { path });
|
|
3311
3407
|
return attachmentUploadError(503, "attachment_store_unavailable", ATTACHMENT_STORAGE_FAILURE_MESSAGE, path);
|
|
3312
3408
|
}
|
|
3313
3409
|
if (!result.ok) {
|
|
3314
3410
|
const reason = redactErrorMessage(result.reason);
|
|
3315
|
-
|
|
3411
|
+
logAttachmentStorageError(logger, "[attachment-upload] stream write rejected", { path, error: reason });
|
|
3316
3412
|
return attachmentUploadError(413, "attachment_write_failed", reason, path);
|
|
3317
3413
|
}
|
|
3318
3414
|
const sniff = finalSniff;
|
|
@@ -3325,262 +3421,132 @@ function createAttachmentUploadRoute(options) {
|
|
|
3325
3421
|
};
|
|
3326
3422
|
return Response.json({ files: [uploaded] });
|
|
3327
3423
|
}
|
|
3328
|
-
return
|
|
3329
|
-
|
|
3330
|
-
|
|
3331
|
-
|
|
3332
|
-
|
|
3333
|
-
|
|
3334
|
-
|
|
3424
|
+
return { streamRawUpload };
|
|
3425
|
+
}
|
|
3426
|
+
async function prepareUploadBatch(files, allowedSniffedMimes, allowedKinds, limitFor, pathFor, atomic, createWriteId, logger, validatePath, maxTotalBytes, sniffMime) {
|
|
3427
|
+
const prepared = [];
|
|
3428
|
+
const seenLogicalPaths = /* @__PURE__ */ new Set();
|
|
3429
|
+
let totalBytes = 0;
|
|
3430
|
+
for (const file of files) {
|
|
3431
|
+
const bytes = new Uint8Array(await file.arrayBuffer());
|
|
3432
|
+
const sniff = sniffBinary(bytes);
|
|
3433
|
+
const name = sanitizeAttachmentFileName(file.name);
|
|
3434
|
+
const typeCheck = checkAttachmentType(name, sniff, allowedSniffedMimes);
|
|
3435
|
+
if (!typeCheck.succeeded) {
|
|
3436
|
+
return attachmentUploadError(
|
|
3437
|
+
typeCheck.code === "attachment_type_mismatch" ? 400 : 415,
|
|
3438
|
+
typeCheck.code,
|
|
3439
|
+
typeCheck.message
|
|
3440
|
+
);
|
|
3335
3441
|
}
|
|
3336
|
-
const
|
|
3337
|
-
|
|
3338
|
-
|
|
3339
|
-
|
|
3340
|
-
|
|
3341
|
-
|
|
3342
|
-
|
|
3343
|
-
|
|
3344
|
-
|
|
3345
|
-
|
|
3346
|
-
|
|
3347
|
-
|
|
3348
|
-
|
|
3349
|
-
|
|
3350
|
-
|
|
3351
|
-
|
|
3352
|
-
|
|
3353
|
-
|
|
3354
|
-
|
|
3355
|
-
|
|
3356
|
-
const body = await readRawBody(request, declaredBytes);
|
|
3357
|
-
if (!body.succeeded) return body.response;
|
|
3358
|
-
files.push(new File([body.value], filename));
|
|
3359
|
-
} else {
|
|
3360
|
-
let formSource = request;
|
|
3361
|
-
if (maxFormBytes !== void 0) {
|
|
3362
|
-
const bounded = await readBodyUpTo(request, maxFormBytes);
|
|
3363
|
-
if (!bounded.succeeded && !bounded.tooLarge) {
|
|
3364
|
-
return attachmentUploadError(400, "invalid_upload", "The upload body ended early");
|
|
3365
|
-
}
|
|
3366
|
-
if (!bounded.succeeded) {
|
|
3367
|
-
return attachmentUploadError(
|
|
3368
|
-
413,
|
|
3369
|
-
"form_upload_too_large",
|
|
3370
|
-
`Form uploads are limited to ${formatBytes(maxFormBytes)}; send a larger file as a raw request body named by the filename query parameter`
|
|
3371
|
-
);
|
|
3372
|
-
}
|
|
3373
|
-
formSource = new Response(bounded.value, { headers: { "Content-Type": request.headers.get("Content-Type") ?? "" } });
|
|
3374
|
-
}
|
|
3375
|
-
let form;
|
|
3442
|
+
const kind = attachmentKindForMime(sniff.mime ?? "");
|
|
3443
|
+
if (!allowedKinds.includes(kind)) {
|
|
3444
|
+
return attachmentUploadError(
|
|
3445
|
+
415,
|
|
3446
|
+
"attachment_kind_not_allowed",
|
|
3447
|
+
`${name} is a "${kind}" attachment, which this upload route does not accept`
|
|
3448
|
+
);
|
|
3449
|
+
}
|
|
3450
|
+
const limit = limitFor(sniff);
|
|
3451
|
+
if (bytes.length > limit) {
|
|
3452
|
+
return attachmentUploadError(
|
|
3453
|
+
413,
|
|
3454
|
+
"attachment_too_large",
|
|
3455
|
+
attachmentSizeErrorMessage(name, bytes.length, limit)
|
|
3456
|
+
);
|
|
3457
|
+
}
|
|
3458
|
+
const logicalPath = pathFor(name);
|
|
3459
|
+
let ownershipId;
|
|
3460
|
+
let path = logicalPath;
|
|
3461
|
+
if (atomic) {
|
|
3376
3462
|
try {
|
|
3377
|
-
|
|
3378
|
-
|
|
3379
|
-
|
|
3463
|
+
ownershipId = createWriteId();
|
|
3464
|
+
path = immutableAttachmentPath(logicalPath, ownershipId);
|
|
3465
|
+
} catch (error) {
|
|
3466
|
+
logAttachmentStorageError(logger, "[attachment-upload] could not allocate ownership key", {
|
|
3467
|
+
path: logicalPath,
|
|
3468
|
+
error: redactErrorMessage(error)
|
|
3469
|
+
});
|
|
3470
|
+
return attachmentUploadError(
|
|
3471
|
+
503,
|
|
3472
|
+
"attachment_store_unavailable",
|
|
3473
|
+
ATTACHMENT_STORAGE_FAILURE_MESSAGE,
|
|
3474
|
+
logicalPath
|
|
3475
|
+
);
|
|
3380
3476
|
}
|
|
3381
|
-
form.forEach((value) => {
|
|
3382
|
-
if (value instanceof File) files.push(value);
|
|
3383
|
-
});
|
|
3384
3477
|
}
|
|
3385
|
-
|
|
3386
|
-
|
|
3478
|
+
const pathCheck = validatePath(path);
|
|
3479
|
+
if (!pathCheck.succeeded) {
|
|
3480
|
+
return attachmentUploadError(400, "invalid_attachment_path", pathCheck.error, path);
|
|
3387
3481
|
}
|
|
3388
|
-
|
|
3482
|
+
const duplicatePath = atomic ? logicalPath : path;
|
|
3483
|
+
if (seenLogicalPaths.has(duplicatePath)) {
|
|
3389
3484
|
return attachmentUploadError(
|
|
3390
3485
|
400,
|
|
3391
|
-
"
|
|
3392
|
-
`
|
|
3486
|
+
"attachment_duplicate_path",
|
|
3487
|
+
`attachments must not repeat a path within one upload: ${duplicatePath}`,
|
|
3488
|
+
path
|
|
3393
3489
|
);
|
|
3394
3490
|
}
|
|
3395
|
-
|
|
3396
|
-
|
|
3491
|
+
seenLogicalPaths.add(duplicatePath);
|
|
3492
|
+
totalBytes += bytes.length;
|
|
3493
|
+
if (totalBytes > maxTotalBytes) {
|
|
3397
3494
|
return attachmentUploadError(
|
|
3398
3495
|
413,
|
|
3399
3496
|
"attachments_total_too_large",
|
|
3400
|
-
attachmentTotalSizeErrorMessage(
|
|
3497
|
+
attachmentTotalSizeErrorMessage(totalBytes, maxTotalBytes)
|
|
3401
3498
|
);
|
|
3402
3499
|
}
|
|
3403
|
-
const
|
|
3404
|
-
|
|
3405
|
-
|
|
3406
|
-
|
|
3407
|
-
|
|
3408
|
-
|
|
3409
|
-
|
|
3410
|
-
|
|
3411
|
-
|
|
3412
|
-
|
|
3413
|
-
|
|
3414
|
-
typeCheck.code,
|
|
3415
|
-
typeCheck.message
|
|
3416
|
-
);
|
|
3417
|
-
}
|
|
3418
|
-
const kind = attachmentKindForMime(sniff.mime ?? "");
|
|
3419
|
-
if (!allowedKinds.includes(kind)) {
|
|
3420
|
-
return attachmentUploadError(
|
|
3421
|
-
415,
|
|
3422
|
-
"attachment_kind_not_allowed",
|
|
3423
|
-
`${name} is a "${kind}" attachment, which this upload route does not accept`
|
|
3424
|
-
);
|
|
3425
|
-
}
|
|
3426
|
-
const limit = limitFor(sniff);
|
|
3427
|
-
if (bytes.length > limit) {
|
|
3428
|
-
return attachmentUploadError(
|
|
3429
|
-
413,
|
|
3430
|
-
"attachment_too_large",
|
|
3431
|
-
attachmentSizeErrorMessage(name, bytes.length, limit)
|
|
3432
|
-
);
|
|
3433
|
-
}
|
|
3434
|
-
const logicalPath = pathFor(name);
|
|
3435
|
-
let ownershipId;
|
|
3436
|
-
let path = logicalPath;
|
|
3437
|
-
if (atomic) {
|
|
3438
|
-
try {
|
|
3439
|
-
ownershipId = createWriteId();
|
|
3440
|
-
path = immutableAttachmentPath(logicalPath, ownershipId);
|
|
3441
|
-
} catch (error) {
|
|
3442
|
-
logAttachmentUploadError(logger, "[attachment-upload] could not allocate ownership key", {
|
|
3443
|
-
path: logicalPath,
|
|
3444
|
-
error: redactErrorMessage(error)
|
|
3445
|
-
});
|
|
3446
|
-
return attachmentUploadError(
|
|
3447
|
-
503,
|
|
3448
|
-
"attachment_store_unavailable",
|
|
3449
|
-
ATTACHMENT_STORAGE_FAILURE_MESSAGE,
|
|
3450
|
-
logicalPath
|
|
3451
|
-
);
|
|
3452
|
-
}
|
|
3453
|
-
}
|
|
3454
|
-
const pathCheck = validatePath(path);
|
|
3455
|
-
if (!pathCheck.succeeded) {
|
|
3456
|
-
return attachmentUploadError(400, "invalid_attachment_path", pathCheck.error, path);
|
|
3457
|
-
}
|
|
3458
|
-
const duplicatePath = atomic ? logicalPath : path;
|
|
3459
|
-
if (seenLogicalPaths.has(duplicatePath)) {
|
|
3460
|
-
return attachmentUploadError(
|
|
3461
|
-
400,
|
|
3462
|
-
"attachment_duplicate_path",
|
|
3463
|
-
`attachments must not repeat a path within one upload: ${duplicatePath}`,
|
|
3464
|
-
path
|
|
3465
|
-
);
|
|
3466
|
-
}
|
|
3467
|
-
seenLogicalPaths.add(duplicatePath);
|
|
3468
|
-
totalBytes += bytes.length;
|
|
3469
|
-
if (totalBytes > maxTotalBytes) {
|
|
3470
|
-
return attachmentUploadError(
|
|
3471
|
-
413,
|
|
3472
|
-
"attachments_total_too_large",
|
|
3473
|
-
attachmentTotalSizeErrorMessage(totalBytes, maxTotalBytes)
|
|
3474
|
-
);
|
|
3475
|
-
}
|
|
3476
|
-
const mediaType = sniff.mime ?? sniffMime(name);
|
|
3477
|
-
prepared.push({ path, ownershipId, name, bytes, originalName: file.name, size: bytes.length, mediaType, kind });
|
|
3478
|
-
}
|
|
3479
|
-
const uploaded = [];
|
|
3480
|
-
const successfulWrites = [];
|
|
3481
|
-
for (const input of prepared) {
|
|
3482
|
-
if (!atomic) {
|
|
3483
|
-
let written2;
|
|
3484
|
-
try {
|
|
3485
|
-
written2 = await legacyWriter(auth.scopeId, input.path, input.bytes, {
|
|
3486
|
-
mediaType: input.mediaType,
|
|
3487
|
-
name: input.name,
|
|
3488
|
-
originalName: input.originalName,
|
|
3489
|
-
size: input.size
|
|
3490
|
-
});
|
|
3491
|
-
} catch (error) {
|
|
3492
|
-
logAttachmentUploadError(logger, "[attachment-upload] legacy writer failed", {
|
|
3493
|
-
path: input.path,
|
|
3494
|
-
error: redactErrorMessage(error)
|
|
3495
|
-
});
|
|
3496
|
-
return attachmentUploadError(
|
|
3497
|
-
503,
|
|
3498
|
-
"attachment_store_unavailable",
|
|
3499
|
-
ATTACHMENT_STORAGE_FAILURE_MESSAGE,
|
|
3500
|
-
input.path
|
|
3501
|
-
);
|
|
3502
|
-
}
|
|
3503
|
-
const result2 = inspectLegacyAttachmentWriteResult(written2);
|
|
3504
|
-
if (!result2) {
|
|
3505
|
-
logAttachmentUploadError(logger, "[attachment-upload] legacy writer returned an invalid result", {
|
|
3506
|
-
path: input.path
|
|
3507
|
-
});
|
|
3508
|
-
return attachmentUploadError(
|
|
3509
|
-
503,
|
|
3510
|
-
"attachment_store_unavailable",
|
|
3511
|
-
ATTACHMENT_STORAGE_FAILURE_MESSAGE,
|
|
3512
|
-
input.path
|
|
3513
|
-
);
|
|
3514
|
-
}
|
|
3515
|
-
if (!result2.ok) {
|
|
3516
|
-
const reason = redactErrorMessage(result2.reason);
|
|
3517
|
-
logAttachmentUploadError(logger, "[attachment-upload] legacy write rejected", {
|
|
3518
|
-
path: input.path,
|
|
3519
|
-
error: reason
|
|
3520
|
-
});
|
|
3521
|
-
return attachmentUploadError(413, "attachment_write_failed", reason, input.path);
|
|
3522
|
-
}
|
|
3523
|
-
uploaded.push({
|
|
3524
|
-
path: input.path,
|
|
3525
|
-
name: input.name,
|
|
3526
|
-
size: input.size,
|
|
3527
|
-
mediaType: input.mediaType,
|
|
3528
|
-
kind: input.kind
|
|
3529
|
-
});
|
|
3530
|
-
continue;
|
|
3531
|
-
}
|
|
3532
|
-
const ownershipId = input.ownershipId;
|
|
3533
|
-
if (!ownershipId) {
|
|
3534
|
-
return attachmentUploadError(503, "attachment_store_unavailable", ATTACHMENT_STORAGE_FAILURE_MESSAGE, input.path);
|
|
3535
|
-
}
|
|
3536
|
-
const ownership = Object.freeze({ id: ownershipId, path: input.path });
|
|
3537
|
-
let written;
|
|
3500
|
+
const mediaType = sniff.mime ?? sniffMime(name);
|
|
3501
|
+
prepared.push({ path, ownershipId, name, bytes, originalName: file.name, size: bytes.length, mediaType, kind });
|
|
3502
|
+
}
|
|
3503
|
+
return { prepared };
|
|
3504
|
+
}
|
|
3505
|
+
async function commitUploadBatch(prepared, legacyWriter, auth, atomicWriter, atomic, logger) {
|
|
3506
|
+
const uploaded = [];
|
|
3507
|
+
const successfulWrites = [];
|
|
3508
|
+
for (const input of prepared) {
|
|
3509
|
+
if (!atomic) {
|
|
3510
|
+
let written2;
|
|
3538
3511
|
try {
|
|
3539
|
-
|
|
3512
|
+
written2 = await legacyWriter(auth.scopeId, input.path, input.bytes, {
|
|
3540
3513
|
mediaType: input.mediaType,
|
|
3541
3514
|
name: input.name,
|
|
3542
3515
|
originalName: input.originalName,
|
|
3543
|
-
size: input.size
|
|
3544
|
-
ownership
|
|
3516
|
+
size: input.size
|
|
3545
3517
|
});
|
|
3546
3518
|
} catch (error) {
|
|
3547
|
-
|
|
3548
|
-
logAttachmentUploadError(logger, "[attachment-upload] write failed", {
|
|
3519
|
+
logAttachmentStorageError(logger, "[attachment-upload] legacy writer failed", {
|
|
3549
3520
|
path: input.path,
|
|
3550
|
-
ownershipId: ownership.id,
|
|
3551
|
-
cleanupFailures,
|
|
3552
3521
|
error: redactErrorMessage(error)
|
|
3553
3522
|
});
|
|
3554
|
-
return
|
|
3523
|
+
return attachmentUploadError(
|
|
3524
|
+
503,
|
|
3525
|
+
"attachment_store_unavailable",
|
|
3526
|
+
ATTACHMENT_STORAGE_FAILURE_MESSAGE,
|
|
3527
|
+
input.path
|
|
3528
|
+
);
|
|
3555
3529
|
}
|
|
3556
|
-
const
|
|
3557
|
-
if (!
|
|
3558
|
-
|
|
3559
|
-
|
|
3560
|
-
path: input.path,
|
|
3561
|
-
ownershipId: ownership.id,
|
|
3562
|
-
cleanupFailures
|
|
3530
|
+
const result2 = inspectLegacyAttachmentWriteResult(written2);
|
|
3531
|
+
if (!result2) {
|
|
3532
|
+
logAttachmentStorageError(logger, "[attachment-upload] legacy writer returned an invalid result", {
|
|
3533
|
+
path: input.path
|
|
3563
3534
|
});
|
|
3564
|
-
return
|
|
3565
|
-
|
|
3566
|
-
|
|
3567
|
-
|
|
3568
|
-
|
|
3569
|
-
], auth.scopeId, atomicWriter, logger) + await rollbackSuccessfulWrites(
|
|
3570
|
-
successfulWrites,
|
|
3571
|
-
auth.scopeId,
|
|
3572
|
-
atomicWriter,
|
|
3573
|
-
logger
|
|
3535
|
+
return attachmentUploadError(
|
|
3536
|
+
503,
|
|
3537
|
+
"attachment_store_unavailable",
|
|
3538
|
+
ATTACHMENT_STORAGE_FAILURE_MESSAGE,
|
|
3539
|
+
input.path
|
|
3574
3540
|
);
|
|
3575
|
-
|
|
3541
|
+
}
|
|
3542
|
+
if (!result2.ok) {
|
|
3543
|
+
const reason = redactErrorMessage(result2.reason);
|
|
3544
|
+
logAttachmentStorageError(logger, "[attachment-upload] legacy write rejected", {
|
|
3576
3545
|
path: input.path,
|
|
3577
|
-
|
|
3578
|
-
cleanupFailures,
|
|
3579
|
-
error: redactErrorMessage(result.reason)
|
|
3546
|
+
error: reason
|
|
3580
3547
|
});
|
|
3581
|
-
return
|
|
3548
|
+
return attachmentUploadError(413, "attachment_write_failed", reason, input.path);
|
|
3582
3549
|
}
|
|
3583
|
-
successfulWrites.push({ path: input.path, ownership, receipt: result.receipt });
|
|
3584
3550
|
uploaded.push({
|
|
3585
3551
|
path: input.path,
|
|
3586
3552
|
name: input.name,
|
|
@@ -3588,9 +3554,69 @@ function createAttachmentUploadRoute(options) {
|
|
|
3588
3554
|
mediaType: input.mediaType,
|
|
3589
3555
|
kind: input.kind
|
|
3590
3556
|
});
|
|
3557
|
+
continue;
|
|
3591
3558
|
}
|
|
3592
|
-
|
|
3593
|
-
|
|
3559
|
+
const ownershipId = input.ownershipId;
|
|
3560
|
+
if (!ownershipId) {
|
|
3561
|
+
return attachmentUploadError(503, "attachment_store_unavailable", ATTACHMENT_STORAGE_FAILURE_MESSAGE, input.path);
|
|
3562
|
+
}
|
|
3563
|
+
const ownership = Object.freeze({ id: ownershipId, path: input.path });
|
|
3564
|
+
let written;
|
|
3565
|
+
try {
|
|
3566
|
+
written = await atomicWriter.write(auth.scopeId, input.path, input.bytes, {
|
|
3567
|
+
mediaType: input.mediaType,
|
|
3568
|
+
name: input.name,
|
|
3569
|
+
originalName: input.originalName,
|
|
3570
|
+
size: input.size,
|
|
3571
|
+
ownership
|
|
3572
|
+
});
|
|
3573
|
+
} catch (error) {
|
|
3574
|
+
const cleanupFailures = await abortOwnership(atomicWriter, auth.scopeId, ownership, logger) + await rollbackSuccessfulWrites(successfulWrites, auth.scopeId, atomicWriter, logger);
|
|
3575
|
+
logAttachmentStorageError(logger, "[attachment-upload] write failed", {
|
|
3576
|
+
path: input.path,
|
|
3577
|
+
ownershipId: ownership.id,
|
|
3578
|
+
cleanupFailures,
|
|
3579
|
+
error: redactErrorMessage(error)
|
|
3580
|
+
});
|
|
3581
|
+
return atomicAttachmentFailure(input.path, cleanupFailures);
|
|
3582
|
+
}
|
|
3583
|
+
const result = inspectAtomicAttachmentWriteResult(written, ownership);
|
|
3584
|
+
if (!result) {
|
|
3585
|
+
const cleanupFailures = await abortOwnership(atomicWriter, auth.scopeId, ownership, logger) + await rollbackSuccessfulWrites(successfulWrites, auth.scopeId, atomicWriter, logger);
|
|
3586
|
+
logAttachmentStorageError(logger, "[attachment-upload] writer returned a mismatched ownership receipt", {
|
|
3587
|
+
path: input.path,
|
|
3588
|
+
ownershipId: ownership.id,
|
|
3589
|
+
cleanupFailures
|
|
3590
|
+
});
|
|
3591
|
+
return atomicAttachmentFailure(input.path, cleanupFailures);
|
|
3592
|
+
}
|
|
3593
|
+
if (!result.ok) {
|
|
3594
|
+
const cleanupFailures = await rollbackSuccessfulWrites([
|
|
3595
|
+
{ path: input.path, ownership, receipt: result.receipt }
|
|
3596
|
+
], auth.scopeId, atomicWriter, logger) + await rollbackSuccessfulWrites(
|
|
3597
|
+
successfulWrites,
|
|
3598
|
+
auth.scopeId,
|
|
3599
|
+
atomicWriter,
|
|
3600
|
+
logger
|
|
3601
|
+
);
|
|
3602
|
+
logAttachmentStorageError(logger, "[attachment-upload] write rejected", {
|
|
3603
|
+
path: input.path,
|
|
3604
|
+
ownershipId: ownership.id,
|
|
3605
|
+
cleanupFailures,
|
|
3606
|
+
error: redactErrorMessage(result.reason)
|
|
3607
|
+
});
|
|
3608
|
+
return atomicAttachmentFailure(input.path, cleanupFailures);
|
|
3609
|
+
}
|
|
3610
|
+
successfulWrites.push({ path: input.path, ownership, receipt: result.receipt });
|
|
3611
|
+
uploaded.push({
|
|
3612
|
+
path: input.path,
|
|
3613
|
+
name: input.name,
|
|
3614
|
+
size: input.size,
|
|
3615
|
+
mediaType: input.mediaType,
|
|
3616
|
+
kind: input.kind
|
|
3617
|
+
});
|
|
3618
|
+
}
|
|
3619
|
+
return Response.json({ files: uploaded });
|
|
3594
3620
|
}
|
|
3595
3621
|
|
|
3596
3622
|
// src/chat-routes/dispatch-parts.ts
|
|
@@ -3918,6 +3944,59 @@ async function produceChatTurnWithIntelligence(options) {
|
|
|
3918
3944
|
}
|
|
3919
3945
|
};
|
|
3920
3946
|
}
|
|
3947
|
+
|
|
3948
|
+
// src/chat-routes/stored-attachments.ts
|
|
3949
|
+
function decodeAttachmentBase64(value) {
|
|
3950
|
+
const binary = atob(value);
|
|
3951
|
+
return Uint8Array.from(binary, (character) => character.charCodeAt(0));
|
|
3952
|
+
}
|
|
3953
|
+
function createStoredChatAttachments(options) {
|
|
3954
|
+
const store = () => typeof options.store === "function" ? options.store() : options.store;
|
|
3955
|
+
const attachmentObjectKey = (scopeId, path) => {
|
|
3956
|
+
const scope = assertSafeKeySegment(scopeId);
|
|
3957
|
+
const checked = defaultValidateAttachmentPath(path);
|
|
3958
|
+
if (!checked.succeeded) throw new Error(checked.error);
|
|
3959
|
+
return `${scope}/${path}`;
|
|
3960
|
+
};
|
|
3961
|
+
const getAttachmentObject = async (scopeId, path) => store().get(attachmentObjectKey(scopeId, path));
|
|
3962
|
+
const writeAttachment = async (scopeId, path, content, opts) => {
|
|
3963
|
+
let bytes;
|
|
3964
|
+
let key;
|
|
3965
|
+
try {
|
|
3966
|
+
bytes = typeof content === "string" ? decodeAttachmentBase64(content) : content;
|
|
3967
|
+
if (opts.size !== void 0 && opts.size !== bytes.byteLength) {
|
|
3968
|
+
return { ok: false, reason: `Attachment size mismatch for ${path}: expected ${opts.size}, received ${bytes.byteLength}` };
|
|
3969
|
+
}
|
|
3970
|
+
key = attachmentObjectKey(scopeId, path);
|
|
3971
|
+
} catch (error) {
|
|
3972
|
+
return { ok: false, reason: `Attachment write failed for ${path}: ${error instanceof Error ? error.message : String(error)}` };
|
|
3973
|
+
}
|
|
3974
|
+
await store().put(key, bytes, {
|
|
3975
|
+
...opts.mediaType ? { contentType: opts.mediaType } : {},
|
|
3976
|
+
contentLength: bytes.byteLength
|
|
3977
|
+
});
|
|
3978
|
+
return { ok: true };
|
|
3979
|
+
};
|
|
3980
|
+
const readAttachment = async (scopeId, path) => {
|
|
3981
|
+
try {
|
|
3982
|
+
const object = await getAttachmentObject(scopeId, path);
|
|
3983
|
+
if (!object) return { ok: false, reason: `Attachment not found: ${path}` };
|
|
3984
|
+
const bytes = new Uint8Array(await new Response(object.stream()).arrayBuffer());
|
|
3985
|
+
if (bytes.byteLength !== object.size) {
|
|
3986
|
+
return { ok: false, reason: `Attachment size mismatch for ${path}: metadata ${object.size}, body ${bytes.byteLength}` };
|
|
3987
|
+
}
|
|
3988
|
+
return {
|
|
3989
|
+
ok: true,
|
|
3990
|
+
size: bytes.byteLength,
|
|
3991
|
+
bytes,
|
|
3992
|
+
...object.contentType ? { mediaType: object.contentType } : {}
|
|
3993
|
+
};
|
|
3994
|
+
} catch (error) {
|
|
3995
|
+
return { ok: false, reason: `Attachment read failed for ${path}: ${error instanceof Error ? error.message : String(error)}` };
|
|
3996
|
+
}
|
|
3997
|
+
};
|
|
3998
|
+
return { readAttachment, writeAttachment, getAttachmentObject, attachmentObjectKey };
|
|
3999
|
+
}
|
|
3921
4000
|
export {
|
|
3922
4001
|
ALLOWED_ATTACHMENT_SNIFFED_MIMES,
|
|
3923
4002
|
ATTACHMENT_ACCEPT,
|
|
@@ -3992,6 +4071,7 @@ export {
|
|
|
3992
4071
|
createRouterTurnProducer,
|
|
3993
4072
|
createSandboxChatProducer,
|
|
3994
4073
|
createSandboxFileIndexRoute,
|
|
4074
|
+
createStoredChatAttachments,
|
|
3995
4075
|
createStreamingSniffer,
|
|
3996
4076
|
createUploadRoute,
|
|
3997
4077
|
defaultValidateAttachmentPath,
|