@jini-ai/chat 0.7.3-next.1 → 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 (220) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +49 -0
  3. package/dist/core/accepted-input.d.ts +1 -1
  4. package/dist/core/ag-ui/event-projection.d.ts +14 -69
  5. package/dist/core/ag-ui/event-projection.js +58 -133
  6. package/dist/core/ag-ui/event-reduction.d.ts +12 -2
  7. package/dist/core/ag-ui/event-reduction.js +35 -10
  8. package/dist/core/ag-ui/resume.d.ts +110 -0
  9. package/dist/core/ag-ui/resume.js +200 -0
  10. package/dist/core/ag-ui/run-input.d.ts +23 -0
  11. package/dist/core/ag-ui/run-input.js +45 -0
  12. package/dist/core/ag-ui/server.d.ts +69 -0
  13. package/dist/core/ag-ui/server.js +71 -0
  14. package/dist/core/agent-plugin-chat-state.js +13 -11
  15. package/dist/core/assistant-client/ag-ui-approval-relay.d.ts +113 -0
  16. package/dist/core/assistant-client/ag-ui-approval-relay.js +287 -0
  17. package/dist/core/assistant-client/ag-ui-fetch-agent.d.ts +25 -10
  18. package/dist/core/assistant-client/ag-ui-fetch-agent.js +25 -6
  19. package/dist/core/assistant-client/ag-ui-transport.d.ts +86 -3
  20. package/dist/core/assistant-client/ag-ui-transport.js +310 -80
  21. package/dist/core/assistant-client/browser-durable-subscription.d.ts +25 -0
  22. package/dist/core/assistant-client/browser-durable-subscription.js +78 -0
  23. package/dist/core/assistant-client/durable-run-subscription.js +141 -130
  24. package/dist/core/assistant-client/entry.d.ts +2 -1
  25. package/dist/core/assistant-client/entry.js +1 -0
  26. package/dist/core/assistant-client/transport-prompt.d.ts +94 -0
  27. package/dist/core/assistant-client/transport-prompt.js +180 -0
  28. package/dist/core/assistant-client/transport-run.d.ts +49 -0
  29. package/dist/core/assistant-client/transport-run.js +432 -0
  30. package/dist/core/assistant-client/transport-stream.d.ts +73 -0
  31. package/dist/core/assistant-client/transport-stream.js +128 -0
  32. package/dist/core/assistant-client/transport.d.ts +1 -1
  33. package/dist/core/assistant-client/transport.js +129 -835
  34. package/dist/core/assistant-content.d.ts +1 -17
  35. package/dist/core/assistant-content.js +16 -0
  36. package/dist/core/assistant-tool-metadata.d.ts +103 -0
  37. package/dist/core/assistant-tool-metadata.js +56 -0
  38. package/dist/core/checkpoint-interval.d.ts +1 -1
  39. package/dist/core/compact-events.d.ts +1 -1
  40. package/dist/core/durable-projection.d.ts +1 -1
  41. package/dist/core/durable-runs/continuation.d.ts +1 -1
  42. package/dist/core/durable-runs/ledger-contracts.d.ts +4 -1
  43. package/dist/core/durable-runs/ports.d.ts +2 -1
  44. package/dist/core/durable-runs/run-contracts.d.ts +1 -1
  45. package/dist/core/durable-runs/run-finalizer.d.ts +145 -0
  46. package/dist/core/durable-runs/run-finalizer.js +171 -0
  47. package/dist/core/events.d.ts +4 -82
  48. package/dist/core/events.js +2 -1
  49. package/dist/core/index.d.ts +4 -1
  50. package/dist/core/index.js +2 -1
  51. package/dist/core/messages.d.ts +1 -1
  52. package/dist/core/persistence/index.d.ts +1 -1
  53. package/dist/core/persistence/index.js +1 -1
  54. package/dist/core/question-form/normalize.d.ts +9 -3
  55. package/dist/core/question-form/normalize.js +20 -20
  56. package/dist/core/question-form/scan.js +15 -19
  57. package/dist/core/run-activity.d.ts +1 -1
  58. package/dist/core/run-events/entry.d.ts +11 -63
  59. package/dist/core/run-events/entry.js +12 -7
  60. package/dist/core/todos.d.ts +1 -1
  61. package/dist/core/todos.js +8 -0
  62. package/dist/core/tool-call-detail.d.ts +8 -1
  63. package/dist/core/tool-call-detail.js +35 -12
  64. package/dist/core/tool-events.d.ts +1 -1
  65. package/dist/core/tool-output.js +2 -6
  66. package/dist/core/tools.d.ts +2 -1
  67. package/dist/core/transport.d.ts +1 -1
  68. package/dist/core/turn-usage.d.ts +1 -1
  69. package/dist/core/util/parser.js +70 -69
  70. package/dist/embed-widget/browser/embed-send-bridge.d.ts +44 -0
  71. package/dist/embed-widget/browser/embed-send-bridge.js +60 -0
  72. package/dist/embed-widget/browser/frontend-invocation-handler.d.ts +39 -0
  73. package/dist/embed-widget/browser/frontend-invocation-handler.js +151 -0
  74. package/dist/embed-widget/browser/frontend-session-bridge.d.ts +28 -0
  75. package/dist/embed-widget/browser/frontend-session-bridge.js +201 -257
  76. package/dist/embed-widget/browser/lazy-loader.js +16 -12
  77. package/dist/embed-widget/browser/session-store.d.ts +19 -1
  78. package/dist/embed-widget/browser/session-store.js +48 -17
  79. package/dist/embed-widget/transports/fetch-sse.d.ts +1 -1
  80. package/dist/embed-widget/vanilla/index.js +131 -67
  81. package/dist/embed-widget/vanilla/state.js +53 -38
  82. package/dist/react/admin-execution/ai-agent-presentation.d.ts +35 -0
  83. package/dist/react/admin-execution/ai-agent-presentation.js +39 -0
  84. package/dist/react/admin-execution/hooks/use-ai-agent-presentation.hooks.d.ts +22 -0
  85. package/dist/react/admin-execution/hooks/use-ai-agent-presentation.hooks.js +25 -0
  86. package/dist/react/chat-cleanup/ChatCleanupPanel.d.ts +15 -0
  87. package/dist/react/chat-cleanup/ChatCleanupPanel.js +17 -0
  88. package/dist/react/chat-cleanup/chat-cleanup.hooks.d.ts +168 -0
  89. package/dist/react/chat-cleanup/chat-cleanup.hooks.js +83 -0
  90. package/dist/react/components/ChatCleanupDialog.d.ts +38 -0
  91. package/dist/react/components/ChatCleanupDialog.js +12 -0
  92. package/dist/react/components/ConversationList.d.ts +14 -5
  93. package/dist/react/components/ConversationList.hooks.d.ts +1 -0
  94. package/dist/react/components/ConversationList.hooks.js +4 -2
  95. package/dist/react/components/ConversationList.js +41 -5
  96. package/dist/react/components/Icon.d.ts +1 -1
  97. package/dist/react/components/Icon.js +2 -0
  98. package/dist/react/components/Markdown.js +6 -6
  99. package/dist/react/components/MarkdownLink.d.ts +25 -0
  100. package/dist/react/components/MarkdownLink.js +17 -0
  101. package/dist/react/components/MessageList.hooks.d.ts +4 -0
  102. package/dist/react/components/MessageList.hooks.js +16 -2
  103. package/dist/react/components/MessageList.js +14 -7
  104. package/dist/react/components/MessageList.rules.d.ts +5 -0
  105. package/dist/react/components/MessageList.rules.js +4 -0
  106. package/dist/react/components/RoutedA2uiSurfaceCard.d.ts +80 -0
  107. package/dist/react/components/RoutedA2uiSurfaceCard.js +15 -0
  108. package/dist/react/components/ToolCard.d.ts +4 -2
  109. package/dist/react/components/ToolCard.js +46 -4
  110. package/dist/react/components/ToolCard.rules.d.ts +5 -2
  111. package/dist/react/components/ToolCard.rules.js +12 -5
  112. package/dist/react/components/mcp-ui-question-input.d.ts +1 -1
  113. package/dist/react/components/mcp-ui-surface-state.d.ts +3 -1
  114. package/dist/react/components/mcp-ui-surface-state.js +2 -2
  115. package/dist/react/components/own-link.d.ts +26 -0
  116. package/dist/react/components/own-link.js +36 -0
  117. package/dist/react/features/bridged-chat/create-staged-attachment-uploader.d.ts +7 -0
  118. package/dist/react/features/bridged-chat/create-staged-attachment-uploader.js +26 -0
  119. package/dist/react/features/bridged-chat/hooks/useBridgedChatTransport.hooks.d.ts +12 -0
  120. package/dist/react/features/bridged-chat/hooks/useBridgedChatTransport.hooks.js +60 -0
  121. package/dist/react/features/bridged-chat/index.d.ts +8 -0
  122. package/dist/react/features/bridged-chat/index.js +7 -0
  123. package/dist/react/features/bridged-chat/types.d.ts +49 -0
  124. package/dist/react/features/bridged-chat/types.js +2 -0
  125. package/dist/react/features/chat-pane/components/RuntimeDropUp.js +1 -1
  126. package/dist/react/features/chat-pane/create-daemon-attachment-uploader.d.ts +6 -0
  127. package/dist/react/features/chat-pane/create-daemon-attachment-uploader.js +101 -59
  128. package/dist/react/features/chat-pane/hooks/useChatPaneNewTabLinks.hooks.d.ts +3 -0
  129. package/dist/react/features/chat-pane/hooks/useChatPaneNewTabLinks.hooks.js +26 -16
  130. package/dist/react/features/chat-pane/model-options.d.ts +3 -1
  131. package/dist/react/features/chat-pane/model-options.js +3 -3
  132. package/dist/react/features/chat-pane/rules.js +4 -3
  133. package/dist/react/features/chat-pane/styles.d.ts +1 -1
  134. package/dist/react/features/chat-pane/styles.js +43 -11
  135. package/dist/react/features/conversation-chat-pane/components/ConversationChatPane.d.ts +10 -0
  136. package/dist/react/features/conversation-chat-pane/components/ConversationChatPane.js +19 -0
  137. package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneChat.d.ts +12 -0
  138. package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneChat.js +21 -0
  139. package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneHeader.d.ts +13 -0
  140. package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneHeader.js +9 -0
  141. package/dist/react/features/conversation-chat-pane/components/ConversationDeleteConfirm.d.ts +12 -0
  142. package/dist/react/features/conversation-chat-pane/components/ConversationDeleteConfirm.js +12 -0
  143. package/dist/react/features/conversation-chat-pane/hooks/useConversationChatPane.hooks.d.ts +7 -0
  144. package/dist/react/features/conversation-chat-pane/hooks/useConversationChatPane.hooks.js +43 -0
  145. package/dist/react/features/conversation-chat-pane/index.d.ts +9 -0
  146. package/dist/react/features/conversation-chat-pane/index.js +8 -0
  147. package/dist/react/features/conversation-chat-pane/rules.d.ts +25 -0
  148. package/dist/react/features/conversation-chat-pane/rules.js +29 -0
  149. package/dist/react/features/conversation-chat-pane/types.d.ts +139 -0
  150. package/dist/react/features/conversation-chat-pane/types.js +2 -0
  151. package/dist/react/features/conversations/conversation-controller.d.ts +16 -0
  152. package/dist/react/features/conversations/conversation-controller.js +280 -0
  153. package/dist/react/features/conversations/hooks/useConversationDeleteConfirmation.hooks.d.ts +15 -0
  154. package/dist/react/features/conversations/hooks/useConversationDeleteConfirmation.hooks.js +33 -0
  155. package/dist/react/features/conversations/hooks/useStoredConversations.hooks.d.ts +16 -0
  156. package/dist/react/features/conversations/hooks/useStoredConversations.hooks.js +36 -0
  157. package/dist/react/features/conversations/index.d.ts +9 -0
  158. package/dist/react/features/conversations/index.js +8 -0
  159. package/dist/react/features/conversations/types.d.ts +120 -0
  160. package/dist/react/features/conversations/types.js +2 -0
  161. package/dist/react/features/voice-input/space-hold-rules.d.ts +65 -0
  162. package/dist/react/features/voice-input/space-hold-rules.js +48 -0
  163. package/dist/react/hooks/testing/fake-transport.d.ts +1 -1
  164. package/dist/react/hooks/useAnsweredCards.d.ts +2 -1
  165. package/dist/react/hooks/useConversation.js +5 -2
  166. package/dist/react/hooks/useExtEventGroups.d.ts +1 -1
  167. package/dist/react/hooks/useRunActivity.d.ts +2 -1
  168. package/dist/react/hooks/useRunStream.d.ts +1 -1
  169. package/dist/react/hooks/useRunStream.js +1 -1
  170. package/dist/react/hooks/useSurfaceRecovery.js +3 -1
  171. package/dist/react/hooks/useToolTimeline.d.ts +2 -1
  172. package/dist/react/index.d.ts +5 -2
  173. package/dist/react/index.js +4 -2
  174. package/dist/react/message-blocks.d.ts +1 -48
  175. package/dist/react/message-blocks.js +47 -0
  176. package/dist/react/styles/chat-settings.css +14 -14
  177. package/dist/server/chat-cleanup-routes.d.ts +56 -0
  178. package/dist/server/chat-cleanup-routes.js +56 -0
  179. package/dist/server/durable-runs/recover.js +193 -171
  180. package/dist/server/run-finalizer/entry.js +133 -110
  181. package/dist/store/legacy/sqlite/conversations.js +29 -17
  182. package/dist/store/pglite/index.d.ts +1 -0
  183. package/dist/store/pglite/index.js +1 -0
  184. package/dist/store/ports.d.ts +12 -0
  185. package/dist/store/postgres/index.d.ts +1 -0
  186. package/dist/store/postgres/index.js +1 -0
  187. package/dist/store/runtime/attempt-base-retention.d.ts +57 -0
  188. package/dist/store/runtime/attempt-base-retention.js +103 -0
  189. package/dist/store/runtime/chat-maintenance.d.ts +16 -0
  190. package/dist/store/runtime/chat-maintenance.js +19 -0
  191. package/dist/store/runtime/chat-principal.d.ts +63 -0
  192. package/dist/store/runtime/chat-principal.js +39 -0
  193. package/dist/store/runtime/checkpoint-delta.d.ts +1 -1
  194. package/dist/store/runtime/durable-run-queries.d.ts +124 -0
  195. package/dist/store/runtime/durable-run-queries.js +122 -0
  196. package/dist/store/runtime/durable-run-store.d.ts +1 -1
  197. package/dist/store/runtime/durable-run-store.js +291 -343
  198. package/dist/store/runtime/entry.d.ts +3 -0
  199. package/dist/store/runtime/entry.js +3 -0
  200. package/dist/store/runtime/events-json.d.ts +1 -1
  201. package/dist/store/runtime/lazy-run-ledger.d.ts +19 -0
  202. package/dist/store/runtime/lazy-run-ledger.js +28 -0
  203. package/dist/store/runtime/run-ledger.d.ts +4 -1
  204. package/dist/store/runtime/run-ledger.js +256 -204
  205. package/dist/store/sql/bulk-deletion.d.ts +36 -0
  206. package/dist/store/sql/bulk-deletion.js +103 -0
  207. package/dist/store/sql/store-queries.d.ts +170 -0
  208. package/dist/store/sql/store-queries.js +212 -0
  209. package/dist/store/sql/store-rows.d.ts +106 -0
  210. package/dist/store/sql/store-rows.js +116 -0
  211. package/dist/store/sql/store-writes.d.ts +46 -0
  212. package/dist/store/sql/store-writes.js +161 -0
  213. package/dist/store/sql/store.d.ts +3 -16
  214. package/dist/store/sql/store.js +58 -428
  215. package/dist/store/sql/tables.d.ts +1 -0
  216. package/dist/store/sqlite/index.d.ts +1 -0
  217. package/dist/store/sqlite/index.js +1 -0
  218. package/dist/store/sqlite/schema.d.ts +1 -1
  219. package/dist/store/sqlite/schema.js +5 -1
  220. package/package.json +174 -23
@@ -36,8 +36,7 @@ import { decodeSseFrames } from '@jini-ai/core/primitives';
36
36
  * belongs in a run request. Park/failure closes the transport; hosts explicitly rebind after wake.
37
37
  */
38
38
  import { CHAT_CAPABILITIES } from '../../core/index.js';
39
- /** How many settled invocation ids to remember for replay suppression. */
40
- const EXECUTED_MEMORY = 256;
39
+ import { createInvocationHandler } from './frontend-invocation-handler.js';
41
40
  /** Ids this surface can actually serve, given what the host wired up. */
42
41
  function claimedCapabilities(options) {
43
42
  if (options.capabilityIds)
@@ -52,9 +51,6 @@ function claimedCapabilities(options) {
52
51
  claims.push(...Object.keys(options.executors ?? {}));
53
52
  return claims;
54
53
  }
55
- function errorMessage(error) {
56
- return error instanceof Error ? error.message : String(error);
57
- }
58
54
  /** Parses a frame's data into an object, or says why it is not one. */
59
55
  function parseFrameObject(data) {
60
56
  let parsed;
@@ -110,21 +106,121 @@ function readFrame(data) {
110
106
  return { kind: 'ignored' };
111
107
  }
112
108
  }
113
- /**
114
- * Opens the surface's connection and starts routing invocations.
115
- *
116
- * @param options - What this page can serve and where the daemon is.
117
- * @returns The pane's bridge, the attach result, and a teardown.
118
- */
119
- export function createFrontendSessionBridge({ baseUrl: base, openStream, request, fetch, endpointPrefix = '/api/frontend-sessions', headers }, options = {}) {
120
- const capabilities = claimedCapabilities(options);
121
- // 0.6.x compatibility: fetch was optional for published hosts;
122
- // remove when fetch injection becomes required in the next minor.
123
- // The only caller (`respond`) never passes its own signal, so the deadline is the whole signal.
124
- const send = request ?? (({ url, init, timeoutMs }) => (fetch ?? globalThis.fetch)(url, { ...init, signal: AbortSignal.timeout(timeoutMs) }));
125
- let sessionId;
126
- /** Replaced on every reattach; a promise resolved once could never carry this. */
127
- let currentBindToken;
109
+ function abortPending(pending) {
110
+ for (const controller of pending.values()) {
111
+ controller.abort();
112
+ }
113
+ pending.clear();
114
+ }
115
+ /** Invalidate before any reopen; queued and running page work cannot cross attachments.
116
+ * O(pending invocations + attachment waiters), with no retained settled waiters. */
117
+ function invalidateSession({ core, error }) {
118
+ abortPending(core.pending);
119
+ core.pageQueue = Promise.resolve();
120
+ // The daemon deletes a session's bind token the instant that connection drops, so by the time
121
+ // this fires the token in hand is already gone from the registry. Holding it until the next
122
+ // `attached` frame leaves a window where `bindToken()` hands back something dead, and a run
123
+ // started in that window fails to bind — reported to the agent only as "no frontend is bound
124
+ // to this run", with the real reason (a reconnect it never saw) nowhere in view.
125
+ // Reporting no token is the honest answer for a surface that is, right now, not attached.
126
+ core.bindToken = undefined;
127
+ core.sessionId = undefined;
128
+ for (const waiter of core.attachments)
129
+ waiter.reject(error);
130
+ core.attachments.clear();
131
+ }
132
+ /** Adopt a fresh attachment: drop work from the previous one, then release every waiter. */
133
+ function adoptAttachment({ frame, core, resolveReady }, _optional = {}) {
134
+ abortPending(core.pending);
135
+ core.sessionId = frame.sessionId;
136
+ core.bindToken = frame.bindToken;
137
+ // A no-op after the first attach — which is exactly why `core.bindToken` exists.
138
+ resolveReady({ sessionId: core.sessionId, bindToken: core.bindToken });
139
+ for (const waiter of core.attachments)
140
+ waiter.resolve({ sessionId: core.sessionId, bindToken: core.bindToken });
141
+ core.attachments.clear();
142
+ }
143
+ /** One waiter on the next attachment; cancelling rejects only this caller's wait. */
144
+ function awaitAttachment({ attachments, signal, connectIfIdle }) {
145
+ return new Promise((resolve, reject) => {
146
+ const cleanup = () => { attachments.delete(waiter); signal?.removeEventListener('abort', abort); };
147
+ const waiter = {
148
+ resolve: (value) => { cleanup(); resolve(value); },
149
+ reject: (error) => { cleanup(); reject(error); },
150
+ };
151
+ const abort = () => waiter.reject(signal?.reason);
152
+ attachments.add(waiter);
153
+ signal?.addEventListener('abort', abort, { once: true });
154
+ connectIfIdle();
155
+ });
156
+ }
157
+ function applyFrame({ frame, pending, actions }) {
158
+ switch (frame.kind) {
159
+ case 'cancelled':
160
+ pending.get(frame.invocationId)?.abort();
161
+ return;
162
+ case 'attached':
163
+ actions.attach(frame);
164
+ return;
165
+ case 'refused':
166
+ actions.refuse(new Error(frame.message));
167
+ return;
168
+ case 'malformed':
169
+ actions.malformed(frame.error);
170
+ return;
171
+ case 'invocation':
172
+ actions.invocation(frame.action);
173
+ return;
174
+ case 'ignored':
175
+ return;
176
+ }
177
+ }
178
+ /** Wires one stream's events to the bridge, ignoring any stream that is no longer the current one. */
179
+ function watchStream({ current, isCurrent, handlers }) {
180
+ current.addEventListener('message', (event) => {
181
+ if (isCurrent())
182
+ handlers.message(event.data);
183
+ });
184
+ current.addEventListener('parked', () => {
185
+ if (isCurrent())
186
+ handlers.parked();
187
+ });
188
+ // Intentional visibility pauses keep their transport owner, which reopens on visibility/activity.
189
+ current.addEventListener('suspended', () => {
190
+ if (isCurrent())
191
+ handlers.suspended();
192
+ });
193
+ current.addEventListener('error', (event) => {
194
+ if (isCurrent())
195
+ handlers.failed(event);
196
+ });
197
+ }
198
+ /** Answers invocations over the HTTP responses endpoint, reading the bind token at send time. */
199
+ function createResponder({ core, send, base, endpointPrefix, headers, maxResponseBytes }) {
200
+ async function respond(invocationId, body) {
201
+ if (core.sessionId === undefined)
202
+ throw new Error('the surface is not attached yet');
203
+ const wire = boundedFrontendResponse({ invocationId, body, maxBytes: maxResponseBytes });
204
+ const response = await send({
205
+ url: `${base}${endpointPrefix}/${encodeURIComponent(core.sessionId)}/responses`,
206
+ init: { method: 'POST', headers: { 'content-type': 'application/json', ...headers?.(), ...(headers ? { 'x-frontend-bind-token': core.bindToken ?? '' } : {}) }, body: wire.payload },
207
+ timeoutMs: 15_000,
208
+ });
209
+ await assertFrontendResponse({ response, invocationId, body, scoped: Boolean(headers), refused: wire.refused });
210
+ }
211
+ return {
212
+ respond,
213
+ respondSuccess: (invocationId, output) => respond(invocationId, { ok: true, output }),
214
+ respondError: (invocationId, message) => respond(invocationId, { ok: false, message }),
215
+ };
216
+ }
217
+ /** 0.6.x compatibility: fetch was optional for published hosts;
218
+ * remove when fetch injection becomes required in the next minor.
219
+ * The only caller (`respond`) never passes its own signal, so the deadline is the whole signal. */
220
+ function resolveSend({ request, fetch }) {
221
+ return request ?? (({ url, init, timeoutMs }) => (fetch ?? globalThis.fetch)(url, { ...init, signal: AbortSignal.timeout(timeoutMs) }));
222
+ }
223
+ function createReadySignal() {
128
224
  // Definite assignment rather than no-op placeholders: a Promise executor runs synchronously, so
129
225
  // both are set before this line finishes, and placeholders would only add two functions that
130
226
  // can never be called.
@@ -134,248 +230,88 @@ export function createFrontendSessionBridge({ baseUrl: base, openStream, request
134
230
  resolveReady = resolve;
135
231
  rejectReady = reject;
136
232
  });
137
- /** Chat-pane listeners. The pane registers exactly one; a second host could register another. */
138
- const chatListeners = new Set();
139
- /** Invocation ids already run here, so a stream reconnect cannot double-click a button. */
140
- const executed = new Set();
141
- const pending = new Map();
142
- const attachments = new Set();
143
- let source;
144
- let closed = false;
145
- // A page driver owns one live screen. Serialize its observations, effect and acknowledgement;
146
- // otherwise a second invocation could overwrite the first one's host-bound navigation plan.
147
- let pageQueue = Promise.resolve();
148
- const abortPending = () => {
149
- for (const controller of pending.values()) {
150
- controller.abort();
151
- }
152
- pending.clear();
233
+ return { ready, resolveReady, rejectReady };
234
+ }
235
+ function createBridgeAccess({ chatListeners, responder }) {
236
+ return {
237
+ subscribe(onAction) {
238
+ chatListeners.add(onAction);
239
+ // Removes this listener only. The connection outlives any one pane — see the module doc.
240
+ return () => chatListeners.delete(onAction);
241
+ },
242
+ respondSuccess: responder.respondSuccess,
243
+ respondError: responder.respondError,
153
244
  };
154
- const query = capabilities.map((id) => `capability=${encodeURIComponent(id)}`).join('&');
155
- /** Invalidate before any reopen; queued and running page work cannot cross attachments.
156
- * O(pending invocations + attachment waiters), with no retained settled waiters. */
157
- function invalidate({ error }) {
158
- abortPending();
159
- pageQueue = Promise.resolve();
160
- // The daemon deletes a session's bind token the instant that connection drops, so by the time
161
- // this fires the token in hand is already gone from the registry. Holding it until the next
162
- // `attached` frame leaves a window where `bindToken()` hands back something dead, and a run
163
- // started in that window fails to bind — reported to the agent only as "no frontend is bound
164
- // to this run", with the real reason (a reconnect it never saw) nowhere in view.
165
- // Reporting no token is the honest answer for a surface that is, right now, not attached.
166
- currentBindToken = undefined;
167
- sessionId = undefined;
168
- for (const waiter of attachments)
169
- waiter.reject(error);
170
- attachments.clear();
171
- }
245
+ }
246
+ function createFrontendStreamConnection({ openStream, base, endpointPrefix, query, headers, core, resolveReady, rejectReady, options, handleInvocation, }) {
247
+ let source;
172
248
  function disconnect({ error }) {
173
249
  const previous = source;
174
250
  source = undefined;
175
- invalidate({ error });
251
+ invalidateSession({ core, error });
176
252
  previous?.close();
177
253
  }
178
- async function respond(invocationId, body) {
179
- if (sessionId === undefined)
180
- throw new Error('the surface is not attached yet');
181
- const wire = boundedFrontendResponse({ invocationId, body, maxBytes: options.maxResponseBytes });
182
- const response = await send({
183
- url: `${base}${endpointPrefix}/${encodeURIComponent(sessionId)}/responses`,
184
- init: { method: 'POST', headers: { 'content-type': 'application/json', ...headers?.(), ...(headers ? { 'x-frontend-bind-token': currentBindToken ?? '' } : {}) }, body: wire.payload },
185
- timeoutMs: 15_000,
186
- });
187
- await assertFrontendResponse({ response, invocationId, body, scoped: Boolean(headers), refused: wire.refused });
188
- }
189
- const respondSuccess = (invocationId, output) => respond(invocationId, { ok: true, output });
190
- const respondError = (invocationId, message) => respond(invocationId, { ok: false, message });
191
- /** Freeze once, ask on the app's existing human-only channel, then use the same page executor.
192
- * The server pauses its execution deadline only after acknowledging the bounded human wait. */
193
- async function servePage(action, signal) {
194
- const input = options.preparePageInput ? options.preparePageInput({ action }) : structuredClone(action.input);
195
- const args = { capabilityId: action.capabilityId, input };
196
- if (options.pageApproval && !options.pageApproval.isDirect(args)) {
197
- await respond(action.invocationId, { phase: 'approval-pending' });
198
- signal.throwIfAborted();
199
- const answer = await options.pageApproval.request({ ...args, input: structuredClone(input), signal });
200
- signal.throwIfAborted();
201
- // Report the decision before effects, including decline/expiry; the server audits it.
202
- await respond(action.invocationId, { phase: 'execution-started', decision: answer.confirmed ? 'approved' : answer.reason });
203
- if (!answer.confirmed)
204
- return { executed: false, reason: answer.reason };
205
- }
206
- if (signal.aborted)
207
- return { executed: false, reason: 'abandoned' };
208
- return options.page.execute(args, { signal });
209
- }
210
- /** Runs one non-chat invocation here and answers it. Chat ones go to the pane instead. */
211
- async function serveLocally(action, controller) {
212
- let output;
213
- try {
214
- controller.signal.throwIfAborted();
215
- if (options.page !== undefined && action.capabilityId.startsWith('page.')) {
216
- output = await servePage(action, controller.signal);
217
- }
218
- else {
219
- const entry = Object.entries(options.executors ?? {})
220
- .find(([prefix]) => action.capabilityId.startsWith(prefix));
221
- if (entry === undefined)
222
- throw new Error(`nothing on this page serves "${action.capabilityId}"`);
223
- output = await entry[1](action.capabilityId, action.input);
224
- }
225
- }
226
- catch (error) {
227
- pending.delete(action.invocationId);
228
- if (controller.signal.aborted)
229
- return;
230
- await respondError(action.invocationId, errorMessage(error)).catch(options.onError ?? (() => undefined));
231
- return;
232
- }
233
- await acknowledge({ action, output, signal: controller.signal });
234
- pending.delete(action.invocationId);
235
- }
236
- async function acknowledge({ action, output, signal }) {
237
- try {
238
- signal.throwIfAborted();
239
- const projected = await options.onBeforeResponse?.({ action, output });
240
- signal.throwIfAborted();
241
- const acceptedOutput = projected ?? output;
242
- await respondSuccess(action.invocationId, acceptedOutput);
243
- signal.throwIfAborted();
244
- await options.onAfterResponse?.({ action, output: acceptedOutput });
245
- }
246
- catch (error) {
247
- options.onError?.(error);
248
- }
249
- }
250
- function remember(invocationId) {
251
- executed.add(invocationId);
252
- if (executed.size > EXECUTED_MEMORY) {
253
- const oldest = executed.values().next().value;
254
- if (oldest !== undefined)
255
- executed.delete(oldest);
256
- }
257
- }
258
- /** Runs one well-formed invocation: replay check, announcement, then pane or local serving. */
259
- function handleInvocation(action) {
260
- // A redelivery after a dropped answer must not re-run the side effect.
261
- if (executed.has(action.invocationId)) {
262
- void respondError(action.invocationId, 'already executed on this surface').catch(() => undefined);
263
- return;
264
- }
265
- if (options.capabilityIds && !options.capabilityIds.includes(action.capabilityId)) {
266
- void respondError(action.invocationId, 'Capability unavailable').catch(() => undefined);
267
- return;
268
- }
269
- remember(action.invocationId);
270
- options.onInvocation?.(action);
271
- if (action.capabilityId.startsWith('chat.')) {
272
- for (const listener of chatListeners)
273
- listener(action);
274
- return;
275
- }
276
- const controller = new AbortController();
277
- pending.set(action.invocationId, controller);
278
- if (action.capabilityId.startsWith('page.')) {
279
- pageQueue = pageQueue.then(() => serveLocally(action, controller)).catch(error => options.onError?.(error));
280
- }
281
- else
282
- void serveLocally(action, controller);
283
- }
284
- /** Adopt a fresh attachment: drop work from the previous one, then release every waiter. */
285
- function attach({ frame }, _optional = {}) {
286
- abortPending();
287
- sessionId = frame.sessionId;
288
- currentBindToken = frame.bindToken;
289
- // A no-op after the first attach — which is exactly why `currentBindToken` exists.
290
- resolveReady({ sessionId, bindToken: currentBindToken });
291
- for (const waiter of attachments)
292
- waiter.resolve({ sessionId, bindToken: currentBindToken });
293
- attachments.clear();
294
- }
254
+ const actions = {
255
+ attach: (frame) => adoptAttachment({ frame, core, resolveReady }),
256
+ refuse: (error) => { rejectReady(error); disconnect({ error }); },
257
+ malformed: (error) => options.onError?.(error),
258
+ invocation: handleInvocation,
259
+ };
295
260
  function connect() {
296
261
  const current = openStream({ url: `${base}${endpointPrefix}/stream?${query}`, ...(headers ? { headers: headers() } : {}) });
297
262
  source = current;
298
- current.addEventListener('message', (event) => {
299
- if (source !== current)
300
- return;
301
- const frame = readFrame(event.data);
302
- switch (frame.kind) {
303
- case 'cancelled':
304
- pending.get(frame.invocationId)?.abort();
305
- return;
306
- case 'attached':
307
- attach({ frame });
308
- return;
309
- case 'refused': {
310
- const error = new Error(frame.message);
311
- rejectReady(error);
312
- disconnect({ error });
313
- return;
314
- }
315
- case 'malformed':
316
- options.onError?.(frame.error);
317
- return;
318
- case 'invocation':
319
- handleInvocation(frame.action);
320
- return;
321
- case 'ignored':
322
- return;
323
- }
324
- });
325
- current.addEventListener('parked', () => {
326
- if (source === current)
327
- disconnect({ error: new Error('the surface is parked') });
328
- });
329
- // Intentional visibility pauses keep their transport owner, which reopens on visibility/activity.
330
- current.addEventListener('suspended', () => {
331
- if (source === current)
332
- invalidate({ error: new Error('the surface is suspended') });
333
- });
334
- current.addEventListener('error', (event) => {
335
- if (source !== current)
336
- return;
337
- disconnect({ error: new Error('the frontend stream failed') });
338
- options.onError?.(event);
339
- });
263
+ watchStream({ current, isCurrent: () => source === current, handlers: {
264
+ message: (data) => applyFrame({ frame: readFrame(data), pending: core.pending, actions }),
265
+ parked: () => disconnect({ error: new Error('the surface is parked') }),
266
+ suspended: () => invalidateSession({ core, error: new Error('the surface is suspended') }),
267
+ failed: (event) => { disconnect({ error: new Error('the frontend stream failed') }); options.onError?.(event); },
268
+ } });
340
269
  }
270
+ return { connect, disconnect, isIdle: () => !source };
271
+ }
272
+ /**
273
+ * Opens the surface's connection and starts routing invocations.
274
+ *
275
+ * @param options - What this page can serve and where the daemon is.
276
+ * @returns The pane's bridge, the attach result, and a teardown.
277
+ */
278
+ export function createFrontendSessionBridge({ baseUrl: base, openStream, request, fetch, endpointPrefix = '/api/frontend-sessions', headers }, options = {}) {
279
+ const query = claimedCapabilities(options).map((id) => `capability=${encodeURIComponent(id)}`).join('&');
280
+ const { ready, resolveReady, rejectReady } = createReadySignal();
281
+ const core = { sessionId: undefined, bindToken: undefined, pageQueue: Promise.resolve(), pending: new Map(), attachments: new Set() };
282
+ const responder = createResponder({ core, send: resolveSend({ request, fetch }), base, endpointPrefix, headers, maxResponseBytes: options.maxResponseBytes });
283
+ /** Chat-pane listeners. The pane registers exactly one; a second host could register another. */
284
+ const chatListeners = new Set();
285
+ const { handleInvocation, acceptRunInvocation } = createInvocationHandler({ deps: {
286
+ options, responder, pending: core.pending, chatListeners,
287
+ enqueuePage: (work) => { core.pageQueue = core.pageQueue.then(work).catch(error => options.onError?.(error)); },
288
+ } });
289
+ const { connect, disconnect, isIdle } = createFrontendStreamConnection({
290
+ openStream, base, endpointPrefix, query, headers, core, resolveReady, rejectReady, options, handleInvocation,
291
+ });
292
+ let closed = false;
341
293
  connect();
342
- const bridgeAccess = {
343
- subscribe(onAction) {
344
- chatListeners.add(onAction);
345
- // Removes this listener only. The connection outlives any one pane — see the module doc.
346
- return () => chatListeners.delete(onAction);
347
- },
348
- respondSuccess,
349
- respondError,
350
- };
351
294
  return {
352
- bridgeAccess,
295
+ bridgeAccess: createBridgeAccess({ chatListeners, responder }),
353
296
  ready,
354
- bindToken: () => currentBindToken,
297
+ bindToken: () => core.bindToken,
298
+ acceptRunInvocation,
355
299
  async rebind({ signal } = {}, _optional = {}) {
356
300
  signal?.throwIfAborted();
357
301
  if (closed)
358
302
  throw new Error('the frontend bridge is closed');
359
- if (sessionId !== undefined && currentBindToken !== undefined)
360
- return { sessionId, bindToken: currentBindToken };
361
- return new Promise((resolve, reject) => {
362
- const cleanup = () => { attachments.delete(waiter); signal?.removeEventListener('abort', abort); };
363
- const waiter = {
364
- resolve: (value) => { cleanup(); resolve(value); },
365
- reject: (error) => { cleanup(); reject(error); },
366
- };
367
- const abort = () => waiter.reject(signal?.reason);
368
- attachments.add(waiter);
369
- signal?.addEventListener('abort', abort, { once: true });
370
- if (!source) {
371
- try {
372
- connect();
373
- }
374
- catch (error) {
375
- disconnect({ error });
303
+ if (core.sessionId !== undefined && core.bindToken !== undefined)
304
+ return { sessionId: core.sessionId, bindToken: core.bindToken };
305
+ return awaitAttachment({ attachments: core.attachments, signal, connectIfIdle: () => {
306
+ if (isIdle()) {
307
+ try {
308
+ connect();
309
+ }
310
+ catch (error) {
311
+ disconnect({ error });
312
+ }
376
313
  }
377
- }
378
- });
314
+ } });
379
315
  },
380
316
  close() {
381
317
  closed = true;
@@ -398,19 +334,10 @@ export function openFetchFrontendStream({ url, headers }, { fetch: send = global
398
334
  let retry;
399
335
  let delay = reconnectMs;
400
336
  async function connect() {
401
- let retryable = true;
402
- try {
403
- const response = await send(url, { credentials: 'same-origin', mode: 'same-origin', redirect: 'error', headers: headers(), signal: abort.signal });
404
- retryable = ![401, 403, 404, 429].includes(response.status);
405
- if (!response.ok || !response.body)
406
- throw new Error('Frontend stream unavailable');
407
- for await (const frame of decodeSseFrames({ source: streamChunks(response.body) }, { maxBufferChars: 128_000 })) {
408
- delay = reconnectMs; // A delivered event proves the connection recovered.
409
- if (!abort.signal.aborted)
410
- events.dispatchEvent(new MessageEvent(frame.event === 'parked' ? 'parked' : 'message', { data: frame.data }));
411
- }
412
- }
413
- catch { /* The stream error has one value-free notification below. */ }
337
+ const { retryable } = await attemptFrontendStream({
338
+ send, url, headers, signal: abort.signal, events,
339
+ onDelivered: () => { delay = reconnectMs; }, // A delivered event proves the connection recovered.
340
+ });
414
341
  if (abort.signal.aborted)
415
342
  return;
416
343
  events.dispatchEvent(new Event('error'));
@@ -423,6 +350,23 @@ export function openFetchFrontendStream({ url, headers }, { fetch: send = global
423
350
  return { addEventListener: events.addEventListener.bind(events),
424
351
  close() { abort.abort(); clearTimeout(retry); } };
425
352
  }
353
+ /** One fetch-and-read pass over the stream; says whether its failure, if any, is worth retrying. */
354
+ async function attemptFrontendStream({ send, url, headers, signal, events, onDelivered }) {
355
+ let retryable = true;
356
+ try {
357
+ const response = await send(url, { credentials: 'same-origin', mode: 'same-origin', redirect: 'error', headers: headers(), signal });
358
+ retryable = ![401, 403, 404, 429].includes(response.status);
359
+ if (!response.ok || !response.body)
360
+ throw new Error('Frontend stream unavailable');
361
+ for await (const frame of decodeSseFrames({ source: streamChunks(response.body) }, { maxBufferChars: 128_000 })) {
362
+ onDelivered();
363
+ if (!signal.aborted)
364
+ events.dispatchEvent(new MessageEvent(frame.event === 'parked' ? 'parked' : 'message', { data: frame.data }));
365
+ }
366
+ }
367
+ catch { /* The stream error has one value-free notification below. */ }
368
+ return { retryable };
369
+ }
426
370
  async function* streamChunks(body) {
427
371
  const reader = body.getReader();
428
372
  try {
@@ -1,20 +1,12 @@
1
1
  const ARIA_LABEL = 'aria-label';
2
2
  export { CHAT_BUBBLE_STYLE } from '../../contracts/chat-bubble-style.js';
3
- /**
4
- * Activates a host-rendered button without importing chat, React, icons or storage.
5
- * One in-flight load serves repeated activation; failures remain retryable. Native button
6
- * keyboard activation also emits click; preventDefault avoids a second toggle after keydown.
7
- */
8
- export function installLazyChatLoader(args, _options = {}) {
3
+ function createLazyChatActivation({ args, initialContent, label, isDisposed }) {
9
4
  let pending = null;
10
5
  let ready = false;
11
- let disposed = false;
12
6
  let shouldOpen = false;
13
7
  let shouldFocus = false;
14
- const initialContent = args.button.innerHTML;
15
- const label = args.button.getAttribute(ARIA_LABEL) ?? '';
16
8
  const activate = async ({ open = true, focus = open } = {}, _options = {}) => {
17
- if (disposed)
9
+ if (isDisposed())
18
10
  return undefined;
19
11
  if (!pending) {
20
12
  shouldOpen = false;
@@ -34,7 +26,7 @@ export function installLazyChatLoader(args, _options = {}) {
34
26
  return args.load({});
35
27
  return undefined;
36
28
  }).then(() => {
37
- if (disposed)
29
+ if (isDisposed())
38
30
  return;
39
31
  // Asset readiness survives an open failure; retry must never evaluate the script twice.
40
32
  ready = true;
@@ -44,7 +36,7 @@ export function installLazyChatLoader(args, _options = {}) {
44
36
  args.button.innerHTML = initialContent;
45
37
  args.button.hidden = true;
46
38
  }).catch(() => {
47
- if (!disposed) {
39
+ if (!isDisposed()) {
48
40
  args.button.hidden = false;
49
41
  args.button.dataset.loadFailed = 'true';
50
42
  args.button.setAttribute(ARIA_LABEL, args.retryLabel);
@@ -56,6 +48,18 @@ export function installLazyChatLoader(args, _options = {}) {
56
48
  });
57
49
  return pending;
58
50
  };
51
+ return activate;
52
+ }
53
+ /**
54
+ * Activates a host-rendered button without importing chat, React, icons or storage.
55
+ * One in-flight load serves repeated activation; failures remain retryable. Native button
56
+ * keyboard activation also emits click; preventDefault avoids a second toggle after keydown.
57
+ */
58
+ export function installLazyChatLoader(args, _options = {}) {
59
+ let disposed = false;
60
+ const initialContent = args.button.innerHTML;
61
+ const label = args.button.getAttribute(ARIA_LABEL) ?? '';
62
+ const activate = createLazyChatActivation({ args, initialContent, label, isDisposed: () => disposed });
59
63
  const click = () => { void activate({}); };
60
64
  const keydown = (event) => {
61
65
  if (event.key !== 'Enter' && event.key !== ' ')
@@ -16,6 +16,9 @@ export interface BrowserSessionStore {
16
16
  }): void;
17
17
  clear(args: Record<string, never>): void;
18
18
  }
19
+ /** Which step failed: storage read, envelope decode (the entry is cleared first), serialization,
20
+ * storage write, or storage remove. */
21
+ export type BrowserSessionStoreOperation = 'load' | 'decode' | 'serialize' | 'save' | 'clear';
19
22
  export interface BrowserSessionStoreArgs {
20
23
  readonly storage: SessionStoragePort;
21
24
  readonly transcriptKey: string;
@@ -24,10 +27,25 @@ export interface BrowserSessionStoreArgs {
24
27
  readonly validateMessage: (args: {
25
28
  value: unknown;
26
29
  }) => boolean;
30
+ /**
31
+ * What `load` does with a stored envelope over `maxMessages`/`maxBytes`. `'clear'` (default) treats
32
+ * it as corrupt. `'read'` rehydrates it whole, for a host whose earlier releases never capped reads:
33
+ * a visitor's existing transcript must survive the upgrade. Writes stay capped either way.
34
+ */
35
+ readonly overCapReads?: 'clear' | 'read';
36
+ /**
37
+ * Receives every swallowed failure. Default: none, so the store stays silent. It runs inside the
38
+ * store's failure path and a throw from it escapes the call, so a host may keep a failure loud.
39
+ */
40
+ readonly onFailure?: (failure: {
41
+ operation: BrowserSessionStoreOperation;
42
+ error: unknown;
43
+ }) => void;
27
44
  }
28
45
  /**
29
46
  * Creates bounded, fail-soft transcript storage.
30
- * Corrupt transcripts are cleared as a whole. Serialization/storage failures never escape.
47
+ * Corrupt transcripts are cleared as a whole. Serialization/storage failures never escape unless
48
+ * the host's `onFailure` rethrows; by default they are swallowed silently.
31
49
  * Reject oversized stored envelopes before parsing, validate the whole message batch, then trim
32
50
  * oldest messages first. Circular serialization is fail-soft. Keys, limits, validator and Storage
33
51
  * are injected so separate controllers never accidentally share a product-selected namespace.