@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,5 +1,6 @@
1
1
  import { describeErrorForLog } from '@jini-ai/core/model-facing-tool-errors';
2
2
  import { EventType } from "@ag-ui/core";
3
+ import { createAgUiApprovalRelay } from "./ag-ui-approval-relay.js";
3
4
  import { createAgUiToAgentTranslationState, translateAgUiEventToAgentEvent } from "../ag-ui/event-reduction.js";
4
5
  export { createAgUiFetchAgent } from "./ag-ui-fetch-agent.js";
5
6
  /** Only the originating attachment can authorize page execution. Read its token and tab for every
@@ -29,6 +30,7 @@ function handleAgUiEvent({ event, ctx, onLiveEvent }, _optional = {}) {
29
30
  return;
30
31
  }
31
32
  ctx.handlers.onError(new Error(event.message || "AG-UI run failed"));
33
+ ctx.finish();
32
34
  return;
33
35
  }
34
36
  if (event.type === EventType.RUN_FINISHED) {
@@ -66,97 +68,245 @@ function toRunAgentInput({ input, runId, threadId }, _optional = {}) {
66
68
  },
67
69
  };
68
70
  }
69
- /** Drops the turn's two handles: its registry entry (so `stopAgUiRun` cannot reach a dead agent) and
70
- * its listener on the host signal. Safe to repeat. */
71
+ /** Drops the segment's registry entry so `stopAgUiRun` cannot reach a dead agent; an accepted
72
+ * follower keeps its signal listeners until completion or detach. Safe to repeat. */
71
73
  function forgetRun({ turn }, _optional = {}) {
72
- turn.agents.delete(turn.runId);
74
+ turn.turns.delete(turn.runId);
75
+ if (turn.durable?.accepted)
76
+ return;
73
77
  turn.signal.removeEventListener("abort", turn.abort);
78
+ turn.durable?.cancelSignal?.removeEventListener("abort", turn.durable.requestStop);
74
79
  }
75
80
  /** The one place a turn is finished: `onDone` receives the collected events exactly once, however
76
81
  * many of RUN_FINISHED, an abort, a stream error and `complete` arrive. */
77
- function settleRunOnce({ turn }, _optional = {}) {
82
+ function settleRunOnce({ turn, error }, _optional = {}) {
78
83
  if (turn.settled)
79
84
  return;
80
85
  turn.settled = true;
81
86
  forgetRun({ turn });
87
+ // An accepted turn's follower owns the one final transcript and usage.
88
+ if (turn.durable?.accepted)
89
+ return;
90
+ // Error THEN finish: an errored Observable never calls `complete`, so without this the turn
91
+ // is never settled and the events collected before the failure never reach `onDone`. Same
92
+ // order as `subscribeToRun`'s `end` listener, so the run is still recorded as failed.
93
+ if (error)
94
+ turn.handlers.onError(error);
82
95
  turn.handlers.onDone(turn.collected);
83
96
  }
97
+ /** Stop through the cancel signal or `stopAgUiRun` converges here: one cancel per accepted run. */
98
+ function cancelAcceptedOnce({ entry, binding }, _optional = {}) {
99
+ entry.cancel ??= binding.cancelAcceptedRun(entry.accepted, {});
100
+ return entry.cancel;
101
+ }
102
+ /** Explicit Stop cancels the prepared message before acceptance and latches the result for the
103
+ * accepted run, so a Stop racing acceptance never leaves a run executing or launches it again. */
104
+ function requestDurableStop({ durable }, _optional = {}) {
105
+ if (durable.stopRequested)
106
+ return;
107
+ durable.stopRequested = true;
108
+ if (durable.accepted) {
109
+ void cancelAcceptedOnce({ entry: durable.accepted, binding: durable.binding }).catch(() => undefined);
110
+ return;
111
+ }
112
+ const { messageId, conversationId } = durable.start.launch;
113
+ if (messageId && conversationId) {
114
+ durable.pendingCancel = durable.binding.cancelPendingRun({ messageId, conversationId }, {});
115
+ void durable.pendingCancel.catch(() => undefined);
116
+ }
117
+ }
84
118
  /**
85
- * Deliberately racing the Observable's first `next`/`error`/`complete` against this Promise rather than
86
- * awaiting it directly — `HttpAgent.run()` returns a cold Observable, never a Promise (module
87
- * doc). The subscription itself keeps running after this Promise settles, driving `handlers`
88
- * through to `settleRunOnce` in the background — matching `startByokRun`'s "resolves once STARTED, not
89
- * once finished" contract.
119
+ * Hand an accepted segment to the canonical run. Acceptance precedes waiting: the binding is
120
+ * persisted before start is reported, so a reload or Stop can always address the canonical run.
121
+ * Saved projections replace replay: later segment frames are dropped and the follower renders the
122
+ * one authoritative transcript, so neither view duplicates the other's deltas.
90
123
  */
91
- function subscribeRun({ turn, runAgentInput, state, ports }, _optional = {}) {
92
- const finish = () => settleRunOnce({ turn });
124
+ function acceptDurableTurn({ turn, durable, event, runAgentInput }, _optional = {}) {
125
+ const accepted = durable.binding.readAcceptedRun({ event, input: runAgentInput }, {});
126
+ if (!accepted)
127
+ return undefined;
128
+ const entry = { accepted, ...(durable.pendingCancel ? { cancel: durable.pendingCancel.catch(() => durable.binding.cancelAcceptedRun(accepted, {})) } : {}) };
129
+ durable.accepted = entry;
130
+ durable.acceptedRuns.set(accepted.runId, entry);
131
+ durable.start.bindRun({ runId: accepted.runId, binding: { messageId: accepted.messageId, conversationId: accepted.conversationId } }, {});
132
+ if (durable.stopRequested)
133
+ void cancelAcceptedOnce({ entry, binding: durable.binding }).catch(() => undefined);
134
+ durable.binding.followAcceptedRun({ ...accepted, handlers: { ...turn.handlers, onDone: (final) => {
135
+ turn.handlers.onDone(final);
136
+ durable.acceptedRuns.delete(accepted.runId);
137
+ durable.cancelSignal?.removeEventListener("abort", durable.requestStop);
138
+ turn.signal.removeEventListener("abort", turn.abort);
139
+ } }, signal: turn.signal }, {});
140
+ if (turn.signal.aborted) {
141
+ durable.cancelSignal?.removeEventListener("abort", durable.requestStop);
142
+ if (entry.cancel)
143
+ void entry.cancel.finally(() => durable.acceptedRuns.delete(accepted.runId)).catch(() => undefined);
144
+ else
145
+ durable.acceptedRuns.delete(accepted.runId);
146
+ }
147
+ return accepted;
148
+ }
149
+ function isDurableSegmentEnd({ event }) {
150
+ return event.type === EventType.RUN_FINISHED || event.type === EventType.RUN_ERROR;
151
+ }
152
+ /** Durable mode settles start only on acceptance; returns the canonical ID once, else undefined. */
153
+ function durableStartEvent({ turn, event, runAgentInput, ports }, _optional = {}) {
154
+ const durable = turn.durable;
155
+ if (!durable)
156
+ return { drop: false };
157
+ if (durable.accepted) {
158
+ ports.onLiveEvent?.({ event });
159
+ if (isDurableSegmentEnd({ event }))
160
+ settleRunOnce({ turn });
161
+ return { drop: true };
162
+ }
163
+ if (event.type !== EventType.RUN_STARTED)
164
+ return { drop: false };
165
+ const accepted = acceptDurableTurn({ turn, durable, event, runAgentInput });
166
+ if (accepted)
167
+ ports.onLiveEvent?.({ event });
168
+ return accepted ? { accepted, drop: true } : { drop: false };
169
+ }
170
+ function waitsForLaunchedRunStart({ turn, frame, runAgentInput }) {
171
+ const launch = turn.durable?.start.launch;
172
+ return !!(launch?.messageId && launch.conversationId && !(frame.type === EventType.RUN_STARTED && frame.runId === runAgentInput.runId));
173
+ }
174
+ const INTERRUPTED = "The assistant stopped before replying. Send your message again.";
175
+ function segmentAborted(turn) {
176
+ return turn.signal.aborted || turn.agent.abortController.signal.aborted;
177
+ }
178
+ /** Subscribe once. The start promise and the later delivery transcript settle independently. */
179
+ function subscribeRun({ turn, runAgentInput, state, ports, onRejected, onStarted }, _optional = {}) {
93
180
  return new Promise((resolve, reject) => {
94
- let startSettled = false;
95
- turn.agent.run(runAgentInput).subscribe({
96
- next: (event) => {
97
- if (!startSettled) {
98
- startSettled = true;
99
- resolve({ runId: turn.runId });
100
- }
101
- handleAgUiEvent({ event: event, onLiveEvent: ports.onLiveEvent, ctx: { collected: turn.collected, handlers: turn.handlers, state, finish } });
102
- },
103
- error: (error) => {
104
- forgetRun({ turn });
105
- const err = runStreamError({ error });
106
- if (!startSettled) {
107
- startSettled = true;
108
- reject(err);
109
- return;
110
- }
111
- // Aborting BEFORE headers arrive rejects the underlying fetch() itself, surfacing here
112
- // rather than through `handleAgUiEvent`'s `code: "abort"` check (module doc).
113
- if (turn.agent.abortController.signal.aborted) {
114
- finish();
115
- return;
116
- }
117
- // Error THEN finish: an errored Observable never calls `complete`, so without this the turn
118
- // is never settled and the events collected before the failure never reach `onDone`. Same
119
- // order as `subscribeToRun`'s `end` listener, so the run is still recorded as failed.
120
- turn.handlers.onError(err);
121
- finish();
122
- },
123
- complete: () => {
124
- // An empty stream has no first notification to settle the start promise.
125
- if (!startSettled) {
126
- startSettled = true;
127
- resolve({ runId: turn.runId });
128
- }
129
- finish();
130
- },
131
- });
181
+ let started = false;
182
+ const noteStart = (runId) => {
183
+ started = true;
184
+ onStarted?.(runId);
185
+ resolve({ runId });
186
+ };
187
+ const finish = (error) => {
188
+ if (turn.settled)
189
+ return;
190
+ if (started) {
191
+ settleRunOnce({ turn, ...(error ? { error } : {}) });
192
+ return;
193
+ }
194
+ turn.settled = true;
195
+ forgetRun({ turn });
196
+ onRejected?.();
197
+ reject(error ?? new DOMException("Run cancelled", "AbortError"));
198
+ };
199
+ const failed = (error) => {
200
+ finish(segmentAborted(turn) || turn.durable?.accepted ? undefined : runStreamError({ error }));
201
+ };
202
+ try {
203
+ turn.agent.run(runAgentInput).subscribe({
204
+ next: (frame) => receiveFrame({ turn, runAgentInput, state, ports, frame, started, noteStart, finish }),
205
+ error: failed,
206
+ complete: () => { finish(segmentAborted(turn) || turn.durable?.accepted ? undefined : new Error(INTERRUPTED)); },
207
+ });
208
+ }
209
+ catch (error) {
210
+ failed(error);
211
+ }
132
212
  });
133
213
  }
214
+ function streamFrameError(frame) {
215
+ if (frame.type !== EventType.RUN_ERROR || frame.code === "abort")
216
+ return undefined;
217
+ return new Error(frame.message || "AG-UI run failed");
218
+ }
219
+ function observeFrame({ turn, event, runAgentInput, ports }) {
220
+ ports.observe?.({ threadId: runAgentInput.threadId, event, input: runAgentInput }, {});
221
+ return durableStartEvent({ turn, event, runAgentInput, ports });
222
+ }
223
+ function receiveFrame({ turn, runAgentInput, state, ports, frame: raw, started, noteStart, finish }) {
224
+ if (turn.settled)
225
+ return;
226
+ const frame = raw;
227
+ if (turn.signal.aborted && frame.type !== EventType.RUN_STARTED) {
228
+ finish();
229
+ return;
230
+ }
231
+ const step = observeFrame({ turn, event: frame, runAgentInput, ports });
232
+ if (step.accepted)
233
+ noteStart(step.accepted.runId);
234
+ if (step.drop)
235
+ return;
236
+ if (segmentAborted(turn)) {
237
+ finish();
238
+ return;
239
+ }
240
+ const error = streamFrameError(frame);
241
+ if (error) {
242
+ finish(error);
243
+ return;
244
+ }
245
+ if (!started) {
246
+ if (waitsForLaunchedRunStart({ turn, frame, runAgentInput }))
247
+ return;
248
+ noteStart(turn.runId);
249
+ }
250
+ handleAgUiEvent({ event: frame, onLiveEvent: ports.onLiveEvent, ctx: { collected: turn.collected, handlers: turn.handlers, state, finish } });
251
+ }
134
252
  function runStreamError({ error }, _optional = {}) {
135
253
  const status = error instanceof Error && "status" in error && typeof error.status === "number" ? `HTTP ${error.status}, ` : "";
136
254
  return new Error(`The agent run stream stopped with an error (${status}${describeErrorForLog({ err: error })}); send the message again.`, { cause: error });
137
255
  }
138
- /**
139
- * The AG-UI canary run path (ADR-059) — drives a real `@ag-ui/client` `HttpAgent` against
140
- * `assistant-ag-ui.ts`'s route, same one-turn-per-call shape as `startByokRun`. `credentials:
141
- * "same-origin"` is explicit even though modern `fetch()` already defaults to it for same-origin
142
- * requests, matching this transport's other paths' explicitness about the session cookie.
143
- */
144
- async function startRun({ ports, agents, input, handlers, resume }, _optional = {}) {
256
+ async function startRun({ ports, turns, input, handlers, resume, durable: start, acceptedRuns }, { prepare } = {}) {
145
257
  const runId = `${ports.runIdPrefix}${ports.mintId({}, {})}`;
146
- // The conversation-level id, stable across turns — a genuine AG-UI `threadId`, distinct from the
147
- // per-turn `runId` minted fresh above. Falls back to minting one only for a conversation that has
148
- // none yet (e.g. the very first turn).
149
258
  const threadId = resume?.threadId ?? input.conversationId ?? ports.mintId({}, {});
150
259
  const agent = ports.createAgent({ url: ports.endpoint, threadId }, {});
151
260
  if (input.signal.aborted)
152
261
  throw new DOMException("Run cancelled", "AbortError");
153
- agents.set(runId, agent);
154
- const abort = () => agent.abortRun();
155
- input.signal.addEventListener("abort", abort, { once: true });
156
- const turn = { runId, agent, signal: input.signal, abort, handlers, collected: [], agents, settled: false };
262
+ const durable = ports.durableLocalCli && start ? durableTurn({ binding: ports.durableLocalCli, start, acceptedRuns, input }) : undefined;
263
+ const wire = requestBody({ input, runId, threadId, resume, durable });
264
+ return subscribeSegment({ ports, turns, acceptedRuns, runId, agent, input, handlers, durable, wire }, { prepare });
265
+ }
266
+ /** Let the host wrap this segment's handlers, register the turn, then subscribe. */
267
+ function subscribeSegment({ ports, turns, acceptedRuns, runId, agent, input, handlers, durable, wire }, { prepare }) {
268
+ const segment = prepare?.({ wire, input, handlers });
269
+ const turn = attachTurn({ turns, runId, agent, signal: input.signal, handlers: segment?.handlers ?? handlers, durable, acceptedRuns });
157
270
  const state = createAgUiToAgentTranslationState({ customEventNames: ports.customEventNames }, {});
158
- return subscribeRun({ turn, runAgentInput: { ...toRunAgentInput({ input, runId, threadId }),
159
- ...(resume ? { parentRunId: resume.parentRunId, resume: resume.resume } : {}) }, state, ports });
271
+ return subscribeRun({ turn, runAgentInput: wire, state, ports, onRejected: segment?.reject, onStarted: segment?.started });
272
+ }
273
+ function attachTurn({ turns, runId, agent, signal, handlers, durable, acceptedRuns }) {
274
+ const abort = () => {
275
+ agent.abortRun();
276
+ if (!durable?.accepted)
277
+ return;
278
+ const entry = durable.accepted;
279
+ durable.cancelSignal?.removeEventListener("abort", durable.requestStop);
280
+ if (entry.cancel)
281
+ void entry.cancel.finally(() => acceptedRuns.delete(entry.accepted.runId)).catch(() => undefined);
282
+ else
283
+ acceptedRuns.delete(entry.accepted.runId);
284
+ };
285
+ signal.addEventListener("abort", abort, { once: true });
286
+ const turn = { runId, agent, signal, abort, handlers,
287
+ collected: [], turns, settled: false, ...(durable ? { durable } : {}) };
288
+ turns.set(runId, turn);
289
+ if (durable)
290
+ listenForDurableStop(durable);
291
+ return turn;
292
+ }
293
+ /** The wire request: the delivery segment's own body, projected by the durable binding when present. */
294
+ function requestBody({ input, runId, threadId, resume, durable }, _optional = {}) {
295
+ const wire = { ...toRunAgentInput({ input, runId, threadId }), ...(resume ? { parentRunId: resume.parentRunId, resume: resume.resume } : {}) };
296
+ return durable ? durable.binding.prepareRunInput({ input, wire, launch: durable.start.launch }, {}) : wire;
297
+ }
298
+ /** Durable state for one start. Only the explicit cancel signal is Stop; the detach signal (`signal`)
299
+ * aborts the delivery segment, because aborting a delivery segment on unload is not Stop. */
300
+ function durableTurn({ binding, start, acceptedRuns, input }, _optional = {}) {
301
+ const durable = { binding, start, acceptedRuns, input, cancelSignal: input.cancelSignal, stopRequested: false, requestStop: () => requestDurableStop({ durable }) };
302
+ return durable;
303
+ }
304
+ function listenForDurableStop(durable) {
305
+ const { cancelSignal, requestStop } = durable;
306
+ if (cancelSignal?.aborted)
307
+ requestStop();
308
+ else
309
+ cancelSignal?.addEventListener("abort", requestStop, { once: true });
160
310
  }
161
311
  /** No server-side run record exists on this path (module doc) — a reload has already discarded the
162
312
  * original `fetch()`'s response body, so there is nothing to resume. Same honest "already over"
@@ -169,24 +319,104 @@ async function fetchAgUiRunStatus(_required, _optional = {}) {
169
319
  return null;
170
320
  }
171
321
  /** Bind the official client without adding its dependency to every chat consumer. */
172
- export function createAgUiRunClient({ ports }, _options = {}) {
173
- /** In-flight AG-UI turns' driving `HttpAgent`, keyed by the client-minted runId — the ONLY way
174
- * `stopAgUiRun` can cancel a turn: like BYOK, there is no server-side run record on THIS
175
- * path to `POST .../cancel` against. Storing the agent (not a bare `AbortController`) lets
176
- * `stopAgUiRun` call its own `abortRun()`, which both aborts the fetch AND (per the package's own
177
- * convention) surfaces a clean `RUN_ERROR{code:"abort"}` through the normal event path rather than
178
- * a raw network error. */
179
- const agents = new Map();
322
+ export function createAgUiRunClient({ ports }, _optional = {}) {
323
+ return runClient({ ports });
324
+ }
325
+ function runClient({ ports }, { prepareStart, prepareResume } = {}) {
326
+ const turns = new Map();
327
+ const acceptedRuns = new Map();
328
+ const binding = ports.durableLocalCli;
180
329
  return {
181
- isAgUiRunId: ({ runId }, _optional = {}) => runId.startsWith(ports.runIdPrefix),
182
- handleAgUiEvent: ({ event, ctx }, _optional = {}) => handleAgUiEvent({ event, ctx, onLiveEvent: ports.onLiveEvent }),
183
- startAgUiRun: ({ input, handlers }, _optional = {}) => startRun({ ports, agents, input, handlers }),
184
- resumeAgUiRun: ({ input, handlers, threadId, parentRunId, resume }, _optional = {}) => startRun({ ports, agents, input, handlers, resume: { threadId, parentRunId, resume } }),
330
+ ...(binding ? { durableLocalCli: true } : {}),
331
+ isAcceptedAgUiRun: ({ runId }) => acceptedRuns.has(runId),
332
+ isAgUiRunId: ({ runId }) => runId.startsWith(ports.runIdPrefix),
333
+ handleAgUiEvent: ({ event, ctx }) => handleAgUiEvent({ event, ctx, onLiveEvent: ports.onLiveEvent }),
334
+ startAgUiRun: ({ input, handlers, durable }) => startRun({ ports, turns, input, handlers, durable, acceptedRuns }, prepareStart ? { prepare: prepareStart } : {}),
335
+ resumeAgUiRun: ({ input, handlers, threadId, parentRunId, resume }) => startRun({ ports, turns, input, handlers, resume: { threadId, parentRunId, resume }, acceptedRuns }, prepareResume ? { prepare: prepareResume } : {}),
185
336
  reattachAgUiRun,
186
337
  fetchAgUiRunStatus,
187
- /** An AG-UI run's only cancellation handle is the `HttpAgent` {@link startRun} registered for
188
- * this exact id — same shape as BYOK's `stopRun` branch. */
189
- stopAgUiRun: async ({ runId }, _optional = {}) => { agents.get(runId)?.abortRun(); },
338
+ async stopAgUiRun({ runId }, _optional = {}) {
339
+ const accepted = acceptedRuns.get(runId);
340
+ if (accepted && binding)
341
+ return cancelAcceptedOnce({ entry: accepted, binding });
342
+ const turn = turns.get(runId);
343
+ if (turn?.durable) {
344
+ if (turn.durable.accepted)
345
+ return cancelAcceptedOnce({ entry: turn.durable.accepted, binding: turn.durable.binding });
346
+ turn.durable.requestStop();
347
+ return turn.durable.pendingCancel;
348
+ }
349
+ turn?.agent.abortRun();
350
+ },
190
351
  };
191
352
  }
353
+ /** Report one error and supply the host's empty-transcript copy only after a started run. */
354
+ export function guardTerminalOutcome({ handlers, intentionalStop, copy }, _optional = {}) {
355
+ let errored = false;
356
+ let sawEvent = false;
357
+ let finished = false;
358
+ const report = (error) => {
359
+ if (errored || finished || intentionalStop())
360
+ return;
361
+ errored = true;
362
+ handlers.onError(error);
363
+ };
364
+ return {
365
+ ...handlers,
366
+ onEvent(event) {
367
+ if (finished)
368
+ return;
369
+ sawEvent = true;
370
+ handlers.onEvent(event);
371
+ },
372
+ onError: report,
373
+ onDone(final) {
374
+ if (finished)
375
+ return;
376
+ if (!errored && !sawEvent && final.length === 0)
377
+ report(new Error(copy.noReply));
378
+ finished = true;
379
+ handlers.onDone(final);
380
+ },
381
+ };
382
+ }
383
+ /** Bind the neutral run client and live confirmation relay to host ports and public copy. */
384
+ export function createAgUiApprovalRunClient({ ports, copy }, _optional = {}) {
385
+ const approvals = createAgUiApprovalRelay({ ports: {
386
+ copy,
387
+ resume: (required, optional) => client.resumeAgUiRun(required, optional),
388
+ isAccepted: (required) => client.isAcceptedAgUiRun?.(required, {}) ?? false,
389
+ } });
390
+ const client = runClient({ ports: { ...ports, observe: (required, optional) => {
391
+ approvals.observe(required, {});
392
+ ports.observe?.(required, optional);
393
+ } } }, {
394
+ prepareStart: ({ wire, input, handlers }) => {
395
+ let stopped = false;
396
+ const guarded = guardTerminalOutcome({ handlers, copy,
397
+ intentionalStop: () => stopped || input.signal.aborted || Boolean(input.cancelSignal?.aborted) });
398
+ const relayed = approvals.beginTurn({ threadId: wire.threadId, signal: input.signal, handlers: guarded }, {
399
+ segmentRunId: wire.runId, onStop: () => { stopped = true; },
400
+ ...(input.cancelSignal ? { cancelSignal: input.cancelSignal } : {}),
401
+ stopResume: runId => { void client.stopAgUiRun({ runId }).catch(() => undefined); },
402
+ });
403
+ return {
404
+ handlers: relayed,
405
+ started: runId => approvals.confirmStart({ segmentRunId: wire.runId, runId }),
406
+ reject: () => approvals.discard({ runId: wire.runId }),
407
+ };
408
+ },
409
+ prepareResume: ({ wire, handlers }) => {
410
+ approvals.bindResume({ input: wire });
411
+ return { handlers };
412
+ },
413
+ });
414
+ return { ...client, approvals, async stopAgUiRun(required, optional = {}) {
415
+ const resumeRunId = approvals.release(required, {});
416
+ const main = client.stopAgUiRun(required, optional);
417
+ if (!resumeRunId || resumeRunId === required.runId)
418
+ return main;
419
+ await Promise.all([main, client.stopAgUiRun({ runId: resumeRunId }, optional)]);
420
+ } };
421
+ }
192
422
  //# sourceMappingURL=ag-ui-transport.js.map
@@ -0,0 +1,25 @@
1
+ import type { DurableSubscriptionPorts } from "./durable-run-subscription.js";
2
+ /** Browser adapters only: active run streams are never visibility-paused. Ports permit DI fakes
3
+ * without replacing modules; native disconnects retain Jini's existing recovery/backoff behavior.
4
+ */
5
+ export declare function browserDurableSubscriptionPorts({ request, open, schedule, runPath }: {
6
+ request: typeof fetch;
7
+ open: (url: string) => Pick<EventSource, "addEventListener" | "close" | "readyState">;
8
+ schedule: (required: {
9
+ work: () => void;
10
+ delayMs: number;
11
+ }) => () => void;
12
+ runPath: (required: {
13
+ runId: string;
14
+ }, optional?: Record<string, never>) => string;
15
+ }, _optional?: Record<string, never>): DurableSubscriptionPorts;
16
+ /**
17
+ * The browser `schedule` port for {@link browserDurableSubscriptionPorts}: one `setTimeout`, cancelled by the
18
+ * returned function. Hosts pass it unless they need their own timer (tests).
19
+ * @complexity O(1).
20
+ */
21
+ export declare function browserTimeoutSchedule({ work, delayMs }: {
22
+ work: () => void;
23
+ delayMs: number;
24
+ }, _optional?: Record<string, never>): () => void;
25
+ //# sourceMappingURL=browser-durable-subscription.d.ts.map
@@ -0,0 +1,78 @@
1
+ import { querySuffix } from "@jini-ai/core/admin-runtime";
2
+ /** Map the existing recovery/checkpoint routes to one fetch. Conditional headers apply only to
3
+ * routine polls; explicit recovery must always reach the finalizer. No response body is read here.
4
+ */
5
+ function requestDurableProjection({ request, runPath, runId, messageId, recover, etag }, _options = {}) {
6
+ const path = runPath({ runId }, {});
7
+ if (recover)
8
+ return request(`${path}/recover`, {
9
+ method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ messageId }),
10
+ });
11
+ const query = messageId ? 'messageId=' + encodeURIComponent(messageId) : '';
12
+ return request(`${path}/checkpoint${querySuffix({ query })}`, {
13
+ method: 'GET', credentials: 'same-origin', ...(etag ? { headers: { 'If-None-Match': etag } } : {}),
14
+ });
15
+ }
16
+ /** Status-only outcomes do not advance the projection checkpoint. */
17
+ function durableReadRefusal(response) {
18
+ if (response.status === 304)
19
+ return null;
20
+ if (response.status === 404)
21
+ return "gone";
22
+ if (!response.ok)
23
+ return null;
24
+ return undefined;
25
+ }
26
+ /** Browser adapters only: active run streams are never visibility-paused. Ports permit DI fakes
27
+ * without replacing modules; native disconnects retain Jini's existing recovery/backoff behavior.
28
+ */
29
+ export function browserDurableSubscriptionPorts({ request, open, schedule, runPath }, _optional = {}) {
30
+ let checkpointKey;
31
+ let checkpointEtag;
32
+ return {
33
+ async read({ runId, messageId }, { recover = true } = {}) {
34
+ const key = messageId ?? runId;
35
+ const etag = checkpointKey === key ? checkpointEtag : undefined;
36
+ const response = await requestDurableProjection({ request, runPath, runId, messageId, recover, etag });
37
+ if (recover) {
38
+ checkpointKey = undefined;
39
+ checkpointEtag = undefined;
40
+ }
41
+ const refused = durableReadRefusal(response);
42
+ if (refused !== undefined)
43
+ return refused;
44
+ if (!recover) {
45
+ checkpointKey = key;
46
+ checkpointEtag = response.headers.get('ETag');
47
+ }
48
+ const payload = await response.json();
49
+ return payload.message;
50
+ },
51
+ stream({ runId, cursor, frame, dropped }, _options) {
52
+ const source = open(`${runPath({ runId }, {})}/events${querySuffix({ query: cursor ? "afterCursor=" + encodeURIComponent(cursor) : "" })}`);
53
+ for (const kind of ["agent", "stdout", "stderr", "end", "error"]) {
54
+ source.addEventListener(kind, (event) => {
55
+ const message = event;
56
+ if (kind === "error" && !message.data) {
57
+ source.close();
58
+ dropped();
59
+ return;
60
+ }
61
+ frame(kind, message.data, message.lastEventId);
62
+ });
63
+ }
64
+ return () => source.close();
65
+ },
66
+ schedule(required, _options) { return schedule(required); },
67
+ };
68
+ }
69
+ /**
70
+ * The browser `schedule` port for {@link browserDurableSubscriptionPorts}: one `setTimeout`, cancelled by the
71
+ * returned function. Hosts pass it unless they need their own timer (tests).
72
+ * @complexity O(1).
73
+ */
74
+ export function browserTimeoutSchedule({ work, delayMs }, _optional = {}) {
75
+ const timer = setTimeout(work, delayMs);
76
+ return () => clearTimeout(timer);
77
+ }
78
+ //# sourceMappingURL=browser-durable-subscription.js.map