@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
@@ -4,6 +4,7 @@
4
4
  * built-in like WebFetch, an unknown MCP tool, a card tool such as `assistant_ask_choice` still
5
5
  * waiting on the person's answer) is left without a readable call.
6
6
  */
7
+ import { orFallbackSync } from '@jini-ai/core/errors/idioms';
7
8
  import { formatToolOutputForDisplay } from './tool-output.js';
8
9
  import { redactUserText } from './user-text-redaction.js';
9
10
  const DEFAULT_MAX_CHARS = 10_000;
@@ -16,14 +17,41 @@ const DEFAULT_MAX_CHARS = 10_000;
16
17
  * @returns Display-ready input and output text plus a note when the output is absent.
17
18
  * @complexity O(n) in the serialized input plus result length.
18
19
  */
19
- export function describeToolCallDetail({ input, result }, { runStreaming = false, runSucceeded = false, maxChars = DEFAULT_MAX_CHARS, redact = redactUserText } = {}) {
20
- const show = (text) => (text === null ? null : truncate(redact({ text: text }).text, maxChars));
21
- const inputText = show(serializeInput(input));
20
+ export function describeToolCallDetail({ input, result }, { runStreaming = false, runSucceeded = false, maxChars = DEFAULT_MAX_CHARS, redact = redactUserText, resultPresentation = 'display' } = {}) {
21
+ const inputText = showSafely({ text: serializeInput(input), redact, maxChars });
22
+ const { text, noteKey } = selectOutputOrNote({ result, runStreaming, runSucceeded, resultPresentation });
23
+ return { inputText, outputText: showSafely({ text, redact, maxChars }), noteKey };
24
+ }
25
+ /** Redacts, then caps — never the reverse, so a cut can never leave part of a secret the redactor would have matched whole. */
26
+ function showSafely({ text, redact, maxChars }, _optional = {}) {
27
+ return text === null ? null : truncate(redact({ text: text }).text, maxChars);
28
+ }
29
+ /** The unredacted output text to show, or the note explaining why there is none. */
30
+ function selectOutputOrNote({ result, runStreaming, runSucceeded, resultPresentation }, _optional = {}) {
22
31
  if (!result)
23
- return { inputText, outputText: null, noteKey: missingResultNote({ runStreaming, runSucceeded }) };
32
+ return { text: null, noteKey: missingResultNote({ runStreaming, runSucceeded }) };
24
33
  if (!result.content.trim())
25
- return { inputText, outputText: null, noteKey: result.isError ? 'Failed without an error message.' : 'Finished with no output.' };
26
- return { inputText, outputText: show(formatToolOutputForDisplay({ text: result.content })), noteKey: null };
34
+ return { text: null, noteKey: result.isError ? 'Failed without an error message.' : 'Finished with no output.' };
35
+ return { text: resultText({ result, resultPresentation }), noteKey: null };
36
+ }
37
+ /**
38
+ * The output text before redaction and the cap: the C130 plain-words sentence for a refused call on the
39
+ * display path, the formatted tool output otherwise. Copy-diagnostic mode skips only that substitution.
40
+ * @complexity O(n) in the result length.
41
+ */
42
+ function resultText({ result, resultPresentation }, _optional = {}) {
43
+ const plainWords = resultPresentation === 'display' && result.isError === true && isRefusedArgumentsError(result.content);
44
+ return plainWords ? REFUSED_ARGUMENTS_SENTENCE : formatToolOutputForDisplay({ text: result.content });
45
+ }
46
+ /**
47
+ * The tool server words a refused call for the model that made it ("invalid arguments for <tool>: change
48
+ * `path`: ..." plus the accepted-argument contract) so it can repair the call. That text is protocol, not
49
+ * something a person can act on, so the card says it in plain words; the model still receives the original.
50
+ */
51
+ const REFUSED_ARGUMENTS_PREFIX = 'invalid arguments for ';
52
+ const REFUSED_ARGUMENTS_SENTENCE = 'This step did not run because the assistant sent details the tool could not use. It usually corrects itself and tries again.';
53
+ function isRefusedArgumentsError(content) {
54
+ return content.trimStart().startsWith(REFUSED_ARGUMENTS_PREFIX);
27
55
  }
28
56
  /** Per-block cap for the text a collapsed row keeps mounted — see {@link describeCollapsedToolCall}. */
29
57
  export const COLLAPSED_DETAIL_MAX_CHARS = 400;
@@ -54,12 +82,7 @@ function serializeInput(input) {
54
82
  return null;
55
83
  if (typeof input === 'string')
56
84
  return formatToolOutputForDisplay({ text: input });
57
- try {
58
- return JSON.stringify(input, null, 2) ?? null;
59
- }
60
- catch {
61
- return null;
62
- }
85
+ return orFallbackSync({ work: () => JSON.stringify(input, null, 2) ?? null, fallback: null, step: 'Format tool input for display' });
63
86
  }
64
87
  function truncate(text, max) {
65
88
  return text.length <= max ? text : text.slice(0, max - 1) + '…';
@@ -1,4 +1,4 @@
1
- import type { AgentEvent } from './events.js';
1
+ import type { AgentEvent } from "@jini-ai/core/contracts/site/chat-core";
2
2
  /**
3
3
  * Drop repeated `tool_use` events that share an `id`. A retried/duplicated
4
4
  * stream can replay the same tool-call id (e.g. reconnect-and-replay landing
@@ -1,3 +1,4 @@
1
+ import { orFallbackSync } from '@jini-ai/core/errors/idioms';
1
2
  /**
2
3
  * Formats a tool result's text for a person to read. Tool results travel to the model as compact
3
4
  * JSON (`@jini-ai/mcp`'s `okResult` — indentation made nested results ~2.5× larger), so a view that
@@ -14,11 +15,6 @@ export function formatToolOutputForDisplay({ text }) {
14
15
  const first = trimmed[0];
15
16
  if (first !== '{' && first !== '[')
16
17
  return text;
17
- try {
18
- return JSON.stringify(JSON.parse(trimmed), null, 2);
19
- }
20
- catch {
21
- return text;
22
- }
18
+ return orFallbackSync({ work: () => JSON.stringify(JSON.parse(trimmed), null, 2), fallback: text, step: 'Format tool output for display' });
23
19
  }
24
20
  //# sourceMappingURL=tool-output.js.map
@@ -9,7 +9,8 @@
9
9
  * `@jini-ai/renderers-react`), not this framework-free package. See
10
10
  * archived provenance ledger.
11
11
  */
12
- import type { ToolResultEvent, ToolResultMediaBlock, ToolUseEvent } from './events.js';
12
+ import type { ToolResultEvent, ToolUseEvent } from './events.js';
13
+ import type { ToolResultMediaBlock } from "@jini-ai/core/contracts/site/chat-core";
13
14
  export { dedupeToolUsesById, foldDelegatedWrapperCalls, isDelegatedWrapperToolName } from './tool-events.js';
14
15
  /** The four-state tool-call lifecycle agreed across AG-UI / CopilotKit / LangGraph render props. */
15
16
  export type ToolStatus = 'inProgress' | 'executing' | 'complete' | 'error';
@@ -21,8 +21,8 @@
21
21
  * `ADS-memory/reports/jini-port/recon/r4b-webui-design.md` §2 for the target shape this
22
22
  * module implements verbatim.
23
23
  */
24
- import type { AgentEvent } from './events.js';
25
24
  import type { ChatAttachment, ChatMessage, ChatRunStatus } from './messages.js';
25
+ import type { AgentEvent } from "@jini-ai/core/contracts/site/chat-core";
26
26
  /**
27
27
  * Per-run event handlers a `ChatTransport` invokes as a run streams.
28
28
  * Mirrors `DaemonStreamHandlers` (`onAgentEvent`/`onToolInputDelta`) plus the
@@ -1,5 +1,5 @@
1
- import type { AgentEvent } from './events.js';
2
1
  import type { ChatMessage } from './messages.js';
2
+ import type { AgentEvent } from "@jini-ai/core/contracts/site/chat-core";
3
3
  type UsageEvent = Extract<AgentEvent, {
4
4
  kind: 'usage';
5
5
  }>;
@@ -119,6 +119,74 @@ function tailPrefixHoldback({ buffer, ranges }) {
119
119
  const slice = buffer.slice(tailLt);
120
120
  return OPEN_PREFIX.startsWith(slice) && slice.length < OPEN_PREFIX.length ? tailLt : -1;
121
121
  }
122
+ /** Emit text up to the next open tag; `true` when an artifact was opened and draining should continue. */
123
+ function* drainOutside(state) {
124
+ const open = findOpenTag(state.buffer);
125
+ const textEnd = open.kind === 'none' ? state.buffer.length : open.start;
126
+ if (textEnd > 0) {
127
+ yield { type: 'text', delta: state.buffer.slice(0, textEnd) };
128
+ state.buffer = state.buffer.slice(textEnd);
129
+ }
130
+ if (open.kind !== 'complete')
131
+ return false;
132
+ const attrs = parseQuotedAttrs({ raw: open.attrs });
133
+ Object.assign(state, {
134
+ inside: true,
135
+ identifier: attrs['identifier'] ?? '',
136
+ artifactType: attrs['type'] ?? '',
137
+ title: attrs['title'] ?? '',
138
+ content: '',
139
+ buffer: state.buffer.slice(open.end - open.start),
140
+ });
141
+ yield {
142
+ type: 'artifact:start',
143
+ identifier: state.identifier,
144
+ artifactType: state.artifactType,
145
+ title: state.title,
146
+ };
147
+ return true;
148
+ }
149
+ /** Emit body up to the close tag; `true` when the artifact closed and draining should continue. */
150
+ function* drainInside(state) {
151
+ const closeIdx = state.buffer.indexOf(CLOSE_TAG);
152
+ // Hold back enough bytes to detect a partial close tag at the tail.
153
+ const chunkEnd = closeIdx === -1 ? state.buffer.length - (CLOSE_TAG.length - 1) : closeIdx;
154
+ if (chunkEnd > 0) {
155
+ const chunk = state.buffer.slice(0, chunkEnd);
156
+ state.content += chunk;
157
+ state.buffer = state.buffer.slice(chunkEnd);
158
+ yield { type: 'artifact:chunk', identifier: state.identifier, delta: chunk };
159
+ }
160
+ if (closeIdx === -1)
161
+ return false;
162
+ yield { type: 'artifact:end', identifier: state.identifier, fullContent: state.content };
163
+ Object.assign(state, {
164
+ inside: false,
165
+ identifier: '',
166
+ artifactType: '',
167
+ title: '',
168
+ content: '',
169
+ buffer: state.buffer.slice(CLOSE_TAG.length),
170
+ });
171
+ return true;
172
+ }
173
+ /** End-of-stream: close an open artifact (emitting its buffered body) or emit the buffered text, then reset. */
174
+ function* flushState(state) {
175
+ const wasInside = state.inside;
176
+ if (wasInside) {
177
+ if (state.buffer.length > 0) {
178
+ state.content += state.buffer;
179
+ yield { type: 'artifact:chunk', identifier: state.identifier, delta: state.buffer };
180
+ state.buffer = '';
181
+ }
182
+ yield { type: 'artifact:end', identifier: state.identifier, fullContent: state.content };
183
+ }
184
+ if (!wasInside && state.buffer.length > 0) {
185
+ yield { type: 'text', delta: state.buffer };
186
+ }
187
+ state.buffer = '';
188
+ state.inside = false;
189
+ }
122
190
  /**
123
191
  * Create a fresh streaming artifact parser. Call `feed({ delta })` for each
124
192
  * chunk as it arrives (iterate its generator to drain queued events), and
@@ -142,77 +210,10 @@ export function createArtifactParser(_requiredArgs) {
142
210
  state.buffer += delta;
143
211
  let progressed = true;
144
212
  while (progressed && state.buffer.length > 0) {
145
- progressed = state.inside ? yield* drainInside() : yield* drainOutside();
146
- }
147
- }
148
- /** Emit text up to the next open tag; `true` when an artifact was opened and draining should continue. */
149
- function* drainOutside() {
150
- const open = findOpenTag(state.buffer);
151
- const textEnd = open.kind === 'none' ? state.buffer.length : open.start;
152
- if (textEnd > 0) {
153
- yield { type: 'text', delta: state.buffer.slice(0, textEnd) };
154
- state.buffer = state.buffer.slice(textEnd);
155
- }
156
- if (open.kind !== 'complete')
157
- return false;
158
- const attrs = parseQuotedAttrs({ raw: open.attrs });
159
- Object.assign(state, {
160
- inside: true,
161
- identifier: attrs['identifier'] ?? '',
162
- artifactType: attrs['type'] ?? '',
163
- title: attrs['title'] ?? '',
164
- content: '',
165
- buffer: state.buffer.slice(open.end - open.start),
166
- });
167
- yield {
168
- type: 'artifact:start',
169
- identifier: state.identifier,
170
- artifactType: state.artifactType,
171
- title: state.title,
172
- };
173
- return true;
174
- }
175
- /** Emit body up to the close tag; `true` when the artifact closed and draining should continue. */
176
- function* drainInside() {
177
- const closeIdx = state.buffer.indexOf(CLOSE_TAG);
178
- // Hold back enough bytes to detect a partial close tag at the tail.
179
- const chunkEnd = closeIdx === -1 ? state.buffer.length - (CLOSE_TAG.length - 1) : closeIdx;
180
- if (chunkEnd > 0) {
181
- const chunk = state.buffer.slice(0, chunkEnd);
182
- state.content += chunk;
183
- state.buffer = state.buffer.slice(chunkEnd);
184
- yield { type: 'artifact:chunk', identifier: state.identifier, delta: chunk };
185
- }
186
- if (closeIdx === -1)
187
- return false;
188
- yield { type: 'artifact:end', identifier: state.identifier, fullContent: state.content };
189
- Object.assign(state, {
190
- inside: false,
191
- identifier: '',
192
- artifactType: '',
193
- title: '',
194
- content: '',
195
- buffer: state.buffer.slice(CLOSE_TAG.length),
196
- });
197
- return true;
198
- }
199
- function* flush(_requiredArgs) {
200
- const wasInside = state.inside;
201
- if (wasInside) {
202
- if (state.buffer.length > 0) {
203
- state.content += state.buffer;
204
- yield { type: 'artifact:chunk', identifier: state.identifier, delta: state.buffer };
205
- state.buffer = '';
206
- }
207
- yield { type: 'artifact:end', identifier: state.identifier, fullContent: state.content };
208
- }
209
- if (!wasInside && state.buffer.length > 0) {
210
- yield { type: 'text', delta: state.buffer };
213
+ progressed = state.inside ? yield* drainInside(state) : yield* drainOutside(state);
211
214
  }
212
- state.buffer = '';
213
- state.inside = false;
214
215
  }
215
- return { feed, flush };
216
+ return { feed, flush: () => flushState(state) };
216
217
  }
217
218
  /**
218
219
  * Convenience wrapper over {@link createArtifactParser} for the common
@@ -0,0 +1,44 @@
1
+ import type { ChatPaneAgentControlOptions } from '../../react/features/chat-pane/types.js';
2
+ export interface InstallEmbedSendBridgeArgs {
3
+ readonly root: HTMLElement;
4
+ /** The mounted widget's own conversation owner; the bridge never sends on its own. */
5
+ readonly send: (input: {
6
+ text: string;
7
+ }, options?: Record<string, never>) => Promise<void>;
8
+ /** CustomEvent name the embedding page dispatches on `root` (host-chosen). */
9
+ readonly requestEventName: string;
10
+ /** `postMessage` type announced to the parent frame once the listener is ready (host-chosen). */
11
+ readonly readyMessageType: string;
12
+ /** Host decision: only opted-in embeddings get a listener; ordinary visitors get none. */
13
+ readonly enabled: boolean;
14
+ }
15
+ export interface EmbedSendBridgeOptions {
16
+ /** Sentence reported to a request that arrives while another one is in flight. */
17
+ readonly busyMessage?: string;
18
+ }
19
+ /**
20
+ * Lets an embedding page drive a mounted widget through native events. Each request uses the
21
+ * mounted widget's conversation owner; it never opens a parallel transport or edits its DOM.
22
+ * One in-flight request per pane prevents a double-click from starting duplicate runs.
23
+ * @complexity O(1) per request.
24
+ */
25
+ export declare function installEmbedSendBridge(args: InstallEmbedSendBridgeArgs, _optional?: EmbedSendBridgeOptions): () => void;
26
+ export interface CreateEmbedSendAgentControlArgs extends Pick<InstallEmbedSendBridgeArgs, 'requestEventName' | 'readyMessageType'> {
27
+ readonly root: HTMLElement | null;
28
+ readonly enabled: boolean;
29
+ /** Invocation id stamped on every relayed `chat.send_message` action (host-chosen). */
30
+ readonly invocationId: string;
31
+ }
32
+ export interface EmbedSendAgentControlOptions extends EmbedSendBridgeOptions {
33
+ /** Capability the relayed action targets; defaults to ChatPane's `chat.send_message`. */
34
+ readonly capabilityId?: string;
35
+ /** Rejection message for a send still in flight when the pane unmounts. */
36
+ readonly unmountedMessage?: string;
37
+ }
38
+ /**
39
+ * Adapts {@link installEmbedSendBridge} to ChatPane's opt-in agent-control bridge, so a React
40
+ * widget reuses its existing send capability; ordinary visitors (`enabled: false`) omit it.
41
+ * @complexity O(1) per relayed action.
42
+ */
43
+ export declare function createEmbedSendAgentControl(args: CreateEmbedSendAgentControlArgs, _optional?: EmbedSendAgentControlOptions): ChatPaneAgentControlOptions | undefined;
44
+ //# sourceMappingURL=embed-send-bridge.d.ts.map
@@ -0,0 +1,60 @@
1
+ const DEFAULT_BUSY_MESSAGE = 'This pane is already replying.';
2
+ /**
3
+ * Lets an embedding page drive a mounted widget through native events. Each request uses the
4
+ * mounted widget's conversation owner; it never opens a parallel transport or edits its DOM.
5
+ * One in-flight request per pane prevents a double-click from starting duplicate runs.
6
+ * @complexity O(1) per request.
7
+ */
8
+ export function installEmbedSendBridge(args, _optional = {}) {
9
+ const { root, send, requestEventName, readyMessageType, enabled } = args;
10
+ if (!enabled)
11
+ return () => { };
12
+ const busyMessage = _optional.busyMessage ?? DEFAULT_BUSY_MESSAGE;
13
+ let busy = false;
14
+ const listener = (event) => {
15
+ const request = event.detail;
16
+ if (!request || typeof request.text !== 'string' || typeof request.done !== 'function')
17
+ return;
18
+ if (busy) {
19
+ request.done(busyMessage);
20
+ return;
21
+ }
22
+ busy = true;
23
+ root.dispatchEvent(new (root.ownerDocument.defaultView.Event)('jini-chat-open'));
24
+ void Promise.resolve().then(() => send({ text: request.text })).then(() => request.done(), (error) => request.done(error instanceof Error ? error.message : String(error))).finally(() => { busy = false; });
25
+ };
26
+ root.addEventListener(requestEventName, listener);
27
+ root.dataset.compareReady = 'true';
28
+ const view = root.ownerDocument.defaultView;
29
+ view?.parent.postMessage({ type: readyMessageType }, view.location.origin);
30
+ return () => { root.removeEventListener(requestEventName, listener); delete root.dataset.compareReady; };
31
+ }
32
+ /**
33
+ * Adapts {@link installEmbedSendBridge} to ChatPane's opt-in agent-control bridge, so a React
34
+ * widget reuses its existing send capability; ordinary visitors (`enabled: false`) omit it.
35
+ * @complexity O(1) per relayed action.
36
+ */
37
+ export function createEmbedSendAgentControl(args, _optional = {}) {
38
+ const { root, enabled, invocationId, requestEventName, readyMessageType } = args;
39
+ if (!root || !enabled)
40
+ return undefined;
41
+ const capabilityId = _optional.capabilityId ?? 'chat.send_message';
42
+ const unmountedMessage = _optional.unmountedMessage ?? 'Embedded pane was unmounted.';
43
+ let pending = null;
44
+ return { enabled: true, bridgeAccess: {
45
+ subscribe: onAction => {
46
+ const dispose = installEmbedSendBridge({ root, enabled: true, requestEventName, readyMessageType, send: ({ text }) => new Promise((resolve, reject) => {
47
+ pending = { resolve, reject };
48
+ onAction({ invocationId, capabilityId, input: { prompt: text } });
49
+ }) }, _optional.busyMessage === undefined ? {} : { busyMessage: _optional.busyMessage });
50
+ return () => {
51
+ dispose();
52
+ pending?.reject(new Error(unmountedMessage));
53
+ pending = null;
54
+ };
55
+ },
56
+ respondSuccess: async () => { pending?.resolve(); pending = null; },
57
+ respondError: async (_id, message) => { pending?.reject(new Error(message)); pending = null; },
58
+ } };
59
+ }
60
+ //# sourceMappingURL=embed-send-bridge.js.map
@@ -0,0 +1,39 @@
1
+ /**
2
+ * @module agent-bridge/frontend-invocation-handler
3
+ *
4
+ * Invocation and result handling for the frontend session bridge: replay suppression, routing a
5
+ * relayed invocation to the chat pane or a local executor, and acknowledging its result. It owns
6
+ * no connection state; the bridge injects the answer functions and the shared work registries.
7
+ */
8
+ import type { ChatPaneAgentToolAction } from '../../react/features/chat-pane/types.js';
9
+ import type { FrontendSessionBridgeOptions } from './frontend-session-bridge.js';
10
+ /** The three ways this surface answers a daemon invocation. */
11
+ export interface InvocationResponder {
12
+ readonly respond: (invocationId: string, body: Record<string, unknown>) => Promise<void>;
13
+ readonly respondSuccess: (invocationId: string, output: unknown) => Promise<void>;
14
+ readonly respondError: (invocationId: string, message: string) => Promise<void>;
15
+ }
16
+ /** Everything one invocation needs from the bridge; none of it is owned here. */
17
+ export interface InvocationDeps {
18
+ readonly options: FrontendSessionBridgeOptions;
19
+ readonly responder: InvocationResponder;
20
+ readonly pending: Map<string, AbortController>;
21
+ readonly chatListeners: ReadonlySet<(action: ChatPaneAgentToolAction) => void>;
22
+ /** Replaces the page work queue's tail; the bridge owns the queue so park can reset it. */
23
+ readonly enqueuePage: (work: () => Promise<void>) => void;
24
+ }
25
+ /** The bridge's two invocation entry points, sharing one replay memory. */
26
+ export interface InvocationHandler {
27
+ /** Runs one well-formed relayed invocation: replay check, announcement, then serving. */
28
+ readonly handleInvocation: (action: ChatPaneAgentToolAction) => void;
29
+ /** Runs one run-delivered invocation, always claiming it through `runInvocations.begin` first. */
30
+ readonly acceptRunInvocation: (required: {
31
+ runId: string;
32
+ action: ChatPaneAgentToolAction;
33
+ }, optional?: Record<string, never>) => void;
34
+ }
35
+ /** Builds the invocation entry points: replay check, announcement, then serving (claimed for run delivery). */
36
+ export declare function createInvocationHandler({ deps }: {
37
+ deps: InvocationDeps;
38
+ }, _optional?: {}): InvocationHandler;
39
+ //# sourceMappingURL=frontend-invocation-handler.d.ts.map
@@ -0,0 +1,151 @@
1
+ /** How many settled invocation ids to remember for replay suppression. */
2
+ const EXECUTED_MEMORY = 256;
3
+ function errorMessage(error) {
4
+ return error instanceof Error ? error.message : String(error);
5
+ }
6
+ /** Freeze once, ask on the app's existing human-only channel, then use the same page executor.
7
+ * The server pauses its execution deadline only after acknowledging the bounded human wait. */
8
+ async function servePage({ action, signal, options, respond }) {
9
+ const input = options.preparePageInput ? options.preparePageInput({ action }) : structuredClone(action.input);
10
+ const args = { capabilityId: action.capabilityId, input };
11
+ if (options.pageApproval && !options.pageApproval.isDirect(args)) {
12
+ await respond(action.invocationId, { phase: 'approval-pending' });
13
+ signal.throwIfAborted();
14
+ const answer = await options.pageApproval.request({ ...args, input: structuredClone(input), signal });
15
+ signal.throwIfAborted();
16
+ // Report the decision before effects, including decline/expiry; the server audits it.
17
+ await respond(action.invocationId, { phase: 'execution-started', decision: answer.confirmed ? 'approved' : answer.reason });
18
+ if (!answer.confirmed)
19
+ return { executed: false, reason: answer.reason };
20
+ }
21
+ if (signal.aborted)
22
+ return { executed: false, reason: 'abandoned' };
23
+ return options.page.execute(args, { signal });
24
+ }
25
+ /** Runs the page driver or the prefix-matched product executor for one non-chat invocation. */
26
+ async function executeLocally({ action, signal, options, respond }) {
27
+ signal.throwIfAborted();
28
+ if (options.page !== undefined && action.capabilityId.startsWith('page.')) {
29
+ return servePage({ action, signal, options, respond });
30
+ }
31
+ const entry = Object.entries(options.executors ?? {})
32
+ .find(([prefix]) => action.capabilityId.startsWith(prefix));
33
+ if (entry === undefined)
34
+ throw new Error(`nothing on this page serves "${action.capabilityId}"`);
35
+ return entry[1](action.capabilityId, action.input);
36
+ }
37
+ async function acknowledge({ action, output, signal, options, respondSuccess }) {
38
+ try {
39
+ signal.throwIfAborted();
40
+ const projected = await options.onBeforeResponse?.({ action, output });
41
+ signal.throwIfAborted();
42
+ const acceptedOutput = projected ?? output;
43
+ await respondSuccess(action.invocationId, acceptedOutput);
44
+ signal.throwIfAborted();
45
+ await options.onAfterResponse?.({ action, output: acceptedOutput });
46
+ }
47
+ catch (error) {
48
+ options.onError?.(error);
49
+ }
50
+ }
51
+ /** Runs one non-chat invocation here and answers it. Chat ones go to the pane instead. */
52
+ async function serveLocally({ action, controller, deps }) {
53
+ const { options, responder, pending } = deps;
54
+ let output;
55
+ try {
56
+ output = await executeLocally({ action, signal: controller.signal, options, respond: responder.respond });
57
+ }
58
+ catch (error) {
59
+ pending.delete(action.invocationId);
60
+ if (controller.signal.aborted)
61
+ return;
62
+ await responder.respondError(action.invocationId, errorMessage(error)).catch(options.onError ?? (() => undefined));
63
+ return;
64
+ }
65
+ await acknowledge({ action, output, signal: controller.signal, options, respondSuccess: responder.respondSuccess });
66
+ pending.delete(action.invocationId);
67
+ }
68
+ function remember({ executed, invocationId }) {
69
+ executed.add(invocationId);
70
+ if (executed.size > EXECUTED_MEMORY) {
71
+ const oldest = executed.values().next().value;
72
+ if (oldest !== undefined)
73
+ executed.delete(oldest);
74
+ }
75
+ }
76
+ /** Registers one abortable serve; page work queues behind earlier page work, the rest runs now. */
77
+ function schedule({ action, deps, serve }) {
78
+ const controller = new AbortController();
79
+ deps.pending.set(action.invocationId, controller);
80
+ if (action.capabilityId.startsWith('page.')) {
81
+ deps.enqueuePage(() => serve(controller));
82
+ }
83
+ else
84
+ void serve(controller);
85
+ }
86
+ /** Hands an accepted invocation to the pane's listeners or to a local abortable serve. */
87
+ function dispatchAccepted({ action, deps }) {
88
+ if (action.capabilityId.startsWith('chat.')) {
89
+ for (const listener of deps.chatListeners)
90
+ listener(action);
91
+ return;
92
+ }
93
+ schedule({ action, deps, serve: (controller) => serveLocally({ action, controller, deps }) });
94
+ }
95
+ /**
96
+ * Registry-authenticated delivery chooses one browser, but delivery alone is not permission:
97
+ * `begin` must claim the invocation against the live binding before any effect. The claim uses
98
+ * the registry-minted invocation id — model tool IDs correlate transcripts and are not capabilities.
99
+ */
100
+ async function serveClaimed({ runId, action, controller, begin, deps }) {
101
+ let begun = false;
102
+ try {
103
+ begun = await begin({ runId, invocationId: action.invocationId, signal: controller.signal });
104
+ }
105
+ catch (error) {
106
+ deps.options.onError?.(error);
107
+ }
108
+ // Checked right after the claim and before the driver: a cancel during the claim retires it.
109
+ if (!begun || controller.signal.aborted) {
110
+ deps.pending.delete(action.invocationId);
111
+ return;
112
+ }
113
+ await serveLocally({ action, controller, deps });
114
+ }
115
+ /** Builds the invocation entry points: replay check, announcement, then serving (claimed for run delivery). */
116
+ export function createInvocationHandler({ deps }, _optional = {}) {
117
+ const { options, responder } = deps;
118
+ /** Invocation ids already run here, so a stream reconnect cannot double-click a button. */
119
+ const executed = new Set();
120
+ /** Replay check and announcement shared by both entry points; `false` means already answered. */
121
+ function admit(action) {
122
+ // A redelivery after a dropped answer must not re-run the side effect.
123
+ if (executed.has(action.invocationId)) {
124
+ void responder.respondError(action.invocationId, 'already executed on this surface').catch(() => undefined);
125
+ return false;
126
+ }
127
+ if (options.capabilityIds && !options.capabilityIds.includes(action.capabilityId)) {
128
+ void responder.respondError(action.invocationId, 'Capability unavailable').catch(() => undefined);
129
+ return false;
130
+ }
131
+ remember({ executed, invocationId: action.invocationId });
132
+ options.onInvocation?.(action);
133
+ return true;
134
+ }
135
+ return {
136
+ /** Runs one well-formed invocation: replay check, announcement, then pane or local serving. */
137
+ handleInvocation(action) {
138
+ if (admit(action))
139
+ dispatchAccepted({ action, deps });
140
+ },
141
+ acceptRunInvocation({ runId, action }, _opt = {}) {
142
+ const begin = options.runInvocations?.begin;
143
+ if (!begin)
144
+ throw new Error('Run-specific frontend delivery needs an injected begin');
145
+ if (!admit(action))
146
+ return;
147
+ schedule({ action, deps, serve: (controller) => serveClaimed({ runId, action, controller, begin, deps }) });
148
+ },
149
+ };
150
+ }
151
+ //# sourceMappingURL=frontend-invocation-handler.js.map
@@ -41,8 +41,25 @@ export interface FrontendSessionBridgeOptions {
41
41
  readonly onInvocation?: (action: ChatPaneAgentToolAction) => void;
42
42
  /** Reported for failures that are nobody's tool call: stream errors, malformed frames. */
43
43
  readonly onError?: (error: unknown) => void;
44
+ /**
45
+ * Opt-in run-specific delivery (`acceptRunInvocation`). `begin` is required within it: delivery
46
+ * alone is not permission, so an opted-in invocation never reaches a driver without a claim.
47
+ */
48
+ readonly runInvocations?: {
49
+ readonly begin: FrontendRunInvocationBegin;
50
+ };
44
51
  }
45
52
  /** The host supplies its origin and stream transport; native fetch defaults may be overridden. */
53
+ /**
54
+ * Claims one run-delivered invocation on the server before this surface acts on it. Resolves
55
+ * `true` only when the live binding granted the claim. Host composition supplies authentication
56
+ * and the request; this package never imports the server that answers it.
57
+ */
58
+ export type FrontendRunInvocationBegin = (required: {
59
+ runId: string;
60
+ invocationId: string;
61
+ signal: AbortSignal;
62
+ }, optional?: Record<string, never>) => Promise<boolean>;
46
63
  export interface FrontendSessionBridgeArgs {
47
64
  /** Pass an empty string for the same-origin proxy used by a browser host. */
48
65
  readonly baseUrl: string;
@@ -90,6 +107,17 @@ export interface FrontendSessionBridge {
90
107
  * after park, suspension, failure or {@link FrontendSessionBridge.close}. Read it at run-start.
91
108
  */
92
109
  bindToken(): string | undefined;
110
+ /**
111
+ * Executes one invocation the host received through run-specific delivery (for example an AG-UI
112
+ * tool call it projected into an action carrying the registry-minted invocation id). It reuses
113
+ * the page queue, executors, pending cancellation and response hooks, but always claims first.
114
+ * Throws when the bridge was built without `runInvocations`. Optional on the interface so hosts
115
+ * and fakes that implement the bridge without run-specific delivery stay source-compatible.
116
+ */
117
+ acceptRunInvocation?(required: {
118
+ runId: string;
119
+ action: ChatPaneAgentToolAction;
120
+ }, optional?: Record<string, never>): void;
93
121
  close(): void;
94
122
  }
95
123
  /**