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

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 (202) hide show
  1. package/CHANGELOG.md +2 -2
  2. package/README.md +3 -3
  3. package/dist/contracts/chat-bubble-style.d.ts +1 -1
  4. package/dist/contracts/chat-bubble-style.js +1 -1
  5. package/dist/core/ag-ui/event-projection.d.ts +125 -0
  6. package/dist/core/ag-ui/event-projection.js +275 -0
  7. package/dist/core/ag-ui/event-reduction.d.ts +39 -0
  8. package/dist/core/ag-ui/event-reduction.js +99 -0
  9. package/dist/core/ag-ui/run-input.d.ts +53 -0
  10. package/dist/core/ag-ui/run-input.js +87 -0
  11. package/dist/core/agentic/chat-capabilities.d.ts +1 -1
  12. package/dist/core/agentic/index.d.ts +2 -4
  13. package/dist/core/agentic/index.js +2 -3
  14. package/dist/core/agents-port.d.ts +50 -0
  15. package/dist/core/agents-port.js +2 -0
  16. package/dist/core/assistant-client/ag-ui-fetch-agent.d.ts +16 -0
  17. package/dist/core/assistant-client/ag-ui-fetch-agent.js +24 -0
  18. package/dist/core/assistant-client/ag-ui-transport.d.ts +15 -1
  19. package/dist/core/assistant-client/ag-ui-transport.js +167 -145
  20. package/dist/core/assistant-client/attachment-liveness.js +13 -11
  21. package/dist/core/assistant-client/durable-run-subscription.d.ts +3 -2
  22. package/dist/core/assistant-client/durable-run-subscription.js +6 -5
  23. package/dist/core/assistant-client/messages.d.ts +7 -4
  24. package/dist/core/assistant-client/messages.js +5 -4
  25. package/dist/core/assistant-client/transport.d.ts +1 -1
  26. package/dist/core/assistant-client/transport.js +4 -4
  27. package/dist/core/index.d.ts +2 -0
  28. package/dist/core/index.js +1 -0
  29. package/dist/core/page-port.d.ts +15 -0
  30. package/dist/core/page-port.js +2 -0
  31. package/dist/core/run-activity.js +1 -1
  32. package/dist/core/run-events/entry.js +1 -0
  33. package/dist/core/user-text-redaction.d.ts +1 -3
  34. package/dist/core/user-text-redaction.js +3 -61
  35. package/dist/embed-widget/browser/agent-inventory.d.ts +37 -0
  36. package/dist/embed-widget/browser/agent-inventory.js +36 -0
  37. package/dist/embed-widget/browser/frontend-session-bridge.d.ts +2 -2
  38. package/dist/embed-widget/browser/frontend-session-bridge.js +17 -14
  39. package/dist/embed-widget/react/dialog.hooks.d.ts +16 -0
  40. package/dist/embed-widget/react/dialog.hooks.js +15 -0
  41. package/dist/embed-widget/react/embed.d.ts +7 -2
  42. package/dist/embed-widget/react/embed.js +6 -16
  43. package/dist/embed-widget/react/header.d.ts +4 -1
  44. package/dist/embed-widget/react/header.js +2 -2
  45. package/dist/embed-widget/vanilla/state.js +2 -2
  46. package/dist/embed-widget/vanilla/style.css +4 -4
  47. package/dist/react/components/A2uiSurfaceCard.d.ts +18 -4
  48. package/dist/react/components/A2uiSurfaceCard.hooks.d.ts +36 -0
  49. package/dist/react/components/A2uiSurfaceCard.hooks.js +174 -0
  50. package/dist/react/components/A2uiSurfaceCard.js +14 -227
  51. package/dist/react/components/A2uiSurfaceCard.rules.d.ts +14 -0
  52. package/dist/react/components/A2uiSurfaceCard.rules.js +24 -0
  53. package/dist/react/components/AttachmentPreviewModal.d.ts +21 -1
  54. package/dist/react/components/AttachmentPreviewModal.hooks.js +1 -3
  55. package/dist/react/components/AttachmentPreviewModal.js +11 -9
  56. package/dist/react/components/AttachmentTray.d.ts +11 -1
  57. package/dist/react/components/AttachmentTray.js +12 -8
  58. package/dist/react/components/ChatFab.d.ts +10 -1
  59. package/dist/react/components/ChatFab.js +2 -2
  60. package/dist/react/components/ChatSettingsDialog.d.ts +4 -3
  61. package/dist/react/components/ChatSettingsDialog.js +9 -6
  62. package/dist/react/components/ChatSettingsSegmented.d.ts +1 -1
  63. package/dist/react/components/ChatSettingsSegmented.js +1 -1
  64. package/dist/react/components/Composer.d.ts +9 -1
  65. package/dist/react/components/Composer.hooks.d.ts +79 -0
  66. package/dist/react/components/Composer.hooks.js +336 -0
  67. package/dist/react/components/Composer.js +40 -341
  68. package/dist/react/components/ComposerDiscovery.js +1 -1
  69. package/dist/react/components/ConversationList.d.ts +34 -1
  70. package/dist/react/components/ConversationList.hooks.d.ts +37 -0
  71. package/dist/react/components/ConversationList.hooks.js +177 -1
  72. package/dist/react/components/ConversationList.js +7 -174
  73. package/dist/react/components/ConversationTitleEditor.d.ts +17 -2
  74. package/dist/react/components/ConversationTitleEditor.hooks.d.ts +15 -0
  75. package/dist/react/components/ConversationTitleEditor.hooks.js +36 -0
  76. package/dist/react/components/ConversationTitleEditor.js +11 -34
  77. package/dist/react/components/CopyMessageButton.d.ts +6 -1
  78. package/dist/react/components/CopyMessageButton.js +4 -4
  79. package/dist/react/components/ExtEventErrorBoundary.d.ts +2 -0
  80. package/dist/react/components/ExtEventErrorBoundary.js +5 -3
  81. package/dist/react/components/FolderChips.d.ts +11 -1
  82. package/dist/react/components/FolderChips.hooks.d.ts +12 -0
  83. package/dist/react/components/FolderChips.hooks.js +10 -0
  84. package/dist/react/components/FolderChips.js +9 -9
  85. package/dist/react/components/Markdown.js +7 -5
  86. package/dist/react/components/McpUiSurfaceCard.d.ts +29 -5
  87. package/dist/react/components/McpUiSurfaceCard.js +29 -16
  88. package/dist/react/components/MessageList.d.ts +10 -1
  89. package/dist/react/components/MessageList.hooks.js +4 -2
  90. package/dist/react/components/MessageList.js +12 -8
  91. package/dist/react/components/MessageRow.d.ts +46 -2
  92. package/dist/react/components/MessageRow.hooks.d.ts +60 -0
  93. package/dist/react/components/MessageRow.hooks.js +94 -0
  94. package/dist/react/components/MessageRow.js +53 -113
  95. package/dist/react/components/MidRunUserMessage.d.ts +6 -1
  96. package/dist/react/components/MidRunUserMessage.js +5 -5
  97. package/dist/react/components/NextStepActions.d.ts +3 -1
  98. package/dist/react/components/NextStepActions.js +3 -3
  99. package/dist/react/components/QuestionForm.answers.hooks.d.ts +26 -0
  100. package/dist/react/components/QuestionForm.answers.hooks.js +89 -0
  101. package/dist/react/components/QuestionForm.d.ts +6 -0
  102. package/dist/react/components/QuestionForm.js +23 -261
  103. package/dist/react/components/QuestionForm.values.d.ts +22 -0
  104. package/dist/react/components/QuestionForm.values.js +58 -0
  105. package/dist/react/components/QuestionFormField.d.ts +17 -0
  106. package/dist/react/components/QuestionFormField.js +114 -0
  107. package/dist/react/components/QuestionsPanel.d.ts +3 -1
  108. package/dist/react/components/QuestionsPanel.js +7 -3
  109. package/dist/react/components/SentAttachment.d.ts +11 -2
  110. package/dist/react/components/SentAttachment.hooks.d.ts +1 -1
  111. package/dist/react/components/SentAttachment.hooks.js +6 -5
  112. package/dist/react/components/SentAttachment.js +5 -3
  113. package/dist/react/components/TodoCard.d.ts +3 -1
  114. package/dist/react/components/TodoCard.js +9 -4
  115. package/dist/react/components/ToolCallGroup.d.ts +11 -1
  116. package/dist/react/components/ToolCallGroup.js +10 -4
  117. package/dist/react/components/ToolCard.d.ts +6 -1
  118. package/dist/react/components/ToolCard.js +79 -69
  119. package/dist/react/components/mcp-ui-question-input.d.ts +1 -1
  120. package/dist/react/components/mcp-ui-question-input.js +3 -3
  121. package/dist/react/components/mcp-ui-surface-state.d.ts +1 -1
  122. package/dist/react/features/chat-pane/agent-tools.d.ts +1 -1
  123. package/dist/react/features/chat-pane/antigravity/model-options.d.ts +2 -0
  124. package/dist/react/features/chat-pane/antigravity/model-options.js +2 -0
  125. package/dist/react/features/chat-pane/claude/model-options.d.ts +2 -0
  126. package/dist/react/features/chat-pane/claude/model-options.js +2 -0
  127. package/dist/react/features/chat-pane/codex/model-options.d.ts +2 -0
  128. package/dist/react/features/chat-pane/codex/model-options.js +2 -0
  129. package/dist/react/features/chat-pane/components/AgentPluginUsage.d.ts +4 -1
  130. package/dist/react/features/chat-pane/components/AgentPluginUsage.js +2 -2
  131. package/dist/react/features/chat-pane/components/AgentRuntimePicker.d.ts +10 -6
  132. package/dist/react/features/chat-pane/components/AgentRuntimePicker.js +18 -132
  133. package/dist/react/features/chat-pane/components/ChatPane.d.ts +24 -2
  134. package/dist/react/features/chat-pane/components/ChatPane.js +45 -297
  135. package/dist/react/features/chat-pane/components/ChatPaneComposerArea.d.ts +33 -0
  136. package/dist/react/features/chat-pane/components/ChatPaneComposerArea.js +119 -0
  137. package/dist/react/features/chat-pane/components/ChatPaneLayout.d.ts +42 -0
  138. package/dist/react/features/chat-pane/components/ChatPaneLayout.js +54 -0
  139. package/dist/react/features/chat-pane/components/ChatPaneStatus.d.ts +27 -0
  140. package/dist/react/features/chat-pane/components/ChatPaneStatus.js +91 -0
  141. package/dist/react/features/chat-pane/components/RuntimeDropUp.d.ts +6 -1
  142. package/dist/react/features/chat-pane/components/RuntimeDropUp.js +20 -19
  143. package/dist/react/features/chat-pane/components/RuntimePickerSections.d.ts +62 -0
  144. package/dist/react/features/chat-pane/components/RuntimePickerSections.js +122 -0
  145. package/dist/react/features/chat-pane/create-mcp-ui-tool-caller.d.ts +1 -1
  146. package/dist/react/features/chat-pane/hooks/useChatPane.hooks.d.ts +5 -3
  147. package/dist/react/features/chat-pane/hooks/useChatPane.hooks.js +78 -26
  148. package/dist/react/features/chat-pane/hooks/useChatPaneAgentControl.hooks.js +6 -6
  149. package/dist/react/features/chat-pane/hooks/useChatPaneFileDrop.hooks.d.ts +5 -1
  150. package/dist/react/features/chat-pane/hooks/useChatPaneFileDrop.hooks.js +7 -7
  151. package/dist/react/features/chat-pane/hooks/useRuntimeDropUp.hooks.d.ts +7 -0
  152. package/dist/react/features/chat-pane/hooks/useRuntimeDropUp.hooks.js +5 -0
  153. package/dist/react/features/chat-pane/model-options.js +7 -4
  154. package/dist/react/features/chat-pane/styles.d.ts +1 -1
  155. package/dist/react/features/chat-pane/styles.js +14 -14
  156. package/dist/react/features/chat-pane/types.d.ts +29 -1
  157. package/dist/react/hooks/assistant-chats-contracts.d.ts +1 -1
  158. package/dist/react/hooks/attachment-preview-cache.d.ts +1 -1
  159. package/dist/react/hooks/attachment-preview-cache.js +1 -1
  160. package/dist/react/hooks/fab-position.js +16 -18
  161. package/dist/react/hooks/useConversation.d.ts +6 -1
  162. package/dist/react/hooks/useConversation.js +11 -10
  163. package/dist/react/hooks/useRunStream.d.ts +3 -0
  164. package/dist/react/hooks/useRunStream.js +12 -12
  165. package/dist/react/hooks/useSurfaceRecovery.d.ts +1 -1
  166. package/dist/react/hooks/useSurfaceRecovery.js +2 -2
  167. package/dist/react/index.d.ts +6 -3
  168. package/dist/react/index.js +5 -3
  169. package/dist/react/styles/chat-settings.css +9 -9
  170. package/dist/react/surfaces.d.ts +91 -0
  171. package/dist/react/surfaces.js +28 -0
  172. package/dist/server/durable-runs/recover.d.ts +4 -3
  173. package/dist/server/durable-runs/recover.js +4 -3
  174. package/dist/store/legacy/sqlite/conversations.d.ts +1 -2
  175. package/dist/store/legacy/sqlite/conversations.js +1 -1
  176. package/dist/store/legacy/sqlite/messages.d.ts +2 -3
  177. package/dist/store/legacy/sqlite/messages.js +6 -6
  178. package/dist/store/pglite/index.d.ts +7 -7
  179. package/dist/store/pglite/index.js +1 -1
  180. package/dist/store/ports.d.ts +5 -2
  181. package/dist/store/postgres/index.d.ts +7 -7
  182. package/dist/store/postgres/index.js +1 -1
  183. package/dist/store/runtime/chat-expiry-sweep.js +2 -4
  184. package/dist/store/runtime/chat-history-store.js +2 -3
  185. package/dist/store/runtime/durable-run-store.js +16 -2
  186. package/dist/store/runtime/history-tools.js +33 -11
  187. package/dist/store/runtime/kernel.d.ts +3 -2
  188. package/dist/store/runtime/run-ledger.js +2 -2
  189. package/dist/store/sql/boundary.d.ts +5 -5
  190. package/dist/store/sql/maintenance.d.ts +3 -2
  191. package/dist/store/sql/store.d.ts +16 -8
  192. package/dist/store/sql/store.js +31 -14
  193. package/dist/store/sqlite/index.d.ts +11 -12
  194. package/dist/store/sqlite/index.js +5 -5
  195. package/dist/store/sqlite/schema.d.ts +1 -1
  196. package/package.json +49 -27
  197. package/dist/core/ag-ui/entry.d.ts +0 -84
  198. package/dist/core/ag-ui/entry.js +0 -225
  199. package/dist/core/browser/page-actions.d.ts +0 -121
  200. package/dist/core/browser/page-actions.js +0 -113
  201. package/dist/embed-widget/browser/page-actions.d.ts +0 -2
  202. package/dist/embed-widget/browser/page-actions.js +0 -3
@@ -1,3 +1,4 @@
1
+ import { type Logger } from '@jini-ai/core/primitives';
1
2
  import type { ChatMessage } from "../messages.js";
2
3
  import type { RunHandlers } from "../transport.js";
3
4
  import type { RunNotices } from "../run-events/entry.js";
@@ -38,8 +39,8 @@ export declare function followDurableRun({ runId: initialRunId, handlers, signal
38
39
  ports: DurableSubscriptionPorts;
39
40
  notices: RunNotices;
40
41
  bindings: Map<string, DurableRunBinding>;
41
- }, { logger }?: {
42
- logger?: Pick<Console, "info">;
42
+ }, { report }?: {
43
+ report?: Pick<Logger, "info">;
43
44
  }): () => void;
44
45
  export {};
45
46
  //# sourceMappingURL=durable-run-subscription.d.ts.map
@@ -1,8 +1,9 @@
1
+ import { createConsoleLogger } from '@jini-ai/core/primitives';
1
2
  import { translateRunFrame } from "../run-events/entry.js";
2
3
  /** SSE is a view of one attempt. The saved message owns terminal state and can point at a new
3
4
  * attempt after recovery; neither a browser 404 nor a closed stream may fail the logical run.
4
5
  * An explicit "gone" result ends observation and releases the caller's streaming state. */
5
- export function followDurableRun({ runId: initialRunId, handlers, signal, binding, ports, notices, bindings }, { logger = console } = {}) {
6
+ export function followDurableRun({ runId: initialRunId, handlers, signal, binding, ports, notices, bindings }, { report = createConsoleLogger({ prefix: '' }) } = {}) {
6
7
  let streamEpoch = 0;
7
8
  let runId = initialRunId;
8
9
  let cursor = "";
@@ -36,12 +37,12 @@ export function followDurableRun({ runId: initialRunId, handlers, signal, bindin
36
37
  stopStream = ports.stream({ runId, cursor,
37
38
  frame: (...args) => { if (epoch === streamEpoch)
38
39
  frame(...args); },
39
- dropped: reason => { if (epoch === streamEpoch)
40
- disconnected(reason); },
40
+ dropped: () => { if (epoch === streamEpoch)
41
+ disconnected(); },
41
42
  }, {});
42
43
  }
43
44
  /** One timer owns reconnects, including faults during a checkpoint read. No cursor reset. */
44
- function disconnected(reason = "stream-error") {
45
+ function disconnected() {
45
46
  if (stopped || dropped)
46
47
  return;
47
48
  dropped = true;
@@ -49,7 +50,7 @@ export function followDurableRun({ runId: initialRunId, handlers, signal, bindin
49
50
  recoveryPending = true;
50
51
  reconnectDelayMs = Math.min(30_000, Math.max(1_000, reconnectDelayMs * 2));
51
52
  // Metadata only: neither frame contents nor saved user messages belong in transport logs.
52
- logger.info("[durable-subscription] " + JSON.stringify({ runId, reason, cursor, retryDelayMs: reconnectDelayMs }));
53
+ report.info({ message: "[durable-subscription] Stream disconnected; retrying." }, { meta: { runId, cursor, retryDelayMs: reconnectDelayMs } });
53
54
  stopStream?.();
54
55
  if (!reading)
55
56
  scheduleRead();
@@ -8,7 +8,8 @@ export interface AssistantConversation {
8
8
  updatedAt: number;
9
9
  }
10
10
  /**
11
- * The subset of a live transcript that is worth writing: accepted user turns, and assistant turns whose run
11
+ * The subset of a live transcript that is worth writing: accepted user turns (or pending ones when
12
+ * the host opts in), and assistant turns whose run
12
13
  * has reached a terminal status.
13
14
  *
14
15
  * An assistant message that is still `queued` or `running` is rewritten on every delta, so
@@ -26,8 +27,10 @@ export interface AssistantConversation {
26
27
  * Deleting them here would trade a history bug for a forensics hole.
27
28
  */
28
29
  export declare function persistableMessages({ messages }: {
29
- messages: ChatMessage[];
30
- }, _options?: Record<string, never>): ChatMessage[];
30
+ messages: readonly ChatMessage[];
31
+ }, { includePendingUser }?: {
32
+ includePendingUser?: boolean;
33
+ }): ChatMessage[];
31
34
  /**
32
35
  * The key the admin's chat writers use to remember "this message is already saved": the message id,
33
36
  * plus the run id when there is one.
@@ -59,7 +62,7 @@ export declare function messageWriteKey({ message }: {
59
62
  * race — recording ITS id as "the current run" would point a future reattach at the wrong turn.
60
63
  *
61
64
  * `saveMessage`'s server-side route upserts by message id (`ON CONFLICT(id) DO UPDATE`,
62
- * `Jini/packages/sqlite`'s `chat-history/store.ts`), so this stub write and the message's eventual
65
+ * `packages/chat/src/store/sql/store.ts`), so this stub write and the message's eventual
63
66
  * terminal-state write (through the normal {@link persistableMessages} path) converge on the same
64
67
  * row rather than creating two — the terminal write simply overwrites `run_status`/`content`/
65
68
  * `events_json` in place once the run settles.
@@ -1,6 +1,7 @@
1
1
  import { isTerminalRunStatus } from "../messages.js";
2
2
  /**
3
- * The subset of a live transcript that is worth writing: accepted user turns, and assistant turns whose run
3
+ * The subset of a live transcript that is worth writing: accepted user turns (or pending ones when
4
+ * the host opts in), and assistant turns whose run
4
5
  * has reached a terminal status.
5
6
  *
6
7
  * An assistant message that is still `queued` or `running` is rewritten on every delta, so
@@ -17,8 +18,8 @@ import { isTerminalRunStatus } from "../messages.js";
17
18
  * side instead — see `assistant-transport.ts`'s `historyForTranscript`/`isAnsweredAssistantTurn`.
18
19
  * Deleting them here would trade a history bug for a forensics hole.
19
20
  */
20
- export function persistableMessages({ messages }, _options = {}) {
21
- return messages.filter((message) => message.role === "user" ? !message.inputPending : isTerminalRunStatus({ status: message.runStatus }));
21
+ export function persistableMessages({ messages }, { includePendingUser = false } = {}) {
22
+ return messages.filter((message) => message.role === "user" ? includePendingUser || !message.inputPending : isTerminalRunStatus({ status: message.runStatus }));
22
23
  }
23
24
  /**
24
25
  * The key the admin's chat writers use to remember "this message is already saved": the message id,
@@ -51,7 +52,7 @@ export function messageWriteKey({ message }, _options = {}) {
51
52
  * race — recording ITS id as "the current run" would point a future reattach at the wrong turn.
52
53
  *
53
54
  * `saveMessage`'s server-side route upserts by message id (`ON CONFLICT(id) DO UPDATE`,
54
- * `Jini/packages/sqlite`'s `chat-history/store.ts`), so this stub write and the message's eventual
55
+ * `packages/chat/src/store/sql/store.ts`), so this stub write and the message's eventual
55
56
  * terminal-state write (through the normal {@link persistableMessages} path) converge on the same
56
57
  * row rather than creating two — the terminal write simply overwrites `run_status`/`content`/
57
58
  * `events_json` in place once the run settles.
@@ -43,7 +43,7 @@ export interface AssistantTransportOptions {
43
43
  * agentId this set contains: "the caller trusts this adapter's CLI to carry its own multi-turn
44
44
  * conversation memory... and should skip resending the rendered transcript on follow-up turns"
45
45
  * (`types.ts`). Resending it anyway would duplicate everything the daemon's own `--resume`/
46
- * `session/load` already restores (`agent-session-resume.ts`).
46
+ * `session/load` already restores (`packages/daemon/src/session-coordination.ts`).
47
47
  *
48
48
  * Read fresh on every `startRun` call, same "never captured" convention {@link getExecutionConfig}/
49
49
  * {@link getAgUiEnabled} already establish: the admin's own `/api/agents` probe resolves
@@ -10,20 +10,20 @@ export function createAssistantTransportClient({ ports }, _options = {}) {
10
10
  const terminalReasonNotice = (reason) => runEvents.terminalReasonNotice({ reason, notice: ports.notices.toolStepLimit }, {});
11
11
  const translateRunAgentPayload = (payload) => runEvents.translateRunAgentPayload({ payload }, {});
12
12
  /**
13
- * Shared HTTP implementation of `@jini-ai/chat/react`'s `ChatTransport` port (originally ADR-049).
13
+ * Shared HTTP implementation of `@jini-ai/chat/react`'s `ChatTransport` port.
14
14
  *
15
15
  * TWO run paths live here, selected per-turn by `getExecutionConfig()` (see
16
16
  * `createAssistantTransport`'s own doc):
17
17
  *
18
18
  * 1. **Local CLI** (the original, unchanged path): binds to the real `@jini-ai/http` run surface
19
- * `src/server/modules/assistant.ts` mounts — `POST /api/runs` to start, `GET
19
+ * the host app's `src/server/runtime/composition/modules/assistant.ts` mounts — `POST /api/runs` to start, `GET
20
20
  * /api/runs/:runId/events` (native `EventSource`) to stream, `GET /api/runs/:runId` for status,
21
21
  * `POST /api/runs/:runId/cancel` to stop. Every SSE frame's `data` is a full `@jini-ai/protocol`
22
22
  * `RunProtocolEvent` (`{kind, payload, ...}`), not chat-core's own `AgentEvent` — chat-core's own
23
23
  * module doc is explicit that this reduction is a transport concern ("a host's transport adapter
24
24
  * is responsible for reducing wire deltas... into the persisted/renderable AgentEvent items"), so
25
25
  * `translateRunAgentPayload` below does that translation.
26
- * 2. **API · BYOK** (2026-08-04, ADR-049's picker): binds to `src/server/modules/assistant-byok.ts`'s
26
+ * 2. **API · BYOK** (2026-08-04, the execution picker): binds to the host app's `src/server/runtime/composition/modules/assistant-byok.ts`'s
27
27
  * `POST /api/admin/v1/assistant/byok-turn` — one request/response holding the WHOLE turn open,
28
28
  * no separate `EventSource`/reattach/cancel-by-runId (see that route's own header for why, and
29
29
  * what it costs). Its SSE frames carry the SAME `payload.type` vocabulary
@@ -454,7 +454,7 @@ export function createAssistantTransportClient({ ports }, _options = {}) {
454
454
  * (`AssistantDock.tsx` supplies it from the live `FrontendSessionBridge`).
455
455
  *
456
456
  * Read by name rather than spreading the whole `input.context` blob: `contextRef` is a shared
457
- * envelope that the host's proxy also writes `principalId` into (`src/server/modules/assistant.ts`),
457
+ * envelope that the host's proxy also writes `principalId` into (the host app's `src/server/runtime/composition/modules/assistant.ts`),
458
458
  * and a spread would let any future `runContext` key silently shadow it — an identity field being
459
459
  * overwritten by a UI prop is not a failure mode worth leaving open to save one line.
460
460
  *
@@ -40,4 +40,6 @@ export { formatUsageCost } from './usage-format.js';
40
40
  export * from './accepted-input.js';
41
41
  export * from './question-answer.js';
42
42
  export { checkpointIntervalMs, checkpointProgress } from './checkpoint-interval.js';
43
+ export type { ChatAgentFailurePort, ChatAgentPolicyPort } from './agents-port.js';
44
+ export { persistableMessages } from "./assistant-client/messages.js";
43
45
  //# sourceMappingURL=index.d.ts.map
@@ -39,4 +39,5 @@ export { formatUsageCost } from './usage-format.js';
39
39
  export * from './accepted-input.js';
40
40
  export * from './question-answer.js';
41
41
  export { checkpointIntervalMs, checkpointProgress } from './checkpoint-interval.js';
42
+ export { persistableMessages } from "./assistant-client/messages.js";
42
43
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @file The page-capability runtime port: chat only forwards page-control requests, it never calls driver
3
+ * methods. The host binds the implementation (a DOM driver, a native shell, a test fake) once.
4
+ */
5
+ export interface ChatPagePort {
6
+ /** Ids of the page capabilities the host can execute. */
7
+ readonly capabilityIds: readonly string[];
8
+ execute(required: {
9
+ capabilityId: string;
10
+ input: Record<string, unknown>;
11
+ }, optional?: {
12
+ signal?: AbortSignal;
13
+ }): Promise<unknown>;
14
+ }
15
+ //# sourceMappingURL=page-port.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=page-port.js.map
@@ -17,7 +17,7 @@
17
17
  * - `code: 'tool_progress'`, `data: { elapsedSeconds }` — a tool call is still running.
18
18
  * - `code: 'thinking'` — the model is reasoning (keeps the idle timer honest).
19
19
  */
20
- import { a2uiSurfaceIdOf, displayOnlySurfaceIdOf } from '@jini-ai/agentic/a2ui';
20
+ import { a2uiSurfaceIdOf, displayOnlySurfaceIdOf } from '@jini-ai/protocol/a2ui';
21
21
  import { isDelegatedWrapperToolName } from './tool-events.js';
22
22
  import { MID_RUN_USER_MESSAGE_EVENT_NAME } from './turn-usage.js';
23
23
  import { SURFACE_QUESTION_META_KEY } from './question-answer.js';
@@ -151,6 +151,7 @@ function translateEnvelopePayload(payload) {
151
151
  // `examples/reference-web/src/daemon-transport.ts`.
152
152
  case "a2ui":
153
153
  return { kind: "ext", name: "a2ui", data: payload.message };
154
+ // The wire has `thinking_start` alone. Drop it to preserve the existing reduction across transports.
154
155
  case "thinking_start":
155
156
  return null;
156
157
  // Streamed tool input (with `--include-partial-messages`): the finished `tool_use` carries the
@@ -18,9 +18,7 @@ export interface UserTextRedactionOptions {
18
18
  }
19
19
  export declare const SECRET_REDACTED_NOTICE = "I removed what looked like a key from your message. If it was real, rotate it. Use the secure form to save it.";
20
20
  export declare const CREDENTIAL_CARD_GUIDANCE = "Use the secure form to save keys, tokens, passwords, and secrets. Chat answers are sent to the assistant.";
21
- /** Stricter than error redaction: also detects unlabelled long tokens, while retaining ordinary URLs,
22
- * filesystem paths, hexadecimal hashes, identifiers and prose. Strong credential syntax inside
23
- * URLs or paths is still caught. */
21
+ /** Masks recognisable secrets only (shared rules plus the chat rules above); paths, file names, ids and prose stay as typed. */
24
22
  export declare function redactUserText({ text }: {
25
23
  readonly text: string;
26
24
  }, { secretField }?: {
@@ -8,44 +8,13 @@ const REDACTION_MARKER = /\[REDACTED:[^\]\r\n]+\]/g;
8
8
  const CHAT_RULES = [
9
9
  { kind: 'chat_key', pattern: /(?<![A-Za-z0-9_-])sk-[A-Za-z0-9_-]{16,}/g, replacement: () => INTERNAL_REMOVED },
10
10
  // Kept on top of the shared Slack rule: that rule refuses a token preceded by `-` (e.g. a URL path
11
- // segment `/-xoxb-…`) and the entropy fallback below exempts URLs, so without this rule such a token
11
+ // segment `/-xoxb-…`), so without this rule such a token
12
12
  // would reach storage and model history. Only drop it once the shared rule covers that case.
13
13
  { kind: 'chat_key', pattern: /(?<!\w)xox[baprs]-[A-Za-z0-9-]{16,}/g, replacement: () => INTERNAL_REMOVED },
14
14
  // Explicit authorization syntax catches even short values. Exempt scheme descriptions in prose.
15
15
  { kind: 'chat_bearer', pattern: /\bBearer[ \t]+(?!\[REDACTED)(?!(?:token|tokens|authentication|authorization|auth|scheme|credentials?)\b)[\w.~+\/=-]+/gi, replacement: () => 'Bearer ' + INTERNAL_REMOVED },
16
16
  ];
17
- function entropy(text) {
18
- const counts = new Map();
19
- for (const char of text)
20
- counts.set(char, (counts.get(char) ?? 0) + 1);
21
- let bits = 0;
22
- for (const count of counts.values()) {
23
- const probability = count / text.length;
24
- bits -= probability * Math.log2(probability);
25
- }
26
- return bits;
27
- }
28
- /** Recognize identifier paths, including the fragment after a space in a typed path.
29
- * Require multiple segments and readable words: arbitrary base64 and long digit-mixed runs
30
- * must still reach the entropy guard. Specific credential rules have already run. */
31
- function isIdentifierPath({ text }, _options = {}) {
32
- const segments = text.replace(/^(?:[a-z]:|~)?[\\/]*/i, '').split(/[\\/]/).filter(Boolean);
33
- return segments.length >= 2 && segments.every(segment => /^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(segment)
34
- || segment.split(/[-_.]/).every(word => /^[A-Z]$/.test(word)
35
- || /^[A-Z]?[a-z]{2,}(?:[A-Z][a-z]{2,}|[0-9]{1,4}(?=[A-Z][a-z]{2,}|$))*$/.test(word)));
36
- }
37
- /** A piece of a random key: long, both letter cases, and a character-class change at most positions.
38
- * Readable names (CamelCase, SCREAMING_CASE, dated file names) change class far less often, and
39
- * every piece of a 40-character base64 key split by '/' is 12+ characters in most keys. */
40
- function isOpaqueSegment(segment) {
41
- if (segment.length < 12 || !/[A-Z]/.test(segment) || !/[a-z]/.test(segment))
42
- return false;
43
- const changes = segment.match(/[A-Z](?=[^A-Z])|[a-z](?=[^a-z])|\d(?=\D)/g)?.length ?? 0;
44
- return changes / (segment.length - 1) >= 0.4;
45
- }
46
- /** Stricter than error redaction: also detects unlabelled long tokens, while retaining ordinary URLs,
47
- * filesystem paths, hexadecimal hashes, identifiers and prose. Strong credential syntax inside
48
- * URLs or paths is still caught. */
17
+ /** Masks recognisable secrets only (shared rules plus the chat rules above); paths, file names, ids and prose stay as typed. */
49
18
  export function redactUserText({ text }, { secretField = false } = {}) {
50
19
  // Existing removal markers must survive a second pass through assignment rules (api_key=…).
51
20
  const literalMarkers = new Map();
@@ -59,34 +28,7 @@ export function redactUserText({ text }, { secretField = false } = {}) {
59
28
  }).replaceAll(REMOVED, INTERNAL_REMOVED);
60
29
  const base = redactSecretShapes({ text: protectedText, policy: { additionalRules: CHAT_RULES } });
61
30
  let count = base.redactions;
62
- // Exempt locations only AFTER specific secret rules. Only quoted paths may contain whitespace;
63
- // unquoted paths and URLs end there, and at , | ; and invisible separators, so an adjacent
64
- // secret glued after them cannot inherit the exemption.
65
- // A quoted path ends at its first matching quote, which must sit on a word boundary, so an
66
- // apostrophe later in the line ("don't") cannot close an unterminated quote and exempt the gap.
67
- // Require a root boundary so a slash inside an opaque token cannot exempt that token, and a
68
- // folder after the root so a bare "/" + token is not mistaken for a path.
69
- const locations = [
70
- ...[...base.text.matchAll(/\b[a-z][a-z0-9+.-]*:\/\/[^\s<>"'`,|;\u200B-\u200D\uFEFF]+|(?<!\w)(["'`])(?:~\/|[a-z]:[\\/]|\\\\|\/)[^\r\n"'`\\/]+[\\/](?:(?!\1)[^\r\n])*\1(?!\w)|(?<![\w+\/=\\~.-])(?:~\/|[a-z]:[\\/]|\\\\|\/)[^\s<>"'`,|;\u200B-\u200D\uFEFF\\/]+[\\/][^\s<>"'`,|;\u200B-\u200D\uFEFF]*/gi)]
71
- .map(match => ({ match, url: /^[a-z][a-z0-9+.-]*:\/\//i.test(match[0]) })),
72
- // The part of a hand-typed unquoted path after a space (Work/CustomerPortal…) has no root.
73
- ...[...base.text.matchAll(/[^\s<>"'`,|;\u200B-\u200D\uFEFF]+/g)]
74
- .filter(match => isIdentifierPath({ text: match[0] })).map(match => ({ match, url: false })),
75
- ].map(({ match, url }) => ({ start: match.index, end: match.index + match[0].length, url }));
76
- let cleaned = base.text.replace(/(?<![A-Za-z0-9_+\/=-])[A-Za-z0-9_+\/=-]{40,}(?![A-Za-z0-9_+\/=-])/g, (candidate, offset) => {
77
- const location = locations.find(span => offset >= span.start && offset + candidate.length <= span.end);
78
- // A key glued straight onto a path (/proj/KEY) is still checked; URLs keep their opaque ids.
79
- if (location && (location.url || !candidate.split(/[\\/]/).some(isOpaqueSegment)))
80
- return candidate;
81
- if (/^[a-f0-9]+$/i.test(candidate) || !/[A-Za-z]/.test(candidate))
82
- return candidate;
83
- const bits = entropy(candidate);
84
- const mixedAlphabet = /[A-Z]/.test(candidate) && /[a-z]/.test(candidate);
85
- if (bits < 4 || (!/\d/.test(candidate) && (!mixedAlphabet || bits < 4.5)))
86
- return candidate;
87
- count += 1;
88
- return INTERNAL_REMOVED;
89
- });
31
+ let cleaned = base.text;
90
32
  // A labelled credential answer can be a short password with no recognisable shape at all.
91
33
  if (secretField && cleaned.trim() !== '' && cleaned !== INTERNAL_REMOVED) {
92
34
  cleaned = INTERNAL_REMOVED;
@@ -0,0 +1,37 @@
1
+ /**
2
+ * @file Last-known agent inventory as an instant placeholder.
3
+ *
4
+ * A host that lists agents from a slow source (a cold daemon re-probing installed CLIs) can show the
5
+ * last live answer this browser saw instead of an empty picker, and swap it for the live list the
6
+ * moment that resolves. The last live answer is the same machine's own probe result, usually still
7
+ * exact, whereas a list bundled into the client would be a hand-maintained duplicate of the server's
8
+ * registry that drifts.
9
+ *
10
+ * Every storage access is fail-soft: browser storage throws in some privacy modes and on quota
11
+ * exhaustion, and a missing placeholder only costs the host's normal loading state.
12
+ */
13
+ import type { SessionStoragePort } from './session-store.js';
14
+ /** The fields a stored entry must carry to be trusted; hosts may store richer entries. */
15
+ export interface AgentInventoryEntry {
16
+ readonly id: string;
17
+ readonly name: string;
18
+ }
19
+ export interface AgentInventorySnapshot<T extends AgentInventoryEntry> {
20
+ /** The last stored inventory, or `undefined` when there is none, it is empty, or it is unreadable. */
21
+ read(args: Record<string, never>): readonly T[] | undefined;
22
+ /** Stores a live inventory. An empty list is not stored: it would replace a useful placeholder with
23
+ * one that shows nothing. Silent no-op on any storage failure. */
24
+ write(args: {
25
+ agents: readonly T[];
26
+ }): void;
27
+ }
28
+ export interface AgentInventorySnapshotArgs {
29
+ readonly storage: Pick<SessionStoragePort, 'getItem' | 'setItem'>;
30
+ /** Version the key so a later change to the stored shape ignores old entries instead of misreading them. */
31
+ readonly key: string;
32
+ }
33
+ /** @complexity read/write O(n) in stored agents. */
34
+ export declare function createAgentInventorySnapshot<T extends AgentInventoryEntry>({ storage, key }: AgentInventorySnapshotArgs, _optional?: {
35
+ readonly [K in never]?: never;
36
+ }): AgentInventorySnapshot<T>;
37
+ //# sourceMappingURL=agent-inventory.d.ts.map
@@ -0,0 +1,36 @@
1
+ function isEntryShape(value) {
2
+ if (typeof value !== 'object' || value === null)
3
+ return false;
4
+ const candidate = value;
5
+ return typeof candidate.id === 'string' && typeof candidate.name === 'string';
6
+ }
7
+ /** @complexity read/write O(n) in stored agents. */
8
+ export function createAgentInventorySnapshot({ storage, key }, _optional = {}) {
9
+ return {
10
+ read: () => {
11
+ try {
12
+ const raw = storage.getItem(key);
13
+ if (!raw)
14
+ return undefined;
15
+ const parsed = JSON.parse(raw);
16
+ if (!Array.isArray(parsed) || parsed.length === 0 || !parsed.every(isEntryShape))
17
+ return undefined;
18
+ return parsed;
19
+ }
20
+ catch {
21
+ return undefined;
22
+ }
23
+ },
24
+ write: ({ agents }) => {
25
+ if (agents.length === 0)
26
+ return;
27
+ try {
28
+ storage.setItem(key, JSON.stringify(agents));
29
+ }
30
+ catch {
31
+ // Best-effort: the live list is already on screen; only the next cold load loses its placeholder.
32
+ }
33
+ },
34
+ };
35
+ }
36
+ //# sourceMappingURL=agent-inventory.js.map
@@ -1,4 +1,4 @@
1
- import { type PageDriver } from '@jini-ai/agentic';
1
+ import type { ChatPagePort } from '../../core/page-port.js';
2
2
  import type { ApprovalAnswer } from '@jini-ai/core';
3
3
  import type { ChatPaneAgentToolAction, ChatPaneAgentBridgeAccess } from '../../react/features/chat-pane/types.js';
4
4
  export interface FrontendSessionBridgeOptions {
@@ -31,7 +31,7 @@ export interface FrontendSessionBridgeOptions {
31
31
  }): Promise<ApprovalAnswer>;
32
32
  };
33
33
  /** Supplying one claims the six `page.*` verbs. Omit for a chat-only surface. */
34
- readonly pageDriver?: PageDriver;
34
+ readonly page?: ChatPagePort;
35
35
  /**
36
36
  * Product capabilities, keyed by id prefix (`'cms.'`). Each claims every capability under it.
37
37
  * This is how a consumer exposes verbs the engine has never heard of.
@@ -18,7 +18,7 @@ import { decodeSseFrames } from '@jini-ai/core/primitives';
18
18
  * control dies when the pane unmounts — and the page is drivable whether or not a chat pane
19
19
  * exists. `subscribe` registers a listener; `close()` tears the connection down.
20
20
  * - **Capabilities are claimed from what is actually wired.** The claim sent at connect time is
21
- * derived from the presence of a `pageDriver` and the keys of `executors`, never from a static
21
+ * derived from the presence of a `page` port and the keys of `executors`, never from a static
22
22
  * list. A surface that claims what it cannot serve turns a fast, named refusal into a timeout.
23
23
  * - **An executed invocation is never executed twice.** If the stream drops between the daemon
24
24
  * delivering an invocation and this page POSTing the answer, the daemon correctly fails that
@@ -36,7 +36,6 @@ import { decodeSseFrames } from '@jini-ai/core/primitives';
36
36
  * belongs in a run request. Park/failure closes the transport; hosts explicitly rebind after wake.
37
37
  */
38
38
  import { CHAT_CAPABILITIES } from '../../core/index.js';
39
- import { PAGE_CAPABILITIES, executePageCapability } from '@jini-ai/agentic';
40
39
  /** How many settled invocation ids to remember for replay suppression. */
41
40
  const EXECUTED_MEMORY = 256;
42
41
  /** Ids this surface can actually serve, given what the host wired up. */
@@ -44,8 +43,8 @@ function claimedCapabilities(options) {
44
43
  if (options.capabilityIds)
45
44
  return [...options.capabilityIds];
46
45
  const claims = CHAT_CAPABILITIES.map((capability) => capability.id);
47
- if (options.pageDriver !== undefined) {
48
- claims.push(...PAGE_CAPABILITIES.map((capability) => capability.id));
46
+ if (options.page !== undefined) {
47
+ claims.push(...options.page.capabilityIds);
49
48
  }
50
49
  // Dialog-support handshake only; page.approval is not an executable tool id.
51
50
  if (options.pageApproval)
@@ -206,14 +205,14 @@ export function createFrontendSessionBridge({ baseUrl: base, openStream, request
206
205
  }
207
206
  if (signal.aborted)
208
207
  return { executed: false, reason: 'abandoned' };
209
- return executePageCapability({ driver: options.pageDriver, ...args }, { signal });
208
+ return options.page.execute(args, { signal });
210
209
  }
211
210
  /** Runs one non-chat invocation here and answers it. Chat ones go to the pane instead. */
212
211
  async function serveLocally(action, controller) {
213
212
  let output;
214
213
  try {
215
214
  controller.signal.throwIfAborted();
216
- if (options.pageDriver !== undefined && action.capabilityId.startsWith('page.')) {
215
+ if (options.page !== undefined && action.capabilityId.startsWith('page.')) {
217
216
  output = await servePage(action, controller.signal);
218
217
  }
219
218
  else {
@@ -282,6 +281,17 @@ export function createFrontendSessionBridge({ baseUrl: base, openStream, request
282
281
  else
283
282
  void serveLocally(action, controller);
284
283
  }
284
+ /** Adopt a fresh attachment: drop work from the previous one, then release every waiter. */
285
+ function attach({ frame }, _optional = {}) {
286
+ abortPending();
287
+ sessionId = frame.sessionId;
288
+ currentBindToken = frame.bindToken;
289
+ // A no-op after the first attach — which is exactly why `currentBindToken` exists.
290
+ resolveReady({ sessionId, bindToken: currentBindToken });
291
+ for (const waiter of attachments)
292
+ waiter.resolve({ sessionId, bindToken: currentBindToken });
293
+ attachments.clear();
294
+ }
285
295
  function connect() {
286
296
  const current = openStream({ url: `${base}${endpointPrefix}/stream?${query}`, ...(headers ? { headers: headers() } : {}) });
287
297
  source = current;
@@ -294,14 +304,7 @@ export function createFrontendSessionBridge({ baseUrl: base, openStream, request
294
304
  pending.get(frame.invocationId)?.abort();
295
305
  return;
296
306
  case 'attached':
297
- abortPending();
298
- sessionId = frame.sessionId;
299
- currentBindToken = frame.bindToken;
300
- // A no-op after the first attach — which is exactly why `currentBindToken` exists.
301
- resolveReady({ sessionId, bindToken: currentBindToken });
302
- for (const waiter of attachments)
303
- waiter.resolve({ sessionId, bindToken: currentBindToken });
304
- attachments.clear();
307
+ attach({ frame });
305
308
  return;
306
309
  case 'refused': {
307
310
  const error = new Error(frame.message);
@@ -1,4 +1,6 @@
1
1
  import { type RefObject } from 'react';
2
+ import type { ChatMessage } from '../../core/messages.js';
3
+ import type { BrowserSessionStore } from '../browser/session-store.js';
2
4
  /**
3
5
  * Shares the panel-kit trap across embeds. Escape respects a child popup's preventDefault;
4
6
  * Closing restores the mounted launcher, including after a lazy-loader handoff.
@@ -25,4 +27,18 @@ export declare function useEmbedChatSurface({ initialOpen }: {
25
27
  launcherRef: RefObject<HTMLDivElement | null>;
26
28
  panelId: string;
27
29
  };
30
+ /** Persist the embed transcript and remount its pane when the host confirms a reset. */
31
+ export declare function useEmbedChatWidget({ session }: {
32
+ session: BrowserSessionStore;
33
+ }, _options?: {}): {
34
+ paneKey: number;
35
+ messages: ChatMessage[];
36
+ reset: () => void;
37
+ onMessagesChange: (next: ChatMessage[]) => void;
38
+ open: boolean;
39
+ toggle: () => void;
40
+ panelRef: RefObject<HTMLDivElement | null>;
41
+ launcherRef: RefObject<HTMLDivElement | null>;
42
+ panelId: string;
43
+ };
28
44
  //# sourceMappingURL=dialog.hooks.d.ts.map
@@ -51,4 +51,19 @@ export function useEmbedChatSurface({ initialOpen }, { resetKey } = {}) {
51
51
  useEmbedChatDialog({ open, onClose: close, panelRef, launcherRef }, { resetKey });
52
52
  return { open, toggle, panelRef, launcherRef, panelId };
53
53
  }
54
+ /** Persist the embed transcript and remount its pane when the host confirms a reset. */
55
+ export function useEmbedChatWidget({ session }, _options = {}) {
56
+ const [initial] = useState(() => session.load({}));
57
+ const [paneKey, setPaneKey] = useState(0);
58
+ const surface = useEmbedChatSurface({ initialOpen: initial.open }, { resetKey: paneKey });
59
+ const [messages, setMessages] = useState(initial.messages);
60
+ useEffect(() => { session.save({ state: { open: surface.open, messages } }); }, [session, surface.open, messages]);
61
+ const reset = useCallback(() => {
62
+ session.clear({});
63
+ setMessages([]);
64
+ setPaneKey(key => key + 1);
65
+ }, [session]);
66
+ const onMessagesChange = useCallback((next) => { setMessages(next); }, []);
67
+ return { ...surface, paneKey, messages, reset, onMessagesChange };
68
+ }
54
69
  //# sourceMappingURL=dialog.hooks.js.map
@@ -1,6 +1,8 @@
1
1
  import type { ChatTransport } from '../../core/transport.js';
2
2
  import type { ChatPaneAgent } from '../../react/chat-pane.js';
3
+ import { type ChatSurfaces } from '../../react/surfaces.js';
3
4
  import type { BrowserSessionStore } from '../browser/session-store.js';
5
+ import { useEmbedChatWidget } from './dialog.hooks.js';
4
6
  export { useEmbedChatDialog } from './dialog.hooks.js';
5
7
  import type { EmbedHeaderCopy, EscapeKeyPort } from './header.js';
6
8
  export { EmbedChatHeader } from './header.js';
@@ -28,11 +30,14 @@ export interface EmbedChatWidgetArgs {
28
30
  * cannot replay effects. Reset remounts the pane after confirmation.
29
31
  * @complexity O(messages + latest reply events) per transcript update; O(message IDs) retained.
30
32
  */
31
- export declare function EmbedChatWidget(args: EmbedChatWidgetArgs): import("react").JSX.Element;
33
+ export declare function EmbedChatWidget({ useEmbedChatWidgetHook, ...args }: EmbedChatWidgetArgs & {
34
+ useEmbedChatWidgetHook?: typeof useEmbedChatWidget;
35
+ }): import("react").JSX.Element;
32
36
  /** Mounts into a host-provided node and returns lifecycle cleanup. O(1) plus React rendering. */
33
- export declare function mountEmbedChat({ element, widget }: {
37
+ export declare function mountEmbedChat({ element, widget, surfaces }: {
34
38
  element: Element;
35
39
  widget: EmbedChatWidgetArgs;
40
+ surfaces: ChatSurfaces;
36
41
  }): {
37
42
  unmount: (args: Record<string, never>) => void;
38
43
  };
@@ -1,11 +1,11 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { useCallback, useEffect, useState } from 'react';
3
2
  import { createRoot } from 'react-dom/client';
4
3
  import { ChatPane } from '../../react/chat-pane.js';
4
+ import { ChatSurfacesProvider } from '../../react/surfaces.js';
5
5
  import { ChatFab } from '../../react/components/ChatFab.js';
6
6
  import { JiniChatProvider } from '../../react/components/JiniChatProvider.js';
7
7
  import { EmbedChatHeader } from './header.js';
8
- import { useEmbedChatSurface } from './dialog.hooks.js';
8
+ import { useEmbedChatWidget } from './dialog.hooks.js';
9
9
  export { useEmbedChatDialog } from './dialog.hooks.js';
10
10
  export { EmbedChatHeader } from './header.js';
11
11
  const shellStyles = `
@@ -21,25 +21,15 @@ const shellStyles = `
21
21
  * cannot replay effects. Reset remounts the pane after confirmation.
22
22
  * @complexity O(messages + latest reply events) per transcript update; O(message IDs) retained.
23
23
  */
24
- export function EmbedChatWidget(args) {
24
+ export function EmbedChatWidget({ useEmbedChatWidgetHook = useEmbedChatWidget, ...args }) {
25
25
  const { agent, copy, transport, session, keyboard } = args;
26
- const [initial] = useState(() => session.load({}));
27
- const [paneKey, setPaneKey] = useState(0);
28
- const { open, toggle, panelRef, launcherRef, panelId } = useEmbedChatSurface({ initialOpen: initial.open }, { resetKey: paneKey });
29
- const [messages, setMessages] = useState(initial.messages);
30
- useEffect(() => { session.save({ state: { open, messages } }); }, [session, open, messages]);
31
- const reset = useCallback(() => {
32
- session.clear({});
33
- setMessages([]);
34
- setPaneKey(key => key + 1);
35
- }, [session]);
36
- const onMessagesChange = useCallback((next) => { setMessages(next); }, []);
26
+ const { open, toggle, panelRef, launcherRef, panelId, paneKey, messages, reset, onMessagesChange } = useEmbedChatWidgetHook({ session });
37
27
  return _jsxs("div", { className: "jini-chat-embed", children: [_jsx("style", { children: shellStyles }), _jsx("div", { ref: launcherRef, tabIndex: -1, children: _jsx(ChatFab, { open: open, onToggle: toggle, "aria-label": copy.fabLabel, label: copy.fabLabel, "aria-controls": panelId, "aria-haspopup": "dialog" }) }), _jsx(JiniChatProvider, { transport: transport, children: _jsx("div", { id: panelId, className: "jini-chat-embed__panel", hidden: !open, ref: panelRef, role: "dialog", "aria-modal": "true", "aria-label": copy.title, children: _jsx(ChatPane, { transport: transport, agents: [agent], initialSelection: { agentId: agent.id }, initialMessages: messages, title: copy.title, placeholder: copy.placeholder, variant: "embed", header: _jsx(EmbedChatHeader, { title: copy.title, hasMessages: messages.length > 0, onReset: reset, copy: copy, keyboard: keyboard }), onMessagesChange: onMessagesChange }, paneKey) }) })] });
38
28
  }
39
29
  /** Mounts into a host-provided node and returns lifecycle cleanup. O(1) plus React rendering. */
40
- export function mountEmbedChat({ element, widget }) {
30
+ export function mountEmbedChat({ element, widget, surfaces }) {
41
31
  const root = createRoot(element);
42
- root.render(_jsx(EmbedChatWidget, { ...widget }));
32
+ root.render(_jsx(ChatSurfacesProvider, { surfaces: surfaces, children: _jsx(EmbedChatWidget, { ...widget }) }));
43
33
  return { unmount: (_args) => root.unmount() };
44
34
  }
45
35
  //# sourceMappingURL=embed.js.map
@@ -1,4 +1,5 @@
1
1
  import type { ReactNode } from 'react';
2
+ import { useEmbedChatHeader } from './header.hooks.js';
2
3
  export interface EmbedHeaderCopy {
3
4
  readonly eyebrow: string;
4
5
  readonly newThread: string;
@@ -19,5 +20,7 @@ export interface EmbedChatHeaderArgs {
19
20
  readonly closeAction?: ReactNode;
20
21
  }
21
22
  /** Two-step reset with safe initial focus, Cancel and host-wide Escape. O(1) state and listeners. */
22
- export declare function EmbedChatHeader({ title, hasMessages, onReset, copy, keyboard, closeAction }: EmbedChatHeaderArgs): import("react").JSX.Element;
23
+ export declare function EmbedChatHeader({ title, hasMessages, onReset, copy, keyboard, closeAction, useEmbedChatHeaderHook }: EmbedChatHeaderArgs & {
24
+ useEmbedChatHeaderHook?: typeof useEmbedChatHeader;
25
+ }): import("react").JSX.Element;
23
26
  //# sourceMappingURL=header.d.ts.map