@jini-ai/chat 0.7.3-next.2 → 0.7.3-next.3

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 (214) hide show
  1. package/README.md +49 -0
  2. package/dist/core/accepted-input.d.ts +1 -1
  3. package/dist/core/ag-ui/event-projection.d.ts +14 -69
  4. package/dist/core/ag-ui/event-projection.js +58 -133
  5. package/dist/core/ag-ui/event-reduction.d.ts +12 -2
  6. package/dist/core/ag-ui/event-reduction.js +35 -10
  7. package/dist/core/ag-ui/resume.d.ts +110 -0
  8. package/dist/core/ag-ui/resume.js +200 -0
  9. package/dist/core/ag-ui/run-input.d.ts +23 -0
  10. package/dist/core/ag-ui/run-input.js +45 -0
  11. package/dist/core/ag-ui/server.d.ts +69 -0
  12. package/dist/core/ag-ui/server.js +71 -0
  13. package/dist/core/agent-plugin-chat-state.js +13 -11
  14. package/dist/core/assistant-client/ag-ui-approval-relay.d.ts +113 -0
  15. package/dist/core/assistant-client/ag-ui-approval-relay.js +287 -0
  16. package/dist/core/assistant-client/ag-ui-fetch-agent.d.ts +25 -10
  17. package/dist/core/assistant-client/ag-ui-fetch-agent.js +25 -6
  18. package/dist/core/assistant-client/ag-ui-transport.d.ts +86 -3
  19. package/dist/core/assistant-client/ag-ui-transport.js +310 -80
  20. package/dist/core/assistant-client/browser-durable-subscription.d.ts +25 -0
  21. package/dist/core/assistant-client/browser-durable-subscription.js +78 -0
  22. package/dist/core/assistant-client/durable-run-subscription.js +141 -130
  23. package/dist/core/assistant-client/entry.d.ts +2 -1
  24. package/dist/core/assistant-client/entry.js +1 -0
  25. package/dist/core/assistant-client/transport-prompt.d.ts +94 -0
  26. package/dist/core/assistant-client/transport-prompt.js +180 -0
  27. package/dist/core/assistant-client/transport-run.d.ts +49 -0
  28. package/dist/core/assistant-client/transport-run.js +432 -0
  29. package/dist/core/assistant-client/transport-stream.d.ts +73 -0
  30. package/dist/core/assistant-client/transport-stream.js +128 -0
  31. package/dist/core/assistant-client/transport.d.ts +1 -1
  32. package/dist/core/assistant-client/transport.js +129 -835
  33. package/dist/core/assistant-content.d.ts +1 -17
  34. package/dist/core/assistant-content.js +16 -0
  35. package/dist/core/assistant-tool-metadata.d.ts +103 -0
  36. package/dist/core/assistant-tool-metadata.js +56 -0
  37. package/dist/core/checkpoint-interval.d.ts +1 -1
  38. package/dist/core/compact-events.d.ts +1 -1
  39. package/dist/core/durable-projection.d.ts +1 -1
  40. package/dist/core/durable-runs/continuation.d.ts +1 -1
  41. package/dist/core/durable-runs/ledger-contracts.d.ts +4 -1
  42. package/dist/core/durable-runs/ports.d.ts +2 -1
  43. package/dist/core/durable-runs/run-contracts.d.ts +1 -1
  44. package/dist/core/durable-runs/run-finalizer.d.ts +145 -0
  45. package/dist/core/durable-runs/run-finalizer.js +171 -0
  46. package/dist/core/events.d.ts +4 -82
  47. package/dist/core/events.js +2 -1
  48. package/dist/core/index.d.ts +4 -1
  49. package/dist/core/index.js +2 -1
  50. package/dist/core/messages.d.ts +1 -1
  51. package/dist/core/persistence/index.d.ts +1 -1
  52. package/dist/core/persistence/index.js +1 -1
  53. package/dist/core/question-form/normalize.d.ts +9 -3
  54. package/dist/core/question-form/normalize.js +20 -20
  55. package/dist/core/question-form/scan.js +15 -19
  56. package/dist/core/run-activity.d.ts +1 -1
  57. package/dist/core/run-events/entry.d.ts +11 -63
  58. package/dist/core/run-events/entry.js +12 -7
  59. package/dist/core/todos.d.ts +1 -1
  60. package/dist/core/todos.js +8 -0
  61. package/dist/core/tool-call-detail.d.ts +8 -1
  62. package/dist/core/tool-call-detail.js +35 -12
  63. package/dist/core/tool-events.d.ts +1 -1
  64. package/dist/core/tool-output.js +2 -6
  65. package/dist/core/tools.d.ts +2 -1
  66. package/dist/core/transport.d.ts +1 -1
  67. package/dist/core/turn-usage.d.ts +1 -1
  68. package/dist/core/util/parser.js +70 -69
  69. package/dist/embed-widget/browser/embed-send-bridge.d.ts +44 -0
  70. package/dist/embed-widget/browser/embed-send-bridge.js +60 -0
  71. package/dist/embed-widget/browser/frontend-invocation-handler.d.ts +39 -0
  72. package/dist/embed-widget/browser/frontend-invocation-handler.js +151 -0
  73. package/dist/embed-widget/browser/frontend-session-bridge.d.ts +28 -0
  74. package/dist/embed-widget/browser/frontend-session-bridge.js +201 -257
  75. package/dist/embed-widget/browser/lazy-loader.js +16 -12
  76. package/dist/embed-widget/browser/session-store.d.ts +19 -1
  77. package/dist/embed-widget/browser/session-store.js +48 -17
  78. package/dist/embed-widget/transports/fetch-sse.d.ts +1 -1
  79. package/dist/embed-widget/vanilla/index.js +131 -67
  80. package/dist/embed-widget/vanilla/state.js +53 -38
  81. package/dist/react/admin-execution/ai-agent-presentation.d.ts +35 -0
  82. package/dist/react/admin-execution/ai-agent-presentation.js +39 -0
  83. package/dist/react/admin-execution/hooks/use-ai-agent-presentation.hooks.d.ts +22 -0
  84. package/dist/react/admin-execution/hooks/use-ai-agent-presentation.hooks.js +25 -0
  85. package/dist/react/chat-cleanup/ChatCleanupPanel.d.ts +15 -0
  86. package/dist/react/chat-cleanup/ChatCleanupPanel.js +17 -0
  87. package/dist/react/chat-cleanup/chat-cleanup.hooks.d.ts +168 -0
  88. package/dist/react/chat-cleanup/chat-cleanup.hooks.js +83 -0
  89. package/dist/react/components/ChatCleanupDialog.d.ts +38 -0
  90. package/dist/react/components/ChatCleanupDialog.js +12 -0
  91. package/dist/react/components/ConversationList.d.ts +14 -5
  92. package/dist/react/components/ConversationList.hooks.d.ts +1 -0
  93. package/dist/react/components/ConversationList.hooks.js +4 -2
  94. package/dist/react/components/ConversationList.js +41 -5
  95. package/dist/react/components/Icon.d.ts +1 -1
  96. package/dist/react/components/Icon.js +2 -0
  97. package/dist/react/components/Markdown.js +6 -6
  98. package/dist/react/components/MarkdownLink.d.ts +25 -0
  99. package/dist/react/components/MarkdownLink.js +17 -0
  100. package/dist/react/components/RoutedA2uiSurfaceCard.d.ts +80 -0
  101. package/dist/react/components/RoutedA2uiSurfaceCard.js +15 -0
  102. package/dist/react/components/ToolCard.d.ts +4 -2
  103. package/dist/react/components/ToolCard.js +46 -4
  104. package/dist/react/components/ToolCard.rules.d.ts +5 -2
  105. package/dist/react/components/ToolCard.rules.js +12 -5
  106. package/dist/react/components/mcp-ui-question-input.d.ts +1 -1
  107. package/dist/react/components/mcp-ui-surface-state.d.ts +3 -1
  108. package/dist/react/components/mcp-ui-surface-state.js +2 -2
  109. package/dist/react/components/own-link.d.ts +26 -0
  110. package/dist/react/components/own-link.js +36 -0
  111. package/dist/react/features/bridged-chat/create-staged-attachment-uploader.d.ts +7 -0
  112. package/dist/react/features/bridged-chat/create-staged-attachment-uploader.js +26 -0
  113. package/dist/react/features/bridged-chat/hooks/useBridgedChatTransport.hooks.d.ts +12 -0
  114. package/dist/react/features/bridged-chat/hooks/useBridgedChatTransport.hooks.js +60 -0
  115. package/dist/react/features/bridged-chat/index.d.ts +8 -0
  116. package/dist/react/features/bridged-chat/index.js +7 -0
  117. package/dist/react/features/bridged-chat/types.d.ts +49 -0
  118. package/dist/react/features/bridged-chat/types.js +2 -0
  119. package/dist/react/features/chat-pane/components/RuntimeDropUp.js +1 -1
  120. package/dist/react/features/chat-pane/create-daemon-attachment-uploader.d.ts +6 -0
  121. package/dist/react/features/chat-pane/create-daemon-attachment-uploader.js +101 -59
  122. package/dist/react/features/chat-pane/hooks/useChatPaneNewTabLinks.hooks.d.ts +3 -0
  123. package/dist/react/features/chat-pane/hooks/useChatPaneNewTabLinks.hooks.js +26 -16
  124. package/dist/react/features/chat-pane/model-options.d.ts +3 -1
  125. package/dist/react/features/chat-pane/model-options.js +3 -3
  126. package/dist/react/features/chat-pane/rules.js +4 -3
  127. package/dist/react/features/chat-pane/styles.d.ts +1 -1
  128. package/dist/react/features/chat-pane/styles.js +16 -0
  129. package/dist/react/features/conversation-chat-pane/components/ConversationChatPane.d.ts +10 -0
  130. package/dist/react/features/conversation-chat-pane/components/ConversationChatPane.js +19 -0
  131. package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneChat.d.ts +12 -0
  132. package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneChat.js +21 -0
  133. package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneHeader.d.ts +13 -0
  134. package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneHeader.js +9 -0
  135. package/dist/react/features/conversation-chat-pane/components/ConversationDeleteConfirm.d.ts +12 -0
  136. package/dist/react/features/conversation-chat-pane/components/ConversationDeleteConfirm.js +12 -0
  137. package/dist/react/features/conversation-chat-pane/hooks/useConversationChatPane.hooks.d.ts +7 -0
  138. package/dist/react/features/conversation-chat-pane/hooks/useConversationChatPane.hooks.js +43 -0
  139. package/dist/react/features/conversation-chat-pane/index.d.ts +9 -0
  140. package/dist/react/features/conversation-chat-pane/index.js +8 -0
  141. package/dist/react/features/conversation-chat-pane/rules.d.ts +25 -0
  142. package/dist/react/features/conversation-chat-pane/rules.js +29 -0
  143. package/dist/react/features/conversation-chat-pane/types.d.ts +139 -0
  144. package/dist/react/features/conversation-chat-pane/types.js +2 -0
  145. package/dist/react/features/conversations/conversation-controller.d.ts +16 -0
  146. package/dist/react/features/conversations/conversation-controller.js +280 -0
  147. package/dist/react/features/conversations/hooks/useConversationDeleteConfirmation.hooks.d.ts +15 -0
  148. package/dist/react/features/conversations/hooks/useConversationDeleteConfirmation.hooks.js +33 -0
  149. package/dist/react/features/conversations/hooks/useStoredConversations.hooks.d.ts +16 -0
  150. package/dist/react/features/conversations/hooks/useStoredConversations.hooks.js +36 -0
  151. package/dist/react/features/conversations/index.d.ts +9 -0
  152. package/dist/react/features/conversations/index.js +8 -0
  153. package/dist/react/features/conversations/types.d.ts +120 -0
  154. package/dist/react/features/conversations/types.js +2 -0
  155. package/dist/react/features/voice-input/space-hold-rules.d.ts +65 -0
  156. package/dist/react/features/voice-input/space-hold-rules.js +48 -0
  157. package/dist/react/hooks/testing/fake-transport.d.ts +1 -1
  158. package/dist/react/hooks/useAnsweredCards.d.ts +2 -1
  159. package/dist/react/hooks/useConversation.js +5 -2
  160. package/dist/react/hooks/useExtEventGroups.d.ts +1 -1
  161. package/dist/react/hooks/useRunActivity.d.ts +2 -1
  162. package/dist/react/hooks/useRunStream.d.ts +1 -1
  163. package/dist/react/hooks/useRunStream.js +1 -1
  164. package/dist/react/hooks/useSurfaceRecovery.js +3 -1
  165. package/dist/react/hooks/useToolTimeline.d.ts +2 -1
  166. package/dist/react/index.d.ts +5 -2
  167. package/dist/react/index.js +4 -2
  168. package/dist/react/message-blocks.d.ts +1 -48
  169. package/dist/react/message-blocks.js +47 -0
  170. package/dist/react/styles/chat-settings.css +14 -14
  171. package/dist/server/chat-cleanup-routes.d.ts +56 -0
  172. package/dist/server/chat-cleanup-routes.js +56 -0
  173. package/dist/server/durable-runs/recover.js +193 -171
  174. package/dist/server/run-finalizer/entry.js +133 -110
  175. package/dist/store/legacy/sqlite/conversations.js +29 -17
  176. package/dist/store/pglite/index.d.ts +1 -0
  177. package/dist/store/pglite/index.js +1 -0
  178. package/dist/store/ports.d.ts +12 -0
  179. package/dist/store/postgres/index.d.ts +1 -0
  180. package/dist/store/postgres/index.js +1 -0
  181. package/dist/store/runtime/attempt-base-retention.d.ts +57 -0
  182. package/dist/store/runtime/attempt-base-retention.js +103 -0
  183. package/dist/store/runtime/chat-maintenance.d.ts +16 -0
  184. package/dist/store/runtime/chat-maintenance.js +19 -0
  185. package/dist/store/runtime/chat-principal.d.ts +63 -0
  186. package/dist/store/runtime/chat-principal.js +39 -0
  187. package/dist/store/runtime/checkpoint-delta.d.ts +1 -1
  188. package/dist/store/runtime/durable-run-queries.d.ts +124 -0
  189. package/dist/store/runtime/durable-run-queries.js +122 -0
  190. package/dist/store/runtime/durable-run-store.d.ts +1 -1
  191. package/dist/store/runtime/durable-run-store.js +291 -343
  192. package/dist/store/runtime/entry.d.ts +3 -0
  193. package/dist/store/runtime/entry.js +3 -0
  194. package/dist/store/runtime/events-json.d.ts +1 -1
  195. package/dist/store/runtime/lazy-run-ledger.d.ts +19 -0
  196. package/dist/store/runtime/lazy-run-ledger.js +28 -0
  197. package/dist/store/runtime/run-ledger.d.ts +4 -1
  198. package/dist/store/runtime/run-ledger.js +256 -204
  199. package/dist/store/sql/bulk-deletion.d.ts +36 -0
  200. package/dist/store/sql/bulk-deletion.js +103 -0
  201. package/dist/store/sql/store-queries.d.ts +170 -0
  202. package/dist/store/sql/store-queries.js +212 -0
  203. package/dist/store/sql/store-rows.d.ts +106 -0
  204. package/dist/store/sql/store-rows.js +116 -0
  205. package/dist/store/sql/store-writes.d.ts +46 -0
  206. package/dist/store/sql/store-writes.js +161 -0
  207. package/dist/store/sql/store.d.ts +3 -16
  208. package/dist/store/sql/store.js +58 -428
  209. package/dist/store/sql/tables.d.ts +1 -0
  210. package/dist/store/sqlite/index.d.ts +1 -0
  211. package/dist/store/sqlite/index.js +1 -0
  212. package/dist/store/sqlite/schema.d.ts +1 -1
  213. package/dist/store/sqlite/schema.js +5 -1
  214. package/package.json +171 -20
@@ -1,842 +1,136 @@
1
- import { readAgentPluginChatState, captureAgentPluginUsage } from '../agent-plugin-chat-state.js';
2
- import { buildTranscript, latestUserPromptFromHistory } from "../transcript.js";
3
- import * as runEvents from "../run-events/entry.js";
1
+ import { historyForTranscript, undeliveredUserPrompt } from "./transport-prompt.js";
2
+ import { buildLocalCliContextRef, refusalError, startTransportRun } from "./transport-run.js";
3
+ import { consumeByokStream, handleByokFrame, subscribeToRun } from "./transport-stream.js";
4
+ /**
5
+ * Shared HTTP implementation of `@jini-ai/chat/react`'s `ChatTransport` port.
6
+ *
7
+ * TWO run paths live here, selected per-turn by `getExecutionConfig()` (see
8
+ * `createAssistantTransport`'s own doc):
9
+ *
10
+ * 1. **Local CLI** (the original, unchanged path): binds to the real `@jini-ai/http` run surface
11
+ * the host app's `src/server/runtime/composition/modules/assistant.ts` mounts — `POST /api/runs` to start, `GET
12
+ * /api/runs/:runId/events` (native `EventSource`) to stream, `GET /api/runs/:runId` for status,
13
+ * `POST /api/runs/:runId/cancel` to stop. Every SSE frame's `data` is a full `@jini-ai/protocol`
14
+ * `RunProtocolEvent` (`{kind, payload, ...}`), not chat-core's own `AgentEvent` — chat-core's own
15
+ * module doc is explicit that this reduction is a transport concern ("a host's transport adapter
16
+ * is responsible for reducing wire deltas... into the persisted/renderable AgentEvent items"), so
17
+ * `translateRunAgentPayload` below does that translation.
18
+ * 2. **API · BYOK** (2026-08-04, the execution picker): binds to the host app's `src/server/runtime/composition/modules/assistant-byok.ts`'s
19
+ * `POST /api/admin/v1/assistant/byok-turn` — one request/response holding the WHOLE turn open,
20
+ * no separate `EventSource`/reattach/cancel-by-runId (see that route's own header for why, and
21
+ * what it costs). Its SSE frames carry the SAME `payload.type` vocabulary
22
+ * (`status`/`text_delta`/`tool_use`/`tool_result`/`usage`/`error`) `translateRunAgentPayload`
23
+ * already parses for path 1 — deliberately, so this path reuses that exact function rather than
24
+ * duplicating the translation switch.
25
+ *
26
+ * `text_delta`/`thinking_delta` are forwarded as their own small `AgentEvent` per delta (not
27
+ * accumulated here) — chat-core's own `ChatMessage.events` array is what concatenates them into one
28
+ * growing message, so accumulating twice would double the text.
29
+ */
30
+ /** Distinguishes a BYOK-run id (client-minted, no server-side run record) from a daemon-run id
31
+ * (server-minted, reattachable) wherever a bare `runId` string is all a `ChatTransport` method
32
+ * receives — see `stopRun`/`fetchRunStatus`/`reattachRun` below for why the distinction matters. */
33
+ function isByokRunId({ transport, runId }) {
34
+ return runId.startsWith(transport.ports.byokRunIdPrefix);
35
+ }
36
+ /** `@jini-ai/protocol`'s `RunState` -> chat-core's flat `RunStatus` union (different spelling: `cancelled` vs `canceled`, `pending` vs `queued`). */
37
+ function toChatCoreRunStatus(state) {
38
+ switch (state) {
39
+ case "pending":
40
+ return "queued";
41
+ case "running":
42
+ return "running";
43
+ case "succeeded":
44
+ return "succeeded";
45
+ case "failed":
46
+ return "failed";
47
+ case "cancelled":
48
+ return "canceled";
49
+ default:
50
+ return undefined;
51
+ }
52
+ }
53
+ /** Reattach by run id; see each branch for why a BYOK or AG-UI run cannot resume. */
54
+ async function reattachTransportRun({ transport, runId, handlers, options }, _optional = {}) {
55
+ // A BYOK run has no server-side record to reattach to (module doc's path-2 section) — the
56
+ // stream lived entirely on the original `fetch()`'s response body, which a reload has already
57
+ // discarded. Reporting the run as simply over (an empty `onDone`) is the honest answer: there
58
+ // is no way to resume it, and pretending otherwise would hang the pane waiting for events that
59
+ // can never arrive.
60
+ if (isByokRunId({ transport, runId })) {
61
+ handlers.onDone([]);
62
+ return undefined;
63
+ }
64
+ // Same "no server-side record to resume" reasoning as the BYOK branch above — see
65
+ // `assistant-transport-ag-ui.ts`'s own doc for why this path has no reattach story yet.
66
+ if (transport.ports.agUi.isAgUiRunId({ runId }, {})) {
67
+ return transport.ports.agUi.reattachAgUiRun({ handlers }, {});
68
+ }
69
+ subscribeToRun({ transport, runId, handlers, signal: options?.signal });
70
+ return undefined;
71
+ }
72
+ /** The run's status by id; `null` is this port's "unknown/not trackable" value. */
73
+ async function fetchTransportRunStatus({ transport, runId }, _optional = {}) {
74
+ // Same reasoning as `reattachRun` above — no server-side run record exists for a BYOK run id,
75
+ // so there is no status to fetch. `null` is this port's existing "unknown/not trackable"
76
+ // value (see the daemon branch below's own `!response.ok` case), not a new state.
77
+ if (isByokRunId({ transport, runId }))
78
+ return null;
79
+ if (transport.ports.agUi.isAgUiRunId({ runId }, {}))
80
+ return transport.ports.agUi.fetchAgUiRunStatus({}, {});
81
+ const response = await transport.ports.fetch(`${transport.ports.runsUrl}/${encodeURIComponent(runId)}`, { credentials: "same-origin" });
82
+ if (!response.ok)
83
+ return null;
84
+ const { run } = (await response.json());
85
+ return toChatCoreRunStatus(run.state) ?? null;
86
+ }
87
+ /** Cancel by run id: a BYOK turn aborts its own in-flight fetch, a daemon run is cancelled server-side. */
88
+ async function stopTransportRun({ transport, runId }, _optional = {}) {
89
+ // A BYOK run's only cancellation handle is the abort controller `startByokRun` registered for
90
+ // this exact id — there is no server-side run to `POST .../cancel` against.
91
+ if (isByokRunId({ transport, runId })) {
92
+ transport.byokAbortControllers.get(runId)?.abort();
93
+ return undefined;
94
+ }
95
+ // A durable AG-UI start's canonical run is cancelled once by its binding, however Stop arrives.
96
+ if (transport.ports.agUi.isAgUiRunId({ runId }, {}) || transport.ports.agUi.isAcceptedAgUiRun?.({ runId }, {})) {
97
+ return transport.ports.agUi.stopAgUiRun({ runId }, {});
98
+ }
99
+ const response = await transport.ports.fetch(`${transport.ports.runsUrl}/${encodeURIComponent(runId)}/cancel`, {
100
+ method: "POST",
101
+ headers: { "Content-Type": "application/json" },
102
+ credentials: "same-origin",
103
+ body: JSON.stringify({ runId, messageId: transport.ports.runBinding({ runId }, {})?.messageId }),
104
+ });
105
+ // 404: the daemon no longer knows this run (it restarted), so nothing is left running to stop.
106
+ if (response.status === 404)
107
+ return undefined;
108
+ // `fetch` resolves on any status: without this a refused cancel (401/403/500) resolved exactly
109
+ // like a successful one while the run kept executing. `useRunStream` logs a rejection here.
110
+ if (!response.ok)
111
+ throw await refusalError({ action: "cancelling agent run failed", response }, {});
112
+ return undefined;
113
+ }
114
+ /** The `ChatTransport` for one execution-config source; every method is a thin dispatch to a helper above or in `transport-run.ts`. */
115
+ function buildChatTransport({ transport, options }) {
116
+ return {
117
+ startRun: (input, handlers) => startTransportRun({ transport, input, handlers }, { options }),
118
+ reattachRun: (runId, handlers, reattachOptions) => reattachTransportRun({ transport, runId, handlers, options: reattachOptions }),
119
+ fetchRunStatus: (runId) => fetchTransportRunStatus({ transport, runId }),
120
+ stopRun: (runId) => stopTransportRun({ transport, runId }),
121
+ };
122
+ }
4
123
  /** Bind transport effects once; in-flight controllers belong to this client, never the package.
5
124
  * Positional run methods implement the existing ChatTransport contract. */
6
125
  export function createAssistantTransportClient({ ports }, _options = {}) {
7
- const asString = (value) => runEvents.asString({ value }, {});
8
- const readSseFrames = (body) => runEvents.readSseFrames({ body }, {});
9
- const readTerminalReason = (raw, wrapped) => runEvents.readTerminalReason({ raw, wrapped }, {});
10
- const terminalReasonNotice = (reason) => runEvents.terminalReasonNotice({ reason, notice: ports.notices.toolStepLimit }, {});
11
- const translateRunAgentPayload = (payload) => runEvents.translateRunAgentPayload({ payload }, {});
12
- /**
13
- * Shared HTTP implementation of `@jini-ai/chat/react`'s `ChatTransport` port.
14
- *
15
- * TWO run paths live here, selected per-turn by `getExecutionConfig()` (see
16
- * `createAssistantTransport`'s own doc):
17
- *
18
- * 1. **Local CLI** (the original, unchanged path): binds to the real `@jini-ai/http` run surface
19
- * the host app's `src/server/runtime/composition/modules/assistant.ts` mounts — `POST /api/runs` to start, `GET
20
- * /api/runs/:runId/events` (native `EventSource`) to stream, `GET /api/runs/:runId` for status,
21
- * `POST /api/runs/:runId/cancel` to stop. Every SSE frame's `data` is a full `@jini-ai/protocol`
22
- * `RunProtocolEvent` (`{kind, payload, ...}`), not chat-core's own `AgentEvent` — chat-core's own
23
- * module doc is explicit that this reduction is a transport concern ("a host's transport adapter
24
- * is responsible for reducing wire deltas... into the persisted/renderable AgentEvent items"), so
25
- * `translateRunAgentPayload` below does that translation.
26
- * 2. **API · BYOK** (2026-08-04, the execution picker): binds to the host app's `src/server/runtime/composition/modules/assistant-byok.ts`'s
27
- * `POST /api/admin/v1/assistant/byok-turn` — one request/response holding the WHOLE turn open,
28
- * no separate `EventSource`/reattach/cancel-by-runId (see that route's own header for why, and
29
- * what it costs). Its SSE frames carry the SAME `payload.type` vocabulary
30
- * (`status`/`text_delta`/`tool_use`/`tool_result`/`usage`/`error`) `translateRunAgentPayload`
31
- * already parses for path 1 — deliberately, so this path reuses that exact function rather than
32
- * duplicating the translation switch.
33
- *
34
- * `text_delta`/`thinking_delta` are forwarded as their own small `AgentEvent` per delta (not
35
- * accumulated here) — chat-core's own `ChatMessage.events` array is what concatenates them into one
36
- * growing message, so accumulating twice would double the text.
37
- */
38
- /** Distinguishes a BYOK-run id (client-minted, no server-side run record) from a daemon-run id
39
- * (server-minted, reattachable) wherever a bare `runId` string is all a `ChatTransport` method
40
- * receives — see `stopRun`/`fetchRunStatus`/`reattachRun` below for why the distinction matters. */
41
- const BYOK_RUN_ID_PREFIX = ports.byokRunIdPrefix;
42
- /**
43
- * How many trailing messages of a conversation go to the agent.
44
- *
45
- * A cap rather than none: each turn cold-boots a fresh subprocess and pays for its whole input, so
46
- * an uncapped transcript makes every message in a long chat more expensive than the last. 40 is
47
- * roughly 20 exchanges — beyond what a working session usually needs to stay coherent, and far
48
- * short of where input cost starts to dominate. `buildTranscript` separately truncates any single
49
- * oversized message, so this bounds the number of turns, not their size.
50
- */
51
- const MAX_TRANSCRIPT_TURNS = 40;
52
- // The daemon-stream translation (`translateRunAgentPayload`, the terminal notices, `translateRunFrame`)
53
- // lives in `@jini-ai/chat/core/run-events`, extracted from the host's 2026-09-27 contract, so the API's
54
- // run finalizer saves exactly what this transport would have. Re-exported here so existing importers
55
- // and tests keep their paths.
56
- /**
57
- * The prompt for one run: the whole conversation so far, not just the newest message.
58
- *
59
- * This used to send only the latest user turn, which is why the assistant appeared to have no
60
- * memory — ask it something, then ask a follow-up, and the second run had never seen the first.
61
- * That looked like a missing capability and was not: `ChatPane` hands the full history to every
62
- * `startRun`, and it was being discarded here, in the browser, before the request was even built.
63
- * Nothing server-side had to change.
64
- *
65
- * `buildTranscript` rather than a hand-rolled join, because flattening a transcript has more edges
66
- * than it first appears: it truncates any single oversized message, escapes `## user`/`## assistant`
67
- * inside message bodies so a user cannot forge a turn boundary by pasting one, summarizes persisted
68
- * artifacts instead of replaying them, and prepends a warning when prior-run telemetry shows the
69
- * context was already large. Every admin turn cold-boots a fresh CLI subprocess, so the transcript
70
- * IS the memory — and the same property makes an unbounded one expensive.
71
- *
72
- * Bounded deliberately: each run is billed, and an unbounded transcript grows the input cost of
73
- * every subsequent turn in a conversation that has no natural end. {@link MAX_TRANSCRIPT_TURNS}
74
- * keeps a long-running chat from silently becoming the most expensive thing in the product.
75
- * Failed turns are labeled outcomes so another agent can explain and recover from them.
76
- */
77
- function runPrompt(history) {
78
- const recent = history.slice(-MAX_TRANSCRIPT_TURNS).map(message => {
79
- if (message.role !== 'assistant' || isAnsweredAssistantTurn(message))
80
- return message;
81
- const detail = message.events?.filter(event => event.kind === 'status')
82
- .map(event => [event.label, event.detail].filter(Boolean).join(': ')).join('\n').slice(-4000);
83
- // Reserve space for the failure reason even when partial output fills the transcript cap.
84
- const outcome = [message.content.slice(0, 6000), detail].filter(Boolean).join('\n\n');
85
- return { ...message, content: `[${message.agentName ?? message.agentId ?? 'Assistant'} run ${message.runStatus}; not a completed answer]\n${outcome || 'No assistant reply was produced.'}` };
86
- });
87
- return buildTranscript({ history: recent });
88
- }
89
- /**
90
- * Whether an assistant message represents a turn the agent actually answered — the single
91
- * definition both {@link historyForTranscript} and {@link undeliveredUserPrompt} key off.
92
- *
93
- * `undefined` counts as answered: rows written before `ai_chat_messages.run_status` existed carry
94
- * no status at all, and treating those as unanswered would re-send the whole history of every
95
- * legacy conversation on its next turn. Every non-`succeeded` status counts as unanswered —
96
- * `failed` and `canceled` obviously, and `queued`/`running` because a run killed mid-flight (a
97
- * daemon respawn, see `daemon-supervisor.ts`) never reaches a terminal status at all and leaves
98
- * exactly such a row behind.
99
- *
100
- * Do not "simplify" this away by deleting the failed rows at the source instead. That was the first
101
- * shape proposed for this fix and it is the wrong trade: `run_status='failed'` was ALREADY the
102
- * explicit failed state, and the only thing missing was somewhere that skips it. The row's
103
- * `events_json` is the sole durable record of why a run died (exit code, signal, the CLI's own
104
- * stderr) once the daemon's in-memory event log is gone, and the pane renders it on reload — so
105
- * dropping the row trades a history bug for a forensics hole. The skip belongs here, on the read
106
- * side. The transcript's hidden-tool mode likewise filters only recovered tool failures and keeps
107
- * unrecovered failures behind a compact disclosure; it never deletes this durable evidence.
108
- * See {@link historyForTranscript} and `assistant-chats.ts`'s `persistableMessages`.
109
- */
110
- function isAnsweredAssistantTurn(message) {
111
- return message.runStatus === undefined || message.runStatus === "succeeded";
112
- }
113
- /**
114
- * The history a transcript may be built from: every user turn, and only those assistant turns the
115
- * agent actually answered.
116
- *
117
- * Defect 3 of the 2026-09-11 chat-lifecycle repair. `ai_chat_messages` in
118
- * the investigated host's `chat.db` holds assistant rows with `run_status='failed'` and
119
- * `length(content)=0` — the durable trace of a run that died before writing a token. Replayed
120
- * through `buildTranscript` they become a `## assistant` block with nothing under it: the next run
121
- * is told the agent replied when what actually happened is that it died, and a failure the user can
122
- * see in the pane is laundered into an empty answer in the model's context.
123
- *
124
- * The rows themselves are deliberately NOT deleted, and this is the fix instead: their
125
- * `events_json` carries the only surviving record of why the run failed (exit code, signal, the
126
- * CLI's own stderr), the daemon's event log is in-memory and gone, and the pane renders that notice
127
- * on reload. Partial output from a failed run stays stored as partial output for the same reason —
128
- * it is visible to the user, and it is not the agent's answer, so it does not go back into a prompt.
129
- *
130
- * @param history - The pane's transcript, oldest first.
131
- * @returns A new array; the input is never mutated.
132
- * @complexity O(n) in history length, one pass, no allocation per message.
133
- */
134
- function historyForTranscript(history) {
135
- return history.filter((message) => message.role !== "assistant" || isAnsweredAssistantTurn(message));
136
- }
137
- /**
138
- * Prepended when more than one user turn is being sent at once, so the agent is not told the user
139
- * typed all of it just now. Deliberately absent from the single-turn case — a note on every
140
- * ordinary message would be a standing lie in the prompt of every turn in every conversation.
141
- */
142
- const UNDELIVERED_TURNS_NOTE = "[Some of the messages below never reached you: the run that should have answered them failed before it could. Treat them as the user's own words, in order, and answer all of them.]";
143
- /**
144
- * The user text a run must carry when the agent carries its own conversation memory: every user
145
- * turn since the last one the agent actually answered, not only the newest.
146
- *
147
- * Defect 2 of the 2026-09-11 chat-lifecycle repair, and the half of it that was actually lossy. In
148
- * the investigated host's `chat.db` conversation `9289701c-…`, position 5's user text is present in
149
- * `ai_chat_messages` and absent from every agent-session transcript: the run meant to answer it
150
- * failed 140 ms after start, so no CLI ever read it — and because
151
- * {@link resolveLocalCliPrompt} sends only the NEWEST user turn to a resume-capable agent, no later
152
- * turn ever carried it either. The message was durable the whole time and still lost, permanently,
153
- * with nothing anywhere saying so.
154
- *
155
- * Re-delivering costs a duplicate whenever the CLI did read the prompt before dying, which the
156
- * agent can reconcile from its own session. Not re-delivering costs the user a message with no
157
- * trace. The two are not symmetric, so this errs toward the duplicate.
158
- *
159
- * @param history - The pane's transcript, oldest first.
160
- * @returns The prompt text — the bare newest turn in the ordinary case (the previous turn was
161
- * answered), or the unanswered turns joined oldest-first behind {@link UNDELIVERED_TURNS_NOTE}.
162
- * Falls back to the newest user turn when the history ends in an answered assistant turn and
163
- * there is therefore nothing pending.
164
- * @complexity O(n) in history length — one forward scan for the boundary plus one slice/filter over
165
- * the tail. A backwards scan with an early exit would be O(1) in practice but needs `break`, and
166
- * `n` here is bounded by one conversation's transcript; this is not a hot path (once per turn).
167
- * The result is capped at {@link MAX_TRANSCRIPT_TURNS} for the pathological case of a
168
- * conversation whose every run has failed.
169
- */
170
- function undeliveredUserPrompt(history) {
171
- // `Array.prototype.findLastIndex` would say this in one call, but it is ES2023 and the
172
- // supported target is ES2022, so the index is accumulated instead.
173
- let lastAnsweredIndex = -1;
174
- history.forEach((message, position) => {
175
- if (message.role === "assistant" && isAnsweredAssistantTurn(message))
176
- lastAnsweredIndex = position;
177
- });
178
- const pending = history
179
- .slice(lastAnsweredIndex + 1)
180
- .filter((message) => message.role === "user")
181
- .slice(-MAX_TRANSCRIPT_TURNS);
182
- if (pending.length === 0)
183
- return latestUserPromptFromHistory({ history: history });
184
- const newest = pending[pending.length - 1];
185
- const newestText = newest.content.trim();
186
- const newestAttachmentRefs = JSON.stringify((newest.attachments ?? []).map((attachment) => attachment.path));
187
- // Collapse resends of the newest text with matching attachment refs: a retry is one request.
188
- const distinct = pending.filter((message, index) => index === pending.length - 1
189
- || message.content.trim() !== newestText
190
- || JSON.stringify((message.attachments ?? []).map((attachment) => attachment.path)) !== newestAttachmentRefs)
191
- .map((message) => message.content);
192
- if (distinct.length === 1)
193
- return distinct[0];
194
- return `${UNDELIVERED_TURNS_NOTE}\n\n${distinct.join("\n\n")}`;
195
- }
196
- /** `@jini-ai/protocol`'s `RunState` -> chat-core's flat `RunStatus` union (different spelling: `cancelled` vs `canceled`, `pending` vs `queued`). */
197
- function toChatCoreRunStatus(state) {
198
- switch (state) {
199
- case "pending":
200
- return "queued";
201
- case "running":
202
- return "running";
203
- case "succeeded":
204
- return "succeeded";
205
- case "failed":
206
- return "failed";
207
- case "cancelled":
208
- return "canceled";
209
- default:
210
- return undefined;
211
- }
212
- }
213
- /** The durable message owns recovery and terminal state; this subscription follows replacement
214
- * attempts without writing a browser-inferred failure into history. */
215
- function subscribeToRun(runId, handlers, signal) {
216
- ports.followRun({ runId, handlers: capturePluginUsage(handlers), ...(signal === undefined ? {} : { signal }) }, {});
217
- }
218
- /** The well-formed plugin usage an `agent_plugins` extension event carries, or `undefined` for any
219
- * other event — the one validity rule both live events and checkpoint replays are captured by. */
220
- function pluginUsageOf({ event }, _optional) {
221
- if (event.kind !== 'ext' || event.name !== 'agent_plugins')
222
- return undefined;
223
- const usage = event.data;
224
- return typeof usage?.conversationId === 'string' && usage.state && Array.isArray(usage.state.excluded) ? usage : undefined;
225
- }
226
- /** Capture before notifying the UI so answers received after reload persist for the next turn.
227
- * Checkpoint panes skip live deltas to avoid duplicate text, so capture their saved events here
228
- * too. Keep this wrapper as the single capture owner for both delivery contracts.
229
- * @complexity O(e + s) per checkpoint; O(s) per live event, in saved events and plugin-state size.
230
- */
231
- function capturePluginUsage(handlers) {
232
- const captured = new Map();
233
- const capture = (event) => {
234
- const usage = pluginUsageOf({ event }, {});
235
- if (!usage)
236
- return;
237
- const state = JSON.stringify(usage.state);
238
- if (captured.get(usage.conversationId) === state)
239
- return;
240
- captured.set(usage.conversationId, state);
241
- captureAgentPluginUsage({ event });
242
- };
243
- return {
244
- ...handlers,
245
- onEvent: event => { capture(event); handlers.onEvent(event); },
246
- ...(handlers.onCheckpoint ? { onCheckpoint: (message) => {
247
- // Historical answers must not roll the current state backwards on every poll.
248
- const latest = new Map();
249
- for (const event of message.events ?? []) {
250
- const usage = pluginUsageOf({ event }, {});
251
- if (usage)
252
- latest.set(usage.conversationId, event);
253
- }
254
- for (const event of latest.values())
255
- capture(event);
256
- handlers.onCheckpoint(message);
257
- } } : {}),
258
- };
259
- }
260
- /** Client-minted, not server-minted — see module doc's path-2 section: a BYOK run has no server-side
261
- * run record to name it. Prefixed so `stopRun`/`fetchRunStatus`/`reattachRun` below can tell a
262
- * BYOK-run id apart from a daemon-run id without any other context. */
263
- function mintByokRunId() { return `${BYOK_RUN_ID_PREFIX}${ports.mintId({}, {})}`; }
264
- /** In-flight BYOK turns' abort controllers, keyed by the client-minted runId — the ONLY way
265
- * `stopRun` can cancel a BYOK turn: unlike the daemon path, there is no server-side run record to
266
- * `POST .../cancel` against, so cancellation has to reach back into THIS tab's own in-flight
267
- * `fetch`. Entries are removed as soon as a turn settles (normally, on error, or on abort) so a
268
- * stale id can never resurrect a finished controller. */
269
- const byokAbortControllers = new Map();
270
- /**
271
- * Dispatches one parsed BYOK SSE frame to the right `RunHandlers` call — the `"agent"`/`"error"`/
272
- * `"end"` handling pulled out of `startByokRun`'s stream-consumer IIFE (2026-08-06, complexity
273
- * pass), where it sat four levels of nesting deep (async IIFE > `try` > `for await` > `if`/
274
- * `else if`, with a further nested `if` inside the `"agent"` and `"end"` cases). At module scope it
275
- * is a single, independently testable function: a plain `{event, data}` frame in, a fake
276
- * `RunHandlers` to assert against, no `ReadableStream`/`fetch`/timers required.
277
- *
278
- * @param ctx.collected - This turn's running event log — the same array `startByokRun` hands to
279
- * `handlers.onDone` once the stream ends.
280
- * @param ctx.finish - `startByokRun`'s own idempotent finish (closes out the turn, deletes its abort
281
- * controller, calls `onDone`). Called on `"end"`, exactly as the inline version did.
282
- */
283
- function handleByokFrame(frame, ctx) {
284
- if (frame.event === "agent") {
285
- const payload = JSON.parse(frame.data);
286
- const translated = translateRunAgentPayload(payload);
287
- if (translated) {
288
- ctx.collected.push(translated);
289
- ctx.handlers.onEvent(translated);
290
- }
291
- }
292
- else if (frame.event === "error") {
293
- const payload = JSON.parse(frame.data);
294
- ctx.handlers.onError(new Error(asString(payload.message) || "BYOK turn failed"));
295
- }
296
- else {
297
- if (frame.event !== "end")
298
- return;
299
- const notice = terminalReasonNotice(readTerminalReason(frame.data, false));
300
- if (notice) {
301
- ctx.collected.push(notice);
302
- ctx.handlers.onEvent(notice);
303
- }
304
- ctx.finish();
305
- }
306
- }
307
- /**
308
- * Drains a BYOK turn's SSE body to completion, dispatching each frame via {@link handleByokFrame}
309
- * and settling the turn through `ctx.finish` — the async IIFE `startByokRun` used to hold its
310
- * stream-consumer loop in, pulled out to a top-level function (2026-08-06, complexity pass, second
311
- * pass). `startByokRun`'s own per-function score is already under the per-function ceiling; this
312
- * split is for the OTHER metric this repo's complexity ceiling tracks — a tool that rolls a nested
313
- * closure's branches into its enclosing function's total still counted this IIFE as part of
314
- * `startByokRun` as long as it stayed physically inside the body. Moving it to a sibling top-level
315
- * function removes it from that rollup instead of just moving it to a different nested scope (a
316
- * `const` inside `startByokRun` would not have changed the rollup at all).
317
- *
318
- * @param ctx.runId - Only used to clear {@link byokAbortControllers} on a genuine (non-abort)
319
- * failure — the abort path itself already deletes its own entry in `startByokRun` before this
320
- * runs, so `ctx.runId` here is scoped to the error branch alone.
321
- * @param ctx.controller - Read only for `.signal.aborted`, to tell a deliberate `stopRun`/composer
322
- * abort apart from a real stream failure — same distinction the inline version drew.
323
- */
324
- async function consumeByokStream(body, ctx) {
325
- try {
326
- for await (const frame of readSseFrames(body)) {
327
- handleByokFrame(frame, { collected: ctx.collected, handlers: ctx.handlers, finish: ctx.finish });
328
- }
329
- ctx.finish();
330
- }
331
- catch (error) {
332
- byokAbortControllers.delete(ctx.runId);
333
- if (ctx.controller.signal.aborted) {
334
- // Cancelled via `stopRun` or the composer's own signal — an expected exit, not a reportable
335
- // failure. `subscribeToRun`'s `EventSource` has no equivalent branch because `.close()`
336
- // doesn't reject a promise the way an aborted `fetch`'s body reader does; this mirrors what a
337
- // cancelled daemon run already looks like to the rest of the pane: silence, not an error toast.
338
- ctx.finish();
339
- return;
340
- }
341
- // Error THEN finish, same order and same reason as `subscribeToRun`'s `end` listener: reporting
342
- // alone left the turn unsettled (no `onDone`, so the events collected before the failure were
343
- // never persisted), and finishing first would record the dead run as succeeded.
344
- ctx.handlers.onError(error instanceof Error ? error : new Error(String(error)));
345
- ctx.finish();
346
- }
347
- }
348
- /**
349
- * The provider-bound history of one BYOK turn: only turns the agent actually answered, never an
350
- * empty one, each carrying its redaction signal.
351
- */
352
- function byokMessages({ history }, _optional) {
353
- // `historyForTranscript` first (Defect 3, 2026-09-11): the empty-content filter below already
354
- // hides a failed run that produced nothing, but NOT one that emitted a few tokens before dying —
355
- // that partial output would be sent to the provider as if it were the assistant's answer. This is
356
- // the same defect as on the Local CLI path, reachable by a second route.
357
- return historyForTranscript(history)
358
- .filter((message) => message.content.trim().length > 0)
359
- .map((message) => ({ role: message.role, content: message.content,
360
- ...(message.secretRedaction?.secretRedacted ? { secretRedacted: true } : {}),
361
- }));
362
- }
363
- /** The credential block of a BYOK turn; an empty base URL and an unset token cap are omitted. */
364
- function byokCredentials({ byok }, _optional) {
365
- return {
366
- protocol: byok.protocol,
367
- apiKey: byok.apiKey,
368
- ...(byok.baseUrl ? { baseUrl: byok.baseUrl } : {}),
369
- model: byok.model,
370
- ...(byok.maxTokens !== undefined ? { maxTokens: byok.maxTokens } : {}),
371
- };
372
- }
373
- /** The JSON body `POST byokTurnUrl` carries for one turn. */
374
- function byokTurnBody({ input, byok }, _optional) {
375
- return {
376
- messages: byokMessages({ history: input.history }, {}),
377
- ...attachmentIdsField(input),
378
- ...(input.folders?.length ? { folders: input.folders } : {}),
379
- ...conversationIdField(input),
380
- agentPluginState: input.context?.["agentPluginState"],
381
- userPrompt: input.context?.["userPrompt"],
382
- ...pluginRefIdsField(input),
383
- // The admin screen, as on the Local CLI path (`buildLocalCliContextRef`): the server puts it
384
- // in front of the newest message so a BYOK turn knows the open page and where drawings go.
385
- ...pageContextField(input),
386
- byok: byokCredentials({ byok }, {}),
387
- };
388
- }
389
- /**
390
- * The error for a refused request: `<action> (<status>)`, plus up to 300 characters of the
391
- * response body when it has one — shared by the BYOK start, Local CLI start and cancel refusals.
392
- */
393
- async function refusalError({ action, response }, _optional) {
394
- // A response whose body stream errors out (e.g. a dropped connection) must not turn "the server
395
- // rejected the request" into "the client crashed reading the rejection".
396
- const detail = await response.text().catch(() => "");
397
- const suffix = detail ? ": " + detail.slice(0, 300) : "";
398
- return new Error(`${action} (${response.status})${suffix}`);
399
- }
400
- /**
401
- * The BYOK run path (2026-08-04) — one held-open `POST` to `assistant-byok.ts`, no separate
402
- * `EventSource`/reattach. See module doc's path-2 section for why this shape differs from
403
- * `subscribeToRun`'s daemon-path pattern, and what it costs (no reattach after a reload; `stopRun`
404
- * works via the abort-controller map above instead of a server-side cancel endpoint).
405
- *
406
- * @complexity Dominated by the network/stream cost of the turn itself; per-frame parsing is O(1).
407
- * @overallScore 100
408
- */
409
- async function startByokRun(input, handlers, byok) {
410
- const runId = mintByokRunId();
411
- const controller = new AbortController();
412
- byokAbortControllers.set(runId, controller);
413
- // Conversation adoption may have yielded while the subscription was torn down.
414
- if (input.signal?.aborted)
415
- controller.abort();
416
- else
417
- input.signal?.addEventListener("abort", () => controller.abort());
418
- let response;
419
- try {
420
- response = await ports.fetch(ports.byokTurnUrl, {
421
- method: "POST",
422
- headers: { "Content-Type": "application/json" },
423
- credentials: "same-origin",
424
- body: JSON.stringify(byokTurnBody({ input, byok }, {})),
425
- signal: controller.signal,
426
- });
427
- }
428
- catch (error) {
429
- byokAbortControllers.delete(runId);
430
- throw error instanceof Error ? error : new Error(String(error));
431
- }
432
- if (!response.ok || !response.body) {
433
- byokAbortControllers.delete(runId);
434
- throw await refusalError({ action: "BYOK turn failed to start", response }, {});
435
- }
436
- const collected = [];
437
- let settled = false;
438
- const finish = () => {
439
- if (settled)
440
- return;
441
- settled = true;
442
- byokAbortControllers.delete(runId);
443
- handlers.onDone(collected);
444
- };
445
- // Deliberately not awaited: `startRun`'s contract (matching the daemon path immediately above)
446
- // is to resolve `{runId}` once the turn has STARTED, not once it has finished — the response
447
- // headers (hence this function reaching this point at all) arrive as soon as
448
- // `assistant-byok.ts` calls `beginStream`, well before generation completes.
449
- void consumeByokStream(response.body, { runId, collected, handlers, finish, controller });
450
- return { runId };
451
- }
452
- /**
453
- * Which browser tab a Local CLI run should be allowed to drive, from `ChatPane`'s `runContext` prop
454
- * (`AssistantDock.tsx` supplies it from the live `FrontendSessionBridge`).
455
- *
456
- * Read by name rather than spreading the whole `input.context` blob: `contextRef` is a shared
457
- * envelope that the host's proxy also writes `principalId` into (the host app's `src/server/runtime/composition/modules/assistant.ts`),
458
- * and a spread would let any future `runContext` key silently shadow it — an identity field being
459
- * overwritten by a UI prop is not a failure mode worth leaving open to save one line.
460
- *
461
- * The tab id accompanies the token so the host can verify the session owner before binding.
462
- * @complexity O(1) time and space.
463
- * @overallScore 100
464
- * Returns `{}` (omitting the fields entirely) when absent, which is a normal state, not an error:
465
- * the daemon treats a run with no bind token as one with no screen to drive
466
- * (`agent-daemon-server.ts`).
467
- */
468
- function frontendBindingFields(input) {
469
- const frontendBindToken = input.context?.["frontendBindToken"];
470
- const frontendTabId = input.context?.["frontendTabId"];
471
- return {
472
- ...(typeof frontendBindToken === "string" && frontendBindToken.length > 0 ? { frontendBindToken } : {}),
473
- ...(typeof frontendTabId === "string" && frontendTabId.length > 0 ? { frontendTabId } : {}),
474
- };
475
- }
476
- /**
477
- * The Local CLI picker's live model selection, from `ChatPane`'s `runContext` prop
478
- * (`AssistantDock.tsx`'s `resolveRunContext`). Same "read by name, not spread" reasoning as
479
- * {@link frontendBindingFields} above, and the same "omit when absent" convention. Forwarded as an
480
- * opaque string — `agent-daemon-server.ts` forwards it the same way, and `AgentExecutor.run()`'s
481
- * def-level `buildArgs` is what decides what an absent or `'default'` value means for a given CLI
482
- * (`@jini-ai/agent-runtime`'s `models.ts`/`resolveModelForAgent`).
483
- */
484
- function modelField(input) {
485
- const model = input.context?.["model"];
486
- return typeof model === "string" && model.length > 0 ? { model } : {};
487
- }
488
- /**
489
- * The Execution tab's "Reasoning effort" pick, from the same `runContext` seam as {@link modelField}
490
- * above and forwarded with the identical "opaque string, omit when absent" convention. What turns it
491
- * into real argv is the def's own `buildArgs` on the daemon side (`claude --effort <level>`, codex's
492
- * `-c model_reasoning_effort=...`) — nothing here interprets it, and a runtime whose effort is
493
- * encoded in the model id (antigravity) never sends it at all, because its level is already inside
494
- * `model`.
495
- */
496
- function reasoningField(input) {
497
- const reasoning = input.context?.["reasoning"];
498
- return typeof reasoning === "string" && reasoning.length > 0 ? { reasoning } : {};
499
- }
500
- /**
501
- * Opaque `attachment:<uuid>` capability ids (`ChatAttachment.path` — never a real filesystem path
502
- * this early; see `@jini-ai/http-kit`'s `attachments.ts` trust-model doc), not the attachments
503
- * themselves — `contextRef` is the one channel `prompt`/`frontendBindToken` already ride on to reach
504
- * `agent-daemon-server.ts`'s `onStarted`, which is where these ids get exchanged for real,
505
- * re-validated paths via `AttachmentStore.claim()`. Nothing on this side of the wire is trusted; the
506
- * id is inert until the daemon claims it.
507
- *
508
- * Returns `{}`, same convention as {@link frontendBindingFields} above — a run with no attachments
509
- * is the overwhelmingly common case and should not carry a key for it.
510
- */
511
- function attachmentIdsField(input) {
512
- return input.attachments && input.attachments.length > 0
513
- ? { attachmentIds: input.attachments.map((attachment) => attachment.path) }
514
- : {};
515
- }
516
- /**
517
- * Opaque Agent Plugin ids (`plugin.json`'s own `name`, e.g. `"ui-ux-design"`) the operator has
518
- * pinned as composer chips — `AssistantDock.tsx`'s `useSelectedAgentPlugins`, threaded here via
519
- * `ChatPane`'s `runContext` prop the same way {@link frontendBindingFields}/{@link modelField}
520
- * above already are. Same "read by name, not spread" and "omit when absent" conventions as those
521
- * two fields: this is not the plugin's CONTENT, only a reference to it —
522
- * `agent-daemon-server.ts`'s `onStarted` is where a ref gets resolved against the real installed
523
- * package on disk and its own text prepended to the prompt (see that function's own doc for the
524
- * resolution/failure rules). Filtered to non-empty strings for the same reason `attachmentIds` is
525
- * filtered on the decode side (`run-start-context.ts`'s `parseRunStartContextRef`) — this is the
526
- * encode side of the same wire value, and a malformed entry here should not silently become a
527
- * malformed one there.
528
- */
529
- function pluginRefIdsField(input) {
530
- const pluginRefIds = input.context?.["pluginRefIds"];
531
- if (!Array.isArray(pluginRefIds))
532
- return {};
533
- const filtered = pluginRefIds.filter((id) => typeof id === "string" && id.length > 0);
534
- return filtered.length > 0 ? { pluginRefIds: filtered } : {};
535
- }
536
- /**
537
- * The active conversation id, from `ChatPane`'s `runContext` prop (`AssistantDock.tsx`'s
538
- * `chats.activeId`, the same `useRunContext` seam {@link frontendBindingFields}/{@link modelField}/
539
- * {@link pluginRefIdsField} above already ride). Lets `agent-daemon-server.ts`'s `onStarted` resume
540
- * this conversation's agent-CLI session across turns instead of spawning cold every time
541
- * (`server/inbound/assistant/agent-session-resume.ts`) — see that file's own doc. Returns `{}`, same
542
- * convention as every other optional field here: a run started before any conversation exists yet
543
- * (or from a future daemon client that never sends one) just gets no session-resume behavior, not
544
- * an error.
545
- */
546
- function conversationIdField(input, resolvedConversationId) {
547
- const conversationId = resolvedConversationId ?? input.context?.["conversationId"];
548
- return typeof conversationId === "string" && conversationId.length > 0 ? { conversationId } : {};
549
- }
550
- /**
551
- * The admin screen this message was sent from (`lib/agent-screen-context.ts`, read by
552
- * `AssistantDock.hooks.tsx`'s `useRunContext` at send time), so the agent knows what "this page"
553
- * means. Forwarded as-is when it is a plain object — the daemon's `run-page-context.ts` owns
554
- * validating and capping its fields, the same split `attachmentIds` has — and omitted otherwise.
555
- */
556
- function pageContextField(input) {
557
- const pageContext = input.context?.["pageContext"];
558
- return typeof pageContext === "object" && pageContext !== null && !Array.isArray(pageContext) ? { pageContext } : {};
559
- }
560
- /**
561
- * Assembles the Local CLI path's `contextRef` — everything `startRun`'s daemon branch sends besides
562
- * `agentId` itself. Pulled out of `startRun` (2026-08-06, complexity pass, second pass) as its own
563
- * pure function, then split again (2026-09-04, complexity pass) into one pure field-helper per
564
- * optional field, each above: six independent, unrelated fields, none sharing state or order
565
- * dependence, each read from `input` by name and included only when present (see each helper's own
566
- * doc for why). Kept as six separate functions rather than grouped, on purpose — the fields have no
567
- * conceptual relationship to group them by (identity, execution config, and content all mixed
568
- * together), and inventing a grouping would obscure the very independence each field's own doc
569
- * argues for. A plain object in, a plain object out — directly testable with a `StartRunInput`
570
- * fixture, no `fetch`/`EventSource` involved.
571
- *
572
- * @param prompt - The already-built transcript string ({@link runPrompt}'s result) — this function
573
- * only decides which of the six OPTIONAL fields ride alongside it, not how the prompt itself is
574
- * built.
575
- * @param resolvedConversationId - {@link resolveRunConversationId}'s answer, when `startRun` had to
576
- * adopt a conversation because `input.context` named none (the first turn of a chat). Omitted by
577
- * every caller that already has an id on `input.context`, and by this function's own unit tests —
578
- * in which case the `context` field is read exactly as before.
579
- * The bounded `coldStartContext` is the complete prompt, including the current request. The
580
- * daemon selects it instead of the resume tail when native resume is unavailable.
581
- */
582
- function buildLocalCliContextRef(input, prompt, resolvedConversationId) {
583
- return {
584
- prompt: ports.projectPrompt({ prompt, context: input.context }, {}),
585
- // Select one complete transcript after binding; concatenating it with the tail repeats turns.
586
- coldStartContext: ports.projectPrompt({ prompt: runPrompt(input.history), context: input.context }, {}),
587
- // The transcript is already sanitized; retain only the CURRENT user's signal across the
588
- // daemon JSON boundary. Replaying an old signal reports another paste on every later turn.
589
- ...(newestUserMessage({ history: input.history }, {})?.secretRedaction?.secretRedacted ? { secretRedacted: true } : {}),
590
- assistantMessageId: input.assistantMessageId,
591
- ...frontendBindingFields(input),
592
- ...modelField(input),
593
- ...reasoningField(input),
594
- ...attachmentIdsField(input),
595
- ...(input.folders?.length ? { folders: input.folders } : {}),
596
- ...pluginRefIdsField(input),
597
- agentPluginState: input.context?.["agentPluginState"],
598
- userPrompt: input.context?.["userPrompt"],
599
- ...conversationIdField(input, resolvedConversationId),
600
- ...pageContextField(input),
601
- };
602
- }
603
- /**
604
- * The conversation id this run must carry, adopting one if the caller had none.
605
- *
606
- * @param input - `startRun`'s own input; `input.context.conversationId` wins whenever it is a
607
- * non-empty string, so turn 2 onward never touches {@link ensureConversationId} and never issues a
608
- * redundant `POST /conversations`.
609
- * @param ensureConversationId - `AssistantTransportOptions.ensureConversationId`, or
610
- * `undefined` for a transport built without it (every test and any non-dock consumer).
611
- * @returns The id to put on the wire, or `undefined` to omit the key entirely — including when
612
- * adoption failed. The `.catch` is load-bearing: `ensureConversationId`'s own contract promises
613
- * `null` over a rejection, and this makes that promise safe to depend on even if a future
614
- * implementation breaks it, rather than failing the user's turn over a lost session id.
615
- * @complexity O(1) plus at most one conversation-creation round trip, on the first turn only.
616
- */
617
- async function resolveRunConversationId(input, ensureConversationId) {
618
- const fromContext = input.context?.["conversationId"];
619
- if (typeof fromContext === "string" && fromContext.length > 0)
620
- return fromContext;
621
- if (!ensureConversationId)
622
- return undefined;
623
- const adopted = await ensureConversationId({}, {}).catch(() => null);
624
- return typeof adopted === "string" && adopted.length > 0 ? adopted : undefined;
625
- }
626
- /** Send a resumed agent only its unseen conversation tail, retaining other agents' outcomes.
627
- * Legacy rows without agent identity retain the existing unanswered-user delivery contract.
628
- * @complexity O(n) to find the last answered turn; transcript rendering is capped at 40 turns.
629
- */
630
- function resolveLocalCliPrompt(input, resumeCapableAgentIds) {
631
- const carriesOwnMemory = input.agentId !== undefined && resumeCapableAgentIds?.has(input.agentId) === true;
632
- if (!carriesOwnMemory)
633
- return runPrompt(input.history);
634
- let lastOwnAnswer = -1;
635
- input.history.forEach((message, index) => {
636
- if (message.role === 'assistant' && (!message.agentId || message.agentId === input.agentId) && isAnsweredAssistantTurn(message))
637
- lastOwnAnswer = index;
638
- });
639
- const unseen = input.history.slice(lastOwnAnswer + 1);
640
- const crossedAgents = unseen.some(message => message.role === 'assistant' && message.agentId && message.agentId !== input.agentId);
641
- // BEHAVIOR CHANGE (2026-09-11, Defect 2): the resume-capable branch was `latestUserPrompt` — the
642
- // single newest user turn, on the assumption that everything before it is already inside the
643
- // CLI's own session. That assumption holds only for turns the agent actually answered; a turn
644
- // whose run died before the CLI read its prompt is in neither place, and nothing ever sent it
645
- // again. `undeliveredUserPrompt` returns the identical single string in the ordinary case and
646
- // differs only when there is genuinely something unanswered to catch up on.
647
- return crossedAgents ? runPrompt(unseen) : undeliveredUserPrompt(input.history);
648
- }
649
- /**
650
- * Writes the newest user turn to durable storage before its run is dispatched, and never fails the
651
- * turn over it.
652
- *
653
- * Defect 2 of the 2026-09-11 chat-lifecycle repair. Message persistence is a client-side
654
- * `Promise.all` driven by `onMessagesChange` deltas (`use-assistant-chats.hooks.ts`'s `flush`) and
655
- * run dispatch is a separate `POST /api/runs` here — nothing orders them and nothing makes them
656
- * atomic, so a browser or daemon death in the window between them could leave a dispatched run whose
657
- * prompt existed nowhere durable. Await the same PUT when a delta has already scheduled it;
658
- * acceptance also carries the exact user message and commits it with the assistant stub when
659
- * browser persistence fails, so sending does not depend on a successful separate PUT.
660
- *
661
- * The idempotency key is the message's own id — `assistant-chats.ts`'s `saveMessage` PUTs to
662
- * `/messages/<id>`, so this write and the `flush` that will race it converge on one row rather than
663
- * two, and a retry of the same content is free. `useAssistantChats`'s own `persistUserTurn` also
664
- * marks the id written, so in practice `flush` skips it entirely.
665
- *
666
- * @param message - The newest `role: "user"` message in `startRun`'s history — what gets written.
667
- * `startRun` has already refused a history without one, so it is always present here.
668
- * @param conversationId - The already-resolved conversation (see `resolveRunConversationId`), or
669
- * `undefined` when adoption failed — there is no row to write into in that case.
670
- * @param persistUserTurn - `AssistantTransportOptions.persistUserTurn`, or `undefined`
671
- * for a transport built without it (every test and any non-dock consumer).
672
- * @returns Nothing, always. The `.catch` keeps a failed browser PUT from refusing the user's turn;
673
- * durable acceptance is now responsible for committing its copy before dispatch.
674
- * @complexity O(1) plus one PUT.
675
- */
676
- async function persistUserTurnBeforeDispatch({ message, conversationId }, { persistUserTurn }) {
677
- // Pending composer input is persisted by atomic run acceptance. An earlier PUT could save a
678
- // rejected (409) draft as a user turn; confirmed/legacy callers retain their existing ordering.
679
- if (message.inputPending || conversationId === undefined || persistUserTurn === undefined)
680
- return;
681
- await persistUserTurn({ conversationId, message }, {}).catch(() => undefined);
682
- }
683
- /** The newest `role: "user"` message in a history, or `undefined` when it has none.
684
- * @complexity O(n) in history length. */
685
- function newestUserMessage({ history }, _optional) {
686
- return [...history].reverse().find((message) => message.role === "user");
687
- }
688
- /**
689
- * Turns `startRun`'s Local CLI `POST /api/runs` response into either a thrown, detailed error or a
690
- * subscribed run — the two outcomes once the request lands. Pulled out of `startRun` (2026-09-04,
691
- * complexity pass) as its own step: `response.ok` in, `{runId}` or a thrown `Error` out. The
692
- * `.text().catch(() => "")` is load-bearing, not decorative — see {@link refusalError}'s inline comment.
693
- */
694
- async function finishLocalCliRun(response, handlers, signal) {
695
- if (!response.ok)
696
- throw await refusalError({ action: "agent run failed to start", response }, {});
697
- const { run, messageId, conversationId } = (await response.json());
698
- if (messageId && conversationId)
699
- ports.bindRun({ runId: run.id, binding: { messageId, conversationId } }, {});
700
- subscribeToRun(run.id, handlers, signal);
701
- return { runId: run.id };
702
- }
703
- /**
704
- * The Local CLI path of `startRun`: durable user turn, then acceptance, then the followed run.
705
- *
706
- * @param input - `startRun`'s input with its conversation identity already merged into `context`.
707
- * @param userMessage - The newest user message; acceptance carries it verbatim.
708
- * @param conversationId - The resolved conversation, or `undefined` when adoption failed.
709
- */
710
- async function startLocalCliRun({ input, handlers, userMessage, conversationId }, { options }) {
711
- // Local CLI path below. `resolveLocalCliPrompt`'s own doc has the full contract for why an
712
- // unresolved/absent agentId fails open to the full transcript rather than the bare message.
713
- const prompt = resolveLocalCliPrompt(input, options.getResumeCapableAgentIds?.({}, {}));
714
- // Also before the POST, and for the same reason it is awaited rather than fired off: the
715
- // user's turn must be durable before a run that can fail to deliver it exists at all
716
- // (Defect 2, 2026-09-11). Ordered after conversation adoption because it needs the id that
717
- // adoption produces. BYOK and AG-UI share the identity above; neither writes a durable
718
- // user turn ahead of dispatch; those transports retain their own persistence behavior.
719
- await persistUserTurnBeforeDispatch({ message: userMessage, conversationId }, { persistUserTurn: options.persistUserTurn });
720
- // Acceptance commits the question and stub together even if the separate browser PUT fails
721
- // or the tab disappears. Carry the exact message ID/payload, never the rendered prompt.
722
- const base = buildLocalCliContextRef(input, prompt, conversationId);
723
- const contextRef = { ...base, userMessage };
724
- const response = await ports.acceptRun({
725
- ...(input.cancelSignal === undefined ? {} : { signal: input.cancelSignal }),
726
- requestSignal: input.cancelSignal ?? input.signal,
727
- body: { contextRef: JSON.stringify(contextRef), agentId: input.agentId, idempotencyKey: base.assistantMessageId },
728
- messageId: base.assistantMessageId,
729
- ...(conversationId === undefined ? {} : { conversationId }),
730
- }, {});
731
- return finishLocalCliRun(response, handlers, input.signal);
732
- }
733
- function createAssistantTransport(options = {}) {
734
- return {
735
- async startRun(input, handlers) {
736
- // Guard on the newest USER turn, not on the assembled transcript: a history containing only
737
- // assistant messages would still produce a non-empty transcript, and sending that as a
738
- // prompt asks the agent to reply to itself. Shared by both paths below, and reused (rather than
739
- // recomputed) by the Local CLI branch's own resume-capable check further down.
740
- const latestUserPrompt = latestUserPromptFromHistory({ history: input.history });
741
- const userMessage = newestUserMessage({ history: input.history }, {});
742
- if (!latestUserPrompt || userMessage === undefined) {
743
- throw new Error("no user message to send");
744
- }
745
- // Adopt identity before either runtime branch so first-turn decisions survive a reload.
746
- const conversationId = await resolveRunConversationId(input, options.ensureConversationId);
747
- input = { ...input, context: { ...input.context, ...(conversationId ? { conversationId, agentPluginState: readAgentPluginChatState({ conversationId }) } : {}), userPrompt: latestUserPrompt } };
748
- const executionConfig = options.getExecutionConfig?.({}, {});
749
- // Dispatches on MODE alone, not on whether a key is typed in this browser right now
750
- // (2026-08-05). `executionConfig.byok.apiKey` is write-only server-side — it is empty on
751
- // every fresh load even when a credential IS stored — so gating on it here would make BYOK
752
- // mode permanently unable to dispatch for exactly the case the server-side store exists to
753
- // support. `assistant-byok.ts`'s route already resolves the credential correctly either way
754
- // (a locally-typed key wins when present; an empty/omitted one falls back to this admin's own
755
- // stored row), so an empty `byok.apiKey` is a legitimate turn, not a reason to fall through to
756
- // the Local CLI path. A turn with genuinely no usable credential anywhere still fails, just one
757
- // level down — the route's own 400 `"no usable BYOK credential..."` — which is a real,
758
- // actionable answer instead of the mode picker silently refusing to try.
759
- if (executionConfig?.mode === "byok") {
760
- return startByokRun(ports.projectInput({ input }, {}), capturePluginUsage(handlers), executionConfig.byok);
761
- }
762
- // AG-UI canary path (ADR-059) — a host-supplied toggle, independent of `executionConfig.mode`
763
- // (Jini's own closed union, never extended for this). Checked AFTER the byok branch above:
764
- // BYOK's single-request shape never touches the daemon at all, so there is nothing for this
765
- // path (which wraps the daemon specifically) to intercept there — the toggle only ever
766
- // diverts the Local CLI branch below.
767
- if (options.getAgUiEnabled?.({}, {})) {
768
- // `historyForTranscript` here rather than inside `startAgUiRun`: that module importing this
769
- // one would be a cycle, and this is its only caller. Same rule as the BYOK and Local CLI paths.
770
- return ports.agUi.startAgUiRun({ input: ports.projectInput({ input: { ...input, history: historyForTranscript(input.history) } }, {}), handlers: capturePluginUsage(handlers) }, {});
771
- }
772
- return startLocalCliRun({ input, handlers, userMessage, conversationId }, { options });
773
- },
774
- async reattachRun(runId, handlers, options) {
775
- // A BYOK run has no server-side record to reattach to (module doc's path-2 section) — the
776
- // stream lived entirely on the original `fetch()`'s response body, which a reload has already
777
- // discarded. Reporting the run as simply over (an empty `onDone`) is the honest answer: there
778
- // is no way to resume it, and pretending otherwise would hang the pane waiting for events that
779
- // can never arrive.
780
- if (runId.startsWith(BYOK_RUN_ID_PREFIX)) {
781
- handlers.onDone([]);
782
- return undefined;
783
- }
784
- // Same "no server-side record to resume" reasoning as the BYOK branch above — see
785
- // `assistant-transport-ag-ui.ts`'s own doc for why this path has no reattach story yet.
786
- if (ports.agUi.isAgUiRunId({ runId }, {})) {
787
- return ports.agUi.reattachAgUiRun({ handlers }, {});
788
- }
789
- subscribeToRun(runId, handlers, options?.signal);
790
- return undefined;
791
- },
792
- async fetchRunStatus(runId) {
793
- // Same reasoning as `reattachRun` above — no server-side run record exists for a BYOK run id,
794
- // so there is no status to fetch. `null` is this port's existing "unknown/not trackable"
795
- // value (see the daemon branch below's own `!response.ok` case), not a new state.
796
- if (runId.startsWith(BYOK_RUN_ID_PREFIX))
797
- return null;
798
- if (ports.agUi.isAgUiRunId({ runId }, {}))
799
- return ports.agUi.fetchAgUiRunStatus({}, {});
800
- const response = await ports.fetch(`${ports.runsUrl}/${encodeURIComponent(runId)}`, { credentials: "same-origin" });
801
- if (!response.ok)
802
- return null;
803
- const { run } = (await response.json());
804
- return toChatCoreRunStatus(run.state) ?? null;
805
- },
806
- async stopRun(runId) {
807
- // A BYOK run's only cancellation handle is the abort controller `startByokRun` registered for
808
- // this exact id — there is no server-side run to `POST .../cancel` against.
809
- if (runId.startsWith(BYOK_RUN_ID_PREFIX)) {
810
- byokAbortControllers.get(runId)?.abort();
811
- return undefined;
812
- }
813
- if (ports.agUi.isAgUiRunId({ runId }, {})) {
814
- return ports.agUi.stopAgUiRun({ runId }, {});
815
- }
816
- const response = await ports.fetch(`${ports.runsUrl}/${encodeURIComponent(runId)}/cancel`, {
817
- method: "POST",
818
- headers: { "Content-Type": "application/json" },
819
- credentials: "same-origin",
820
- body: JSON.stringify({ runId, messageId: ports.runBinding({ runId }, {})?.messageId }),
821
- });
822
- // 404: the daemon no longer knows this run (it restarted), so nothing is left running to stop.
823
- if (response.status === 404)
824
- return undefined;
825
- // `fetch` resolves on any status: without this a refused cancel (401/403/500) resolved exactly
826
- // like a successful one while the run kept executing. `useRunStream` logs a rejection here.
827
- if (!response.ok)
828
- throw await refusalError({ action: "cancelling agent run failed", response }, {});
829
- return undefined;
830
- },
831
- };
832
- }
126
+ const transport = { ports, byokAbortControllers: new Map() };
833
127
  return {
834
- createAssistantTransport: ({ options = {} }, _optional = {}) => createAssistantTransport(options),
835
- historyForTranscript: ({ history }, _optional = {}) => historyForTranscript(history),
836
- undeliveredUserPrompt: ({ history }, _optional = {}) => undeliveredUserPrompt(history),
837
- buildLocalCliContextRef: ({ input, prompt, resolvedConversationId }, _optional = {}) => buildLocalCliContextRef(input, prompt, resolvedConversationId),
838
- handleByokFrame: ({ frame, ctx }, _optional = {}) => handleByokFrame(frame, ctx),
839
- consumeByokStream: ({ body, ctx }, _optional = {}) => consumeByokStream(body, ctx),
128
+ createAssistantTransport: ({ options = {} }, _optional = {}) => buildChatTransport({ transport, options }),
129
+ historyForTranscript: ({ history }, _optional = {}) => historyForTranscript({ history }),
130
+ undeliveredUserPrompt: ({ history }, _optional = {}) => undeliveredUserPrompt({ history }),
131
+ buildLocalCliContextRef: ({ input, prompt, resolvedConversationId }, _optional = {}) => buildLocalCliContextRef({ transport, input, prompt, resolvedConversationId }),
132
+ handleByokFrame: ({ frame, ctx }, _optional = {}) => handleByokFrame({ transport, frame, ctx }),
133
+ consumeByokStream: ({ body, ctx }, _optional = {}) => consumeByokStream({ transport, body, ctx }),
840
134
  };
841
135
  }
842
136
  //# sourceMappingURL=transport.js.map