@tangle-network/agent-app 0.63.25 → 0.63.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/assistant/index.js +7 -7
  2. package/dist/chat-react/index.js +3 -3
  3. package/dist/chat-routes/hybrid-producer.d.ts +4 -0
  4. package/dist/chat-routes/index.js +24 -24
  5. package/dist/chat-routes/wire.d.ts +2 -0
  6. package/dist/chat-store/index.js +4 -4
  7. package/dist/chat-store/parts.d.ts +2 -0
  8. package/dist/{chunk-6RGNXPXW.js → chunk-36HSG7HU.js} +5 -5
  9. package/dist/chunk-36HSG7HU.js.map +1 -0
  10. package/dist/{chunk-VOXKDO4T.js → chunk-56JUV4DK.js} +110 -35
  11. package/dist/chunk-56JUV4DK.js.map +1 -0
  12. package/dist/{chunk-QJ5DSIHV.js → chunk-6LMM3OVX.js} +3 -3
  13. package/dist/{chunk-56OUN2WP.js → chunk-BQGJ5IDP.js} +10 -10
  14. package/dist/{chunk-KADVQCAS.js → chunk-CWO2LHXH.js} +2 -2
  15. package/dist/{chunk-3WU6HDEZ.js → chunk-DCJCZ7EP.js} +38 -29
  16. package/dist/chunk-DCJCZ7EP.js.map +1 -0
  17. package/dist/{chunk-VUBJZEZB.js → chunk-O5AUJQIA.js} +2 -2
  18. package/dist/{chunk-NHVSO47Q.js → chunk-P7UB7ZVP.js} +2 -2
  19. package/dist/{chunk-WRCMVBUJ.js → chunk-PFTOGTHH.js} +3 -3
  20. package/dist/{chunk-5TSRFF5W.js → chunk-QGJOT6R6.js} +1 -1
  21. package/dist/chunk-QGJOT6R6.js.map +1 -0
  22. package/dist/{chunk-6VQCFJWP.js → chunk-SRZTL3Z5.js} +3 -3
  23. package/dist/{chunk-6VQCFJWP.js.map → chunk-SRZTL3Z5.js.map} +1 -1
  24. package/dist/{chunk-ZLP75JF5.js → chunk-ZZTPTCMY.js} +2 -2
  25. package/dist/interactions/contract.d.ts +3 -1
  26. package/dist/interactions/index.js +2 -2
  27. package/dist/operator/index.js +2 -2
  28. package/dist/preset-cloudflare/index.js +6 -6
  29. package/dist/public-consultation/index.js +8 -8
  30. package/dist/sandbox/app-tools.d.ts +24 -4
  31. package/dist/sandbox/index.js +4 -1
  32. package/dist/sandbox/payload-limits.d.ts +29 -0
  33. package/dist/sandbox/prompt-options.d.ts +5 -0
  34. package/dist/sandbox/sandbox-run-tool.d.ts +14 -3
  35. package/dist/stream/index.js +2 -2
  36. package/dist/web-react/index.js +29 -29
  37. package/package.json +1 -1
  38. package/dist/chunk-3WU6HDEZ.js.map +0 -1
  39. package/dist/chunk-5TSRFF5W.js.map +0 -1
  40. package/dist/chunk-6RGNXPXW.js.map +0 -1
  41. package/dist/chunk-VOXKDO4T.js.map +0 -1
  42. /package/dist/{chunk-QJ5DSIHV.js.map → chunk-6LMM3OVX.js.map} +0 -0
  43. /package/dist/{chunk-56OUN2WP.js.map → chunk-BQGJ5IDP.js.map} +0 -0
  44. /package/dist/{chunk-KADVQCAS.js.map → chunk-CWO2LHXH.js.map} +0 -0
  45. /package/dist/{chunk-VUBJZEZB.js.map → chunk-O5AUJQIA.js.map} +0 -0
  46. /package/dist/{chunk-NHVSO47Q.js.map → chunk-P7UB7ZVP.js.map} +0 -0
  47. /package/dist/{chunk-WRCMVBUJ.js.map → chunk-PFTOGTHH.js.map} +0 -0
  48. /package/dist/{chunk-ZLP75JF5.js.map → chunk-ZZTPTCMY.js.map} +0 -0
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  ReasoningRow,
3
3
  chatToolCallPart
4
- } from "../chunk-56OUN2WP.js";
4
+ } from "../chunk-BQGJ5IDP.js";
5
5
  import "../chunk-3HUFJ5LO.js";
6
6
  import "../chunk-UHSUY6H6.js";
7
7
  import "../chunk-7PULOECS.js";
@@ -9,7 +9,7 @@ import "../chunk-ZOS3D26Z.js";
9
9
  import "../chunk-Y6PRDUFJ.js";
10
10
  import {
11
11
  ChatComposer
12
- } from "../chunk-ZLP75JF5.js";
12
+ } from "../chunk-ZZTPTCMY.js";
13
13
  import "../chunk-L7MB2LLM.js";
14
14
  import "../chunk-2VG6Q4TS.js";
15
15
  import "../chunk-2HQP2CTA.js";
@@ -30,13 +30,13 @@ import {
30
30
  AsyncView
31
31
  } from "../chunk-AVP5SNIG.js";
32
32
  import "../chunk-FQYAJYPW.js";
33
- import "../chunk-NHVSO47Q.js";
33
+ import "../chunk-P7UB7ZVP.js";
34
34
  import "../chunk-B7CL7ENS.js";
35
- import "../chunk-6RGNXPXW.js";
35
+ import "../chunk-36HSG7HU.js";
36
36
  import "../chunk-ZVEEWGDK.js";
37
- import "../chunk-5TSRFF5W.js";
38
- import "../chunk-VUBJZEZB.js";
39
- import "../chunk-6VQCFJWP.js";
37
+ import "../chunk-O5AUJQIA.js";
38
+ import "../chunk-SRZTL3Z5.js";
39
+ import "../chunk-QGJOT6R6.js";
40
40
  import "../chunk-AMUXRAUO.js";
41
41
  import "../chunk-PV33JZKV.js";
42
42
  import "../chunk-ELX5YITO.js";
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  ComposerModeControls,
3
3
  EntryComposer
4
- } from "../chunk-ZLP75JF5.js";
4
+ } from "../chunk-ZZTPTCMY.js";
5
5
  import "../chunk-L7MB2LLM.js";
6
6
  import "../chunk-2HQP2CTA.js";
7
7
  import "../chunk-SJWIZT7B.js";
@@ -10,8 +10,8 @@ import "../chunk-QAHBSKWG.js";
10
10
  import "../chunk-RO25WIVS.js";
11
11
  import "../chunk-ZAMHLXNS.js";
12
12
  import "../chunk-RASGKEAL.js";
13
- import "../chunk-NHVSO47Q.js";
14
- import "../chunk-5TSRFF5W.js";
13
+ import "../chunk-P7UB7ZVP.js";
14
+ import "../chunk-QGJOT6R6.js";
15
15
  import "../chunk-AMUXRAUO.js";
16
16
  import "../chunk-ELX5YITO.js";
17
17
  import "../chunk-TXD5HXLE.js";
@@ -32,6 +32,8 @@
32
32
  * run are recorded under the turn's `trace` when the route gives one.
33
33
  * A typed computer failure also emits a persisted warning; the Router keeps
34
34
  * answering without relying on the model to explain that failure faithfully.
35
+ * The warning's `detail` is the failure's redacted cause chain, so the cause is
36
+ * in the transcript, not only in a log line a Worker does not keep.
35
37
  */
36
38
  import type { SandboxInstance } from '@tangle-network/sandbox';
37
39
  import type { RouterTurnTool } from '../runtime/router-turn';
@@ -54,6 +56,8 @@ export interface HybridTurnBox {
54
56
  /** Wall-clock cap for one `sandbox_run` call, box start included. Default 4 minutes. */
55
57
  timeoutMs?: number;
56
58
  warm?: SandboxRunToolOptions['warm'];
59
+ /** Every computer failure with its cause. The producer already persists the redacted cause chain on the turn's
60
+ * warning notice (`detail`), and logs it when this is omitted. */
57
61
  onFailure?: SandboxRunToolOptions['onFailure'];
58
62
  /** The tool's name and description. Default `sandbox_run` and its shared description. */
59
63
  name?: string;
@@ -27,7 +27,7 @@ import {
27
27
  sanitizeAttachmentFileName,
28
28
  sniffBinary,
29
29
  sniffedMimeImpliedByName
30
- } from "../chunk-NHVSO47Q.js";
30
+ } from "../chunk-P7UB7ZVP.js";
31
31
  import {
32
32
  assertSafeKeySegment
33
33
  } from "../chunk-6DOQ6T2O.js";
@@ -40,7 +40,7 @@ import {
40
40
  observeNativeCompletion,
41
41
  readCompletedSandboxTurn,
42
42
  recoverSandboxAssistantMessage
43
- } from "../chunk-WRCMVBUJ.js";
43
+ } from "../chunk-PFTOGTHH.js";
44
44
  import {
45
45
  runProtectedRouterTurn
46
46
  } from "../chunk-G3LZITCA.js";
@@ -79,15 +79,15 @@ import {
79
79
  turnCarriesFiles,
80
80
  turnPromptText,
81
81
  withProducerStream
82
- } from "../chunk-3WU6HDEZ.js";
83
- import "../chunk-KADVQCAS.js";
82
+ } from "../chunk-DCJCZ7EP.js";
83
+ import "../chunk-CWO2LHXH.js";
84
84
  import {
85
85
  sniffMimeFromName
86
86
  } from "../chunk-ZNE4NYU7.js";
87
87
  import "../chunk-RN4WPTBH.js";
88
88
  import "../chunk-4DBHC63F.js";
89
89
  import "../chunk-MM6RLOXF.js";
90
- import "../chunk-VOXKDO4T.js";
90
+ import "../chunk-56JUV4DK.js";
91
91
  import "../chunk-F4TUZYMX.js";
92
92
  import {
93
93
  redactErrorMessage
@@ -98,15 +98,31 @@ import {
98
98
  isDraftContentEvent,
99
99
  rowIdOf,
100
100
  storeSupportsDraftPersistence
101
- } from "../chunk-QJ5DSIHV.js";
101
+ } from "../chunk-6LMM3OVX.js";
102
102
  import "../chunk-2PCNHHN2.js";
103
103
  import "../chunk-YG66IHDU.js";
104
104
  import {
105
105
  attachmentInputToPart,
106
106
  attachmentKindForMime,
107
107
  toChatMessageParts
108
- } from "../chunk-6RGNXPXW.js";
108
+ } from "../chunk-36HSG7HU.js";
109
109
  import "../chunk-ZVEEWGDK.js";
110
+ import {
111
+ getPartKey,
112
+ mergePersistedPart
113
+ } from "../chunk-O5AUJQIA.js";
114
+ import "../chunk-SRZTL3Z5.js";
115
+ import "../chunk-H4JL74GP.js";
116
+ import "../chunk-ALIWB2P3.js";
117
+ import {
118
+ DEFAULT_STALE_TURN_LOCK_GRACE_MS,
119
+ DEFAULT_TERMINAL_TURN_LOCK_GRACE_MS,
120
+ reconcileStaleTurnLock
121
+ } from "../chunk-N5RWYR5N.js";
122
+ import {
123
+ coalesceDeltas,
124
+ createBufferedTurnTap
125
+ } from "../chunk-3Q3UEWKK.js";
110
126
  import {
111
127
  ChatTurnInputError,
112
128
  DISPATCH_MAX_MEDIA_PARTS,
@@ -139,23 +155,7 @@ import {
139
155
  settleTurnResponse,
140
156
  turnResponseEventFor,
141
157
  validateSandboxMentionPath
142
- } from "../chunk-5TSRFF5W.js";
143
- import {
144
- getPartKey,
145
- mergePersistedPart
146
- } from "../chunk-VUBJZEZB.js";
147
- import "../chunk-6VQCFJWP.js";
148
- import "../chunk-H4JL74GP.js";
149
- import "../chunk-ALIWB2P3.js";
150
- import {
151
- DEFAULT_STALE_TURN_LOCK_GRACE_MS,
152
- DEFAULT_TERMINAL_TURN_LOCK_GRACE_MS,
153
- reconcileStaleTurnLock
154
- } from "../chunk-N5RWYR5N.js";
155
- import {
156
- coalesceDeltas,
157
- createBufferedTurnTap
158
- } from "../chunk-3Q3UEWKK.js";
158
+ } from "../chunk-QGJOT6R6.js";
159
159
  import "../chunk-QUT3T2IN.js";
160
160
  import "../chunk-XELWWXJJ.js";
161
161
  import "../chunk-DSMGS4IV.js";
@@ -85,6 +85,8 @@ export interface ProducerNoticeEvent {
85
85
  text: string;
86
86
  /** Typed reason, on an `error` notice. */
87
87
  code?: string;
88
+ /** The failure's redacted cause chain, persisted with the notice and not rendered. */
89
+ detail?: string;
88
90
  }
89
91
  /** Represent an error event emitted by a producer containing message, code, and optional details */
90
92
  export interface ProducerErrorEvent {
@@ -15,13 +15,13 @@ import {
15
15
  mentionInputToPart,
16
16
  mentionPartsFromMessageParts,
17
17
  toChatMessageParts
18
- } from "../chunk-6RGNXPXW.js";
18
+ } from "../chunk-36HSG7HU.js";
19
19
  import "../chunk-ZVEEWGDK.js";
20
- import "../chunk-5TSRFF5W.js";
21
20
  import {
22
21
  attachmentPartKey
23
- } from "../chunk-VUBJZEZB.js";
24
- import "../chunk-6VQCFJWP.js";
22
+ } from "../chunk-O5AUJQIA.js";
23
+ import "../chunk-SRZTL3Z5.js";
24
+ import "../chunk-QGJOT6R6.js";
25
25
  import "../chunk-TXD5HXLE.js";
26
26
  import "../chunk-WL7PZK7Q.js";
27
27
 
@@ -187,6 +187,8 @@ export interface ChatNoticePart {
187
187
  text: string;
188
188
  /** Typed reason for an `error` notice, e.g. the sandbox or upstream error code. */
189
189
  code?: string;
190
+ /** The failure's redacted cause chain, for operators and support. Kept with the transcript; not rendered. */
191
+ detail?: string;
190
192
  }
191
193
  /**
192
194
  * A file the user `@`-mentioned on this turn: a workspace-relative path into
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  persistedPartToWorkProduct
3
3
  } from "./chunk-ZVEEWGDK.js";
4
- import {
5
- mentionKindForPath
6
- } from "./chunk-5TSRFF5W.js";
7
4
  import {
8
5
  persistedPartToInteraction
9
- } from "./chunk-6VQCFJWP.js";
6
+ } from "./chunk-SRZTL3Z5.js";
7
+ import {
8
+ mentionKindForPath
9
+ } from "./chunk-QGJOT6R6.js";
10
10
  import {
11
11
  persistedPartToPlan,
12
12
  planToPersistedPart
@@ -146,4 +146,4 @@ export {
146
146
  buildAttachmentPromptBlock,
147
147
  historyContentWithAttachments
148
148
  };
149
- //# sourceMappingURL=chunk-6RGNXPXW.js.map
149
+ //# sourceMappingURL=chunk-36HSG7HU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/chat-store/parts.ts"],"sourcesContent":["/**\n * The stored shape of `message.parts` — one typed vocabulary for every part a\n * product persists into a chat transcript. NOT an ad-hoc union reverse-\n * engineered from product schemas; each member is matched field-for-field to\n * its canonical source:\n *\n * - `text` / `reasoning` / `tool`: the persisted projection `/stream`'s\n * `normalizePersistedPart` produces from the harness lane's\n * `message.part.updated` events (ADC sidecar\n * `apps/sidecar/src/events/session-events.ts:56` wraps the canonical part in\n * an `{id, sessionID, messageID}` envelope; the projection strips the\n * session/message ids and keeps the per-segment part id).\n * - `file` / `image` / `step-start` / `step-finish`: the sidecar's canonical\n * `MessagePartSchema` members (ADC\n * `apps/sidecar/src/schemas/agent-schemas.ts:50-154`); `step-finish` carries\n * the harness's per-step usage receipt — tokens\n * `{total, input, output, reasoning, cache{write, read}}` + `cost` — which is\n * also the shape the message-level token/cost columns mirror.\n * - `subtask`: `@tangle-network/agent-interface`'s `SubtaskPart` (a spawned\n * sub-agent task).\n * - `interaction` / `notice`: the persisted-part codecs in\n * `/web-react`'s chat-interactions contract (`interactionToPersistedPart`,\n * `noticePart`) — type-only imports, one source of truth for their statuses\n * and field shapes.\n * - `plan`: the durable-plan projection in `/plans`, derived from the sandbox\n * SDK's authoritative plan lifecycle.\n * - `work_product`: the persisted work-product anchor card in\n * `/work-product`'s contract (`workProductToPersistedPart` /\n * `persistedPartToWorkProduct`) — SYSTEM-authored on the ready transition\n * and updated on a reviewer verdict; no prompt teaches an agent to author\n * one.\n * - `mention`: an `@`-picked reference to a file that already lives in the\n * workspace sandbox (`FileMention` in `/chat-routes`'s wire contract, plus\n * the image/file discriminant). Neither transport lane produces it — the\n * turn route persists it from the request's `mentions` field — but it is a\n * part a product persists into a transcript, so it belongs in this\n * vocabulary rather than in a parallel one.\n *\n * `@tangle-network/agent-interface` exports the canonical wire `Part` union,\n * but its `PartBase` requires the `sessionID`/`messageID` stream envelope that\n * is deliberately NOT persisted, so the stored union is defined here as the\n * envelope-free projection (a type-level coverage check against the peer's\n * `Part['type']` lives in the tests). Contribute-down candidate: if\n * agent-interface grows envelope-free persisted-part types, re-export them\n * here and delete these definitions.\n *\n * Two transport lanes serialize into this SAME stored shape:\n * - harness lane: canonical `message.part.updated` parts, merged/normalized by\n * `/stream` (`mergePersistedPart`, `finalizeAssistantParts`);\n * - router/openai-compat lane: `text_delta`/`tool_call` stream events are\n * mapped INTO canonical part events first (`/runtime`'s `toLoopEvents` +\n * `/stream`'s `normalizeToolEvent`) and then persisted identically — the\n * store never sees a router-specific shape.\n */\n\nimport type { Part as HarnessWirePart } from '@tangle-network/agent-interface'\nimport type {\n ChatInteractionField,\n ChatInteractionStatus,\n InteractionAnswers,\n NoticeKind,\n} from '../web-react/chat-interactions'\nimport { persistedPartToInteraction } from '../interactions/contract'\nimport {\n persistedPartToWorkProduct,\n type WorkProductPersistedPart,\n} from '../work-product/types'\nimport {\n persistedPartToPlan,\n planToPersistedPart,\n type ChatPlanPersistedPart,\n} from '../plans/index'\n// `./wire` is import-free by construction, so this edge costs the store\n// nothing and keeps ONE image-extension table for the whole mention layer.\nimport {\n mentionKindForPath,\n type ChatAttachmentInput,\n type ChatAttachmentKind,\n type ChatMentionKind,\n type FileMention,\n} from '../chat-routes/wire'\n\nexport type { ChatMentionKind, ChatAttachmentKind }\n\n/** Start/end wall-clock millis, as normalized by `/stream`'s `normalizeTime`. */\nexport interface ChatPartTime {\n start?: number\n end?: number\n}\n\n/** `id` is the harness's per-segment identity; absent on legacy/router parts,\n * which collapse to a single logical text stream. Never invented client-side. */\nexport interface ChatTextPart {\n type: 'text'\n text: string\n id?: string\n}\n\n/** Define a reasoning part of a chat with text content and optional metadata fields */\nexport interface ChatReasoningPart {\n type: 'reasoning'\n text: string\n id?: string\n time?: ChatPartTime\n}\n\n/** Superset of the sidecar's status enum (`pending|running|completed|failed`)\n * and agent-interface's `ToolState` statuses; `error` is the persisted\n * terminal form `/stream`'s `normalizePersistedPart` settles on. */\nexport type ChatToolStatus = 'pending' | 'running' | 'completed' | 'error' | 'failed'\n\n/** Describe the current state and data of a chat tool including status, input, output, and metadata */\nexport interface ChatToolState {\n status: ChatToolStatus\n input?: unknown\n output?: unknown\n error?: string\n title?: string\n metadata?: Record<string, unknown>\n time?: ChatPartTime\n}\n\n/** Define a chat component representing a tool with its state and optional call identifier */\nexport interface ChatToolPart {\n type: 'tool'\n id: string\n tool: string\n callID?: string\n state: ChatToolState\n}\n\n/** Union of the sidecar's legacy (path-based) and AI-SDK (url-based) file\n * shapes; response-side every field besides `type` is optional. `name` is the\n * attachment-flavored display label an uploaded/promoted file carries (see\n * {@link ChatAttachmentPart}) — absent on a harness-emitted file part, which\n * uses `filename`. */\nexport interface ChatFilePart {\n type: 'file'\n id?: string\n filename?: string\n name?: string\n mediaType?: string\n url?: string\n path?: string\n content?: string\n}\n\n/** Define properties for an image part within a chat message including optional metadata fields */\nexport interface ChatImagePart {\n type: 'image'\n filename?: string\n name?: string\n mediaType?: string\n url?: string\n path?: string\n}\n\n/** Define a subtask part of a chat with prompt, description, agent, and optional identifier */\nexport interface ChatSubtaskPart {\n type: 'subtask'\n prompt: string\n description: string\n agent: string\n id?: string\n}\n\n/** OpenCode step-boundary marker — no renderable text; preserved so mappers\n * never coerce it into a \"[object Object]\" text part. */\nexport interface ChatStepStartPart {\n type: 'step-start'\n}\n\n/** Per-step usage receipt as the harness reports it (sidecar\n * `StepFinishPartSchema`). The message-level token/cost columns are this\n * shape flattened. */\nexport interface ChatUsageTokens {\n total?: number\n input?: number\n output?: number\n reasoning?: number\n cache?: {\n write?: number\n read?: number\n }\n}\n\n/** Define a chat step finish part indicating completion with optional reason, tokens, and cost */\nexport interface ChatStepFinishPart {\n type: 'step-finish'\n reason?: string\n tokens?: ChatUsageTokens\n cost?: number\n}\n\n/** Persisted human-in-the-loop ask — byte-matches\n * `interactionToPersistedPart` in `/web-react`'s chat-interactions contract. */\nexport interface ChatInteractionPart {\n type: 'interaction'\n id: string\n kind: string\n title: string\n body?: string\n answerSpec: { fields: ChatInteractionField[] }\n status: ChatInteractionStatus\n answers?: InteractionAnswers\n cancelReason?: string\n}\n\n/** Resolve a chat plan part by aliasing it to the persisted chat plan part type */\nexport type ChatPlanPart = ChatPlanPersistedPart\n\n/** Persisted work-product anchor card — byte-matches\n * `workProductToPersistedPart` in `/work-product`'s contract. Written by the\n * PLATFORM on the ready transition (and updated on a verdict); never\n * authored by a prompt. */\nexport type ChatWorkProductPart = WorkProductPersistedPart\n\n/** Persisted one-line transcript notice — byte-matches `noticePart` in\n * `/web-react`'s chat-interactions contract. */\nexport interface ChatNoticePart {\n type: 'notice'\n id: string\n noticeKind: NoticeKind\n text: string\n /** Typed reason for an `error` notice, e.g. the sandbox or upstream error code. */\n code?: string\n /** The failure's redacted cause chain, for operators and support. Kept with the transcript; not rendered. */\n detail?: string\n}\n\n/**\n * A file the user `@`-mentioned on this turn: a workspace-relative path into\n * the sandbox, never bytes. `type: 'mention'` is its own discriminant\n * precisely so it does NOT collide with the `file`/`image` attachment parts —\n * an attachment carries content the product uploaded, a mention points at\n * something the box already has, and a transcript renders them differently\n * (an inline pill, not an attachment card).\n *\n * `path` is the identity: mentioning one file twice in a turn folds to one\n * part. `turnId` is optional and set by products that rebuild a turn's\n * mentions on retry.\n */\nexport interface ChatMentionPart {\n type: 'mention'\n mentionKind: ChatMentionKind\n path: string\n name: string\n size?: number\n turnId?: string\n}\n\n/** Represent parts of a chat message including text, reasoning, tools, files, images, subtasks, steps, interactions, notices, plans, and mentions */\nexport type ChatMessagePart =\n | ChatTextPart\n | ChatReasoningPart\n | ChatToolPart\n | ChatFilePart\n | ChatImagePart\n | ChatSubtaskPart\n | ChatStepStartPart\n | ChatStepFinishPart\n | ChatInteractionPart\n | ChatNoticePart\n | ChatPlanPart\n | ChatWorkProductPart\n | ChatMentionPart\n\n/** Every canonical harness wire-part kind must be storable — compile-time\n * guarantee that a new agent-interface part kind cannot silently fall out of\n * the persisted vocabulary. */\nexport type StorableHarnessPartKind = HarnessWirePart['type'] & ChatMessagePart['type']\n\n/**\n * The typed projection at the `/stream` → `/chat-store` boundary. The stream\n * normalizers (`normalizePersistedPart`/`mergePersistedPart`/\n * `finalizeAssistantParts`) deliberately produce untyped `JsonRecord`s — they\n * normalize wire shapes and do not own the stored vocabulary. THIS module\n * owns it, so this is where rows gain the `ChatMessagePart` type: each entry\n * is validated against its kind's required fields and narrowed, junk is\n * dropped, and — enforced by the exhaustiveness check below — no storable\n * kind can silently fall out (the step-finish/interaction trap).\n */\nexport function toChatMessageParts(parts: Array<Record<string, unknown>>): ChatMessagePart[] {\n const out: ChatMessagePart[] = []\n for (const part of parts) {\n const typed = toChatMessagePart(part)\n if (typed) out.push(typed)\n }\n return out\n}\n\nconst str = (value: unknown): value is string => typeof value === 'string'\n\nfunction toChatMessagePart(part: Record<string, unknown>): ChatMessagePart | null {\n if (!part || typeof part !== 'object') return null\n const type = part.type as ChatMessagePart['type'] | undefined\n switch (type) {\n case 'text':\n case 'reasoning':\n return str(part.text) ? (part as unknown as ChatTextPart | ChatReasoningPart) : null\n case 'tool':\n return str(part.id) && str(part.tool) && part.state && typeof part.state === 'object'\n ? (part as unknown as ChatToolPart)\n : null\n case 'file':\n case 'image':\n return part as unknown as ChatFilePart | ChatImagePart\n case 'subtask':\n return str(part.prompt) && str(part.description) && str(part.agent)\n ? (part as unknown as ChatSubtaskPart)\n : null\n case 'step-start':\n return { type: 'step-start' }\n case 'step-finish':\n return part as unknown as ChatStepFinishPart\n case 'interaction':\n return persistedPartToInteraction(part) ? (part as unknown as ChatInteractionPart) : null\n case 'notice':\n return str(part.id) && str(part.noticeKind) && str(part.text)\n ? (part as unknown as ChatNoticePart)\n : null\n case 'plan': {\n const plan = persistedPartToPlan(part)\n return plan ? ({ ...part, ...planToPersistedPart(plan) } as ChatPlanPart) : null\n }\n case 'work_product':\n // Validate via the codec but keep the original row (extra fields the\n // product persisted round-trip, matching the interaction case).\n return persistedPartToWorkProduct(part) ? (part as unknown as ChatWorkProductPart) : null\n case 'mention':\n return isChatMentionPart(part) ? part : null\n case undefined:\n return null\n default: {\n // Compile-time exhaustiveness: a new ChatMessagePart kind that is not\n // handled above makes `type` non-never here and this line fails.\n const _exhaustive: never = type\n void _exhaustive\n return null\n }\n }\n}\n/** Resolve whether a ChatMessagePart is a ChatInteractionPart based on its type property */\nexport function isChatInteractionPart(part: ChatMessagePart): part is ChatInteractionPart {\n return part.type === 'interaction'\n}\n/** Widened to `unknown` — unlike its siblings this guard also runs over raw\n * untyped stored rows (a transcript renderer reads `message.parts` before the\n * typed projection), which is exactly what {@link mentionPartsFromMessageParts}\n * needs. `path` and `name` carry the pill; a row missing either is unrenderable.\n *\n * Mirrors the write contract exactly (`parseFileMention` in `/chat-routes`,\n * then {@link mentionInputToPart}): a blank `name` is rejected there and so is\n * rejected here, and `size` — optional, but typed `number` once present — is\n * type-checked so `'12'` or `null` cannot ride through the guard wearing a\n * type it does not have. Negative sizes are NOT re-rejected: the wire screens\n * them, `mentionInputToPart` trusts its input, and a read guard stricter than\n * what the writer can emit would drop rows it produced itself. */\nexport function isChatMentionPart(part: unknown): part is ChatMentionPart {\n if (!part || typeof part !== 'object') return false\n const record = part as Record<string, unknown>\n if (record.size !== undefined && (typeof record.size !== 'number' || !Number.isFinite(record.size))) {\n return false\n }\n return (\n record.type === 'mention' &&\n typeof record.path === 'string' &&\n record.path.length > 0 &&\n typeof record.name === 'string' &&\n record.name.trim().length > 0 &&\n (record.mentionKind === 'image' || record.mentionKind === 'file')\n )\n}\n\n/** Every mention part on one message, in stored order. The projection a\n * transcript renderer runs before deciding which mentions the message text\n * already shows inline (see `segmentMentionContent` in `/web-react`). */\nexport function mentionPartsFromMessageParts(\n parts: ReadonlyArray<Record<string, unknown>> | ReadonlyArray<ChatMessagePart> | null | undefined,\n): ChatMentionPart[] {\n if (!parts) return []\n return (parts as ReadonlyArray<unknown>).filter(isChatMentionPart)\n}\n\n/** A validated wire mention (`parseFileMentions` in `/chat-routes`) as the\n * part the turn route persists. An absent/non-finite `size` is DROPPED rather\n * than stored as `undefined`, so a stored row never carries a key that means\n * nothing. */\nexport function mentionInputToPart(input: FileMention): ChatMentionPart {\n const part: ChatMentionPart = {\n type: 'mention',\n mentionKind: mentionKindForPath(input.path),\n path: input.path,\n name: input.name,\n }\n if (typeof input.size === 'number' && Number.isFinite(input.size)) part.size = input.size\n return part\n}\n\n// ── attachments ──────────────────────────────────────────────────────────\n//\n// An attachment is a file the product uploaded into its own store (vault /\n// object-store) ahead of the turn — content the box did not already have,\n// unlike a `@`-mention. It persists NOT as a new `ChatMessagePart` union\n// member but as an attachment-flavored `file`/`image` part: `type` is the\n// existing `image`/`file` discriminant, with `path` + `name` load-bearing.\n// That reuse is deliberate — a transcript already renders `file`/`image`\n// parts, and `toChatMessagePart` passes them through by cast (fields survive),\n// so an attachment slots into the same stored `parts` array without a parallel\n// vocabulary. These helpers own the input→part projection, the path-keyed\n// stream key, and the agent-facing prompt block, all byte-identical to the gtm\n// source they were lifted from (gtm-agent#618 adoption reproduces its rows and\n// dispatched prompt bytes through them).\n\n/** `image` for any `image/*` mime, `file` for everything else (including an\n * absent/empty mime) — the same split the composer and the persisted-part\n * discriminant both key on. */\nexport function attachmentKindForMime(mime?: string): ChatAttachmentKind {\n return mime?.startsWith('image/') ? 'image' : 'file'\n}\n\n/** Stream/transcript part key for an attachment — ONE declaration, owned by\n * `/stream`'s normalizer (whose `getPartKey` routes path-bearing file/image\n * parts through it). Re-exported here (not redefined) so the root barrel's\n * star-exports of both modules resolve to the same symbol instead of\n * colliding (TS2308 in the dts build). */\nexport { attachmentPartKey } from '../stream/stream-normalizer'\n\n/**\n * Persisted attachment part: structurally an attachment-flavored `ChatFilePart`\n * / `ChatImagePart` (`path` + `name` promoted to required) rather than a\n * separate union member — see the section note above. The index signature keeps\n * it a `Record<string, unknown>` so it drops into the same untyped `parts`\n * arrays every other stored part rides in, and lets the `type`-driven\n * constructors below build it without union-discriminant gymnastics.\n */\nexport interface ChatAttachmentPart {\n type: ChatAttachmentKind\n path: string\n name: string\n size?: number\n mediaType?: string\n turnId?: string\n [key: string]: unknown\n}\n\n/** True for any `image`/`file` part carrying a non-empty string `path`.\n * DELIBERATELY also matches a sidecar path-bearing file part (a mention-style\n * `file` part with only `path`) — the guard is a structural attachment shape,\n * not proof of provenance; a caller that needs to exclude those filters\n * upstream. The `path.length > 0` check diverges from gtm's original guard\n * (which only checked `typeof`), mirroring sibling {@link isChatMentionPart}:\n * read-side robustness against a stored `{type:'file', path:''}` row — which\n * would otherwise render a malformed `(vault: )` pointer line — justifies the\n * small divergence from byte-for-byte gtm parity here; no legitimate write\n * path ever produces an empty `path`. */\nexport function isChatAttachmentPart(part: unknown): part is ChatAttachmentPart {\n if (!part || typeof part !== 'object') return false\n const record = part as Record<string, unknown>\n return (\n (record.type === 'image' || record.type === 'file') &&\n typeof record.path === 'string' &&\n record.path.length > 0\n )\n}\n\n/** Drop absent/empty optional fields rather than persisting `undefined`/`''`\n * — keeps stored parts minimal. */\nexport function attachmentInputToPart(input: ChatAttachmentInput): ChatAttachmentPart {\n const part: ChatAttachmentPart = { type: input.kind, path: input.path, name: input.name }\n if (typeof input.size === 'number' && Number.isFinite(input.size)) part.size = input.size\n if (input.mediaType) part.mediaType = input.mediaType\n return part\n}\n\n/** Every attachment part on one message's stored `parts`, in stored order. */\nexport function attachmentPartsFromMessageParts(\n parts: ReadonlyArray<Record<string, unknown>> | null | undefined,\n): ChatAttachmentPart[] {\n if (!parts) return []\n return parts.filter(isChatAttachmentPart)\n}\n\n/** Attachment carry-forward in first-seen path order. Current-turn paths\n * are excluded; a later history row replaces a path's value without moving\n * the Map entry, matching the existing product dispatches. */\nexport function historyAttachmentsFromMessages(\n currentAttachments: ReadonlyArray<Pick<ChatAttachmentPart, 'path'>>,\n priorMessages: ReadonlyArray<{ parts?: ReadonlyArray<Record<string, unknown>> | null }>,\n): ChatAttachmentPart[] {\n const currentPaths = new Set(currentAttachments.map((part) => part.path))\n const historyByPath = new Map<string, ChatAttachmentPart>()\n for (const message of priorMessages) {\n for (const part of attachmentPartsFromMessageParts(message.parts)) {\n if (!currentPaths.has(part.path)) historyByPath.set(part.path, part)\n }\n }\n return [...historyByPath.values()]\n}\n\n/** gtm's exact default header for {@link buildAttachmentPromptBlock} — kept\n * byte-identical because it feeds dispatched prompts (gtm-agent#618\n * reproduces the prompt bytes through this module). Override only with intent. */\nexport const DEFAULT_ATTACHMENT_PROMPT_HEADER =\n 'Attached files (already saved to the workspace vault — read them from these paths):'\n\n/** Same C0-control/DEL sweep as `/chat-routes`'s `resolve-attachments.ts`\n * (kept as a separate literal rather than a shared import — this module is\n * the read side and must stay usable over PERSISTED rows the wire validator\n * never saw). Replaced with a single space, not stripped or collapsed: this\n * is defense-in-depth for legacy/corrupt stored rows that bypassed wire\n * validation, not the primary control — a name/path a `resolveChatAttachments`\n * call validated today never contains one, so this is a no-op on legitimate\n * input and gtm byte-compat holds. */\nconst PROMPT_BLOCK_CONTROL_CHARS = /[\\x00-\\x1F\\x7F]/g\n\n/**\n * The agent-facing pointer block appended to the dispatched prompt — never\n * persisted in `message.content`. Empty array → `''` so callers can append\n * unconditionally. The sole producer of this text: both the current turn's\n * dispatch and history projection ({@link historyContentWithAttachments}) build\n * it from here, so the two can never drift. `header` overrides the first line\n * ({@link DEFAULT_ATTACHMENT_PROMPT_HEADER}); the per-file line format is fixed.\n *\n * Every interpolated `name`/`path` is swept for control characters first\n * (newline/carriage-return/tab included) and each one replaced with a single\n * space — a single-line-per-file guarantee. Without it, a control character\n * riding through on a PERSISTED row (`historyContentWithAttachments` reads\n * whatever is already stored; a legacy or hand-edited row was never re-checked\n * against `resolveChatAttachments`) could inject extra lines — fabricated\n * pointer entries or instructions — into a prompt the agent trusts verbatim.\n * The wire-side validator is the primary control; this is the backstop for\n * rows it never saw.\n */\nexport function buildAttachmentPromptBlock(\n atts: ReadonlyArray<Pick<ChatAttachmentPart, 'name' | 'path'>>,\n header: string = DEFAULT_ATTACHMENT_PROMPT_HEADER,\n): string {\n if (atts.length === 0) return ''\n const clean = (value: string) => value.replace(PROMPT_BLOCK_CONTROL_CHARS, ' ')\n const lines = atts.map((a) => `- ${clean(a.name)} (vault: ${clean(a.path)})`)\n return `\\n\\n${header}\\n${lines.join('\\n')}`\n}\n\n/**\n * History projection for a persisted message: `content` unchanged when it\n * carries no attachment parts, else the block is appended once. The\n * no-double-annotation guarantee holds under the invariant that the block is\n * never persisted INTO `message.content` — it is appended only at read time,\n * by this function and the current turn's dispatch, both sourcing from\n * `attachmentPartsFromMessageParts` — never by content inspection. This\n * function does not (and cannot) detect an already-embedded block by scanning\n * `content` for its text: a message whose stored `content` happens to already\n * contain the block's bytes, alongside attachment parts, still gets the block\n * appended a second time. See the pinned test for that boundary.\n */\nexport function historyContentWithAttachments(\n message: {\n content: string\n parts?: ReadonlyArray<Record<string, unknown>> | null\n },\n header?: string,\n): string {\n const attachmentParts = attachmentPartsFromMessageParts(message.parts)\n if (attachmentParts.length === 0) return message.content\n return `${message.content}${buildAttachmentPromptBlock(attachmentParts, header)}`\n}\n"],"mappings":"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","names":[]}
@@ -21,6 +21,9 @@ import {
21
21
  import {
22
22
  createD1TurnEventStore
23
23
  } from "./chunk-3Q3UEWKK.js";
24
+ import {
25
+ DISPATCH_REQUEST_MAX_BYTES
26
+ } from "./chunk-QGJOT6R6.js";
24
27
  import {
25
28
  assertProfilePromptWithinBudget,
26
29
  fingerprintAgentProfile
@@ -560,31 +563,44 @@ var SandboxRunError = class extends Error {
560
563
  var DEFAULT_TIMEOUT_MS = 5 * 6e4;
561
564
  var TASK_LIMIT = 2e4;
562
565
  var SANDBOX_RUN_DESCRIPTION = "Run work that needs a computer in this workspace's sandbox: executing code or scripts, reading or converting PDFs, spreadsheets and archives, filling forms with the installed toolkits, or editing many files. Describe the member's requirements, file paths and exact field names, not model-written code; the sandbox agent writes and runs the code and returns its answer. Takes seconds to minutes, so use it only when the answer needs the computer.";
566
+ function sandboxRunFailureDetail(error) {
567
+ return serializeSandboxProvisioningError(error).causes.map((cause) => [
568
+ cause.name,
569
+ cause.code !== void 0 ? `code=${cause.code}` : "",
570
+ cause.status !== void 0 ? `status=${cause.status}` : "",
571
+ cause.message
572
+ ].filter(Boolean).join(" ")).join(" <- ").slice(0, 2e3);
573
+ }
563
574
  function sandboxPromptRunner(shell, prompt = {}) {
564
575
  return async (box, task, { callId, signal, timeoutMs, trace, span }) => {
565
576
  const parent = prompt.executionId?.trim() || prompt.turnId?.trim();
566
577
  const identity = parent ? new TextEncoder().encode(JSON.stringify([parent, prompt.sessionId, callId?.trim() || crypto.randomUUID()])) : void 0;
567
578
  const digest = identity ? await crypto.subtle.digest("SHA-256", identity) : void 0;
568
579
  const child = digest ? Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("") : void 0;
569
- return runSandboxPrompt(shell, box, task, {
570
- ...prompt,
571
- ...child ? { executionId: child, turnId: child } : {},
572
- signal,
573
- timeoutMs,
574
- disallowQuestions: true,
575
- ...trace ? { trace } : {},
576
- ...span ? { traceParent: span } : {}
577
- });
580
+ let sent = false;
581
+ try {
582
+ return await runSandboxPrompt(shell, box, task, {
583
+ ...prompt,
584
+ ...child ? { executionId: child, turnId: child } : {},
585
+ signal,
586
+ timeoutMs,
587
+ disallowQuestions: true,
588
+ ...trace ? { trace } : {},
589
+ ...span ? { traceParent: span } : {},
590
+ onDispatch: () => {
591
+ sent = true;
592
+ prompt.onDispatch?.();
593
+ }
594
+ });
595
+ } catch (error) {
596
+ if (sent || error instanceof SandboxRunError || signal.aborted) throw error;
597
+ throw new SandboxRunError("sandbox_unavailable", "The computer step was refused before it was sent to the box.", { cause: error });
598
+ }
578
599
  };
579
600
  }
580
601
  function createSandboxRunTool(options) {
581
602
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
582
603
  const runTask = options.runTask;
583
- const fail2 = (code, message, cause) => {
584
- const error = new SandboxRunError(code, message, cause === void 0 ? void 0 : { cause });
585
- options.onFailure?.(error);
586
- throw error;
587
- };
588
604
  return {
589
605
  name: options.name ?? "sandbox_run",
590
606
  description: options.description ?? SANDBOX_RUN_DESCRIPTION,
@@ -595,6 +611,11 @@ function createSandboxRunTool(options) {
595
611
  additionalProperties: false
596
612
  },
597
613
  async run(args, context) {
614
+ const fail2 = (code, message, cause) => {
615
+ const error = new SandboxRunError(code, message, cause === void 0 ? void 0 : { cause });
616
+ options.onFailure?.(error, { ...context?.callId ? { callId: context.callId } : {} });
617
+ throw error;
618
+ };
598
619
  const emit = (kind, data) => {
599
620
  try {
600
621
  context?.emit(kind, data);
@@ -2008,14 +2029,47 @@ function sandboxToolPath(options) {
2008
2029
  const toolName = normalizeSandboxToolSegment(options.toolName, "sandbox tool name");
2009
2030
  return `${sandboxToolBinDir(options)}/${toolName}`;
2010
2031
  }
2032
+ var DUPLICATE_PROGRAM_MIN_BYTES = 4096;
2033
+ function sandboxToolAliasShim(alias, program) {
2034
+ return [
2035
+ "#!/bin/sh",
2036
+ `# ${alias} runs ${program} under its own name. Mounted by buildSandboxToolFileMounts (aliasOf).`,
2037
+ `program=${shellSingleQuote(program)}`,
2038
+ `link="\${TMPDIR:-/tmp}/sandbox-tool-aliases\${program}.d/${alias}"`,
2039
+ '[ -L "$link" ] || { mkdir -p "${link%/*}" && { ln -s "$program" "$link" 2>/dev/null || [ -L "$link" ]; }; } || {',
2040
+ ` echo "${alias}: cannot create its alias link under \${TMPDIR:-/tmp}" >&2`,
2041
+ " exit 126",
2042
+ "}",
2043
+ 'exec "$link" "$@"',
2044
+ ""
2045
+ ].join("\n");
2046
+ }
2011
2047
  function buildSandboxToolFileMounts(options) {
2048
+ const programs = /* @__PURE__ */ new Map();
2049
+ const byContent = /* @__PURE__ */ new Map();
2050
+ for (const tool of options.tools) {
2051
+ if (tool.aliasOf !== void 0) continue;
2052
+ const name = normalizeSandboxToolSegment(tool.name, "sandbox tool name");
2053
+ if (tool.executable !== false) programs.set(name, sandboxToolPath({ ...options, toolName: name }));
2054
+ const first = byContent.get(tool.content);
2055
+ if (first !== void 0 && new TextEncoder().encode(tool.content).byteLength >= DUPLICATE_PROGRAM_MIN_BYTES) {
2056
+ throw new Error(
2057
+ `sandbox tools ${first} and ${name} mount the same program; mount it once and declare ${name} as { name: '${name}', aliasOf: '${first}' }.`
2058
+ );
2059
+ }
2060
+ if (first === void 0) byContent.set(tool.content, name);
2061
+ }
2012
2062
  return options.tools.map((tool) => {
2013
2063
  const name = normalizeSandboxToolSegment(tool.name, "sandbox tool name");
2014
- return {
2015
- path: sandboxToolPath({ ...options, toolName: name }),
2016
- resource: { kind: "inline", name, content: tool.content },
2017
- executable: tool.executable ?? true
2018
- };
2064
+ const path = sandboxToolPath({ ...options, toolName: name });
2065
+ if (tool.aliasOf === void 0) {
2066
+ return { path, resource: { kind: "inline", name, content: tool.content }, executable: tool.executable ?? true };
2067
+ }
2068
+ const program = programs.get(normalizeSandboxToolSegment(tool.aliasOf, "sandbox tool aliasOf"));
2069
+ if (!program) {
2070
+ throw new Error(`sandbox tool ${name} is an alias of ${tool.aliasOf}, which is not an executable program in this call.`);
2071
+ }
2072
+ return { path, resource: { kind: "inline", name, content: sandboxToolAliasShim(name, program) }, executable: true };
2019
2073
  });
2020
2074
  }
2021
2075
  function buildSandboxToolBinDirsEnv(apps) {
@@ -2348,6 +2402,18 @@ function assertEnvWithinLimits(env) {
2348
2402
  );
2349
2403
  }
2350
2404
  }
2405
+ function assertIsolatedDispatchWithinCap(input) {
2406
+ const isolated = input.backend.metadata?.profileSecretIsolation === true || Boolean(input.expectedSecretProfileReceipt);
2407
+ if (!isolated) return;
2408
+ const total = utf8ByteLength({ parts: input.prompt, backend: input.backend });
2409
+ if (total <= DISPATCH_REQUEST_MAX_BYTES) return;
2410
+ const profile = input.backend.profile;
2411
+ const files = (typeof profile === "string" ? void 0 : profile?.resources?.files) ?? [];
2412
+ const largest = files.map((file) => ({ path: typeof file.path === "string" ? file.path : "(unnamed)", bytes: utf8ByteLength(file) })).sort((a, b) => b.bytes - a.bytes).slice(0, 5).map((file) => `${file.path}=${file.bytes}B`);
2413
+ throw new Error(
2414
+ `The isolated computer dispatch is ${total} bytes, over the sandbox gateway's ${DISPATCH_REQUEST_MAX_BYTES}-byte request cap, so it was not sent. An isolated session sends every file mount inline. prompt=${utf8ByteLength(input.prompt)}B, profile files=${utf8ByteLength(files)}B` + (largest.length ? `; largest: ${largest.join(", ")}` : "") + ". Mount one program under several names with `aliasOf` in buildSandboxToolFileMounts, or move large content out of the isolated profile."
2415
+ );
2416
+ }
2351
2417
 
2352
2418
  // src/sandbox/workspace-boxes.ts
2353
2419
  async function listRunning(client, name) {
@@ -3360,6 +3426,7 @@ async function* detachedSandboxPromptEvents(box, prompt, options, backend) {
3360
3426
  options.signal?.throwIfAborted();
3361
3427
  const lastEventId = options.lastEventId?.trim() || void 0;
3362
3428
  const turnId = options.turnId?.trim() || executionId;
3429
+ if (!lastEventId) options.onDispatch?.();
3363
3430
  const admission = lastEventId ? null : await box.dispatchPrompt(prompt, {
3364
3431
  sessionId,
3365
3432
  executionId,
@@ -3580,30 +3647,35 @@ async function* resendRefusedDispatch(dispatch, signal) {
3580
3647
  }
3581
3648
  }
3582
3649
  async function* streamSandboxPrompt(shell, box, message, options) {
3650
+ const prompt = typeof message === "string" ? flattenHistory(message, options?.history) : mergeHistoryIntoParts(message, options?.history);
3583
3651
  let backend;
3584
3652
  try {
3585
3653
  options?.signal?.throwIfAborted();
3586
3654
  backend = await resolveSandboxPromptBackend(shell, options ?? {}, "streamSandboxPrompt");
3655
+ assertIsolatedDispatchWithinCap({ prompt, backend, expectedSecretProfileReceipt: options?.expectedSecretProfileReceipt });
3587
3656
  options?.signal?.throwIfAborted();
3588
3657
  } catch (error) {
3589
3658
  if (error instanceof SandboxModelResolutionError) throw error;
3590
3659
  throw new SandboxRunError("sandbox_unavailable", error instanceof Error ? error.message : "The sandbox prompt was not dispatched because its configuration or admission was refused.", { cause: error });
3591
3660
  }
3592
- const prompt = typeof message === "string" ? flattenHistory(message, options?.history) : mergeHistoryIntoParts(message, options?.history);
3593
- const dispatch = () => options?.detach ? detachedSandboxPromptEvents(box, prompt, options, backend) : box.streamPrompt(prompt, {
3594
- sessionId: options?.sessionId,
3595
- executionId: options?.executionId,
3596
- turnId: options?.turnId,
3597
- lastEventId: options?.lastEventId,
3598
- ...options?.signal ? { signal: options.signal } : {},
3599
- ...options?.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {},
3600
- ...options?.ttlMs !== void 0 ? { ttlMs: options.ttlMs } : {},
3601
- ...options?.requireVisibleAssistantOutput !== void 0 ? { requireVisibleAssistantOutput: options.requireVisibleAssistantOutput } : {},
3602
- ...options?.expectedPublicProfileRequestDigest ? { expectedPublicProfileRequestDigest: options.expectedPublicProfileRequestDigest } : {},
3603
- ...options?.expectedSecretProfileReceipt ? { expectedSecretProfileReceipt: options.expectedSecretProfileReceipt } : {},
3604
- ...options?.trace ? { traceId: options.trace.traceId } : {},
3605
- backend
3606
- });
3661
+ const dispatch = () => {
3662
+ if (options?.detach) return detachedSandboxPromptEvents(box, prompt, options, backend);
3663
+ if (!options?.lastEventId) options?.onDispatch?.();
3664
+ return box.streamPrompt(prompt, {
3665
+ sessionId: options?.sessionId,
3666
+ executionId: options?.executionId,
3667
+ turnId: options?.turnId,
3668
+ lastEventId: options?.lastEventId,
3669
+ ...options?.signal ? { signal: options.signal } : {},
3670
+ ...options?.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {},
3671
+ ...options?.ttlMs !== void 0 ? { ttlMs: options.ttlMs } : {},
3672
+ ...options?.requireVisibleAssistantOutput !== void 0 ? { requireVisibleAssistantOutput: options.requireVisibleAssistantOutput } : {},
3673
+ ...options?.expectedPublicProfileRequestDigest ? { expectedPublicProfileRequestDigest: options.expectedPublicProfileRequestDigest } : {},
3674
+ ...options?.expectedSecretProfileReceipt ? { expectedSecretProfileReceipt: options.expectedSecretProfileReceipt } : {},
3675
+ ...options?.trace ? { traceId: options.trace.traceId } : {},
3676
+ backend
3677
+ });
3678
+ };
3607
3679
  const stream = options?.lastEventId ? dispatch() : resendRefusedDispatch(dispatch, options?.signal);
3608
3680
  emitSandboxActivity(options?.spend, box);
3609
3681
  let severedFinishReason = null;
@@ -3729,7 +3801,9 @@ async function runSandboxPrompt(shell, box, message, options) {
3729
3801
  async function driveSandboxTurn(shell, box, message, options) {
3730
3802
  const backend = await resolveSandboxPromptBackend(shell, options, "driveSandboxTurn");
3731
3803
  const prompt = typeof message === "string" ? flattenHistory(message, options.history) : mergeHistoryIntoParts(message, options.history);
3804
+ assertIsolatedDispatchWithinCap({ prompt, backend, expectedSecretProfileReceipt: options.expectedSecretProfileReceipt });
3732
3805
  try {
3806
+ options.onDispatch?.();
3733
3807
  const drive = await box.driveTurn(prompt, {
3734
3808
  sessionId: options.sessionId,
3735
3809
  ...options.turnId ? { turnId: options.turnId } : {},
@@ -3926,7 +4000,8 @@ export {
3926
4000
  deleteSecret,
3927
4001
  mintSandboxScopedToken,
3928
4002
  SANDBOX_RUN_DESCRIPTION,
4003
+ sandboxRunFailureDetail,
3929
4004
  sandboxPromptRunner,
3930
4005
  createSandboxRunTool
3931
4006
  };
3932
- //# sourceMappingURL=chunk-VOXKDO4T.js.map
4007
+ //# sourceMappingURL=chunk-56JUV4DK.js.map