@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
@@ -0,0 +1,287 @@
1
+ /** Live-only confirmation correlation for one logical turn across AG-UI delivery segments. */
2
+ import { EventType } from "@ag-ui/core";
3
+ import { EventSchemas } from "@ag-ui/core/schemas";
4
+ const EXCHANGE_ID_PARAM = "__exchangeId";
5
+ function exchangeIdFor(entry) {
6
+ const raw = entry.metadata?.exchangeId;
7
+ return typeof raw === "string" && raw ? raw : undefined;
8
+ }
9
+ function findConfirmation(entries, requireExchange) {
10
+ for (const entry of entries) {
11
+ if (entry.reason !== "confirmation" || !entry.id)
12
+ continue;
13
+ const exchangeId = exchangeIdFor(entry);
14
+ if (requireExchange && !exchangeId)
15
+ continue;
16
+ return { interruptId: entry.id, ...(entry.message === undefined ? {} : { message: entry.message }),
17
+ ...(exchangeId ? { exchangeId } : {}) };
18
+ }
19
+ return undefined;
20
+ }
21
+ /** Read a validated confirmation from an AG-UI terminal, optionally requiring exchange metadata. */
22
+ export function readAgUiConfirmationInterrupt({ event }, { requireExchange = false } = {}) {
23
+ if (event?.type !== EventType.RUN_FINISHED)
24
+ return undefined;
25
+ const parsed = EventSchemas.safeParse(event);
26
+ if (!parsed.success || parsed.data.type !== EventType.RUN_FINISHED || parsed.data.outcome?.type !== "interrupt")
27
+ return undefined;
28
+ // The validator's type includes explicit undefined on optionals, unlike the generated wire type.
29
+ const approval = findConfirmation(parsed.data.outcome.interrupts, requireExchange);
30
+ return approval ? { ...approval, threadId: parsed.data.threadId, parentRunId: parsed.data.runId } : undefined;
31
+ }
32
+ function resumeEntry(interruptId, decision) {
33
+ return decision === "cancelled" ? { interruptId, status: "cancelled" } : { interruptId, status: "resolved", payload: decision };
34
+ }
35
+ /** Address one paused run with a fresh segment ID and no history or tool registrations. */
36
+ export function createAgUiResumeInput({ threadId, runId, parentRunId, interruptId, decision }, _optional = {}) {
37
+ return { threadId, runId, parentRunId, state: null, messages: [], tools: [], context: [], resume: [resumeEntry(interruptId, decision)] };
38
+ }
39
+ /** Record the first choice before invoking I/O and give every caller the same promise. */
40
+ export function createAgUiAnswerOnce({ submit }, _optional = {}) {
41
+ let answer;
42
+ return { answer({ choice }, _optional = {}) {
43
+ if (answer)
44
+ return answer;
45
+ let resolve;
46
+ let reject;
47
+ answer = new Promise((yes, no) => { resolve = yes; reject = no; });
48
+ try {
49
+ resolve(submit({ choice }, {}));
50
+ }
51
+ catch (error) {
52
+ reject(error);
53
+ }
54
+ return answer;
55
+ } };
56
+ }
57
+ function plainResumeFailure(error, copy) {
58
+ const visited = new Set();
59
+ for (let current = error; current instanceof Error && !visited.has(current); current = current.cause) {
60
+ visited.add(current);
61
+ const status = current.status;
62
+ if (status === 400 || /\bHTTP 400\b/.test(current.message))
63
+ return new Error(copy.expired);
64
+ }
65
+ return new Error(copy.unsent);
66
+ }
67
+ function durable(state, turn) {
68
+ return turn.canonicalRunId !== undefined && state.ports.isAccepted({ runId: turn.canonicalRunId }, {});
69
+ }
70
+ function forgetTurn(state, turn) {
71
+ turn.cleanup();
72
+ if (state.turns.get(turn.threadId) === turn)
73
+ state.turns.delete(turn.threadId);
74
+ for (const id of turn.runIds)
75
+ if (state.runs.get(id) === turn)
76
+ state.runs.delete(id);
77
+ for (const id of turn.exchangeIds)
78
+ if (state.exchanges.get(id)?.turn === turn)
79
+ state.exchanges.delete(id);
80
+ turn.runIds.clear();
81
+ turn.exchangeIds.clear();
82
+ turn.pending = undefined;
83
+ }
84
+ function settleTurn(state, turn, final) {
85
+ if (turn.settled)
86
+ return;
87
+ turn.settled = true;
88
+ forgetTurn(state, turn);
89
+ const events = [...turn.carried, ...final];
90
+ const lastUsage = events.findLastIndex(event => event.kind === "usage");
91
+ turn.handlers.onDone(events.filter((event, index) => event.kind !== "usage" || index === lastUsage));
92
+ }
93
+ function stopTurn(state, turn) {
94
+ const resumeRunId = turn.resumeRunId;
95
+ turn.stopped = true;
96
+ turn.onStop();
97
+ forgetTurn(state, turn);
98
+ if (turn.heldDone)
99
+ settleTurn(state, turn, []);
100
+ return resumeRunId;
101
+ }
102
+ function segmentHandlers(state, turn) {
103
+ const live = () => !turn.settled && !turn.stopped;
104
+ return {
105
+ ...(turn.handlers.onCheckpoint ? { onCheckpoint: (message) => { if (!turn.settled)
106
+ turn.handlers.onCheckpoint?.(message); } } : {}),
107
+ ...(turn.handlers.onToolInputDelta ? { onToolInputDelta: (id, name, delta) => {
108
+ if (live())
109
+ turn.handlers.onToolInputDelta?.(id, name, delta);
110
+ } } : {}),
111
+ onEvent(event) { if (live())
112
+ turn.handlers.onEvent(event); },
113
+ onError(error) { if (live())
114
+ turn.handlers.onError(error); },
115
+ onDone(final) {
116
+ if (turn.settled)
117
+ return;
118
+ if (turn.pending && !durable(state, turn)) {
119
+ turn.carried.push(...final);
120
+ turn.heldDone = true;
121
+ return;
122
+ }
123
+ settleTurn(state, turn, final);
124
+ },
125
+ };
126
+ }
127
+ const DURABLE_RESUME_SINK = { onEvent: () => { }, onError: () => { }, onDone: () => { } };
128
+ function refuseResume(state, turn, parked, error) {
129
+ if (turn.stopped || turn.settled || turn.refused)
130
+ return;
131
+ if (turn.pending === parked)
132
+ turn.pending = undefined;
133
+ turn.refused = true;
134
+ turn.handlers.onError(plainResumeFailure(error, state.ports.copy));
135
+ if (turn.heldDone)
136
+ settleTurn(state, turn, []);
137
+ }
138
+ async function resumeParked(state, turn, parked, allow) {
139
+ if (turn.stopped || turn.settled)
140
+ return false;
141
+ parked.claimed = true;
142
+ try {
143
+ const started = await state.ports.resume({
144
+ input: { history: [], signal: turn.signal, conversationId: turn.threadId },
145
+ handlers: durable(state, turn) ? DURABLE_RESUME_SINK : segmentHandlers(state, turn),
146
+ threadId: turn.threadId, parentRunId: parked.parentRunId, resume: [resumeEntry(parked.interruptId, allow ? "allow" : "deny")],
147
+ }, {});
148
+ if (turn.stopped)
149
+ return false;
150
+ if (!turn.settled && turn.pending === parked)
151
+ turn.resumeRunId = started.runId;
152
+ return true;
153
+ }
154
+ catch (error) {
155
+ refuseResume(state, turn, parked, error);
156
+ return false;
157
+ }
158
+ }
159
+ function rememberRun(state, turn, runId) {
160
+ turn.runIds.add(runId);
161
+ state.runs.set(runId, turn);
162
+ }
163
+ function noteCanonicalRun(state, turn, event, input) {
164
+ if (input.parentRunId || turn.segmentRunId !== undefined)
165
+ return;
166
+ const start = event;
167
+ if (start?.type !== EventType.RUN_STARTED || typeof start.runId !== "string")
168
+ return;
169
+ turn.canonicalRunId ??= start.runId;
170
+ rememberRun(state, turn, turn.canonicalRunId);
171
+ }
172
+ function observedInterrupt(turn, event, input) {
173
+ const interrupt = readAgUiConfirmationInterrupt({ event }, { requireExchange: true });
174
+ if (!interrupt?.exchangeId || interrupt.threadId !== turn.threadId)
175
+ return undefined;
176
+ const expectedRunId = input.parentRunId ? input.runId : turn.canonicalRunId ?? input.runId;
177
+ return interrupt.parentRunId === expectedRunId ? { ...interrupt, exchangeId: interrupt.exchangeId } : undefined;
178
+ }
179
+ function observeTurn(state, turn, event, input) {
180
+ if (turn.segmentRunId !== undefined && (turn.segmentRunId !== input.runId || !turn.canonicalRunId))
181
+ return;
182
+ noteCanonicalRun(state, turn, event, input);
183
+ const pending = turn.pending;
184
+ if (pending?.claimed && input.parentRunId === pending.parentRunId)
185
+ turn.pending = undefined;
186
+ const interrupt = observedInterrupt(turn, event, input);
187
+ if (interrupt)
188
+ parkInterrupt(state, turn, interrupt);
189
+ }
190
+ function parkInterrupt(state, turn, interrupt) {
191
+ if (state.exchanges.has(interrupt.exchangeId))
192
+ return;
193
+ const parked = { interruptId: interrupt.interruptId, parentRunId: interrupt.parentRunId, claimed: false,
194
+ answer: createAgUiAnswerOnce({ submit: ({ choice }) => resumeParked(state, turn, parked, choice) }) };
195
+ turn.pending = parked;
196
+ turn.exchangeIds.add(interrupt.exchangeId);
197
+ state.exchanges.set(interrupt.exchangeId, { turn, parked });
198
+ }
199
+ function beginTurn(state, { threadId, signal, handlers }, { segmentRunId, onStop = () => { }, cancelSignal, stopResume }) {
200
+ const old = state.turns.get(threadId);
201
+ if (old) {
202
+ old.settled = true;
203
+ old.stopped = true;
204
+ forgetTurn(state, old);
205
+ }
206
+ const detach = () => { stopTurn(state, turn); };
207
+ const cancel = () => {
208
+ const resumeRunId = stopTurn(state, turn);
209
+ if (resumeRunId)
210
+ stopResume?.(resumeRunId);
211
+ };
212
+ const cleanup = () => {
213
+ signal.removeEventListener("abort", detach);
214
+ cancelSignal?.removeEventListener("abort", cancel);
215
+ };
216
+ const turn = { threadId, signal, handlers, segmentRunId, onStop, carried: [], runIds: new Set(), exchangeIds: new Set(),
217
+ cleanup, settled: false, stopped: false, heldDone: false, refused: false };
218
+ state.turns.set(threadId, turn);
219
+ if (segmentRunId !== undefined)
220
+ rememberRun(state, turn, segmentRunId);
221
+ signal.addEventListener("abort", detach, { once: true });
222
+ cancelSignal?.addEventListener("abort", cancel, { once: true });
223
+ if (signal.aborted)
224
+ detach();
225
+ else if (cancelSignal?.aborted)
226
+ cancel();
227
+ return segmentHandlers(state, turn);
228
+ }
229
+ /** Correlate live approval cards without storing them in the conversation transcript. */
230
+ export function createAgUiApprovalRelay({ ports }, _optional = {}) {
231
+ const state = { ports, turns: new Map(), runs: new Map(), exchanges: new Map() };
232
+ return {
233
+ beginTurn(required, optional = {}) { return beginTurn(state, required, optional); },
234
+ answersExchange({ exchangeId }, _optional = {}) { return state.exchanges.has(exchangeId); },
235
+ answer({ exchangeId, allow }, _optional = {}) {
236
+ return state.exchanges.get(exchangeId)?.parked.answer.answer({ choice: allow }) ?? Promise.resolve(false);
237
+ },
238
+ observe({ threadId, event, input }, _optional = {}) {
239
+ const turn = state.turns.get(threadId);
240
+ if (turn)
241
+ observeTurn(state, turn, event, input);
242
+ },
243
+ bindRun({ threadId, runId }, _optional = {}) {
244
+ const turn = state.turns.get(threadId);
245
+ if (turn)
246
+ rememberRun(state, turn, runId);
247
+ },
248
+ confirmStart({ segmentRunId, runId }, _optional = {}) {
249
+ const turn = state.runs.get(segmentRunId);
250
+ if (!turn)
251
+ return;
252
+ turn.canonicalRunId = runId;
253
+ rememberRun(state, turn, runId);
254
+ },
255
+ bindResume({ input }, _optional = {}) {
256
+ const turn = state.turns.get(input.threadId);
257
+ if (!turn?.pending?.claimed || turn.pending.parentRunId !== input.parentRunId)
258
+ return;
259
+ turn.segmentRunId = input.runId;
260
+ turn.resumeRunId = input.runId;
261
+ rememberRun(state, turn, input.runId);
262
+ },
263
+ discard({ runId }, _optional = {}) {
264
+ const turn = state.runs.get(runId);
265
+ if (!turn)
266
+ return;
267
+ turn.stopped = true;
268
+ turn.settled = true;
269
+ forgetTurn(state, turn);
270
+ },
271
+ release({ runId }, _optional = {}) {
272
+ const turn = state.runs.get(runId);
273
+ return turn ? stopTurn(state, turn) : undefined;
274
+ },
275
+ };
276
+ }
277
+ /** Keep ordinary MCP-UI calls on their original route. Only a live exchange can resume AG-UI. */
278
+ export function routeApprovalToolCall({ approvals, fallback, copy }, _optional = {}) {
279
+ return async (call) => {
280
+ const exchangeId = call.arguments[EXCHANGE_ID_PARAM];
281
+ if (typeof exchangeId !== "string" || !approvals.answersExchange({ exchangeId }, {}))
282
+ return fallback(call);
283
+ const sent = await approvals.answer({ exchangeId, allow: call.arguments.decision === "confirm" }, {});
284
+ return { isError: !sent, content: [{ type: "text", text: sent ? copy.sent : copy.notSent }] };
285
+ };
286
+ }
287
+ //# sourceMappingURL=ag-ui-approval-relay.js.map
@@ -1,16 +1,31 @@
1
- import { type RunAgentInput } from '@ag-ui/core';
1
+ import type { AGUIEvent, RunAgentInput } from '@ag-ui/core';
2
2
  import type { AgUiClient } from './ag-ui-transport.js';
3
- declare function readAgUiResponse({ request, input, signal, observer }: {
4
- request: (required: {
5
- input: RunAgentInput;
6
- signal: AbortSignal;
7
- }) => Promise<Response>;
3
+ /** The fetch agent's own run handle: the common {@link AgUiClient} port, typed with the official event union. */
4
+ export interface AgUiFetchAgent extends AgUiClient {
5
+ run(input: RunAgentInput): {
6
+ subscribe(observer: {
7
+ next(event: AGUIEvent): void;
8
+ error(error: unknown): void;
9
+ complete(): void;
10
+ }): Promise<void>;
11
+ };
12
+ }
13
+ type AgUiRequest = (required: {
8
14
  input: RunAgentInput;
9
15
  signal: AbortSignal;
10
- observer: Parameters<ReturnType<AgUiClient['run']>['subscribe']>[0];
11
- }): Promise<void>;
16
+ }) => Promise<Response>;
17
+ type AgUiByteActivity = (required: {
18
+ byteLength: number;
19
+ }, optional?: Record<string, never>) => void;
20
+ /**
21
+ * Create a minimal fetch-backed AG-UI agent. The host injects HTTP (`request`), and may inject the
22
+ * controller that owns cancellation and a byte-activity callback for its idle policy.
23
+ */
12
24
  export declare function createAgUiFetchAgent({ request }: {
13
- request: Parameters<typeof readAgUiResponse>[0]['request'];
14
- }, _optional?: Record<string, never>): AgUiClient;
25
+ request: AgUiRequest;
26
+ }, { abortController, onBytes, }?: {
27
+ abortController?: AbortController;
28
+ onBytes?: AgUiByteActivity;
29
+ }): AgUiFetchAgent;
15
30
  export {};
16
31
  //# sourceMappingURL=ag-ui-fetch-agent.d.ts.map
@@ -1,22 +1,41 @@
1
- import { EventSchemas } from '@ag-ui/core';
1
+ import { EventSchemas } from '@ag-ui/core/schemas';
2
2
  import { readSseFrames } from '../run-events/entry.js';
3
- async function readAgUiResponse({ request, input, signal, observer }) {
3
+ /**
4
+ * Read one AG-UI response body into validated events.
5
+ * Byte activity is reported per nonempty network chunk, before SSE framing, so a heartbeat or a
6
+ * half-delivered frame still proves the connection is alive; the host owns what that means (idle
7
+ * timers), while `readSseFrames` and `EventSchemas.parse` stay the sole parser and validator.
8
+ * @complexity O(n) in response bytes.
9
+ */
10
+ async function readAgUiResponse({ request, input, signal, observer, onBytes }) {
4
11
  const response = await request({ input, signal });
5
12
  if (!response.body)
6
13
  throw new Error('The agent response has no event stream');
7
- const body = response.body.pipeThrough(new TransformStream(), { signal });
14
+ const activity = new TransformStream({
15
+ transform(chunk, controller) {
16
+ if (chunk.byteLength > 0)
17
+ onBytes?.({ byteLength: chunk.byteLength });
18
+ controller.enqueue(chunk);
19
+ },
20
+ });
21
+ const body = response.body.pipeThrough(activity, { signal });
8
22
  for await (const frame of readSseFrames({ body })) {
23
+ // AG-UI 1.0's validator output types optional fields as `T | undefined` while its generated
24
+ // event types are absent-or-`T`; a parsed event never carries an explicit `undefined`.
9
25
  observer.next(EventSchemas.parse(JSON.parse(frame.data)));
10
26
  }
11
27
  }
12
- export function createAgUiFetchAgent({ request }, _optional = {}) {
13
- const abortController = new AbortController();
28
+ /**
29
+ * Create a minimal fetch-backed AG-UI agent. The host injects HTTP (`request`), and may inject the
30
+ * controller that owns cancellation and a byte-activity callback for its idle policy.
31
+ */
32
+ export function createAgUiFetchAgent({ request }, { abortController = new AbortController(), onBytes, } = {}) {
14
33
  return {
15
34
  abortController,
16
35
  abortRun: () => abortController.abort(),
17
36
  run: (input) => ({
18
37
  subscribe(observer) {
19
- return readAgUiResponse({ request, input, signal: abortController.signal, observer }).then(() => observer.complete(), (error) => observer.error(error));
38
+ return readAgUiResponse({ request, input, signal: abortController.signal, observer, onBytes }).then(() => observer.complete(), (error) => observer.error(error));
20
39
  },
21
40
  }),
22
41
  };
@@ -8,12 +8,15 @@
8
8
  * Before headers, abort instead rejects fetch and reaches subscription.error; inspect the signal
9
9
  * there so an intentional stop cannot become a user-facing failure.
10
10
  */
11
- import type { RunAgentInput } from "@ag-ui/core";
11
+ import type { RunAgentInput, RunStartedEvent } from "@ag-ui/core";
12
+ import { type AgUiApprovalPoster, type AgUiApprovalRelayPorts } from "./ag-ui-approval-relay.js";
12
13
  import type { AgUiToAgentTranslationState } from "../ag-ui/event-reduction.js";
13
14
  import type { AgUiEvent, CustomEventNames } from "../ag-ui/event-projection.js";
14
- import type { AgentEvent } from "../events.js";
15
15
  import type { RunHandlers, StartRunInput } from "../transport.js";
16
+ import type { DurableRunBinding } from "./durable-run-subscription.js";
17
+ import type { AgentEvent } from "@jini-ai/core/contracts/site/chat-core";
16
18
  export { createAgUiFetchAgent } from "./ag-ui-fetch-agent.js";
19
+ export type { AgUiFetchAgent } from "./ag-ui-fetch-agent.js";
17
20
  export interface AgUiClient {
18
21
  readonly abortController: AbortController;
19
22
  abortRun(): void;
@@ -26,6 +29,12 @@ export interface AgUiClient {
26
29
  };
27
30
  }
28
31
  export interface AgUiClientPorts {
32
+ /** Observe the request and raw, SDK-validated frame before durable delivery drops it. */
33
+ readonly observe?: (required: {
34
+ threadId: string;
35
+ event: unknown;
36
+ input: RunAgentInput;
37
+ }, optional: Record<string, never>) => void;
29
38
  readonly onLiveEvent?: (required: {
30
39
  event: AgUiEvent;
31
40
  }) => boolean;
@@ -37,6 +46,56 @@ export interface AgUiClientPorts {
37
46
  url: string;
38
47
  threadId: string;
39
48
  }, optional: Record<string, never>) => AgUiClient;
49
+ /** Opt-in: bind each start to the durable Local CLI lifecycle. Absent, behavior is unchanged. */
50
+ readonly durableLocalCli?: AgUiDurableLocalCliBinding;
51
+ }
52
+ /** The prepared Local CLI start (`prepareLocalRunStart`): the same launch projection, agent
53
+ * selection, message identity and conversation binding the Local CLI acceptance sends. */
54
+ export interface LocalRunLaunch {
55
+ readonly contextRef: Record<string, unknown>;
56
+ readonly agentId?: string | undefined;
57
+ readonly messageId?: string | undefined;
58
+ readonly conversationId?: string | undefined;
59
+ }
60
+ /** The canonical durable run a host accepted for one AG-UI start. */
61
+ export interface AcceptedAgUiRun {
62
+ readonly runId: string;
63
+ readonly messageId: string;
64
+ readonly conversationId: string;
65
+ }
66
+ /** Neutral host hooks that bind an AG-UI delivery segment to the durable chat lifecycle. The
67
+ * logical message is durable; the AG-UI stream only delivers part of it. */
68
+ export interface AgUiDurableLocalCliBinding {
69
+ /** Project the prepared launch onto the wire request. `wire` keeps the client segment ID. */
70
+ prepareRunInput(required: {
71
+ input: StartRunInput;
72
+ wire: RunAgentInput;
73
+ launch: LocalRunLaunch;
74
+ }, optional?: Record<string, never>): RunAgentInput;
75
+ /** Interpret the validated RUN_STARTED as an acceptance, or `undefined` when it carries none. */
76
+ readAcceptedRun(required: {
77
+ event: RunStartedEvent;
78
+ input: RunAgentInput;
79
+ }, optional?: Record<string, never>): AcceptedAgUiRun | undefined;
80
+ /** Follow the canonical run's saved checkpoints. `signal` is detach only, never Stop. */
81
+ followAcceptedRun(required: AcceptedAgUiRun & {
82
+ handlers: RunHandlers;
83
+ signal: AbortSignal;
84
+ }, optional?: Record<string, never>): void;
85
+ /** Explicit Stop of the canonical run. Called at most once per accepted run. */
86
+ cancelAcceptedRun(required: AcceptedAgUiRun, optional?: Record<string, never>): Promise<void>;
87
+ cancelPendingRun(required: {
88
+ messageId: string;
89
+ conversationId: string;
90
+ }, optional?: Record<string, never>): Promise<void>;
91
+ }
92
+ /** What `startAgUiRun` needs to bind a durable start: the prepared launch and the binding store. */
93
+ export interface AgUiDurableStart {
94
+ readonly launch: LocalRunLaunch;
95
+ readonly bindRun: (required: {
96
+ runId: string;
97
+ binding: DurableRunBinding;
98
+ }, optional: Record<string, never>) => void;
40
99
  }
41
100
  export interface AgUiEventContext {
42
101
  collected: AgentEvent[];
@@ -55,6 +114,7 @@ export interface AgUiRunClient {
55
114
  startAgUiRun(required: {
56
115
  input: StartRunInput;
57
116
  handlers: RunHandlers;
117
+ durable?: AgUiDurableStart;
58
118
  }, optional?: Record<string, never>): Promise<{
59
119
  runId: string;
60
120
  }>;
@@ -74,9 +134,32 @@ export interface AgUiRunClient {
74
134
  stopAgUiRun(required: {
75
135
  runId: string;
76
136
  }, optional?: Record<string, never>): Promise<void>;
137
+ /** True for a canonical run ID this client accepted through its durable binding. */
138
+ readonly durableLocalCli?: boolean;
139
+ isAcceptedAgUiRun?(required: {
140
+ runId: string;
141
+ }, optional?: Record<string, never>): boolean;
77
142
  }
78
143
  /** Bind the official client without adding its dependency to every chat consumer. */
79
144
  export declare function createAgUiRunClient({ ports }: {
80
145
  ports: AgUiClientPorts;
81
- }, _options?: Record<string, never>): AgUiRunClient;
146
+ }, _optional?: Record<string, never>): AgUiRunClient;
147
+ type ApprovalCopy = AgUiApprovalRelayPorts["copy"] & {
148
+ noReply: string;
149
+ };
150
+ /** Report one error and supply the host's empty-transcript copy only after a started run. */
151
+ export declare function guardTerminalOutcome({ handlers, intentionalStop, copy }: {
152
+ handlers: RunHandlers;
153
+ intentionalStop: () => boolean;
154
+ copy: {
155
+ noReply: string;
156
+ };
157
+ }, _optional?: Record<string, never>): RunHandlers;
158
+ /** Bind the neutral run client and live confirmation relay to host ports and public copy. */
159
+ export declare function createAgUiApprovalRunClient({ ports, copy }: {
160
+ ports: AgUiClientPorts;
161
+ copy: ApprovalCopy;
162
+ }, _optional?: Record<string, never>): AgUiRunClient & {
163
+ approvals: AgUiApprovalPoster;
164
+ };
82
165
  //# sourceMappingURL=ag-ui-transport.d.ts.map