@tangle-network/agent-app 4.0.35 → 4.0.37

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 (59) hide show
  1. package/dist/assistant/index.js +5 -5
  2. package/dist/chat-react/index.js +3 -3
  3. package/dist/chat-routes/index.js +19 -11
  4. package/dist/chat-routes/index.js.map +1 -1
  5. package/dist/chat-routes/turn-event-stream.d.ts +10 -1
  6. package/dist/chat-routes/turn-execution.d.ts +34 -3
  7. package/dist/chat-routes/turn-intent.d.ts +5 -0
  8. package/dist/chat-routes/turn-progress.d.ts +25 -1
  9. package/dist/chat-routes/turn-route-contracts.d.ts +31 -2
  10. package/dist/chat-routes/turn-settlement.d.ts +23 -0
  11. package/dist/chat-store/index.js +2 -2
  12. package/dist/{chunk-NAMSFODC.js → chunk-4YBNKXUE.js} +54 -4
  13. package/dist/chunk-4YBNKXUE.js.map +1 -0
  14. package/dist/{chunk-K2JPSXKI.js → chunk-6YLVFV3F.js} +39 -3
  15. package/dist/chunk-6YLVFV3F.js.map +1 -0
  16. package/dist/{chunk-PZTBXHPE.js → chunk-725RZ5JQ.js} +2 -2
  17. package/dist/{chunk-ONIIKYVV.js → chunk-77UNTK66.js} +357 -290
  18. package/dist/chunk-77UNTK66.js.map +1 -0
  19. package/dist/{chunk-KPCNNFBO.js → chunk-AOSQ5JCO.js} +41 -2
  20. package/dist/{chunk-KPCNNFBO.js.map → chunk-AOSQ5JCO.js.map} +1 -1
  21. package/dist/{chunk-GOKFD7ZZ.js → chunk-BMRKOPL6.js} +2 -2
  22. package/dist/{chunk-E633CJFH.js → chunk-COUT2WD5.js} +2 -2
  23. package/dist/{chunk-7VJCMEEE.js → chunk-DPD7LY3T.js} +11 -6
  24. package/dist/chunk-DPD7LY3T.js.map +1 -0
  25. package/dist/{chunk-5WVGSCBN.js → chunk-MGW25KMR.js} +4 -4
  26. package/dist/{chunk-IAK227OO.js → chunk-Q7NELHRU.js} +2 -2
  27. package/dist/{chunk-QFT2V2OE.js → chunk-RSSK6FUF.js} +2 -2
  28. package/dist/{chunk-4YZKDWMB.js → chunk-SADNHPAY.js} +2 -2
  29. package/dist/{chunk-LTCRS46I.js → chunk-VUI4IUIM.js} +25 -7
  30. package/dist/chunk-VUI4IUIM.js.map +1 -0
  31. package/dist/operator/index.js +2 -2
  32. package/dist/preset-cloudflare/index.js +6 -6
  33. package/dist/public-consultation/index.d.ts +1 -1
  34. package/dist/public-consultation/index.js +8 -8
  35. package/dist/runtime/index.js +3 -3
  36. package/dist/runtime/router-turn.js +2 -2
  37. package/dist/sandbox/index.js +4 -4
  38. package/dist/turn-stream/cancellation.d.ts +16 -0
  39. package/dist/turn-stream/core.d.ts +4 -0
  40. package/dist/turn-stream/do.d.ts +4 -2
  41. package/dist/turn-stream/hosted-turn.d.ts +20 -0
  42. package/dist/turn-stream/index.js +122 -5
  43. package/dist/turn-stream/index.js.map +1 -1
  44. package/dist/turn-trace/index.js +1 -1
  45. package/dist/web-react/chat-stream.d.ts +4 -2
  46. package/dist/web-react/index.js +13 -5
  47. package/package.json +1 -1
  48. package/dist/chunk-7VJCMEEE.js.map +0 -1
  49. package/dist/chunk-K2JPSXKI.js.map +0 -1
  50. package/dist/chunk-LTCRS46I.js.map +0 -1
  51. package/dist/chunk-NAMSFODC.js.map +0 -1
  52. package/dist/chunk-ONIIKYVV.js.map +0 -1
  53. /package/dist/{chunk-PZTBXHPE.js.map → chunk-725RZ5JQ.js.map} +0 -0
  54. /package/dist/{chunk-GOKFD7ZZ.js.map → chunk-BMRKOPL6.js.map} +0 -0
  55. /package/dist/{chunk-E633CJFH.js.map → chunk-COUT2WD5.js.map} +0 -0
  56. /package/dist/{chunk-5WVGSCBN.js.map → chunk-MGW25KMR.js.map} +0 -0
  57. /package/dist/{chunk-IAK227OO.js.map → chunk-Q7NELHRU.js.map} +0 -0
  58. /package/dist/{chunk-QFT2V2OE.js.map → chunk-RSSK6FUF.js.map} +0 -0
  59. /package/dist/{chunk-4YZKDWMB.js.map → chunk-SADNHPAY.js.map} +0 -0
@@ -5,6 +5,14 @@ import {
5
5
  // src/chat-routes/turn-progress.ts
6
6
  var TURN_PROGRESS_HEADER = "x-turn-progress";
7
7
  var TURN_PROGRESS_FIRST = "first";
8
+ var TURN_HOST_CONTROL_HEADER = "x-turn-host-control";
9
+ var TURN_HOST_CONTROL_FIRST = "first";
10
+ var TURN_HOST_CONTROL_EVENT = "turn.host.control";
11
+ function isTurnHostControlEvent(value) {
12
+ const event = value;
13
+ const target = event?.data;
14
+ return event?.type === TURN_HOST_CONTROL_EVENT && !!target && [target.hostId, target.workspaceId, target.threadId].every((value2) => typeof value2 === "string" && !!value2.trim()) && [target.clientTurnId, target.retryAttemptId].every((value2) => value2 === void 0 || typeof value2 === "string" && !!value2.trim());
15
+ }
8
16
  var TURN_PHASE_EVENT = "session.run.phase";
9
17
  var TURN_ROUTE_PHASE_MESSAGES = {
10
18
  accepted: "Loading your conversation\u2026",
@@ -43,13 +51,15 @@ async function turnResponseEventFor(response) {
43
51
  });
44
52
  return { type: TURN_RESPONSE_EVENT, data: { status: response.status, headers, body: await response.text() } };
45
53
  }
46
- async function settleTurnResponse(response, onPhase, onIntent) {
47
- if (response.headers.get(TURN_PROGRESS_HEADER) !== TURN_PROGRESS_FIRST || !response.body) return response;
54
+ async function settleTurnResponse(response, onPhase, onIntent, onHostControl) {
55
+ if (response.headers.get(TURN_PROGRESS_HEADER) !== TURN_PROGRESS_FIRST && response.headers.get(TURN_HOST_CONTROL_HEADER) !== TURN_HOST_CONTROL_FIRST || !response.body) return response;
48
56
  const reader = response.body.getReader();
49
57
  const decoder = new TextDecoder();
50
58
  const encoder = new TextEncoder();
51
59
  let buffer = "";
52
60
  let ended = false;
61
+ const requiresHostControl = response.headers.get(TURN_HOST_CONTROL_HEADER) === TURN_HOST_CONTROL_FIRST;
62
+ let hostControlReceived = false;
53
63
  for (; ; ) {
54
64
  let newline = buffer.indexOf("\n");
55
65
  while (newline < 0) {
@@ -80,6 +90,28 @@ async function settleTurnResponse(response, onPhase, onIntent) {
80
90
  } catch {
81
91
  event = null;
82
92
  }
93
+ if (isTurnHostControlEvent(event)) {
94
+ if (!requiresHostControl || hostControlReceived || !onHostControl) {
95
+ await reader.cancel().catch(() => {
96
+ });
97
+ throw new Error("Unexpected hosted control identity or missing onHostControl handler");
98
+ }
99
+ buffer = buffer.slice(newline + 1);
100
+ try {
101
+ onHostControl(event.data);
102
+ } catch (error) {
103
+ await reader.cancel().catch(() => {
104
+ });
105
+ throw error;
106
+ }
107
+ hostControlReceived = true;
108
+ continue;
109
+ }
110
+ if (requiresHostControl && !hostControlReceived) {
111
+ await reader.cancel().catch(() => {
112
+ });
113
+ throw new Error("The hosted envelope did not begin with a valid control identity");
114
+ }
83
115
  if (isTurnPhaseEvent(event)) {
84
116
  buffer = buffer.slice(newline + 1);
85
117
  onPhase(event.data);
@@ -376,6 +408,10 @@ function parseChatTurnParts(raw) {
376
408
  export {
377
409
  TURN_PROGRESS_HEADER,
378
410
  TURN_PROGRESS_FIRST,
411
+ TURN_HOST_CONTROL_HEADER,
412
+ TURN_HOST_CONTROL_FIRST,
413
+ TURN_HOST_CONTROL_EVENT,
414
+ isTurnHostControlEvent,
379
415
  TURN_PHASE_EVENT,
380
416
  TURN_ROUTE_PHASE_MESSAGES,
381
417
  buildTurnPhaseEvent,
@@ -412,4 +448,4 @@ export {
412
448
  parseFileMentions,
413
449
  parseChatTurnParts
414
450
  };
415
- //# sourceMappingURL=chunk-K2JPSXKI.js.map
451
+ //# sourceMappingURL=chunk-6YLVFV3F.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/chat-routes/turn-progress.ts","../src/chat-routes/wire.ts"],"sourcesContent":["/**\n * Turn progress: the real stage a chat turn is in, on the turn stream.\n *\n * A turn can spend seconds before its first answer token: authorization, the\n * conversation load, the single-flight lock, the product's pre-turn work, a\n * sandbox, the harness and the model's first token. `session.run.phase` events\n * name those stages as they happen, so a chat shows where the turn is instead\n * of a spinner.\n *\n * A client that sends {@link TURN_PROGRESS_HEADER} gets the response stream as\n * soon as the route has parsed the body and `authorize` has admitted the\n * caller. Authorization never runs inside the stream: every refusal it makes\n * (400, 401, 402, 403, 404, 429) is a plain HTTP response, so an unadmitted\n * caller sees no stage, holds no stream and starts no work. After admission,\n * anything the route answers with a non-stream response (a held lock's 409, a\n * gate's own response, a handoff, a failure) arrives as one\n * {@link TURN_RESPONSE_EVENT} carrying that response's status, headers and\n * body, and {@link settleTurnResponse} turns it back into the `Response` the\n * caller already handles. A client that does not send the header gets exactly\n * the responses it got before.\n *\n * The separate opt-in host-control envelope starts after identity/editor/thread\n * authorization, before paid admission. Its control event grants no execution\n * permission. Full admission still precedes accepted progress and all execution;\n * a later refusal is carried by turn.response. Legacy callers are unchanged.\n *\n * Product work that only an admitted turn may do (resolving its profile and\n * model, any write) belongs in `prepareTurn`, which runs after admission and,\n * on a progress-first stream, inside it with its own named stages.\n * `tests/chat-routes/authorize-before-stream.test.ts` is the gate that keeps\n * every shared route behind its `authorize`.\n *\n * Browser-safe and import-free: the server route and the web client share it.\n */\n\n/** Request header that asks for a progress-first turn stream. */\nexport const TURN_PROGRESS_HEADER = 'x-turn-progress'\n/** The only value of {@link TURN_PROGRESS_HEADER}. The route echoes it on a progress-first response. */\nexport const TURN_PROGRESS_FIRST = 'first'\n\n/** Opt in to the hosted invocation's identity envelope before paid admission. */\nexport const TURN_HOST_CONTROL_HEADER = 'x-turn-host-control'\nexport const TURN_HOST_CONTROL_FIRST = 'first'\n/** A control address, never paid admission, execution authority or assistant content. */\nexport const TURN_HOST_CONTROL_EVENT = 'turn.host.control'\nexport interface TurnHostControlTarget {\n hostId: string\n workspaceId: string\n threadId: string\n clientTurnId?: string\n retryAttemptId?: string\n}\nexport type TurnHostControlEvent = { type: typeof TURN_HOST_CONTROL_EVENT; data: TurnHostControlTarget }\n\n/** Validate the envelope without interpreting its opaque host id as authority. */\nexport function isTurnHostControlEvent(value: unknown): value is TurnHostControlEvent {\n const event = value as Partial<TurnHostControlEvent> | null\n const target = event?.data\n return event?.type === TURN_HOST_CONTROL_EVENT && !!target\n && [target.hostId, target.workspaceId, target.threadId].every(value => typeof value === 'string' && !!value.trim())\n && [target.clientTurnId, target.retryAttemptId].every(value => value === undefined || typeof value === 'string' && !!value.trim())\n}\n\n/** Stream event naming the turn's current stage. Non-terminal and never turn content. */\nexport const TURN_PHASE_EVENT = 'session.run.phase'\n\n/**\n * Stages the shared route emits before the producer runs. Products add their\n * own (a sandbox product emits `provisioning`, `starting`,\n * `awaiting-first-token`).\n * - `accepted`: the caller is admitted; the conversation and the lock are loading.\n * - `preparing`: the turn holds its lock; the product's pre-turn work is running.\n */\nexport type TurnRoutePhase = 'accepted' | 'preparing'\n\n/** The data of a {@link TURN_PHASE_EVENT}. */\nexport type TurnPhaseData = {\n /** Stage id: a {@link TurnRoutePhase} or a product's own stage. */\n phase: string\n /** Text the client shows verbatim. */\n message: string\n /** A keepalive for the current stage rather than a new stage. */\n heartbeat?: boolean\n /** Milliseconds since the current wait began. */\n elapsedMs?: number\n /** Milliseconds since the server received the request. */\n sinceRequestMs?: number\n}\n\n/** A {@link TURN_PHASE_EVENT} as it crosses the wire. */\nexport type TurnPhaseEvent = { type: typeof TURN_PHASE_EVENT; data: TurnPhaseData }\n\n/** Default text for the route's own stages. Products override it through `createChatTurnRoutes({ progressMessages })`. */\nexport const TURN_ROUTE_PHASE_MESSAGES: Record<TurnRoutePhase, string> = {\n accepted: 'Loading your conversation…',\n preparing: 'Preparing the agent…',\n}\n\n/** Build a {@link TURN_PHASE_EVENT}. */\nexport function buildTurnPhaseEvent(\n phase: string,\n message: string,\n opts: { heartbeat?: boolean; elapsedMs?: number; sinceRequestMs?: number } = {},\n): TurnPhaseEvent {\n return {\n type: TURN_PHASE_EVENT,\n data: {\n phase,\n message,\n ...(opts.heartbeat ? { heartbeat: true } : {}),\n ...(typeof opts.elapsedMs === 'number' ? { elapsedMs: opts.elapsedMs } : {}),\n ...(typeof opts.sinceRequestMs === 'number' ? { sinceRequestMs: opts.sinceRequestMs } : {}),\n },\n }\n}\n\n/** True for a {@link TURN_PHASE_EVENT} with a usable `phase` and `message`. */\nexport function isTurnPhaseEvent(event: unknown): event is TurnPhaseEvent {\n if (!event || typeof event !== 'object') return false\n const candidate = event as { type?: unknown; data?: { phase?: unknown; message?: unknown } }\n return candidate.type === TURN_PHASE_EVENT\n && typeof candidate.data?.phase === 'string'\n && typeof candidate.data?.message === 'string'\n}\n\n/**\n * Stream event carrying the turn's intent line: one plain sentence, written by\n * a fast model call at admission, saying what the agent is about to do (\"Looking\n * at your three competitors' pricing pages, then I'll draft the comparison.\").\n * A client shows it as a labeled status line, never as the answer, until the\n * turn's first answer text replaces it. It narrates intent; it never answers\n * or acts. Non-terminal and never turn content; at most one per turn.\n */\nexport const TURN_INTENT_EVENT = 'session.run.intent'\n\n/** The data of a {@link TURN_INTENT_EVENT}. */\nexport type TurnIntentData = {\n /** The sentence, shown verbatim. */\n text: string\n /** Milliseconds since the server received the request. */\n sinceRequestMs?: number\n}\n\n/** A {@link TURN_INTENT_EVENT} as it crosses the wire. */\nexport type TurnIntentEvent = { type: typeof TURN_INTENT_EVENT; data: TurnIntentData }\n\n/** True for a {@link TURN_INTENT_EVENT} with non-empty text. */\nexport function isTurnIntentEvent(event: unknown): event is TurnIntentEvent {\n if (!event || typeof event !== 'object') return false\n const candidate = event as { type?: unknown; data?: { text?: unknown } }\n return candidate.type === TURN_INTENT_EVENT\n && typeof candidate.data?.text === 'string'\n && candidate.data.text.trim().length > 0\n}\n\n/** Terminal event of a progress-first stream that ended without a turn: the response the route returned instead. */\nexport const TURN_RESPONSE_EVENT = 'turn.response'\n\n/** The data of a {@link TURN_RESPONSE_EVENT}. */\nexport type TurnResponseData = {\n status: number\n /** Response headers other than `set-cookie` and framing headers. */\n headers: Record<string, string>\n body: string\n}\n\n/** Headers a {@link TURN_RESPONSE_EVENT} cannot carry: cookies cannot be set after the stream opened, and framing belongs to the outer response. */\nconst UNCARRIED_HEADERS = new Set(['set-cookie', 'content-length', 'content-encoding', 'transfer-encoding', 'connection'])\n\n/** Error code {@link settleTurnResponse} reports when a progress-first stream closes before the turn started. */\nexport const TURN_STREAM_LOST_CODE = 'turn_stream_lost'\n\n/** Serialize a non-stream response for a {@link TURN_RESPONSE_EVENT}. */\nexport async function turnResponseEventFor(response: Response): Promise<{ type: typeof TURN_RESPONSE_EVENT; data: TurnResponseData }> {\n const headers: Record<string, string> = {}\n response.headers.forEach((value, key) => {\n if (!UNCARRIED_HEADERS.has(key.toLowerCase())) headers[key.toLowerCase()] = value\n })\n return { type: TURN_RESPONSE_EVENT, data: { status: response.status, headers, body: await response.text() } }\n}\n\n/**\n * Settle a turn response for a client that sent {@link TURN_PROGRESS_HEADER}.\n *\n * Reads the stream's leading progress events, handing each to `onPhase` (and an\n * intent line to `onIntent`, or dropping it when there is none), until the\n * first other event. A {@link TURN_RESPONSE_EVENT} resolves to a `Response`\n * with the original status, headers and body, so the caller's existing error\n * handling runs unchanged. Any other event resolves to a `Response` whose body\n * starts at that event and continues with the rest of the stream. A response\n * that is not progress-first is returned as it is.\n * Opt-in host envelopes require onHostControl; its receipt is not admission.\n */\nexport async function settleTurnResponse(\n response: Response,\n onPhase: (phase: TurnPhaseData) => void,\n onIntent?: (intent: TurnIntentData) => void,\n onHostControl?: (target: TurnHostControlTarget) => void,\n): Promise<Response> {\n if ((response.headers.get(TURN_PROGRESS_HEADER) !== TURN_PROGRESS_FIRST\n && response.headers.get(TURN_HOST_CONTROL_HEADER) !== TURN_HOST_CONTROL_FIRST) || !response.body) return response\n const reader = response.body.getReader()\n const decoder = new TextDecoder()\n const encoder = new TextEncoder()\n let buffer = ''\n let ended = false\n const requiresHostControl = response.headers.get(TURN_HOST_CONTROL_HEADER) === TURN_HOST_CONTROL_FIRST\n let hostControlReceived = false\n for (;;) {\n let newline = buffer.indexOf('\\n')\n while (newline < 0) {\n if (ended) {\n // The stream closed inside the progress prefix: the turn never started.\n return Response.json(\n { error: 'The connection closed before the turn started. Try again.', code: TURN_STREAM_LOST_CODE },\n { status: 502 },\n )\n }\n const { done, value } = await reader.read()\n if (done) {\n ended = true\n buffer += decoder.decode()\n // A final line without its newline is still a line.\n if (buffer.trim()) buffer += '\\n'\n } else {\n buffer += decoder.decode(value, { stream: true })\n }\n newline = buffer.indexOf('\\n')\n }\n const line = buffer.slice(0, newline).trim()\n if (!line) {\n buffer = buffer.slice(newline + 1)\n continue\n }\n let event: unknown\n try {\n event = JSON.parse(line)\n } catch {\n event = null\n }\n if (isTurnHostControlEvent(event)) {\n if (!requiresHostControl || hostControlReceived || !onHostControl) {\n await reader.cancel().catch(() => {})\n throw new Error('Unexpected hosted control identity or missing onHostControl handler')\n }\n buffer = buffer.slice(newline + 1)\n try { onHostControl(event.data) }\n catch (error) { await reader.cancel().catch(() => {}); throw error }\n hostControlReceived = true\n continue\n }\n if (requiresHostControl && !hostControlReceived) {\n await reader.cancel().catch(() => {})\n throw new Error('The hosted envelope did not begin with a valid control identity')\n }\n if (isTurnPhaseEvent(event)) {\n buffer = buffer.slice(newline + 1)\n onPhase(event.data)\n continue\n }\n // An intent line is progress too: a response the route answers after it\n // (a held lock's 409) still settles with its own status.\n if (isTurnIntentEvent(event)) {\n buffer = buffer.slice(newline + 1)\n onIntent?.(event.data)\n continue\n }\n const answered = event as { type?: unknown; data?: Partial<TurnResponseData> } | null\n if (answered?.type === TURN_RESPONSE_EVENT && typeof answered.data?.status === 'number') {\n await reader.cancel().catch(() => {})\n return new Response(answered.data.status === 204 || answered.data.status === 304 ? null : String(answered.data.body ?? ''), {\n status: answered.data.status,\n headers: answered.data.headers ?? {},\n })\n }\n return streamFrom(reader, buffer, encoder, response)\n }\n}\n\n/** The rest of a progress-first stream, starting with bytes already read. */\nfunction streamFrom(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n pending: string,\n encoder: TextEncoder,\n original: Response,\n): Response {\n let first = pending\n const body = new ReadableStream<Uint8Array>({\n async pull(controller) {\n if (first) {\n controller.enqueue(encoder.encode(first))\n first = ''\n return\n }\n const { done, value } = await reader.read()\n if (done) controller.close()\n else controller.enqueue(value)\n },\n cancel(reason) {\n return reader.cancel(reason)\n },\n })\n return new Response(body, { status: original.status, headers: original.headers })\n}\n","import { isWorkspaceFileExportable } from '../web/file-export'\nimport { TURN_PROGRESS_FIRST, TURN_PROGRESS_HEADER } from './turn-progress'\nimport type { ReasoningEffort } from '@tangle-network/agent-interface'\n\n/**\n * Wire contract between the chat client (composer + `streamChatTurn`) and the\n * assembled server vertical (`createChatTurnRoutes`). This module must remain\n * browser-safe: `/web-react` re-exports these types into browser bundles, so\n * imports must not reach a Node builtin or an engine package.\n *\n * The client part shape permits an absolute file path until the server converts\n * it to the URL required by the sandbox SDK. It is derived here, not imported,\n * so the client bundle never touches the SDK.\n */\n\nexport interface ChatTurnTextPartInput {\n type: 'text'\n text: string\n}\n\n/** A non-text prompt part the upload route hands back and the client echoes\n * on send. `url` carries an inline `data:` URI for small files; `path` is a\n * sandbox workspace reference for large ones (the >1 MiB gateway body cap\n * makes the two-step upload mandatory). */\nexport interface ChatTurnFilePartInput {\n type: 'image' | 'file'\n filename?: string\n mediaType?: string\n url?: string\n path?: string\n}\n\n/** Resolve input as either a text part or a file part of a chat turn */\nexport type ChatTurnPartInput = ChatTurnTextPartInput | ChatTurnFilePartInput\n\n/** A chat turn's automatic sentinel plus the canonical agent reasoning levels. */\nexport type ChatReasoningEffort = 'auto' | ReasoningEffort\n\n// ── producer stream vocabulary ───────────────────────────────────────────────\n\n/** Represent a text event produced by a source with a fixed type and associated text content */\nexport interface ProducerTextEvent {\n type: 'text'\n text: string\n}\n\n/** Define an event representing reasoning output with a fixed type and associated text */\nexport interface ProducerReasoningEvent {\n type: 'reasoning'\n text: string\n}\n\n/** Represent an event triggered by a producer tool call with its identifier, name, and arguments */\nexport interface ProducerToolCallEvent {\n type: 'tool_call'\n call: {\n toolCallId: string\n toolName: string\n args: Record<string, unknown>\n }\n}\n\n/** Describe the structure of an event representing the result of a producer tool call */\nexport interface ProducerToolResultEvent {\n type: 'tool_result'\n toolCallId: string\n toolName: string\n outcome: {\n ok: boolean\n result?: unknown\n message?: string\n /** Typed reason for a failed call, when the producer knows it. */\n code?: string\n }\n}\n\n/** Describe cumulative provider usage reported by a producer. */\nexport interface ProducerUsageEvent {\n type: 'usage'\n usage: {\n promptTokens: number\n completionTokens: number\n /** Prompt tokens the provider served from its prompt cache. */\n cachedPromptTokens?: number\n reasoningTokens?: number\n toolTokens?: number\n toolCallCount?: number\n providerCostUsd?: number\n /** Present only when the provider enforced the complete execution budget. */\n budgetEnforced?: boolean\n }\n}\n\n/** Define the structure for a producer notice event with type, id, kind, and text fields */\nexport interface ProducerNoticeEvent {\n type: 'notice'\n id: string\n /** Kept inline with `/interactions`' `NoticeKind` so this file stays import-free. */\n noticeKind: 'warning' | 'auto-declined' | 'error'\n text: string\n /** Typed reason, on an `error` notice. */\n code?: string\n /** The failure's redacted cause chain, persisted with the notice and not rendered. */\n detail?: string\n}\n\n/** Represent an error event emitted by a producer containing message, code, and optional details */\nexport interface ProducerErrorEvent {\n type: 'error'\n data: {\n message: string\n code?: string\n details?: Record<string, unknown>\n }\n}\n\n/** Stable raw lifecycle/interaction/plan/route events forwarded unchanged. */\nexport type ProducerPassthroughEventType =\n | 'turn'\n | 'metadata'\n | 'interaction'\n | 'interaction.cancel'\n | 'plan.submitted'\n | 'done'\n | 'warning'\n /** A tool's typed side event while it runs (`data`: toolCallId, toolName, kind, data, at). */\n | 'tool.event'\n | 'session.run.started'\n | 'session.run.completed'\n | 'session.run.failed'\n | 'turn_status'\n\n/** Define an event carrying passthrough data with flexible properties for producer communication */\nexport interface ProducerPassthroughEvent {\n type: ProducerPassthroughEventType\n data?: Record<string, unknown>\n /** Route markers and raw passthroughs may carry `turnId`, `status`, `seq`, etc. */\n [key: string]: unknown\n}\n\n/** Represent events emitted by a producer during its operation for processing and handling */\nexport type ProducerWireEvent =\n | ProducerTextEvent\n | ProducerReasoningEvent\n | ProducerToolCallEvent\n | ProducerToolResultEvent\n | ProducerUsageEvent\n | ProducerNoticeEvent\n | ProducerErrorEvent\n | ProducerPassthroughEvent\n\n/** The image/file split an attachment is rendered and persisted under — the\n * same discriminant as {@link ChatMentionKind}, but a distinct name because an\n * attachment carries content the product uploaded (`ChatAttachmentInput`)\n * while a mention points at a file the box already has. Defined HERE (the\n * import-free layer) so `ChatAttachmentInput` can reference it and the client\n * composer imports it without pulling the persisted-part vocabulary;\n * `/chat-store`'s parts module re-exports it alongside the attachment helpers. */\nexport type ChatAttachmentKind = 'image' | 'file'\n\n/** `POST` turn-body entry describing a file already uploaded to the product's\n * store (vault/object-store) — distinct from an inline {@link\n * ChatTurnFilePartInput} (which carries bytes) and from a {@link FileMention}\n * (a sandbox path the box already holds). The route resolves this field with\n * {@link resolveChatAttachments}: every path is re-validated and every size is\n * re-derived from the stored body, so nothing here is trusted as sent. */\nexport interface ChatAttachmentInput {\n path: string\n name: string\n size: number\n mediaType: string\n kind: ChatAttachmentKind\n}\n\n/** POST body for the turn route. `content` may be empty when `parts` carry the\n * message (an image-only send). Product routing fields (workspaceId etc.) ride\n * alongside and are read by the product's `authorize` seam. */\nexport interface ChatTurnRequestPayload {\n threadId: string\n content?: string\n /** Non-text parts from the upload route, echoed back verbatim. */\n parts?: ChatTurnFilePartInput[]\n /** `@`-picked file mentions for this turn — path references into the\n * workspace sandbox, NOT uploads, so they travel in their own field rather\n * than as `parts` entries. A product whose `parts` field is already spoken\n * for (an attachment sentinel) can still send mentions, and mentions\n * persist as their own `ChatMentionPart`s so a retry rebuilds them. The\n * route validates this field with {@link parseFileMentions} and replaces it\n * on the payload with the validated, deduped list. */\n mentions?: ChatMention[]\n /** Files uploaded to the product's store ahead of the turn — path\n * references, NOT inline bytes (those ride `parts`). Validated and\n * size-re-derived by {@link resolveChatAttachments} into persistable\n * attachment parts; a product whose `parts` field is spoken for by inline\n * uploads still sends store-backed files here. */\n attachments?: ChatAttachmentInput[]\n model?: string\n effort?: ChatReasoningEffort\n harness?: string\n /** Client-generated idempotency key for the logical turn (retry-safe). */\n turnId?: string\n /** New token for a deliberate retry; reuse it for transport retries of that attempt. */\n retryAttemptId?: string\n [key: string]: unknown\n}\n\n/** `fetch` init for the turn route — the one place the client wire shape is\n * serialized, so composer glue and products never drift from the server's\n * parser. */\nexport function chatTurnRequestInit(\n payload: ChatTurnRequestPayload,\n options: { progressFirst?: boolean } = {},\n): RequestInit {\n return {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n // Ask for a progress-first stream (`./turn-progress`); settle the response with `settleTurnResponse`.\n ...(options.progressFirst ? { [TURN_PROGRESS_HEADER]: TURN_PROGRESS_FIRST } : {}),\n },\n body: JSON.stringify(payload),\n }\n}\n\n// ── inline-part byte budget ─────────────────────────────────────────────────\n//\n// The sandbox gateway caps request bodies at 1 MiB; a turn body whose inline\n// `data:` parts exceed it dies at the gateway with an opaque 413. Enforce the\n// budget at the route boundary instead, with headroom for the JSON envelope\n// (same fail-loud-at-the-choke-point style as /sandbox's provision-payload and\n// env-size gates).\n\n/** Define the maximum byte size allowed for inline parts in data processing */\nexport const INLINE_PARTS_MAX_BYTES = 950_000\n\n// ── dispatch (parts[]) budget vocabulary ────────────────────────────────────\n//\n// The default caps `buildDispatchParts` sizes an attachment/mention dispatch\n// against — the sidecar/proxy limits an assembled `parts` array crosses, one\n// step past `INLINE_PARTS_MAX_BYTES` (which gates the raw turn BODY). Grouped\n// here, in the import-free layer, so the numbers are one overridable\n// vocabulary the client can read and a product can tune per call rather than\n// constants buried in the server module. NOTE: these model sidecar/proxy caps,\n// not a product's MIME accept-list or vault bucketing — those are DOMAIN\n// values the product supplies, never defaulted here.\n\n/** Hard cap on the whole `/prompt` request body as it crosses the sandbox\n * proxy — smaller in practice than a raw-file write cap because a dispatch\n * carries several inline parts plus the flattened history in one request. */\nexport const DISPATCH_REQUEST_MAX_BYTES = 1024 * 1024\n\n/** Bytes reserved off the top of {@link DISPATCH_REQUEST_MAX_BYTES} for the\n * JSON structure around the parts array (keys, delimiters, per-part\n * `type`/`filename`/`mediaType` fields) that {@link base64WireLen} does not\n * account for — keeps the inline budget off the exact proxy cap where one\n * stray byte trips the 413. */\nexport const DISPATCH_STRUCTURAL_RESERVE_BYTES = 64 * 1024\n\n/** Sidecar's hard cap on the `parts` array of one prompt request — a dispatch\n * must never assemble more parts than this or the whole turn 400s. */\nexport const DISPATCH_MAX_PARTS = 64\n\n/** Product-side cap on media parts per dispatch (current turn + carried\n * history), well under {@link DISPATCH_MAX_PARTS}. History trimming that keeps\n * a transcript's native media under this is a PRODUCT concern (the pointer\n * block keeps trimmed media reachable); `buildDispatchParts` enforces only the\n * total {@link DISPATCH_MAX_PARTS} cap. */\nexport const DISPATCH_MAX_MEDIA_PARTS = 24\n\n/** Size a base64-encoded string occupies on the wire given the raw\n * (pre-encoding) byte length: base64 packs 3 raw bytes into 4 output\n * characters, rounded up to the next multiple of 4. */\nexport function base64WireLen(byteLen: number): number {\n return Math.ceil(byteLen / 3) * 4\n}\n\n/**\n * Render a raw byte count as a human-readable size (`512B`, `3KB`, `12MB\n * 500KB`). Ported EXACTLY from gtm-agent's `attachment-limits.ts` — byte-\n * identical implementation, not a reinterpretation — so `resolve-attachments`'s\n * and `promote-file-part`'s error strings match gtm's wording verbatim. Lives\n * in the import-free wire layer (not `resolve-attachments.ts` alone) because\n * BOTH the aggregate-cap message here and the per-file oversize message in\n * `promote-file-part.ts` need it; a browser composer wanting the same\n * formatting for a client-side pre-check can also import it with no engine\n * pulled in.\n */\nexport function formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes}B`\n if (bytes >= 1024 * 1024) {\n const megabytes = Math.floor(bytes / (1024 * 1024))\n const remainder = bytes % (1024 * 1024)\n return remainder === 0 ? `${megabytes}MB` : `${megabytes}MB ${formatBytes(remainder)}`\n }\n return `${Math.round(bytes / 1024)}KB`\n}\n\n/** Represent errors for invalid chat turn inputs with status and code properties */\nexport class ChatTurnInputError extends Error {\n constructor(message: string, readonly status = 400, readonly code = 'INVALID_CHAT_TURN') {\n super(message)\n this.name = 'ChatTurnInputError'\n }\n}\n\nfunction partByteSize(part: ChatTurnPartInput): number {\n let bytes = 0\n if (part.type === 'text') return part.text.length\n if (part.url) bytes += part.url.length\n if (part.path) bytes += part.path.length\n return bytes\n}\n\n/** Calculate the total byte size of an array of chat turn parts */\nexport function promptPartsByteSize(parts: ChatTurnPartInput[]): number {\n return parts.reduce((total, part) => total + partByteSize(part), 0)\n}\n\n/** Throws `ChatTurnInputError` (413) when the parts' inline payload would blow\n * the gateway cap. Path-ref parts are tiny by construction and always pass. */\nexport function assertPromptPartsWithinCap(\n parts: ChatTurnPartInput[],\n maxBytes = INLINE_PARTS_MAX_BYTES,\n): void {\n const total = promptPartsByteSize(parts)\n if (total <= maxBytes) return\n const largest = [...parts].sort((a, b) => partByteSize(b) - partByteSize(a))[0]\n const largestName = largest && largest.type !== 'text' ? largest.filename ?? largest.path ?? largest.type : 'text'\n throw new ChatTurnInputError(\n `Inline prompt parts total ${total}B, over the ${maxBytes}B budget (largest: ${largestName}, ${largest ? partByteSize(largest) : 0}B). ` +\n 'Upload large files through the upload route so they travel as sandbox path references.',\n 413,\n 'PROMPT_PARTS_TOO_LARGE',\n )\n}\n\n// ── file mentions ────────────────────────────────────────────────────────\n//\n// A file mention (`@`-picked in the composer, sandbox-ui#184) is a path\n// reference into the workspace sandbox — no byte upload. These helpers turn\n// a resolved mention list into wire parts and the prompt pointer block that\n// tells the agent where to read them from.\n\n/** A file mention resolved from the composer's `@`-picker: the\n * workspace-relative path plus enough metadata to build a prompt part and\n * pointer text. `path` is the canonical identity — the mention pill's\n * `MentionItem.id` for the file kind (`/web-react`'s `useFileMentions`). */\nexport interface FileMention {\n path: string\n name: string\n size?: number\n}\n\n/** An agent mention from the composer's `@`-picker: a workspace agent the\n * turn is addressed to. `handle` is the `@`-token identity (the pill's\n * `MentionItem.id`, what the message text carries as `@<handle>`);\n * `agentId` is the stable profile id, so a renamed agent still resolves from\n * an old message. A file mention has no `kind`; this one always does. */\nexport interface AgentMention {\n kind: 'agent'\n agentId: string\n handle: string\n name: string\n}\n\n/** Everything the composer can `@`: a file in the box or an agent in the workspace. */\nexport type ChatMention = FileMention | AgentMention\n\nexport function isAgentMention(mention: ChatMention): mention is AgentMention {\n return (mention as AgentMention).kind === 'agent'\n}\n\n/** The file mentions of a validated list, for the seams that read the box. */\nexport function fileMentionsOf(mentions: readonly ChatMention[]): FileMention[] {\n return mentions.filter((mention): mention is FileMention => !isAgentMention(mention))\n}\n\n/** The agent mentions of a validated list, in mention order: the turn's responders. */\nexport function agentMentionsOf(mentions: readonly ChatMention[]): AgentMention[] {\n return mentions.filter(isAgentMention)\n}\n\n/** A handle is what a person types after `@`: lowercase letters, digits and\n * hyphens, as `normalizeProfileName` in `/agent-profiles` spells a name. */\nexport const AGENT_HANDLE_PATTERN = /^[a-z0-9][a-z0-9-]{0,62}$/\n\n/** The handle a profile name gets: lowercase, runs of anything else become one\n * hyphen, no leading or trailing hyphen, at most 63 characters. \"Research\n * Lead\" is `research-lead`. One spelling for the composer, the route and the\n * rail, so a product never derives its own. An empty result (a name with no\n * letters or digits) is `agent`. */\nexport function agentHandle(name: string): string {\n const handle = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 63).replace(/-+$/, '')\n return handle || 'agent'\n}\nconst AGENT_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/\n\nconst MENTION_IMAGE_MEDIA_TYPES: ReadonlyMap<string, string> = new Map([\n ['.png', 'image/png'],\n ['.jpg', 'image/jpeg'],\n ['.jpeg', 'image/jpeg'],\n ['.gif', 'image/gif'],\n ['.webp', 'image/webp'],\n ['.svg', 'image/svg+xml'],\n ['.bmp', 'image/bmp'],\n ['.heic', 'image/heic'],\n ['.heif', 'image/heif'],\n ['.avif', 'image/avif'],\n])\n\nfunction extensionOf(path: string): string {\n const base = path.split('/').filter(Boolean).pop() ?? path\n const dot = base.lastIndexOf('.')\n return dot > 0 ? base.slice(dot).toLowerCase() : ''\n}\n\n/** The `image/*` mime for a mention path by extension, or `undefined` for\n * anything not in the known image set (dispatched as `type: 'file'`). */\nexport function mediaTypeForMentionPath(path: string): string | undefined {\n return MENTION_IMAGE_MEDIA_TYPES.get(extensionOf(path))\n}\n\n/** The image/file split a mention is rendered and persisted under — the\n * composer pill's icon, the dispatched part's `type`, and\n * `ChatMentionPart.mentionKind` are all this one value. */\nexport type ChatMentionKind = 'image' | 'file' | 'agent'\n\n/** `image` when the path's extension is in the known image set (the same table\n * {@link mediaTypeForMentionPath} reads), `file` otherwise. Exported so a\n * client that needs only the discriminant — a pill icon, a persisted part's\n * `mentionKind` — never re-declares the extension table; two frozen copies of\n * one mime table is how one gains a format and the other doesn't. */\nexport function mentionKindForPath(path: string): ChatMentionKind {\n return mediaTypeForMentionPath(path) ? 'image' : 'file'\n}\n\n/** Define options to resolve mention paths when converting file mentions to parts */\nexport interface FileMentionsToPartsOptions {\n /** Resolve a mention's workspace-relative path to the absolute path the\n * dispatched part should carry (e.g. a host prefixing the in-box vault\n * root). Default: identity — the path travels unchanged. */\n resolvePath?: (path: string) => string\n}\n\n/** Maps resolved file mentions to path-only `ChatTurnFilePartInput`s —\n * `image` vs `file` by extension, and always a `path`, never a `url` (the\n * url/path XOR invariant: a mention is a sandbox path reference, never\n * inline bytes). */\nexport function fileMentionsToParts(\n mentions: readonly ChatMention[],\n opts: FileMentionsToPartsOptions = {},\n): ChatTurnFilePartInput[] {\n const resolvePath = opts.resolvePath ?? ((path: string) => path)\n // An agent mention addresses a responder; it points at nothing in the box.\n return fileMentionsOf(mentions).map((mention) => {\n const mediaType = mediaTypeForMentionPath(mention.path)\n const part: ChatTurnFilePartInput = {\n type: mediaType ? 'image' : 'file',\n filename: mention.name,\n path: resolvePath(mention.path),\n }\n if (mediaType) part.mediaType = mediaType\n return part\n })\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. This is the sole producer of that text: the current\n * turn's dispatch and any history projection built from the same mention\n * list both route through here, so the two can't drift apart. */\nexport function buildMentionPromptBlock(\n mentions: readonly (Pick<FileMention, 'name' | 'path'> | AgentMention)[],\n): string {\n const files = mentions.filter((m): m is Pick<FileMention, 'name' | 'path'> => (m as AgentMention).kind !== 'agent')\n if (files.length === 0) return ''\n const lines = files.map((m) => `- ${m.name} (${m.path})`)\n return `\\n\\nMentioned files — read them from these paths:\\n${lines.join('\\n')}`\n}\n\n// ── mention validation ───────────────────────────────────────────────────\n//\n// This package owns BOTH ends of the mention path contract — it emits paths\n// from `createSandboxFileIndexRoute` and consumes them in `fileMentionsToParts`\n// / `buildMentionPromptBlock` — so the validation belongs here rather than in\n// each app that wires the pair up. A mention names a file that already exists\n// in the sandbox, so validation is a pure path/charset/count check with no\n// I/O: existence is proven later, when the agent reads the path and the turn\n// fails loudly if it is gone.\n\n/** Hard cap on mentions per turn. Bounds the prompt pointer block, the\n * persisted parts, and whatever media budget a dispatch draws from them. */\nexport const MENTION_MAX_COUNT = 16\n\n/** Longest mention display name accepted — bounds the pointer-block text and\n * the transcript pill label. */\nconst MAX_MENTION_NAME_LENGTH = 256\n/** Longest mention path accepted. */\nconst MAX_MENTION_PATH_LENGTH = 1024\n\n/** Represent the result of a sandbox mention path check indicating success or failure with an error message */\nexport type SandboxMentionPathCheck =\n | { succeeded: true }\n | { succeeded: false; error: string }\n\n/**\n * Validate a workspace-relative sandbox mention path. Rejects traversal (a\n * `..` path segment), absolute paths (leading `/`), backslashes, and null\n * bytes — the four ways a path picked in a client can escape the root the\n * index route scanned.\n *\n * Spaces and unicode are deliberately ALLOWED: in-box filenames are arbitrary,\n * and an ASCII-only charset would silently drop real files from a feature\n * whose whole job is naming them.\n */\nexport function validateSandboxMentionPath(path: unknown): SandboxMentionPathCheck {\n if (typeof path !== 'string' || path.length === 0) {\n return { succeeded: false, error: 'mention path must be a non-empty string' }\n }\n if (path.length > MAX_MENTION_PATH_LENGTH) {\n return { succeeded: false, error: `mention path must not exceed ${MAX_MENTION_PATH_LENGTH} characters` }\n }\n if (path.includes('\\0')) {\n return { succeeded: false, error: 'mention path must not contain null bytes' }\n }\n if (path.includes('\\\\')) {\n return { succeeded: false, error: 'mention path must not contain backslashes' }\n }\n if (path.startsWith('/')) {\n return { succeeded: false, error: 'mention path must be workspace-relative, not absolute' }\n }\n if (path.split('/').some((segment) => segment === '..')) {\n return { succeeded: false, error: 'mention path must not contain \"..\" segments' }\n }\n return { succeeded: true }\n}\n\nfunction parseFileMention(value: unknown, index: number): FileMention {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new ChatTurnInputError(`mentions[${index}] must be an object`)\n }\n const record = value as Record<string, unknown>\n\n const pathCheck = validateSandboxMentionPath(record.path)\n if (!pathCheck.succeeded) throw new ChatTurnInputError(`mentions[${index}]: ${pathCheck.error}`)\n\n if (!isWorkspaceFileExportable(record.path as string)) {\n throw new ChatTurnInputError(`mentions[${index}]: file is not exportable`)\n }\n\n const name = record.name\n if (typeof name !== 'string' || !name.trim()) {\n throw new ChatTurnInputError(`mentions[${index}].name must be a non-empty string`)\n }\n if (name.length > MAX_MENTION_NAME_LENGTH) {\n throw new ChatTurnInputError(`mentions[${index}].name must not exceed ${MAX_MENTION_NAME_LENGTH} characters`)\n }\n\n const size = record.size\n if (size !== undefined) {\n if (typeof size !== 'number' || !Number.isFinite(size)) {\n throw new ChatTurnInputError(`mentions[${index}].size must be a finite number`)\n }\n if (size < 0) {\n throw new ChatTurnInputError(`mentions[${index}].size must not be negative`)\n }\n }\n\n return { path: record.path as string, name, ...(typeof size === 'number' ? { size } : {}) }\n}\n\n/**\n * Validates the untyped `mentions` array off the wire, mirroring\n * {@link parseChatTurnParts}: the typed list, or `ChatTurnInputError` (400)\n * naming the offending entry. Never sanitizes-and-continues — a traversal path\n * is a rejected request, not a trimmed one.\n *\n * A path repeated within one turn is deduped to its first occurrence rather\n * than rejected: mentioning the same file twice is plausible user input, not\n * an attack.\n */\n/** The validated, deduped mention list off the wire: files by path, agents\n * by id, in the order typed. One cap covers both kinds. */\nexport function parseMentions(raw: unknown): ChatMention[] {\n if (raw === undefined || raw === null) return []\n if (!Array.isArray(raw)) throw new ChatTurnInputError('mentions must be an array')\n if (raw.length > MENTION_MAX_COUNT) {\n throw new ChatTurnInputError(`mentions must not exceed ${MENTION_MAX_COUNT} entries`)\n }\n\n const mentions: ChatMention[] = []\n const seen = new Set<string>()\n for (let index = 0; index < raw.length; index += 1) {\n const entry = raw[index] as Record<string, unknown> | null\n const mention = entry && typeof entry === 'object' && entry.kind === 'agent'\n ? parseAgentMention(entry, index)\n : parseFileMention(raw[index], index)\n const key = isAgentMention(mention) ? `agent:${mention.agentId}` : `file:${mention.path}`\n if (seen.has(key)) continue\n seen.add(key)\n mentions.push(mention)\n }\n return mentions\n}\n\n/** The file mentions of the wire list; agent mentions are validated and set aside. */\nexport function parseFileMentions(raw: unknown): FileMention[] {\n return fileMentionsOf(parseMentions(raw))\n}\n\nfunction parseAgentMention(record: Record<string, unknown>, index: number): AgentMention {\n const agentId = record.agentId\n if (typeof agentId !== 'string' || !AGENT_ID_PATTERN.test(agentId)) {\n throw new ChatTurnInputError(`mentions[${index}].agentId must be 1–128 letters, digits, dots, colons, underscores or hyphens`)\n }\n const handle = record.handle\n if (typeof handle !== 'string' || !AGENT_HANDLE_PATTERN.test(handle)) {\n throw new ChatTurnInputError(`mentions[${index}].handle must be lowercase letters, digits and hyphens`)\n }\n const name = record.name\n if (typeof name !== 'string' || !name.trim()) {\n throw new ChatTurnInputError(`mentions[${index}].name must be a non-empty string`)\n }\n if (name.length > MAX_MENTION_NAME_LENGTH) {\n throw new ChatTurnInputError(`mentions[${index}].name must not exceed ${MAX_MENTION_NAME_LENGTH} characters`)\n }\n return { kind: 'agent', agentId, handle, name: name.trim() }\n}\n\n/** Validates the untyped `parts` array off the wire. Returns the typed parts\n * or throws `ChatTurnInputError` (400) naming the offending entry. */\nexport function parseChatTurnParts(raw: unknown): ChatTurnFilePartInput[] {\n if (raw === undefined || raw === null) return []\n if (!Array.isArray(raw)) throw new ChatTurnInputError('parts must be an array')\n return raw.map((entry, index) => {\n const part = entry as Record<string, unknown> | null\n if (!part || typeof part !== 'object') {\n throw new ChatTurnInputError(`parts[${index}] must be an object`)\n }\n if (part.type !== 'image' && part.type !== 'file') {\n throw new ChatTurnInputError(`parts[${index}].type must be 'image' or 'file'`)\n }\n for (const key of ['filename', 'mediaType', 'url', 'path'] as const) {\n if (part[key] !== undefined && typeof part[key] !== 'string') {\n throw new ChatTurnInputError(`parts[${index}].${key} must be a string`)\n }\n }\n if (part.content !== undefined) {\n throw new ChatTurnInputError(`parts[${index}].content is not supported; provide a url or path`)\n }\n\n const url = typeof part.url === 'string' && part.url.length > 0 ? part.url : undefined\n const path = typeof part.path === 'string' && part.path.length > 0 ? part.path : undefined\n if (Boolean(url) === Boolean(path)) {\n throw new ChatTurnInputError(`parts[${index}] requires exactly one url or path`)\n }\n if (path && !path.startsWith('/')) {\n throw new ChatTurnInputError(`parts[${index}].path must be absolute`)\n }\n\n const filename = typeof part.filename === 'string' ? part.filename.trim() : undefined\n if (part.type === 'file' && !filename) {\n throw new ChatTurnInputError(`parts[${index}].filename is required for file parts`)\n }\n return {\n type: part.type,\n ...(filename ? { filename } : {}),\n ...(part.mediaType !== undefined ? { mediaType: part.mediaType as string } : {}),\n ...(url ? { url } : { path: path! }),\n }\n })\n}\n"],"mappings":";;;;;AAoCO,IAAM,uBAAuB;AAE7B,IAAM,sBAAsB;AAG5B,IAAM,2BAA2B;AACjC,IAAM,0BAA0B;AAEhC,IAAM,0BAA0B;AAWhC,SAAS,uBAAuB,OAA+C;AACpF,QAAM,QAAQ;AACd,QAAM,SAAS,OAAO;AACtB,SAAO,OAAO,SAAS,2BAA2B,CAAC,CAAC,UAC/C,CAAC,OAAO,QAAQ,OAAO,aAAa,OAAO,QAAQ,EAAE,MAAM,CAAAA,WAAS,O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oB,IAAI,CAAC;AAAA,MAC9E,GAAI,MAAM,EAAE,IAAI,IAAI,EAAE,KAAY;AAAA,IACpC;AAAA,EACF,CAAC;AACH;","names":["value"]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  runRouterTurn
3
- } from "./chunk-QFT2V2OE.js";
3
+ } from "./chunk-RSSK6FUF.js";
4
4
 
5
5
  // src/runtime/protected-model.ts
6
6
  var GATEWAY_ORIGIN = "https://candidate-router.tangle.tools";
@@ -217,4 +217,4 @@ export {
217
217
  createRouterProtectedModelPort,
218
218
  runProtectedRouterTurn
219
219
  };
220
- //# sourceMappingURL=chunk-PZTBXHPE.js.map
220
+ //# sourceMappingURL=chunk-725RZ5JQ.js.map