@adapttable/ai-react 0.2.20 → 0.2.22

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,53 @@
1
1
  # @adapttable/ai-react
2
2
 
3
+ ## 0.2.22
4
+
5
+ ### Patch Changes
6
+
7
+ - 360e323: `@adapttable/ai-react` no longer depends on `@adapttable/core`; it reaches the table only through `@adapttable/react` and `@adapttable/ai`.
8
+ - fb0e3af: Doc comments name a link target only when the entry point that publishes the comment exports it; any other name is written as code. Editor hovers and the API reference show no broken links.
9
+ - Updated dependencies [75dbf94]
10
+ - Updated dependencies [fb0e3af]
11
+ - Updated dependencies [2582d80]
12
+ - Updated dependencies [42282d3]
13
+ - @adapttable/react@1.11.0
14
+ - @adapttable/ai@0.7.1
15
+
16
+ ## 0.2.21
17
+
18
+ ### Patch Changes
19
+
20
+ - 0fca0b0: The AI packages run one definition per command.
21
+
22
+ - Each built-in agent capability is one command object — schema, argument reading, live guide, preview and apply — and the session runs every capability, built-in or custom, through the same registry. `@adapttable/ai/openai` no longer loads the capability guides (about 2.7 KB gzip off that entry).
23
+ - `describe` publishes output schemas matching what each capability returns (`rows.read`'s row envelope, `view.describe`'s columns, filters and pagination, and write results with `partial` approval, `approvalReason` and per-row `results`).
24
+ - Dictation and the assistant run on shared helpers (`createSpeechSession` on `@adapttable/ai/voice`; `tableAssistantInputs`, `tableAssistantFields`, `assistantUndoView` on `@adapttable/ai/assistant`), so React, Vue and Angular behave the same: choosing a dictation language with voice off writes nothing, and a panel inside the table reports a write waiting on the reader as awaiting approval.
25
+ - Approvals answer the keyboard in every binding: Vue's strip above the table moves focus to Reject when a change arrives and Escape rejects it; in Angular, Escape belongs to an open approval dialog and leaves the assistant panel open.
26
+ - The transports and the agent contract are organized into modules by responsibility, with every export unchanged.
27
+ - Updated dependencies [0fca0b0]
28
+ - Updated dependencies [0fca0b0]
29
+ - Updated dependencies [d92b039]
30
+ - Updated dependencies [693ad8e]
31
+ - Updated dependencies [cbda297]
32
+ - Updated dependencies [39057e0]
33
+ - Updated dependencies [0fca0b0]
34
+ - Updated dependencies [9897b46]
35
+ - Updated dependencies [0fca0b0]
36
+ - Updated dependencies [8bc96c5]
37
+ - Updated dependencies [f20f914]
38
+ - Updated dependencies [39057e0]
39
+ - Updated dependencies [aa07a99]
40
+ - Updated dependencies [39057e0]
41
+ - Updated dependencies [0fca0b0]
42
+ - Updated dependencies [b8b52f4]
43
+ - Updated dependencies [0fca0b0]
44
+ - Updated dependencies [0fca0b0]
45
+ - Updated dependencies [0fca0b0]
46
+ - Updated dependencies [0fca0b0]
47
+ - @adapttable/core@3.14.0
48
+ - @adapttable/react@1.10.0
49
+ - @adapttable/ai@0.7.0
50
+
3
51
  ## 0.2.20
4
52
 
5
53
  ### Patch Changes
package/dist/index.cjs CHANGED
@@ -49,10 +49,16 @@ function useTableAssistant(options) {
49
49
  const progress = (0, _adapttable_react_adapter.useFeatureState)(_adapttable_react_adapter.AGENT_PROGRESS_STATE);
50
50
  const storeRef = (0, react.useRef)(null);
51
51
  const mountRef = (0, react.useRef)(null);
52
- storeRef.current ??= (0, _adapttable_ai.createTableAssistant)(inputsOf(options, approval, alwaysAllow, viewState, progress));
52
+ const table = {
53
+ approval,
54
+ alwaysAllow,
55
+ viewState,
56
+ progress
57
+ };
58
+ storeRef.current ??= (0, _adapttable_ai.createTableAssistant)((0, _adapttable_ai.tableAssistantInputs)(options, table));
53
59
  const store = storeRef.current;
54
60
  (0, react.useEffect)(() => {
55
- store.update(inputsOf(options, approval, alwaysAllow, viewState, progress));
61
+ store.update((0, _adapttable_ai.tableAssistantInputs)(options, table));
56
62
  });
57
63
  (0, react.useEffect)(() => {
58
64
  const mount = { superseded: false };
@@ -73,59 +79,10 @@ function useTableAssistant(options) {
73
79
  onOpenChange?.(next);
74
80
  }, [options.open, onOpenChange]);
75
81
  return {
76
- messages: state.messages,
77
- draft: state.draft,
78
- setDraft: store.setDraft,
79
- send: store.send,
80
- sendClip: store.sendClip,
81
- stop: store.stop,
82
- resume: store.resume,
83
- interrupted: state.interrupted,
84
- resumable: state.resumable,
85
- clear: store.clear,
86
- status: state.status,
87
- busy: state.busy,
82
+ ...(0, _adapttable_ai.tableAssistantFields)(state, store),
88
83
  approval: approval ?? null,
89
- progress: state.progress,
90
- answer: store.answer,
91
- undo: state.undo ? {
92
- messageId: state.undo.messageId,
93
- available: state.undo.available,
94
- ...state.undo.blocked ? { blockedCode: state.undo.blocked.code } : {}
95
- } : null,
96
- undoTurn: store.undoTurn,
97
- undoAction: store.undoAction,
98
- alwaysAllowed: state.alwaysAllowed,
99
- revokeAlwaysAllow: store.revokeAlwaysAllow,
100
- suggestions: state.suggestions,
101
- runSuggestion: store.runSuggestion,
102
84
  open,
103
- setOpen,
104
- error: state.error,
105
- errorCode: state.errorCode
106
- };
107
- }
108
- /** The hook's options as the store's live inputs. A projection, not a decision. */
109
- function inputsOf(options, approval, alwaysAllow, viewState, progress) {
110
- const contextInputs = options.contextInputs ?? (viewState ? () => viewState.read() : void 0);
111
- return {
112
- session: options.session,
113
- transport: options.transport,
114
- transportKey: options.transportKey,
115
- suggestions: options.suggestions,
116
- awaitingApproval: options.awaitingApproval,
117
- approval: approval ?? null,
118
- progress: progress ?? null,
119
- ...contextInputs ? { contextInputs } : {},
120
- ...options.onDetach ? { onDetach: options.onDetach } : {},
121
- ...options.messages ? { messages: options.messages } : {},
122
- ...options.onMessagesChange ? { onMessagesChange: options.onMessagesChange } : {},
123
- ...options.conversation === void 0 ? {} : { conversation: options.conversation },
124
- ...options.resumeHandle ? { resumeHandle: options.resumeHandle } : {},
125
- ...options.alwaysAllow ?? alwaysAllow ? {
126
- alwaysAllowed: (options.alwaysAllow ?? alwaysAllow)?.capabilities,
127
- onRevokeAlwaysAllow: (options.alwaysAllow ?? alwaysAllow)?.revoke
128
- } : {}
85
+ setOpen
129
86
  };
130
87
  }
131
88
  //#endregion
@@ -220,12 +177,13 @@ function tableAgent(options) {
220
177
  /**
221
178
  * Dictation, as a React hook — `@adapttable/ai-react`.
222
179
  *
223
- * Thin on purpose. The controller in `@adapttable/ai/voice` owns the browser
224
- * APIs, the permission states and the language choice; this subscribes to it,
225
- * keeps it alive for the life of the composer, and writes what it hears
226
- * through the caller's `setDraft` — which is the one channel voice is allowed
227
- * to use, so a spoken sentence becomes a draft the reader can see and fix
228
- * rather than a request the table has already acted on.
180
+ * Thin on purpose. The speech session in `@adapttable/ai/voice` owns the
181
+ * browser APIs, the permission states, the language choice and when the
182
+ * microphone is replaced; this subscribes to it, keeps it alive for the life
183
+ * of the composer, and writes what it hears through the caller's `setDraft` —
184
+ * which is the one channel voice is allowed to use, so a spoken sentence
185
+ * becomes a draft the reader can see and fix rather than a request the table
186
+ * has already acted on.
229
187
  *
230
188
  * It lives here rather than in `@adapttable/react` because it imports
231
189
  * `@adapttable/ai`, and that package must stay out of the base graph. The
@@ -233,11 +191,6 @@ function tableAgent(options) {
233
191
  * from `@adapttable/react/adapter`, which declares it without importing
234
192
  * anything.
235
193
  */
236
- const IDLE = {
237
- status: "unsupported",
238
- language: "",
239
- interim: ""
240
- };
241
194
  /**
242
195
  * Run dictation for one composer.
243
196
  *
@@ -247,48 +200,14 @@ const IDLE = {
247
200
  * @public
248
201
  */
249
202
  function useSpeechInput(options) {
250
- const { voice, locale, setDraft, onClip } = options;
251
- const draftRef = (0, react.useRef)(setDraft);
252
- draftRef.current = setDraft;
253
- const clipRef = (0, react.useRef)(onClip);
254
- clipRef.current = onClip;
255
- const enabled = voice !== void 0;
256
- const mode = voice?.mode ?? "browser";
257
- const languagesKey = JSON.stringify(voice?.languages?.length ? voice.languages : [locale ?? "en-US"]);
258
- const languages = (0, react.useMemo)(() => JSON.parse(languagesKey), [languagesKey]);
259
- const [input, setInput] = (0, react.useState)(null);
203
+ const latest = (0, react.useRef)(options);
204
+ latest.current = options;
205
+ const [session] = (0, react.useState)(() => (0, _adapttable_ai_voice.createSpeechSession)(() => latest.current));
260
206
  (0, react.useEffect)(() => {
261
- if (!enabled) {
262
- setInput(null);
263
- return;
264
- }
265
- const remembered = (0, _adapttable_ai_voice.readRememberedLanguage)();
266
- const current = (0, _adapttable_ai_voice.createSpeechInput)({
267
- mode,
268
- languages,
269
- ...remembered ? { initialLanguage: remembered } : {},
270
- onDraft: (text) => draftRef.current(text),
271
- onClip: (clip) => clipRef.current?.(clip)
272
- });
273
- setInput(current);
274
- return () => current.dispose();
275
- }, [
276
- enabled,
277
- mode,
278
- languages
279
- ]);
280
- const state = (0, react.useSyncExternalStore)((listener) => input?.subscribe(listener) ?? (() => void 0), () => input?.getState() ?? IDLE, () => IDLE);
281
- return {
282
- available: Boolean(voice && input?.supported()),
283
- state,
284
- languages,
285
- start: () => input?.start(),
286
- stop: () => input?.stop(),
287
- setLanguage: (language) => {
288
- input?.setLanguage(language);
289
- (0, _adapttable_ai_voice.rememberLanguage)(language);
290
- }
291
- };
207
+ session.sync();
208
+ });
209
+ (0, react.useEffect)(() => () => session.release(), [session]);
210
+ return (0, react.useSyncExternalStore)(session.subscribe, session.getSnapshot, session.getSnapshot);
292
211
  }
293
212
  //#endregion
294
213
  exports.TABLE_AGENT_STATE = _adapttable_ai.TABLE_AGENT_STATE;
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["useState","useFeatureState","AGENT_APPROVAL_STATE","AGENT_ALWAYS_ALLOW_STATE","AGENT_VIEW_STATE","AGENT_PROGRESS_STATE","useRef","createTableAssistant","useSyncExternalStore","useCallback","useTableRuntime","useRef","useState","createTableAgentController","flushSync","useCallback","useSyncExternalStore","FeatureStateScope","TABLE_AGENT_STATE","AGENT_APPROVAL_STATE","AGENT_ALWAYS_ALLOW_STATE","AGENT_VIEW_STATE","AGENT_PROGRESS_STATE","useRef","useMemo","useState","readRememberedLanguage","createSpeechInput","useSyncExternalStore"],"sources":["../src/assistant.tsx","../src/react.tsx","../src/useSpeechInput.ts"],"sourcesContent":["/**\n * `@adapttable/ai-react` — the conversation lifecycle, without a UI.\n *\n * This entry owns state and nothing else: no markup, no launcher, no\n * provider client. A host renders its own panel from what the hook returns,\n * and the shipped widget is written against these same public values — which\n * is the only way to be sure it is not required.\n *\n * The rules that shape it:\n *\n * - **One send at a time**, reserved before any await. Two sends racing would\n * interleave two turns' actions against one table.\n * - **A draft survives failure.** Losing what someone typed because a\n * backend was down is worse than the outage.\n * - **A cancelled send is not a cancelled action.** Aborting before the\n * transport answers is clean; aborting after actions began is reported for\n * what it is, and nothing is retried — a mutation whose outcome is unknown\n * is never sent twice.\n * - **A late reply is dropped.** A turn that was stopped, or that belonged\n * to a previous table, never writes into the transcript.\n */\n\"use client\";\n\nimport {\n type AgentContextInputs,\n type AgentSession,\n type AlwaysAllowedState,\n type AssistantAllowance,\n type AssistantAudio,\n type AssistantInterruption,\n type AssistantMessage,\n type AssistantResumeHandle,\n type AssistantStatus,\n type AssistantSuggestion,\n type AssistantTransport,\n createTableAssistant,\n} from \"@adapttable/ai\";\nimport {\n AGENT_ALWAYS_ALLOW_STATE,\n AGENT_APPROVAL_STATE,\n AGENT_PROGRESS_STATE,\n AGENT_VIEW_STATE,\n type AgentAlwaysAllowState,\n type AgentApprovalPending,\n type AgentProgress,\n type AgentViewState,\n useFeatureState,\n} from \"@adapttable/react/adapter\";\nimport {\n useCallback,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\n\n// The hook's own options and state name these, so the entry that publishes\n// the hook publishes them too — a consumer typing a variable from it should\n// not have to reach into another entry point for the pieces.\nexport type {\n ApprovalPolicy,\n AssistantReceiptStatus,\n AssistantReceiptSubject,\n CommitPolicy,\n RowAddressScope,\n WritePolicy,\n} from \"@adapttable/ai\";\nexport type {\n AssistantInterruption,\n AssistantMessage,\n AssistantResumeHandle,\n AssistantStatus,\n AssistantTransport,\n};\nexport type {\n AssistantExchange,\n AssistantQuestion,\n AssistantReceipt,\n AssistantTransportReply,\n AssistantTurnStatus,\n} from \"@adapttable/ai\";\nexport type { AssistantUndoOffer } from \"@adapttable/ai\";\n\n/** How {@link useTableAssistant} is configured. @public */\nexport interface TableAssistantOptions {\n /** The live session. Changing it starts a new conversation. */\n readonly session: AgentSession | undefined;\n /**\n * Where a turn goes. Omit and the assistant stays disconnected.\n *\n * May be a fresh object every render — the controller reads the latest one\n * rather than reconnecting on its identity, so a host is not forced to\n * memoize it.\n */\n readonly transport?: AssistantTransport;\n /**\n * Changes when the transport should be re-established.\n *\n * The conversation resets on a new session, because that is a new table.\n * Swapping one transport for another — a backend for a scripted one — is\n * not visible in the object identity, so a host that does it names the\n * change here. A backend transport must never quietly become a simulated\n * one under the same key.\n */\n readonly transportKey?: string;\n /** Everything authored, filtered live against what the table offers. */\n readonly suggestions?: readonly AssistantSuggestion[];\n /** Controlled panel state. Omit for uncontrolled. */\n readonly open?: boolean;\n /** Called on every open/close request, controlled or not. */\n readonly onOpenChange?: (open: boolean) => void;\n /**\n * Whether a write from this conversation is waiting on a human.\n *\n * `execute` does not return while an approval is open, so the turn looks\n * like thinking from in here. A host that renders the approval — or wires\n * `bridge.approvals` — passes it back so the panel can say what is\n * actually happening. The turn is still in flight and still stoppable.\n */\n readonly awaitingApproval?: boolean;\n /**\n * What the reader has waved through, when the panel is mounted outside the\n * table.\n *\n * A panel inside the table reads this from feature state and needs nothing\n * here. One beside it cannot, so a host wires `bridge.alwaysAllowed` and\n * passes what it publishes — the same arrangement `bridge.approvals` and\n * `bridge.viewInputs` already have. Without it a reader can wave a\n * capability through and have no way to take it back.\n */\n readonly alwaysAllow?: AlwaysAllowedState;\n /**\n * Live view and filter data the manifest does not carry.\n *\n * Read when a turn starts and again when it settles, so per-turn undo can\n * tell what the turn moved. A function rather than a value: a fixed object\n * would report that nothing changed.\n */\n readonly contextInputs?: () => AgentContextInputs;\n /**\n * Work that outlived its connection, handed over the moment it does.\n *\n * Durable recovery starts here and ends outside this package: a host that\n * stores the handle where it survives a reload can offer a resume when the\n * reader comes back, and a host that does nothing loses the work with the\n * page.\n */\n readonly onDetach?: (handle: AssistantResumeHandle) => void;\n /** A handle kept from a previous page, to resume into this one. */\n readonly resumeHandle?: AssistantResumeHandle;\n /**\n * The transcript, when your app owns it.\n *\n * Omit it and the conversation lives in the controller. Supply it to load\n * the last conversation from your own API, append a message that arrived on\n * a socket, or keep it where it survives a reload — pass a new array and the\n * panel shows it. Pair it with `onMessagesChange`.\n */\n readonly messages?: readonly AssistantMessage[];\n /** Told whenever the transcript changes, with the whole of it. */\n readonly onMessagesChange?: (messages: readonly AssistantMessage[]) => void;\n /**\n * How much of the conversation travels with each turn.\n *\n * `\"full\"` (default) sends every earlier message, for a backend that\n * remembers nothing. A number sends that many of the most recent. `0` sends\n * none — the reader's message still travels, and a backend holding its own\n * session supplies the rest. What the reader sees is never trimmed.\n */\n readonly conversation?: \"full\" | number;\n}\n\n/** What a host renders from. @public */\nexport interface TableAssistantState {\n readonly status: AssistantStatus;\n /**\n * Whether a turn is in flight and can still be stopped.\n *\n * Separate from {@link TableAssistantState.status}: a write parked on a\n * human approval reports `awaiting-approval` but is still running, and\n * Stop still ends it.\n */\n readonly busy: boolean;\n readonly messages: readonly AssistantMessage[];\n readonly draft: string;\n readonly setDraft: (draft: string) => void;\n /** Send the draft, or the given text. Resolves when the turn settles. */\n readonly send: (text?: string) => Promise<void>;\n /**\n * Send a recording as the reader's turn — pass it as `onClip` to\n * backend-mode `useSpeechInput`. The transcript the backend returns becomes\n * the reader's message.\n */\n readonly sendClip: (clip: AssistantAudio) => Promise<void>;\n /** Abort the turn in flight. Safe to call when nothing is in flight. */\n readonly stop: () => void;\n /**\n * Rejoin work a released connection left running.\n *\n * A no-op with nothing to rejoin, which is what `resumable` says.\n */\n readonly resume: () => Promise<void>;\n /**\n * What became of the last turn, when no reply ended it.\n *\n * `\"stopped\"` is the reader's own decision; `\"detached\"` is a released\n * connection, where the work may still be running.\n */\n readonly interrupted: AssistantInterruption | undefined;\n /** The work `resume` would rejoin, or nothing. */\n readonly resumable: AssistantResumeHandle | undefined;\n /** Drop the transcript. Refuses while a turn is in flight. */\n readonly clear: () => void;\n /**\n * A write waiting on the reader, or nothing.\n *\n * Hand it to the panel as `approval` and the conversation reviews it —\n * which is where a write asked for in the conversation belongs. The panel\n * draws it only when the approval's presentation names the widget, so\n * passing it costs nothing on a table reviewing elsewhere.\n */\n readonly approval: AgentApprovalPending | null;\n /**\n * How far the capability now running has got, or nothing.\n *\n * Published by the table while a long call works through its rows. It never\n * becomes the receipt: when the turn settles this goes and the receipts say\n * what happened.\n */\n readonly progress: AgentProgress | null;\n /** Answer the pending question and let the turn continue. */\n readonly answer: (answer: { optionId?: string; text?: string }) => void;\n /**\n * Whether the last turn that moved the table can still be put back.\n *\n * Null when no turn moved it. Re-read every render, because the offer ends\n * the moment anything else changes the view. `blockedCode` is a token the\n * labels translate — the panel never shows a reader a code.\n */\n readonly undo: {\n readonly messageId: string;\n readonly available: boolean;\n readonly blockedCode?: string;\n } | null;\n /** Put that turn back. A no-op once the offer has expired. */\n readonly undoTurn: () => Promise<void>;\n /** Put one action of the last turn back, by its receipt's replay identity. */\n readonly undoAction: (idempotencyKey: string) => Promise<void>;\n /** What the reader said not to ask about again, each with its own name. */\n readonly alwaysAllowed: readonly AssistantAllowance[];\n /** Ask about one of them again from now on. */\n readonly revokeAlwaysAllow: (capability: string) => void;\n /** The suggestions this table can run right now, re-checked every render. */\n readonly suggestions: readonly AssistantSuggestion[];\n /** Send a suggestion's prompt as if the reader had typed it. */\n readonly runSuggestion: (id: string) => Promise<void>;\n readonly open: boolean;\n readonly setOpen: (open: boolean) => void;\n /** The last failure, cleared by the next successful turn. */\n readonly error: string | undefined;\n /**\n * The machine code behind {@link error}, when a turn ended with work\n * pending. A surface with labels turns it into a sentence for the reader;\n * the message beside it is written for whoever is debugging the turn.\n */\n readonly errorCode: string | undefined;\n}\n\n/**\n * Run a table assistant.\n *\n * A thin subscriber to the neutral controller in `@adapttable/ai/assistant`:\n * React supplies the external-store mechanism, the live inputs and the\n * controlled presentation state, and owns none of the lifecycle.\n *\n * @param options - Session, transport and presentation.\n * @returns Everything a panel needs, and nothing about how it looks.\n *\n * @public\n */\nexport function useTableAssistant(\n options: TableAssistantOptions\n): TableAssistantState {\n const { onOpenChange } = options;\n const [uncontrolledOpen, setUncontrolledOpen] = useState(false);\n // The live approval, so a host wires the panel with one prop rather than\n // reaching for feature state itself.\n const approval = useFeatureState(AGENT_APPROVAL_STATE);\n // What the reader has waved through, published by the binding whether or\n // not an approval is open.\n const alwaysAllow = useFeatureState(AGENT_ALWAYS_ALLOW_STATE);\n // The table's own live view, published by `tableAgent`. A host that drives\n // the panel from state of its own passes `contextInputs` and this is unused.\n const viewState = useFeatureState(AGENT_VIEW_STATE);\n // How far a running capability has got, for the same reason: a panel inside\n // the table needs no host wiring to say what the work is doing.\n const progress = useFeatureState(AGENT_PROGRESS_STATE);\n\n // Created once, inert until the mount effect connects it. Constructing a\n // store during render must not open a connection — a render can be thrown\n // away, and Strict Mode throws the first one away on purpose.\n const storeRef = useRef<ReturnType<typeof createTableAssistant> | null>(null);\n const mountRef = useRef<{ superseded: boolean } | null>(null);\n storeRef.current ??= createTableAssistant(\n inputsOf(options, approval, alwaysAllow, viewState, progress)\n );\n const store = storeRef.current;\n\n // Live inputs, every render. The store decides what a change means: a new\n // session resets the conversation, a new transport key reconnects, and an\n // updated catalog or a newly arrived approval does neither.\n useEffect(() => {\n store.update(inputsOf(options, approval, alwaysAllow, viewState, progress));\n });\n\n useEffect(() => {\n const mount = { superseded: false };\n if (mountRef.current) mountRef.current.superseded = true;\n mountRef.current = mount;\n store.connect();\n return () => {\n // React may replay this effect without rendering a replacement store.\n // Release the connection, retaining the inert controller for that next\n // setup. This also hands durable work to the host before unmounting.\n // useSyncExternalStore removes its own subscription on cleanup.\n store.disconnect();\n queueMicrotask(() => {\n if (!mount.superseded) store.dispose();\n });\n };\n }, [store]);\n\n const state = useSyncExternalStore(\n store.subscribe,\n store.getState,\n store.getState\n );\n\n const open = options.open ?? uncontrolledOpen;\n const setOpen = useCallback(\n (next: boolean) => {\n if (options.open === undefined) setUncontrolledOpen(next);\n onOpenChange?.(next);\n },\n [options.open, onOpenChange]\n );\n\n return {\n messages: state.messages,\n draft: state.draft,\n setDraft: store.setDraft,\n send: store.send,\n sendClip: store.sendClip,\n stop: store.stop,\n resume: store.resume,\n interrupted: state.interrupted,\n resumable: state.resumable,\n clear: store.clear,\n status: state.status,\n busy: state.busy,\n approval: approval ?? null,\n progress: state.progress,\n answer: store.answer,\n undo: state.undo\n ? {\n messageId: state.undo.messageId,\n available: state.undo.available,\n ...(state.undo.blocked\n ? { blockedCode: state.undo.blocked.code }\n : {}),\n }\n : null,\n undoTurn: store.undoTurn,\n undoAction: store.undoAction,\n alwaysAllowed: state.alwaysAllowed,\n revokeAlwaysAllow: store.revokeAlwaysAllow,\n suggestions: state.suggestions,\n runSuggestion: store.runSuggestion,\n open,\n setOpen,\n error: state.error,\n errorCode: state.errorCode,\n };\n}\n\n/** The hook's options as the store's live inputs. A projection, not a decision. */\nfunction inputsOf(\n options: TableAssistantOptions,\n approval: AgentApprovalPending | null | undefined,\n alwaysAllow: AgentAlwaysAllowState | null | undefined,\n viewState: AgentViewState | null | undefined,\n progress: AgentProgress | null | undefined\n) {\n // The host's own reader wins; otherwise the table's, which is what makes\n // per-turn undo work without a host lifting page and sort into its state.\n const contextInputs =\n options.contextInputs ??\n (viewState ? () => viewState.read() as AgentContextInputs : undefined);\n return {\n session: options.session,\n transport: options.transport,\n transportKey: options.transportKey,\n suggestions: options.suggestions,\n awaitingApproval: options.awaitingApproval,\n approval: approval ?? null,\n progress: progress ?? null,\n ...(contextInputs ? { contextInputs } : {}),\n ...(options.onDetach ? { onDetach: options.onDetach } : {}),\n ...(options.messages ? { messages: options.messages } : {}),\n ...(options.onMessagesChange\n ? { onMessagesChange: options.onMessagesChange }\n : {}),\n ...(options.conversation === undefined\n ? {}\n : { conversation: options.conversation }),\n ...(options.resumeHandle ? { resumeHandle: options.resumeHandle } : {}),\n // The host's own wins, for the same reason `contextInputs` does: a panel\n // beside the table has no feature state to read.\n ...((options.alwaysAllow ?? alwaysAllow)\n ? {\n alwaysAllowed: (options.alwaysAllow ?? alwaysAllow)?.capabilities,\n onRevokeAlwaysAllow: (options.alwaysAllow ?? alwaysAllow)?.revoke,\n }\n : {}),\n };\n}\n","/**\n * Opt-in table feature — `@adapttable/ai-react`.\n *\n * `@adapttable/ai` stays React-free. This package mounts a provider that\n * drives `@adapttable/ai`'s table agent controller from React: it keeps the\n * controller's inputs current, re-renders on its snapshot and the table's\n * changes, and publishes what the controller holds as feature state.\n */\nimport {\n type AgentSession,\n createTableAgentController,\n TABLE_AGENT_STATE,\n type TableAgentBridge as NeutralBridge,\n type TableAgentController,\n type TableAgentControllerOptions,\n} from \"@adapttable/ai\";\nimport {\n AGENT_ALWAYS_ALLOW_STATE,\n AGENT_APPROVAL_STATE,\n AGENT_PROGRESS_STATE,\n AGENT_VIEW_STATE,\n type AgentApprovalPending,\n type FeatureProviderProps,\n FeatureStateScope,\n type StaticTableFeature,\n useTableRuntime,\n} from \"@adapttable/react/adapter\";\nimport {\n type ReactNode,\n useCallback,\n useDebugValue,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport { flushSync } from \"react-dom\";\n\nexport type { SharedApproval, TableAgentColumnPatch } from \"@adapttable/ai\";\n\n// The bridge contract is `@adapttable/ai`'s — a manifest, a session and a\n// pending approval are what any binding publishes, none of it React. Named\n// here with this binding's own pending shape so every existing import keeps\n// working.\nexport type TableAgentBridge = NeutralBridge<AgentApprovalPending>;\n\n// The live session's key is `@adapttable/ai`'s, so every agent binding\n// publishes and reads the same one.\nexport { TABLE_AGENT_STATE };\n\n/**\n * Options for {@link tableAgent}.\n *\n * The same options `@adapttable/ai`'s table agent controller takes: the\n * runtime half — identity, policy, columns, the host's callbacks and\n * capabilities — plus where updates are published and whether the table is\n * offered to a browser-resident agent.\n *\n * @public\n */\nexport type TableAgentOptions = TableAgentControllerOptions;\n\ninterface TableAgentFeature extends StaticTableFeature {\n readonly options: TableAgentOptions;\n}\n\nfunction TableAgentProvider({\n feature,\n children,\n}: Readonly<FeatureProviderProps>): ReactNode {\n const options = (feature as TableAgentFeature).options;\n const runtime = useTableRuntime();\n const optionsRef = useRef(options);\n optionsRef.current = options;\n const runtimeRef = useRef(runtime);\n runtimeRef.current = runtime;\n // A concrete provider update, rather than an empty `flushSync`, makes React\n // finish controlled-state work already queued by the reader before the\n // session takes its admission snapshot.\n const [admissionTick, setAdmissionTick] = useState(0);\n const flushAdmission = useRef<() => void>(() => undefined);\n flushAdmission.current = () => {\n flushSync(() => {\n setAdmissionTick(admissionTick + 1);\n });\n };\n\n // Built once and never during a render that is thrown away twice: the\n // controller opens nothing until `sync`, which only an effect calls.\n const controllerRef = useRef<TableAgentController | null>(null);\n controllerRef.current ??= createTableAgentController({\n options: optionsRef,\n runtime: runtimeRef,\n flushAdmission: () => {\n flushAdmission.current();\n },\n flush: flushSync,\n });\n const controller = controllerRef.current;\n\n // The table as a store: subscribe where there is one to subscribe to, and\n // read the stamp on every render either way. React re-reads the stamp after\n // it attaches, so a table that moved between the render and the\n // subscription is caught rather than missed. The value is not rendered;\n // re-rendering is the point, because that republishes the manifest.\n const neutralTable = runtime.view()?.neutralTable;\n // The controller subscribes to the table current at the call, so a\n // replaced table is a new subscription.\n const subscribeToTable = useCallback(\n (onStoreChange: () => void) =>\n neutralTable ? controller.subscribeTable(onStoreChange) : () => undefined,\n [controller, neutralTable]\n );\n const stamp = useSyncExternalStore(\n subscribeToTable,\n controller.tableStamp,\n controller.tableStamp\n );\n useDebugValue(stamp);\n\n const state = useSyncExternalStore(\n controller.subscribe,\n controller.getState,\n controller.getState\n );\n\n // Every commit: the controller decides what changed and tells only those\n // who need telling. A layout effect, so a host reading the manifest in its\n // own effects already has this render's.\n useLayoutEffect(() => {\n controller.sync();\n });\n\n // Going away is a close. Strict Mode's setup/cleanup/setup lands here too:\n // the cleanup releases everything, and the next sync sets it up again.\n useEffect(\n () => () => {\n controller.disconnect();\n },\n [controller]\n );\n\n // A new value every render on purpose. The table publishes its runtime\n // while its children render, after this provider has, so a surface below\n // learns what the session now offers only by re-rendering with it — and it\n // re-renders because the value it holds is a different one.\n const session = state.session;\n const published: AgentSession = {\n catalog: () => session.catalog(),\n describe: (key) => session.describe(key),\n execute: (key, args, expectedRevision, idempotencyKey, signal) =>\n session.execute(key, args, expectedRevision, idempotencyKey, signal),\n manifest: () => session.manifest(),\n };\n\n return (\n <FeatureStateScope stateKey={TABLE_AGENT_STATE} value={published}>\n <FeatureStateScope stateKey={AGENT_APPROVAL_STATE} value={state.approval}>\n <FeatureStateScope\n stateKey={AGENT_ALWAYS_ALLOW_STATE}\n value={state.alwaysAllow}\n >\n <FeatureStateScope stateKey={AGENT_VIEW_STATE} value={state.view}>\n <FeatureStateScope\n stateKey={AGENT_PROGRESS_STATE}\n value={state.progress}\n >\n {children}\n </FeatureStateScope>\n </FeatureStateScope>\n </FeatureStateScope>\n </FeatureStateScope>\n </FeatureStateScope>\n );\n}\n\n/**\n * Observe a live table and publish a deterministic capability manifest.\n *\n * Omitting this feature from `features` ships no agent bytes.\n *\n * @public\n */\nexport function tableAgent(options: TableAgentOptions): StaticTableFeature {\n const feature: TableAgentFeature = {\n id: \"table-agent\",\n options,\n provider: { Provider: TableAgentProvider },\n };\n return feature;\n}\n","/**\n * Dictation, as a React hook — `@adapttable/ai-react`.\n *\n * Thin on purpose. The controller in `@adapttable/ai/voice` owns the browser\n * APIs, the permission states and the language choice; this subscribes to it,\n * keeps it alive for the life of the composer, and writes what it hears\n * through the caller's `setDraft` — which is the one channel voice is allowed\n * to use, so a spoken sentence becomes a draft the reader can see and fix\n * rather than a request the table has already acted on.\n *\n * It lives here rather than in `@adapttable/react` because it imports\n * `@adapttable/ai`, and that package must stay out of the base graph. The\n * chrome takes `SpeechInputHandle` — the structural shape this returns —\n * from `@adapttable/react/adapter`, which declares it without importing\n * anything.\n */\n\"use client\";\n\nimport {\n createSpeechInput,\n readRememberedLanguage,\n rememberLanguage,\n type SpeechClip,\n type SpeechInput,\n type SpeechState,\n type VoiceOptions,\n} from \"@adapttable/ai/voice\";\nimport type { SpeechInputHandle } from \"@adapttable/react/adapter\";\nimport {\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\n\n/** How the hook is configured. @public */\nexport interface UseSpeechInputOptions {\n readonly voice?: VoiceOptions;\n /** The table's locale, used when no language list was given. */\n readonly locale?: string;\n /** Where heard text goes. Always the draft, never a send. */\n readonly setDraft: (text: string) => void;\n /** Where a recording goes, in backend mode. */\n readonly onClip?: (clip: SpeechClip) => void;\n}\n\nconst IDLE: SpeechState = { status: \"unsupported\", language: \"\", interim: \"\" };\n\n/**\n * Run dictation for one composer.\n *\n * @param options - Voice configuration and where heard text should go.\n * @returns What the composer needs, or an unavailable handle when voice is off.\n *\n * @public\n */\nexport function useSpeechInput(\n options: UseSpeechInputOptions\n): SpeechInputHandle {\n const { voice, locale, setDraft, onClip } = options;\n // Live callbacks, so the controller is built once and still calls whatever\n // the latest render passed rather than what the first one did.\n const draftRef = useRef(setDraft);\n draftRef.current = setDraft;\n const clipRef = useRef(onClip);\n clipRef.current = onClip;\n\n const enabled = voice !== undefined;\n const mode = voice?.mode ?? \"browser\";\n // A host may construct the same language array on each render. Compare its\n // values so an active recognizer survives those equivalent configurations.\n const languagesKey = JSON.stringify(\n voice?.languages?.length ? voice.languages : [locale ?? \"en-US\"]\n );\n const languages = useMemo(\n () => JSON.parse(languagesKey) as readonly string[],\n [languagesKey]\n );\n const [input, setInput] = useState<SpeechInput | null>(null);\n useEffect(() => {\n if (!enabled) {\n setInput(null);\n return;\n }\n const remembered = readRememberedLanguage();\n const current = createSpeechInput({\n mode,\n languages,\n ...(remembered ? { initialLanguage: remembered } : {}),\n onDraft: (text) => draftRef.current(text),\n onClip: (clip) => clipRef.current?.(clip),\n });\n setInput(current);\n // Every effect setup owns a fresh controller. Strict Mode can clean up\n // and set up again without leaving the composer attached to a disposed one.\n return () => current.dispose();\n }, [enabled, mode, languages]);\n\n const state = useSyncExternalStore(\n (listener) => input?.subscribe(listener) ?? (() => undefined),\n () => input?.getState() ?? IDLE,\n () => IDLE\n );\n\n return {\n // Absent rather than dead: a mic that cannot listen is not drawn.\n available: Boolean(voice && input?.supported()),\n state,\n languages,\n start: () => input?.start(),\n stop: () => input?.stop(),\n setLanguage: (language) => {\n input?.setLanguage(language);\n rememberLanguage(language);\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwRA,SAAgB,kBACd,SACqB;CACrB,MAAM,EAAE,iBAAiB;CACzB,MAAM,CAAC,kBAAkB,wBAAA,GAAuBA,MAAAA,SAAAA,CAAS,KAAK;CAG9D,MAAM,YAAA,GAAWC,0BAAAA,gBAAAA,CAAgBC,0BAAAA,oBAAoB;CAGrD,MAAM,eAAA,GAAcD,0BAAAA,gBAAAA,CAAgBE,0BAAAA,wBAAwB;CAG5D,MAAM,aAAA,GAAYF,0BAAAA,gBAAAA,CAAgBG,0BAAAA,gBAAgB;CAGlD,MAAM,YAAA,GAAWH,0BAAAA,gBAAAA,CAAgBI,0BAAAA,oBAAoB;CAKrD,MAAM,YAAA,GAAWC,MAAAA,OAAAA,CAAuD,IAAI;CAC5E,MAAM,YAAA,GAAWA,MAAAA,OAAAA,CAAuC,IAAI;CAC5D,SAAS,aAAA,GAAYC,eAAAA,qBAAAA,CACnB,SAAS,SAAS,UAAU,aAAa,WAAW,QAAQ,CAC9D;CACA,MAAM,QAAQ,SAAS;CAKvB,CAAA,GAAA,MAAA,UAAA,OAAgB;EACd,MAAM,OAAO,SAAS,SAAS,UAAU,aAAa,WAAW,QAAQ,CAAC;CAC5E,CAAC;CAED,CAAA,GAAA,MAAA,UAAA,OAAgB;EACd,MAAM,QAAQ,EAAE,YAAY,MAAM;EAClC,IAAI,SAAS,SAAS,SAAS,QAAQ,aAAa;EACpD,SAAS,UAAU;EACnB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EAAS;EAAM;CAAS,CAAC;CAE7B,MAAM,SAAA,GAAQC,MAAAA,qBAAAA,EACX,aAAa,OAAO,UAAU,QAAQ,YAAY,KAAA,UAC7C,OAAO,SAAS,KAAK,YACrB,IACR;CAEA,OAAO;EAEL,WAAW,QAAQ,SAAS,OAAO,UAAU,CAAC;EAC9C;EACA;EACA,aAAa,OAAO,MAAM;EAC1B,YAAY,OAAO,KAAK;EACxB,cAAc,aAAa;GACzB,OAAO,YAAY,QAAQ;GAC3B,CAAA,GAAA,qBAAA,iBAAA,CAAiB,QAAQ;EAC3B;CACF;AACF"}
1
+ {"version":3,"file":"index.cjs","names":["useState","useFeatureState","AGENT_APPROVAL_STATE","AGENT_ALWAYS_ALLOW_STATE","AGENT_VIEW_STATE","AGENT_PROGRESS_STATE","useRef","createTableAssistant","tableAssistantInputs","useSyncExternalStore","useCallback","tableAssistantFields","useTableRuntime","useRef","useState","createTableAgentController","flushSync","useCallback","useSyncExternalStore","FeatureStateScope","TABLE_AGENT_STATE","AGENT_APPROVAL_STATE","AGENT_ALWAYS_ALLOW_STATE","AGENT_VIEW_STATE","AGENT_PROGRESS_STATE","useRef","useState","createSpeechSession","useSyncExternalStore"],"sources":["../src/assistant.tsx","../src/react.tsx","../src/useSpeechInput.ts"],"sourcesContent":["/**\n * `@adapttable/ai-react` — the conversation lifecycle, without a UI.\n *\n * This entry owns state and nothing else: no markup, no launcher, no\n * provider client. A host renders its own panel from what the hook returns,\n * and the shipped widget is written against these same public values — which\n * is the only way to be sure it is not required.\n *\n * The rules that shape it:\n *\n * - **One send at a time**, reserved before any await. Two sends racing would\n * interleave two turns' actions against one table.\n * - **A draft survives failure.** Losing what someone typed because a\n * backend was down is worse than the outage.\n * - **A cancelled send is not a cancelled action.** Aborting before the\n * transport answers is clean; aborting after actions began is reported for\n * what it is, and nothing is retried — a mutation whose outcome is unknown\n * is never sent twice.\n * - **A late reply is dropped.** A turn that was stopped, or that belonged\n * to a previous table, never writes into the transcript.\n */\n\"use client\";\n\nimport {\n type AgentContextInputs,\n type AgentSession,\n type AlwaysAllowedState,\n type AssistantAllowance,\n type AssistantAudio,\n type AssistantInterruption,\n type AssistantMessage,\n type AssistantResumeHandle,\n type AssistantStatus,\n type AssistantSuggestion,\n type AssistantTransport,\n type AssistantUndoView,\n createTableAssistant,\n tableAssistantFields,\n tableAssistantInputs,\n} from \"@adapttable/ai\";\nimport {\n AGENT_ALWAYS_ALLOW_STATE,\n AGENT_APPROVAL_STATE,\n AGENT_PROGRESS_STATE,\n AGENT_VIEW_STATE,\n type AgentApprovalPending,\n type AgentProgress,\n useFeatureState,\n} from \"@adapttable/react/adapter\";\nimport {\n useCallback,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\n\n// The hook's own options and state name these, so the entry that publishes\n// the hook publishes them too — a consumer typing a variable from it should\n// not have to reach into another entry point for the pieces.\nexport type {\n ApprovalPolicy,\n AssistantReceiptStatus,\n AssistantReceiptSubject,\n CommitPolicy,\n RowAddressScope,\n WritePolicy,\n} from \"@adapttable/ai\";\nexport type {\n AssistantInterruption,\n AssistantMessage,\n AssistantResumeHandle,\n AssistantStatus,\n AssistantTransport,\n};\nexport type {\n AssistantExchange,\n AssistantQuestion,\n AssistantReceipt,\n AssistantTransportReply,\n AssistantTurnStatus,\n} from \"@adapttable/ai\";\nexport type { AssistantUndoOffer } from \"@adapttable/ai\";\n\n/** How {@link useTableAssistant} is configured. @public */\nexport interface TableAssistantOptions {\n /** The live session. Changing it starts a new conversation. */\n readonly session: AgentSession | undefined;\n /**\n * Where a turn goes. Omit and the assistant stays disconnected.\n *\n * May be a fresh object every render — the controller reads the latest one\n * rather than reconnecting on its identity, so a host is not forced to\n * memoize it.\n */\n readonly transport?: AssistantTransport;\n /**\n * Changes when the transport should be re-established.\n *\n * The conversation resets on a new session, because that is a new table.\n * Swapping one transport for another — a backend for a scripted one — is\n * not visible in the object identity, so a host that does it names the\n * change here. A backend transport must never quietly become a simulated\n * one under the same key.\n */\n readonly transportKey?: string;\n /** Everything authored, filtered live against what the table offers. */\n readonly suggestions?: readonly AssistantSuggestion[];\n /** Controlled panel state. Omit for uncontrolled. */\n readonly open?: boolean;\n /** Called on every open/close request, controlled or not. */\n readonly onOpenChange?: (open: boolean) => void;\n /**\n * Whether a write from this conversation is waiting on a human.\n *\n * `execute` does not return while an approval is open, so the turn looks\n * like thinking from in here. Defaults to whether the table has a write\n * waiting on the reader; a host that renders the approval elsewhere — or\n * wires `bridge.approvals` — passes it so the panel can say what is\n * actually happening. The turn is still in flight and still stoppable.\n */\n readonly awaitingApproval?: boolean;\n /**\n * What the reader has waved through, when the panel is mounted outside the\n * table.\n *\n * A panel inside the table reads this from feature state and needs nothing\n * here. One beside it cannot, so a host wires `bridge.alwaysAllowed` and\n * passes what it publishes — the same arrangement `bridge.approvals` and\n * `bridge.viewInputs` already have. Without it a reader can wave a\n * capability through and have no way to take it back.\n */\n readonly alwaysAllow?: AlwaysAllowedState;\n /**\n * Live view and filter data the manifest does not carry.\n *\n * Read when a turn starts and again when it settles, so per-turn undo can\n * tell what the turn moved. A function rather than a value: a fixed object\n * would report that nothing changed.\n */\n readonly contextInputs?: () => AgentContextInputs;\n /**\n * Work that outlived its connection, handed over the moment it does.\n *\n * Durable recovery starts here and ends outside this package: a host that\n * stores the handle where it survives a reload can offer a resume when the\n * reader comes back, and a host that does nothing loses the work with the\n * page.\n */\n readonly onDetach?: (handle: AssistantResumeHandle) => void;\n /** A handle kept from a previous page, to resume into this one. */\n readonly resumeHandle?: AssistantResumeHandle;\n /**\n * The transcript, when your app owns it.\n *\n * Omit it and the conversation lives in the controller. Supply it to load\n * the last conversation from your own API, append a message that arrived on\n * a socket, or keep it where it survives a reload — pass a new array and the\n * panel shows it. Pair it with `onMessagesChange`.\n */\n readonly messages?: readonly AssistantMessage[];\n /** Told whenever the transcript changes, with the whole of it. */\n readonly onMessagesChange?: (messages: readonly AssistantMessage[]) => void;\n /**\n * How much of the conversation travels with each turn.\n *\n * `\"full\"` (default) sends every earlier message, for a backend that\n * remembers nothing. A number sends that many of the most recent. `0` sends\n * none — the reader's message still travels, and a backend holding its own\n * session supplies the rest. What the reader sees is never trimmed.\n */\n readonly conversation?: \"full\" | number;\n}\n\n/** What a host renders from. @public */\nexport interface TableAssistantState {\n readonly status: AssistantStatus;\n /**\n * Whether a turn is in flight and can still be stopped.\n *\n * Separate from {@link TableAssistantState.status}: a write parked on a\n * human approval reports `awaiting-approval` but is still running, and\n * Stop still ends it.\n */\n readonly busy: boolean;\n readonly messages: readonly AssistantMessage[];\n readonly draft: string;\n readonly setDraft: (draft: string) => void;\n /** Send the draft, or the given text. Resolves when the turn settles. */\n readonly send: (text?: string) => Promise<void>;\n /**\n * Send a recording as the reader's turn — pass it as `onClip` to\n * backend-mode `useSpeechInput`. The transcript the backend returns becomes\n * the reader's message.\n */\n readonly sendClip: (clip: AssistantAudio) => Promise<void>;\n /** Abort the turn in flight. Safe to call when nothing is in flight. */\n readonly stop: () => void;\n /**\n * Rejoin work a released connection left running.\n *\n * A no-op with nothing to rejoin, which is what `resumable` says.\n */\n readonly resume: () => Promise<void>;\n /**\n * What became of the last turn, when no reply ended it.\n *\n * `\"stopped\"` is the reader's own decision; `\"detached\"` is a released\n * connection, where the work may still be running.\n */\n readonly interrupted: AssistantInterruption | undefined;\n /** The work `resume` would rejoin, or nothing. */\n readonly resumable: AssistantResumeHandle | undefined;\n /** Drop the transcript. Refuses while a turn is in flight. */\n readonly clear: () => void;\n /**\n * A write waiting on the reader, or nothing.\n *\n * Hand it to the panel as `approval` and the conversation reviews it —\n * which is where a write asked for in the conversation belongs. The panel\n * draws it only when the approval's presentation names the widget, so\n * passing it costs nothing on a table reviewing elsewhere.\n */\n readonly approval: AgentApprovalPending | null;\n /**\n * How far the capability now running has got, or nothing.\n *\n * Published by the table while a long call works through its rows. It never\n * becomes the receipt: when the turn settles this goes and the receipts say\n * what happened.\n */\n readonly progress: AgentProgress | null;\n /** Answer the pending question and let the turn continue. */\n readonly answer: (answer: { optionId?: string; text?: string }) => void;\n /**\n * Whether the last turn that moved the table can still be put back.\n *\n * Null when no turn moved it. Re-read every render, because the offer ends\n * the moment anything else changes the view. `blockedCode` is a token the\n * labels translate — the panel never shows a reader a code.\n */\n readonly undo: AssistantUndoView | null;\n /** Put that turn back. A no-op once the offer has expired. */\n readonly undoTurn: () => Promise<void>;\n /** Put one action of the last turn back, by its receipt's replay identity. */\n readonly undoAction: (idempotencyKey: string) => Promise<void>;\n /** What the reader said not to ask about again, each with its own name. */\n readonly alwaysAllowed: readonly AssistantAllowance[];\n /** Ask about one of them again from now on. */\n readonly revokeAlwaysAllow: (capability: string) => void;\n /** The suggestions this table can run right now, re-checked every render. */\n readonly suggestions: readonly AssistantSuggestion[];\n /** Send a suggestion's prompt as if the reader had typed it. */\n readonly runSuggestion: (id: string) => Promise<void>;\n readonly open: boolean;\n readonly setOpen: (open: boolean) => void;\n /** The last failure, cleared by the next successful turn. */\n readonly error: string | undefined;\n /**\n * The machine code behind `error`, when a turn ended with work\n * pending. A surface with labels turns it into a sentence for the reader;\n * the message beside it is written for whoever is debugging the turn.\n */\n readonly errorCode: string | undefined;\n}\n\n/**\n * Run a table assistant.\n *\n * A thin subscriber to the neutral controller in `@adapttable/ai/assistant`:\n * React supplies the external-store mechanism, the live inputs and the\n * controlled presentation state, and owns none of the lifecycle.\n *\n * @param options - Session, transport and presentation.\n * @returns Everything a panel needs, and nothing about how it looks.\n *\n * @public\n */\nexport function useTableAssistant(\n options: TableAssistantOptions\n): TableAssistantState {\n const { onOpenChange } = options;\n const [uncontrolledOpen, setUncontrolledOpen] = useState(false);\n // The live approval, so a host wires the panel with one prop rather than\n // reaching for feature state itself.\n const approval = useFeatureState(AGENT_APPROVAL_STATE);\n // What the reader has waved through, published by the binding whether or\n // not an approval is open.\n const alwaysAllow = useFeatureState(AGENT_ALWAYS_ALLOW_STATE);\n // The table's own live view, published by `tableAgent`. A host that drives\n // the panel from state of its own passes `contextInputs` and this is unused.\n const viewState = useFeatureState(AGENT_VIEW_STATE);\n // How far a running capability has got, for the same reason: a panel inside\n // the table needs no host wiring to say what the work is doing.\n const progress = useFeatureState(AGENT_PROGRESS_STATE);\n\n // Created once, inert until the mount effect connects it. Constructing a\n // store during render must not open a connection — a render can be thrown\n // away, and Strict Mode throws the first one away on purpose.\n const storeRef = useRef<ReturnType<typeof createTableAssistant> | null>(null);\n const mountRef = useRef<{ superseded: boolean } | null>(null);\n const table = { approval, alwaysAllow, viewState, progress };\n storeRef.current ??= createTableAssistant(\n tableAssistantInputs(options, table)\n );\n const store = storeRef.current;\n\n // Live inputs, every render. The store decides what a change means: a new\n // session resets the conversation, a new transport key reconnects, and an\n // updated catalog or a newly arrived approval does neither.\n useEffect(() => {\n store.update(tableAssistantInputs(options, table));\n });\n\n useEffect(() => {\n const mount = { superseded: false };\n if (mountRef.current) mountRef.current.superseded = true;\n mountRef.current = mount;\n store.connect();\n return () => {\n // React may replay this effect without rendering a replacement store.\n // Release the connection, retaining the inert controller for that next\n // setup. This also hands durable work to the host before unmounting.\n // useSyncExternalStore removes its own subscription on cleanup.\n store.disconnect();\n queueMicrotask(() => {\n if (!mount.superseded) store.dispose();\n });\n };\n }, [store]);\n\n const state = useSyncExternalStore(\n store.subscribe,\n store.getState,\n store.getState\n );\n\n const open = options.open ?? uncontrolledOpen;\n const setOpen = useCallback(\n (next: boolean) => {\n if (options.open === undefined) setUncontrolledOpen(next);\n onOpenChange?.(next);\n },\n [options.open, onOpenChange]\n );\n\n return {\n ...tableAssistantFields(state, store),\n approval: approval ?? null,\n open,\n setOpen,\n };\n}\n","/**\n * Opt-in table feature — `@adapttable/ai-react`.\n *\n * `@adapttable/ai` stays React-free. This package mounts a provider that\n * drives `@adapttable/ai`'s table agent controller from React: it keeps the\n * controller's inputs current, re-renders on its snapshot and the table's\n * changes, and publishes what the controller holds as feature state.\n */\nimport {\n type AgentSession,\n createTableAgentController,\n TABLE_AGENT_STATE,\n type TableAgentBridge as NeutralBridge,\n type TableAgentController,\n type TableAgentControllerOptions,\n} from \"@adapttable/ai\";\nimport {\n AGENT_ALWAYS_ALLOW_STATE,\n AGENT_APPROVAL_STATE,\n AGENT_PROGRESS_STATE,\n AGENT_VIEW_STATE,\n type AgentApprovalPending,\n type FeatureProviderProps,\n FeatureStateScope,\n type StaticTableFeature,\n useTableRuntime,\n} from \"@adapttable/react/adapter\";\nimport {\n type ReactNode,\n useCallback,\n useDebugValue,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport { flushSync } from \"react-dom\";\n\nexport type { SharedApproval, TableAgentColumnPatch } from \"@adapttable/ai\";\n\n// The bridge contract is `@adapttable/ai`'s — a manifest, a session and a\n// pending approval are what any binding publishes, none of it React. Named\n// here with this binding's own pending shape so every existing import keeps\n// working.\nexport type TableAgentBridge = NeutralBridge<AgentApprovalPending>;\n\n// The live session's key is `@adapttable/ai`'s, so every agent binding\n// publishes and reads the same one.\nexport { TABLE_AGENT_STATE };\n\n/**\n * Options for {@link tableAgent}.\n *\n * The same options `@adapttable/ai`'s table agent controller takes: the\n * runtime half — identity, policy, columns, the host's callbacks and\n * capabilities — plus where updates are published and whether the table is\n * offered to a browser-resident agent.\n *\n * @public\n */\nexport type TableAgentOptions = TableAgentControllerOptions;\n\ninterface TableAgentFeature extends StaticTableFeature {\n readonly options: TableAgentOptions;\n}\n\nfunction TableAgentProvider({\n feature,\n children,\n}: Readonly<FeatureProviderProps>): ReactNode {\n const options = (feature as TableAgentFeature).options;\n const runtime = useTableRuntime();\n const optionsRef = useRef(options);\n optionsRef.current = options;\n const runtimeRef = useRef(runtime);\n runtimeRef.current = runtime;\n // A concrete provider update, rather than an empty `flushSync`, makes React\n // finish controlled-state work already queued by the reader before the\n // session takes its admission snapshot.\n const [admissionTick, setAdmissionTick] = useState(0);\n const flushAdmission = useRef<() => void>(() => undefined);\n flushAdmission.current = () => {\n flushSync(() => {\n setAdmissionTick(admissionTick + 1);\n });\n };\n\n // Built once and never during a render that is thrown away twice: the\n // controller opens nothing until `sync`, which only an effect calls.\n const controllerRef = useRef<TableAgentController | null>(null);\n controllerRef.current ??= createTableAgentController({\n options: optionsRef,\n runtime: runtimeRef,\n flushAdmission: () => {\n flushAdmission.current();\n },\n flush: flushSync,\n });\n const controller = controllerRef.current;\n\n // The table as a store: subscribe where there is one to subscribe to, and\n // read the stamp on every render either way. React re-reads the stamp after\n // it attaches, so a table that moved between the render and the\n // subscription is caught rather than missed. The value is not rendered;\n // re-rendering is the point, because that republishes the manifest.\n const neutralTable = runtime.view()?.neutralTable;\n // The controller subscribes to the table current at the call, so a\n // replaced table is a new subscription.\n const subscribeToTable = useCallback(\n (onStoreChange: () => void) =>\n neutralTable ? controller.subscribeTable(onStoreChange) : () => undefined,\n [controller, neutralTable]\n );\n const stamp = useSyncExternalStore(\n subscribeToTable,\n controller.tableStamp,\n controller.tableStamp\n );\n useDebugValue(stamp);\n\n const state = useSyncExternalStore(\n controller.subscribe,\n controller.getState,\n controller.getState\n );\n\n // Every commit: the controller decides what changed and tells only those\n // who need telling. A layout effect, so a host reading the manifest in its\n // own effects already has this render's.\n useLayoutEffect(() => {\n controller.sync();\n });\n\n // Going away is a close. Strict Mode's setup/cleanup/setup lands here too:\n // the cleanup releases everything, and the next sync sets it up again.\n useEffect(\n () => () => {\n controller.disconnect();\n },\n [controller]\n );\n\n // A new value every render on purpose. The table publishes its runtime\n // while its children render, after this provider has, so a surface below\n // learns what the session now offers only by re-rendering with it — and it\n // re-renders because the value it holds is a different one.\n const session = state.session;\n const published: AgentSession = {\n catalog: () => session.catalog(),\n describe: (key) => session.describe(key),\n execute: (key, args, expectedRevision, idempotencyKey, signal) =>\n session.execute(key, args, expectedRevision, idempotencyKey, signal),\n manifest: () => session.manifest(),\n };\n\n return (\n <FeatureStateScope stateKey={TABLE_AGENT_STATE} value={published}>\n <FeatureStateScope stateKey={AGENT_APPROVAL_STATE} value={state.approval}>\n <FeatureStateScope\n stateKey={AGENT_ALWAYS_ALLOW_STATE}\n value={state.alwaysAllow}\n >\n <FeatureStateScope stateKey={AGENT_VIEW_STATE} value={state.view}>\n <FeatureStateScope\n stateKey={AGENT_PROGRESS_STATE}\n value={state.progress}\n >\n {children}\n </FeatureStateScope>\n </FeatureStateScope>\n </FeatureStateScope>\n </FeatureStateScope>\n </FeatureStateScope>\n );\n}\n\n/**\n * Observe a live table and publish a deterministic capability manifest.\n *\n * Omitting this feature from `features` ships no agent bytes.\n *\n * @public\n */\nexport function tableAgent(options: TableAgentOptions): StaticTableFeature {\n const feature: TableAgentFeature = {\n id: \"table-agent\",\n options,\n provider: { Provider: TableAgentProvider },\n };\n return feature;\n}\n","/**\n * Dictation, as a React hook — `@adapttable/ai-react`.\n *\n * Thin on purpose. The speech session in `@adapttable/ai/voice` owns the\n * browser APIs, the permission states, the language choice and when the\n * microphone is replaced; this subscribes to it, keeps it alive for the life\n * of the composer, and writes what it hears through the caller's `setDraft` —\n * which is the one channel voice is allowed to use, so a spoken sentence\n * becomes a draft the reader can see and fix rather than a request the table\n * has already acted on.\n *\n * It lives here rather than in `@adapttable/react` because it imports\n * `@adapttable/ai`, and that package must stay out of the base graph. The\n * chrome takes `SpeechInputHandle` — the structural shape this returns —\n * from `@adapttable/react/adapter`, which declares it without importing\n * anything.\n */\n\"use client\";\n\nimport {\n createSpeechSession,\n type SpeechClip,\n type VoiceOptions,\n} from \"@adapttable/ai/voice\";\nimport type { SpeechInputHandle } from \"@adapttable/react/adapter\";\nimport { useEffect, useRef, useState, useSyncExternalStore } from \"react\";\n\n/** How the hook is configured. @public */\nexport interface UseSpeechInputOptions {\n readonly voice?: VoiceOptions;\n /** The table's locale, used when no language list was given. */\n readonly locale?: string;\n /** Where heard text goes. Always the draft, never a send. */\n readonly setDraft: (text: string) => void;\n /** Where a recording goes, in backend mode. */\n readonly onClip?: (clip: SpeechClip) => void;\n}\n\n/**\n * Run dictation for one composer.\n *\n * @param options - Voice configuration and where heard text should go.\n * @returns What the composer needs, or an unavailable handle when voice is off.\n *\n * @public\n */\nexport function useSpeechInput(\n options: UseSpeechInputOptions\n): SpeechInputHandle {\n // The latest options, read by the session whenever it needs them, so heard\n // text reaches whatever the latest render passed.\n const latest = useRef(options);\n latest.current = options;\n const [session] = useState(() => createSpeechSession(() => latest.current));\n // Every commit brings the microphone in line with the options; equivalent\n // options keep the one that is listening.\n useEffect(() => {\n session.sync();\n });\n // Strict Mode releases and syncs again, so each setup owns a live controller.\n useEffect(() => () => session.release(), [session]);\n return useSyncExternalStore(\n session.subscribe,\n session.getSnapshot,\n session.getSnapshot\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsRA,SAAgB,kBACd,SACqB;CACrB,MAAM,EAAE,iBAAiB;CACzB,MAAM,CAAC,kBAAkB,wBAAA,GAAuBA,MAAAA,SAAAA,CAAS,KAAK;CAG9D,MAAM,YAAA,GAAWC,0BAAAA,gBAAAA,CAAgBC,0BAAAA,oBAAoB;CAGrD,MAAM,eAAA,GAAcD,0BAAAA,gBAAAA,CAAgBE,0BAAAA,wBAAwB;CAG5D,MAAM,aAAA,GAAYF,0BAAAA,gBAAAA,CAAgBG,0BAAAA,gBAAgB;CAGlD,MAAM,YAAA,GAAWH,0BAAAA,gBAAAA,CAAgBI,0BAAAA,oBAAoB;CAKrD,MAAM,YAAA,GAAWC,MAAAA,OAAAA,CAAuD,IAAI;CAC5E,MAAM,YAAA,GAAWA,MAAAA,OAAAA,CAAuC,IAAI;CAC5D,MAAM,QAAQ;EAAE;EAAU;EAAa;EAAW;CAAS;CAC3D,SAAS,aAAA,GAAYC,eAAAA,qBAAAA,EAAAA,GACnBC,eAAAA,qBAAAA,CAAqB,SAAS,KAAK,CACrC;CACA,MAAM,QAAQ,SAAS;CAKvB,CAAA,GAAA,MAAA,UAAA,OAAgB;EACd,MAAM,QAAA,GAAOA,eAAAA,qBAAAA,CAAqB,SAAS,KAAK,CAAC;CACnD,CAAC;CAED,CAAA,GAAA,MAAA,UAAA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AAA;KAAkB,OAAO,MAAM;KAC1D,UAAA,iBAAA,GAAA,kBAAA,IAAA,CAACJ,0BAAAA,mBAAD;MACE,UAAUK,0BAAAA;MACV,OAAO,MAAM;MAEZ;KACgB,CAAA;IACF,CAAA;GACF,CAAA;EACF,CAAA;CACF,CAAA;AAEvB;;;;;;;;AASA,SAAgB,WAAW,SAAgD;CAMzE,OAAO;EAJL,IAAI;EACJ;EACA,UAAU,EAAE,UAAU,mBAAmB;CAE9B;AACf;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACjJA,SAAgB,eACd,SACmB;CAGnB,MAAM,UAAA,GAASC,MAAAA,OAAAA,CAAO,OAAO;CAC7B,OAAO,UAAU;CACjB,MAAM,CAAC,YAAA,GAAWC,MAAAA,SAAAA,QAAAA,GAAeC,qBAAAA,oBAAAA,OAA0B,OAAO,OAAO,CAAC;CAG1E,CAAA,GAAA,MAAA,UAAA,OAAgB;EACd,QAAQ,KAAK;CACf,CAAC;CAED,CAAA,GAAA,MAAA,UAAA,aAAsB,QAAQ,QAAQ,GAAG,CAAC,OAAO,CAAC;CAClD,QAAA,GAAOC,MAAAA,qBAAAA,CACL,QAAQ,WACR,QAAQ,aACR,QAAQ,WACV;AACF"}
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
 
2
- import { AgentContextInputs, AgentSession, AlwaysAllowedState, AssistantAllowance, AssistantAnswer, AssistantAudio, AssistantInterruption, AssistantInterruption as AssistantInterruption$1, AssistantMessage, AssistantQuestion, AssistantResumeHandle, AssistantResumeHandle as AssistantResumeHandle$1, AssistantStatus, AssistantSuggestion, AssistantSuggestion as AssistantSuggestion$1, AssistantTransport, SharedApproval, TABLE_AGENT_STATE, TableAgentBridge as TableAgentBridge$1, TableAgentColumnPatch, TableAgentControllerOptions, TableAssistantSnapshot, TableAssistantStore } from "@adapttable/ai";
2
+ import { AgentContextInputs, AgentSession, AlwaysAllowedState, AssistantAllowance, AssistantAnswer, AssistantAudio, AssistantInterruption, AssistantInterruption as AssistantInterruption$1, AssistantMessage, AssistantQuestion, AssistantResumeHandle, AssistantResumeHandle as AssistantResumeHandle$1, AssistantStatus, AssistantSuggestion, AssistantSuggestion as AssistantSuggestion$1, AssistantTransport, AssistantUndoView, SharedApproval, TABLE_AGENT_STATE, TableAgentBridge as TableAgentBridge$1, TableAgentColumnPatch, TableAgentControllerOptions, TableAssistantSnapshot, TableAssistantStore } from "@adapttable/ai";
3
3
  import { AgentApprovalPending, AgentProgress, SpeechInputHandle, StaticTableFeature } from "@adapttable/react/adapter";
4
4
  import { SpeechClip, VoiceOptions } from "@adapttable/ai/voice";
5
5
  //#region src/assistant.d.ts
@@ -35,8 +35,9 @@ interface TableAssistantOptions {
35
35
  * Whether a write from this conversation is waiting on a human.
36
36
  *
37
37
  * `execute` does not return while an approval is open, so the turn looks
38
- * like thinking from in here. A host that renders the approval — or wires
39
- * `bridge.approvals` — passes it back so the panel can say what is
38
+ * like thinking from in here. Defaults to whether the table has a write
39
+ * waiting on the reader; a host that renders the approval elsewhere — or
40
+ * wires `bridge.approvals` — passes it so the panel can say what is
40
41
  * actually happening. The turn is still in flight and still stoppable.
41
42
  */
42
43
  readonly awaitingApproval?: boolean;
@@ -161,11 +162,7 @@ interface TableAssistantState {
161
162
  * the moment anything else changes the view. `blockedCode` is a token the
162
163
  * labels translate — the panel never shows a reader a code.
163
164
  */
164
- readonly undo: {
165
- readonly messageId: string;
166
- readonly available: boolean;
167
- readonly blockedCode?: string;
168
- } | null;
165
+ readonly undo: AssistantUndoView | null;
169
166
  /** Put that turn back. A no-op once the offer has expired. */
170
167
  readonly undoTurn: () => Promise<void>;
171
168
  /** Put one action of the last turn back, by its receipt's replay identity. */
@@ -183,7 +180,7 @@ interface TableAssistantState {
183
180
  /** The last failure, cleared by the next successful turn. */
184
181
  readonly error: string | undefined;
185
182
  /**
186
- * The machine code behind {@link error}, when a turn ended with work
183
+ * The machine code behind `error`, when a turn ended with work
187
184
  * pending. A surface with labels turns it into a sentence for the reader;
188
185
  * the message beside it is written for whoever is debugging the turn.
189
186
  */
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":[],"sources":["../src/assistant.tsx","../src/react.tsx","../src/useSpeechInput.ts"],"mappings":";;;;;;UAoFiB;;WAEN,SAAS;;;;;;;;WAQT,YAAY;;;;;;;;;;WAUZ;;WAEA,uBAAuB;;WAEvB;;WAEA,gBAAgB;;;;;;;;;WAShB;;;;;;;;;;;WAWA,cAAc;;;;;;;;WAQd,sBAAsB;;;;;;;;;WAStB,YAAY,QAAQ;;WAEpB,eAAe;;;;;;;;;WASf,oBAAoB;;WAEpB,oBAAoB,mBAAmB;;;;;;;;;WASvC;;;UAIM;WACN,QAAQ;;;;;;;;WAQR;WACA,mBAAmB;WACnB;WACA,WAAW;;WAEX,OAAO,kBAAkB;;;;;;WAMzB,WAAW,MAAM,mBAAmB;;WAEpC;;;;;;WAMA,cAAc;;;;;;;WAOd,aAAa;;WAEb,WAAW;;WAEX;;;;;;;;;WASA,UAAU;;;;;;;;WAQV,UAAU;;WAEV,SAAS;IAAU;IAAmB;;;;;;;;;WAQtC;aACE;aACA;aACA;;;WAGF,gBAAgB;;WAEhB,aAAa,2BAA2B;;WAExC,wBAAwB;;WAExB,oBAAoB;;WAEpB,sBAAsB;;WAEtB,gBAAgB,eAAe;WAC/B;WACA,UAAU;;WAEV;;;;;;WAMA;;;;;;;;;;;;;;iBAeK,kBACd,SAAS,wBACR;;;KC7OS,mBAAmB,mBAAc;;;;;;;;;;;KAgBjC,oBAAoB;;;;;;;;iBA2HhB,WAAW,SAAS,oBAAoB;;;;UCnJvC;WACN,QAAQ;;WAER;;WAEA,WAAW;;WAEX,UAAU,MAAM;;;;;;;;;;iBAaX,eACd,SAAS,wBACR"}
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../src/assistant.tsx","../src/react.tsx","../src/useSpeechInput.ts"],"mappings":";;;;;;UAqFiB;;WAEN,SAAS;;;;;;;;WAQT,YAAY;;;;;;;;;;WAUZ;;WAEA,uBAAuB;;WAEvB;;WAEA,gBAAgB;;;;;;;;;;WAUhB;;;;;;;;;;;WAWA,cAAc;;;;;;;;WAQd,sBAAsB;;;;;;;;;WAStB,YAAY,QAAQ;;WAEpB,eAAe;;;;;;;;;WASf,oBAAoB;;WAEpB,oBAAoB,mBAAmB;;;;;;;;;WASvC;;;UAIM;WACN,QAAQ;;;;;;;;WAQR;WACA,mBAAmB;WACnB;WACA,WAAW;;WAEX,OAAO,kBAAkB;;;;;;WAMzB,WAAW,MAAM,mBAAmB;;WAEpC;;;;;;WAMA,cAAc;;;;;;;WAOd,aAAa;;WAEb,WAAW;;WAEX;;;;;;;;;WASA,UAAU;;;;;;;;WAQV,UAAU;;WAEV,SAAS;IAAU;IAAmB;;;;;;;;;WAQtC,MAAM;;WAEN,gBAAgB;;WAEhB,aAAa,2BAA2B;;WAExC,wBAAwB;;WAExB,oBAAoB;;WAEpB,sBAAsB;;WAEtB,gBAAgB,eAAe;WAC/B;WACA,UAAU;;WAEV;;;;;;WAMA;;;;;;;;;;;;;;iBAeK,kBACd,SAAS,wBACR;;;KC3OS,mBAAmB,mBAAc;;;;;;;;;;;KAgBjC,oBAAoB;;;;;;;;iBA2HhB,WAAW,SAAS,oBAAoB;;;;UC5JvC;WACN,QAAQ;;WAER;;WAEA,WAAW;;WAEX,UAAU,MAAM;;;;;;;;;;iBAWX,eACd,SAAS,wBACR"}
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
 
2
- import { AgentContextInputs, AgentSession, AlwaysAllowedState, AssistantAllowance, AssistantAnswer, AssistantAudio, AssistantInterruption, AssistantInterruption as AssistantInterruption$1, AssistantMessage, AssistantQuestion, AssistantResumeHandle, AssistantResumeHandle as AssistantResumeHandle$1, AssistantStatus, AssistantSuggestion, AssistantSuggestion as AssistantSuggestion$1, AssistantTransport, SharedApproval, TABLE_AGENT_STATE, TableAgentBridge as TableAgentBridge$1, TableAgentColumnPatch, TableAgentControllerOptions, TableAssistantSnapshot, TableAssistantStore } from "@adapttable/ai";
2
+ import { AgentContextInputs, AgentSession, AlwaysAllowedState, AssistantAllowance, AssistantAnswer, AssistantAudio, AssistantInterruption, AssistantInterruption as AssistantInterruption$1, AssistantMessage, AssistantQuestion, AssistantResumeHandle, AssistantResumeHandle as AssistantResumeHandle$1, AssistantStatus, AssistantSuggestion, AssistantSuggestion as AssistantSuggestion$1, AssistantTransport, AssistantUndoView, SharedApproval, TABLE_AGENT_STATE, TableAgentBridge as TableAgentBridge$1, TableAgentColumnPatch, TableAgentControllerOptions, TableAssistantSnapshot, TableAssistantStore } from "@adapttable/ai";
3
3
  import { AgentApprovalPending, AgentProgress, SpeechInputHandle, StaticTableFeature } from "@adapttable/react/adapter";
4
4
  import { SpeechClip, VoiceOptions } from "@adapttable/ai/voice";
5
5
  //#region src/assistant.d.ts
@@ -35,8 +35,9 @@ interface TableAssistantOptions {
35
35
  * Whether a write from this conversation is waiting on a human.
36
36
  *
37
37
  * `execute` does not return while an approval is open, so the turn looks
38
- * like thinking from in here. A host that renders the approval — or wires
39
- * `bridge.approvals` — passes it back so the panel can say what is
38
+ * like thinking from in here. Defaults to whether the table has a write
39
+ * waiting on the reader; a host that renders the approval elsewhere — or
40
+ * wires `bridge.approvals` — passes it so the panel can say what is
40
41
  * actually happening. The turn is still in flight and still stoppable.
41
42
  */
42
43
  readonly awaitingApproval?: boolean;
@@ -161,11 +162,7 @@ interface TableAssistantState {
161
162
  * the moment anything else changes the view. `blockedCode` is a token the
162
163
  * labels translate — the panel never shows a reader a code.
163
164
  */
164
- readonly undo: {
165
- readonly messageId: string;
166
- readonly available: boolean;
167
- readonly blockedCode?: string;
168
- } | null;
165
+ readonly undo: AssistantUndoView | null;
169
166
  /** Put that turn back. A no-op once the offer has expired. */
170
167
  readonly undoTurn: () => Promise<void>;
171
168
  /** Put one action of the last turn back, by its receipt's replay identity. */
@@ -183,7 +180,7 @@ interface TableAssistantState {
183
180
  /** The last failure, cleared by the next successful turn. */
184
181
  readonly error: string | undefined;
185
182
  /**
186
- * The machine code behind {@link error}, when a turn ended with work
183
+ * The machine code behind `error`, when a turn ended with work
187
184
  * pending. A surface with labels turns it into a sentence for the reader;
188
185
  * the message beside it is written for whoever is debugging the turn.
189
186
  */
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/assistant.tsx","../src/react.tsx","../src/useSpeechInput.ts"],"mappings":";;;;;;UAoFiB;;WAEN,SAAS;;;;;;;;WAQT,YAAY;;;;;;;;;;WAUZ;;WAEA,uBAAuB;;WAEvB;;WAEA,gBAAgB;;;;;;;;;WAShB;;;;;;;;;;;WAWA,cAAc;;;;;;;;WAQd,sBAAsB;;;;;;;;;WAStB,YAAY,QAAQ;;WAEpB,eAAe;;;;;;;;;WASf,oBAAoB;;WAEpB,oBAAoB,mBAAmB;;;;;;;;;WASvC;;;UAIM;WACN,QAAQ;;;;;;;;WAQR;WACA,mBAAmB;WACnB;WACA,WAAW;;WAEX,OAAO,kBAAkB;;;;;;WAMzB,WAAW,MAAM,mBAAmB;;WAEpC;;;;;;WAMA,cAAc;;;;;;;WAOd,aAAa;;WAEb,WAAW;;WAEX;;;;;;;;;WASA,UAAU;;;;;;;;WAQV,UAAU;;WAEV,SAAS;IAAU;IAAmB;;;;;;;;;WAQtC;aACE;aACA;aACA;;;WAGF,gBAAgB;;WAEhB,aAAa,2BAA2B;;WAExC,wBAAwB;;WAExB,oBAAoB;;WAEpB,sBAAsB;;WAEtB,gBAAgB,eAAe;WAC/B;WACA,UAAU;;WAEV;;;;;;WAMA;;;;;;;;;;;;;;iBAeK,kBACd,SAAS,wBACR;;;KC7OS,mBAAmB,mBAAc;;;;;;;;;;;KAgBjC,oBAAoB;;;;;;;;iBA2HhB,WAAW,SAAS,oBAAoB;;;;UCnJvC;WACN,QAAQ;;WAER;;WAEA,WAAW;;WAEX,UAAU,MAAM;;;;;;;;;;iBAaX,eACd,SAAS,wBACR"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/assistant.tsx","../src/react.tsx","../src/useSpeechInput.ts"],"mappings":";;;;;;UAqFiB;;WAEN,SAAS;;;;;;;;WAQT,YAAY;;;;;;;;;;WAUZ;;WAEA,uBAAuB;;WAEvB;;WAEA,gBAAgB;;;;;;;;;;WAUhB;;;;;;;;;;;WAWA,cAAc;;;;;;;;WAQd,sBAAsB;;;;;;;;;WAStB,YAAY,QAAQ;;WAEpB,eAAe;;;;;;;;;WASf,oBAAoB;;WAEpB,oBAAoB,mBAAmB;;;;;;;;;WASvC;;;UAIM;WACN,QAAQ;;;;;;;;WAQR;WACA,mBAAmB;WACnB;WACA,WAAW;;WAEX,OAAO,kBAAkB;;;;;;WAMzB,WAAW,MAAM,mBAAmB;;WAEpC;;;;;;WAMA,cAAc;;;;;;;WAOd,aAAa;;WAEb,WAAW;;WAEX;;;;;;;;;WASA,UAAU;;;;;;;;WAQV,UAAU;;WAEV,SAAS;IAAU;IAAmB;;;;;;;;;WAQtC,MAAM;;WAEN,gBAAgB;;WAEhB,aAAa,2BAA2B;;WAExC,wBAAwB;;WAExB,oBAAoB;;WAEpB,sBAAsB;;WAEtB,gBAAgB,eAAe;WAC/B;WACA,UAAU;;WAEV;;;;;;WAMA;;;;;;;;;;;;;;iBAeK,kBACd,SAAS,wBACR;;;KC3OS,mBAAmB,mBAAc;;;;;;;;;;;KAgBjC,oBAAoB;;;;;;;;iBA2HhB,WAAW,SAAS,oBAAoB;;;;UC5JvC;WACN,QAAQ;;WAER;;WAEA,WAAW;;WAEX,UAAU,MAAM;;;;;;;;;;iBAWX,eACd,SAAS,wBACR"}
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  "use client";
2
- import { TABLE_AGENT_STATE, createTableAgentController, createTableAssistant } from "@adapttable/ai";
2
+ import { TABLE_AGENT_STATE, createTableAgentController, createTableAssistant, tableAssistantFields, tableAssistantInputs } from "@adapttable/ai";
3
3
  import { AGENT_ALWAYS_ALLOW_STATE, AGENT_APPROVAL_STATE, AGENT_PROGRESS_STATE, AGENT_VIEW_STATE, FeatureStateScope, useFeatureState, useTableRuntime } from "@adapttable/react/adapter";
4
- import { useCallback, useDebugValue, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
4
+ import { useCallback, useDebugValue, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore } from "react";
5
5
  import { flushSync } from "react-dom";
6
6
  import { jsx } from "react/jsx-runtime";
7
- import { createSpeechInput, readRememberedLanguage, rememberLanguage } from "@adapttable/ai/voice";
7
+ import { createSpeechSession } from "@adapttable/ai/voice";
8
8
  //#region src/assistant.tsx
9
9
  /**
10
10
  * `@adapttable/ai-react` — the conversation lifecycle, without a UI.
@@ -48,10 +48,16 @@ function useTableAssistant(options) {
48
48
  const progress = useFeatureState(AGENT_PROGRESS_STATE);
49
49
  const storeRef = useRef(null);
50
50
  const mountRef = useRef(null);
51
- storeRef.current ??= createTableAssistant(inputsOf(options, approval, alwaysAllow, viewState, progress));
51
+ const table = {
52
+ approval,
53
+ alwaysAllow,
54
+ viewState,
55
+ progress
56
+ };
57
+ storeRef.current ??= createTableAssistant(tableAssistantInputs(options, table));
52
58
  const store = storeRef.current;
53
59
  useEffect(() => {
54
- store.update(inputsOf(options, approval, alwaysAllow, viewState, progress));
60
+ store.update(tableAssistantInputs(options, table));
55
61
  });
56
62
  useEffect(() => {
57
63
  const mount = { superseded: false };
@@ -72,59 +78,10 @@ function useTableAssistant(options) {
72
78
  onOpenChange?.(next);
73
79
  }, [options.open, onOpenChange]);
74
80
  return {
75
- messages: state.messages,
76
- draft: state.draft,
77
- setDraft: store.setDraft,
78
- send: store.send,
79
- sendClip: store.sendClip,
80
- stop: store.stop,
81
- resume: store.resume,
82
- interrupted: state.interrupted,
83
- resumable: state.resumable,
84
- clear: store.clear,
85
- status: state.status,
86
- busy: state.busy,
81
+ ...tableAssistantFields(state, store),
87
82
  approval: approval ?? null,
88
- progress: state.progress,
89
- answer: store.answer,
90
- undo: state.undo ? {
91
- messageId: state.undo.messageId,
92
- available: state.undo.available,
93
- ...state.undo.blocked ? { blockedCode: state.undo.blocked.code } : {}
94
- } : null,
95
- undoTurn: store.undoTurn,
96
- undoAction: store.undoAction,
97
- alwaysAllowed: state.alwaysAllowed,
98
- revokeAlwaysAllow: store.revokeAlwaysAllow,
99
- suggestions: state.suggestions,
100
- runSuggestion: store.runSuggestion,
101
83
  open,
102
- setOpen,
103
- error: state.error,
104
- errorCode: state.errorCode
105
- };
106
- }
107
- /** The hook's options as the store's live inputs. A projection, not a decision. */
108
- function inputsOf(options, approval, alwaysAllow, viewState, progress) {
109
- const contextInputs = options.contextInputs ?? (viewState ? () => viewState.read() : void 0);
110
- return {
111
- session: options.session,
112
- transport: options.transport,
113
- transportKey: options.transportKey,
114
- suggestions: options.suggestions,
115
- awaitingApproval: options.awaitingApproval,
116
- approval: approval ?? null,
117
- progress: progress ?? null,
118
- ...contextInputs ? { contextInputs } : {},
119
- ...options.onDetach ? { onDetach: options.onDetach } : {},
120
- ...options.messages ? { messages: options.messages } : {},
121
- ...options.onMessagesChange ? { onMessagesChange: options.onMessagesChange } : {},
122
- ...options.conversation === void 0 ? {} : { conversation: options.conversation },
123
- ...options.resumeHandle ? { resumeHandle: options.resumeHandle } : {},
124
- ...options.alwaysAllow ?? alwaysAllow ? {
125
- alwaysAllowed: (options.alwaysAllow ?? alwaysAllow)?.capabilities,
126
- onRevokeAlwaysAllow: (options.alwaysAllow ?? alwaysAllow)?.revoke
127
- } : {}
84
+ setOpen
128
85
  };
129
86
  }
130
87
  //#endregion
@@ -219,12 +176,13 @@ function tableAgent(options) {
219
176
  /**
220
177
  * Dictation, as a React hook — `@adapttable/ai-react`.
221
178
  *
222
- * Thin on purpose. The controller in `@adapttable/ai/voice` owns the browser
223
- * APIs, the permission states and the language choice; this subscribes to it,
224
- * keeps it alive for the life of the composer, and writes what it hears
225
- * through the caller's `setDraft` — which is the one channel voice is allowed
226
- * to use, so a spoken sentence becomes a draft the reader can see and fix
227
- * rather than a request the table has already acted on.
179
+ * Thin on purpose. The speech session in `@adapttable/ai/voice` owns the
180
+ * browser APIs, the permission states, the language choice and when the
181
+ * microphone is replaced; this subscribes to it, keeps it alive for the life
182
+ * of the composer, and writes what it hears through the caller's `setDraft` —
183
+ * which is the one channel voice is allowed to use, so a spoken sentence
184
+ * becomes a draft the reader can see and fix rather than a request the table
185
+ * has already acted on.
228
186
  *
229
187
  * It lives here rather than in `@adapttable/react` because it imports
230
188
  * `@adapttable/ai`, and that package must stay out of the base graph. The
@@ -232,11 +190,6 @@ function tableAgent(options) {
232
190
  * from `@adapttable/react/adapter`, which declares it without importing
233
191
  * anything.
234
192
  */
235
- const IDLE = {
236
- status: "unsupported",
237
- language: "",
238
- interim: ""
239
- };
240
193
  /**
241
194
  * Run dictation for one composer.
242
195
  *
@@ -246,48 +199,14 @@ const IDLE = {
246
199
  * @public
247
200
  */
248
201
  function useSpeechInput(options) {
249
- const { voice, locale, setDraft, onClip } = options;
250
- const draftRef = useRef(setDraft);
251
- draftRef.current = setDraft;
252
- const clipRef = useRef(onClip);
253
- clipRef.current = onClip;
254
- const enabled = voice !== void 0;
255
- const mode = voice?.mode ?? "browser";
256
- const languagesKey = JSON.stringify(voice?.languages?.length ? voice.languages : [locale ?? "en-US"]);
257
- const languages = useMemo(() => JSON.parse(languagesKey), [languagesKey]);
258
- const [input, setInput] = useState(null);
202
+ const latest = useRef(options);
203
+ latest.current = options;
204
+ const [session] = useState(() => createSpeechSession(() => latest.current));
259
205
  useEffect(() => {
260
- if (!enabled) {
261
- setInput(null);
262
- return;
263
- }
264
- const remembered = readRememberedLanguage();
265
- const current = createSpeechInput({
266
- mode,
267
- languages,
268
- ...remembered ? { initialLanguage: remembered } : {},
269
- onDraft: (text) => draftRef.current(text),
270
- onClip: (clip) => clipRef.current?.(clip)
271
- });
272
- setInput(current);
273
- return () => current.dispose();
274
- }, [
275
- enabled,
276
- mode,
277
- languages
278
- ]);
279
- const state = useSyncExternalStore((listener) => input?.subscribe(listener) ?? (() => void 0), () => input?.getState() ?? IDLE, () => IDLE);
280
- return {
281
- available: Boolean(voice && input?.supported()),
282
- state,
283
- languages,
284
- start: () => input?.start(),
285
- stop: () => input?.stop(),
286
- setLanguage: (language) => {
287
- input?.setLanguage(language);
288
- rememberLanguage(language);
289
- }
290
- };
206
+ session.sync();
207
+ });
208
+ useEffect(() => () => session.release(), [session]);
209
+ return useSyncExternalStore(session.subscribe, session.getSnapshot, session.getSnapshot);
291
210
  }
292
211
  //#endregion
293
212
  export { TABLE_AGENT_STATE, tableAgent, useSpeechInput, useTableAssistant };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/assistant.tsx","../src/react.tsx","../src/useSpeechInput.ts"],"sourcesContent":["/**\n * `@adapttable/ai-react` — the conversation lifecycle, without a UI.\n *\n * This entry owns state and nothing else: no markup, no launcher, no\n * provider client. A host renders its own panel from what the hook returns,\n * and the shipped widget is written against these same public values — which\n * is the only way to be sure it is not required.\n *\n * The rules that shape it:\n *\n * - **One send at a time**, reserved before any await. Two sends racing would\n * interleave two turns' actions against one table.\n * - **A draft survives failure.** Losing what someone typed because a\n * backend was down is worse than the outage.\n * - **A cancelled send is not a cancelled action.** Aborting before the\n * transport answers is clean; aborting after actions began is reported for\n * what it is, and nothing is retried — a mutation whose outcome is unknown\n * is never sent twice.\n * - **A late reply is dropped.** A turn that was stopped, or that belonged\n * to a previous table, never writes into the transcript.\n */\n\"use client\";\n\nimport {\n type AgentContextInputs,\n type AgentSession,\n type AlwaysAllowedState,\n type AssistantAllowance,\n type AssistantAudio,\n type AssistantInterruption,\n type AssistantMessage,\n type AssistantResumeHandle,\n type AssistantStatus,\n type AssistantSuggestion,\n type AssistantTransport,\n createTableAssistant,\n} from \"@adapttable/ai\";\nimport {\n AGENT_ALWAYS_ALLOW_STATE,\n AGENT_APPROVAL_STATE,\n AGENT_PROGRESS_STATE,\n AGENT_VIEW_STATE,\n type AgentAlwaysAllowState,\n type AgentApprovalPending,\n type AgentProgress,\n type AgentViewState,\n useFeatureState,\n} from \"@adapttable/react/adapter\";\nimport {\n useCallback,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\n\n// The hook's own options and state name these, so the entry that publishes\n// the hook publishes them too — a consumer typing a variable from it should\n// not have to reach into another entry point for the pieces.\nexport type {\n ApprovalPolicy,\n AssistantReceiptStatus,\n AssistantReceiptSubject,\n CommitPolicy,\n RowAddressScope,\n WritePolicy,\n} from \"@adapttable/ai\";\nexport type {\n AssistantInterruption,\n AssistantMessage,\n AssistantResumeHandle,\n AssistantStatus,\n AssistantTransport,\n};\nexport type {\n AssistantExchange,\n AssistantQuestion,\n AssistantReceipt,\n AssistantTransportReply,\n AssistantTurnStatus,\n} from \"@adapttable/ai\";\nexport type { AssistantUndoOffer } from \"@adapttable/ai\";\n\n/** How {@link useTableAssistant} is configured. @public */\nexport interface TableAssistantOptions {\n /** The live session. Changing it starts a new conversation. */\n readonly session: AgentSession | undefined;\n /**\n * Where a turn goes. Omit and the assistant stays disconnected.\n *\n * May be a fresh object every render — the controller reads the latest one\n * rather than reconnecting on its identity, so a host is not forced to\n * memoize it.\n */\n readonly transport?: AssistantTransport;\n /**\n * Changes when the transport should be re-established.\n *\n * The conversation resets on a new session, because that is a new table.\n * Swapping one transport for another — a backend for a scripted one — is\n * not visible in the object identity, so a host that does it names the\n * change here. A backend transport must never quietly become a simulated\n * one under the same key.\n */\n readonly transportKey?: string;\n /** Everything authored, filtered live against what the table offers. */\n readonly suggestions?: readonly AssistantSuggestion[];\n /** Controlled panel state. Omit for uncontrolled. */\n readonly open?: boolean;\n /** Called on every open/close request, controlled or not. */\n readonly onOpenChange?: (open: boolean) => void;\n /**\n * Whether a write from this conversation is waiting on a human.\n *\n * `execute` does not return while an approval is open, so the turn looks\n * like thinking from in here. A host that renders the approval — or wires\n * `bridge.approvals` — passes it back so the panel can say what is\n * actually happening. The turn is still in flight and still stoppable.\n */\n readonly awaitingApproval?: boolean;\n /**\n * What the reader has waved through, when the panel is mounted outside the\n * table.\n *\n * A panel inside the table reads this from feature state and needs nothing\n * here. One beside it cannot, so a host wires `bridge.alwaysAllowed` and\n * passes what it publishes — the same arrangement `bridge.approvals` and\n * `bridge.viewInputs` already have. Without it a reader can wave a\n * capability through and have no way to take it back.\n */\n readonly alwaysAllow?: AlwaysAllowedState;\n /**\n * Live view and filter data the manifest does not carry.\n *\n * Read when a turn starts and again when it settles, so per-turn undo can\n * tell what the turn moved. A function rather than a value: a fixed object\n * would report that nothing changed.\n */\n readonly contextInputs?: () => AgentContextInputs;\n /**\n * Work that outlived its connection, handed over the moment it does.\n *\n * Durable recovery starts here and ends outside this package: a host that\n * stores the handle where it survives a reload can offer a resume when the\n * reader comes back, and a host that does nothing loses the work with the\n * page.\n */\n readonly onDetach?: (handle: AssistantResumeHandle) => void;\n /** A handle kept from a previous page, to resume into this one. */\n readonly resumeHandle?: AssistantResumeHandle;\n /**\n * The transcript, when your app owns it.\n *\n * Omit it and the conversation lives in the controller. Supply it to load\n * the last conversation from your own API, append a message that arrived on\n * a socket, or keep it where it survives a reload — pass a new array and the\n * panel shows it. Pair it with `onMessagesChange`.\n */\n readonly messages?: readonly AssistantMessage[];\n /** Told whenever the transcript changes, with the whole of it. */\n readonly onMessagesChange?: (messages: readonly AssistantMessage[]) => void;\n /**\n * How much of the conversation travels with each turn.\n *\n * `\"full\"` (default) sends every earlier message, for a backend that\n * remembers nothing. A number sends that many of the most recent. `0` sends\n * none — the reader's message still travels, and a backend holding its own\n * session supplies the rest. What the reader sees is never trimmed.\n */\n readonly conversation?: \"full\" | number;\n}\n\n/** What a host renders from. @public */\nexport interface TableAssistantState {\n readonly status: AssistantStatus;\n /**\n * Whether a turn is in flight and can still be stopped.\n *\n * Separate from {@link TableAssistantState.status}: a write parked on a\n * human approval reports `awaiting-approval` but is still running, and\n * Stop still ends it.\n */\n readonly busy: boolean;\n readonly messages: readonly AssistantMessage[];\n readonly draft: string;\n readonly setDraft: (draft: string) => void;\n /** Send the draft, or the given text. Resolves when the turn settles. */\n readonly send: (text?: string) => Promise<void>;\n /**\n * Send a recording as the reader's turn — pass it as `onClip` to\n * backend-mode `useSpeechInput`. The transcript the backend returns becomes\n * the reader's message.\n */\n readonly sendClip: (clip: AssistantAudio) => Promise<void>;\n /** Abort the turn in flight. Safe to call when nothing is in flight. */\n readonly stop: () => void;\n /**\n * Rejoin work a released connection left running.\n *\n * A no-op with nothing to rejoin, which is what `resumable` says.\n */\n readonly resume: () => Promise<void>;\n /**\n * What became of the last turn, when no reply ended it.\n *\n * `\"stopped\"` is the reader's own decision; `\"detached\"` is a released\n * connection, where the work may still be running.\n */\n readonly interrupted: AssistantInterruption | undefined;\n /** The work `resume` would rejoin, or nothing. */\n readonly resumable: AssistantResumeHandle | undefined;\n /** Drop the transcript. Refuses while a turn is in flight. */\n readonly clear: () => void;\n /**\n * A write waiting on the reader, or nothing.\n *\n * Hand it to the panel as `approval` and the conversation reviews it —\n * which is where a write asked for in the conversation belongs. The panel\n * draws it only when the approval's presentation names the widget, so\n * passing it costs nothing on a table reviewing elsewhere.\n */\n readonly approval: AgentApprovalPending | null;\n /**\n * How far the capability now running has got, or nothing.\n *\n * Published by the table while a long call works through its rows. It never\n * becomes the receipt: when the turn settles this goes and the receipts say\n * what happened.\n */\n readonly progress: AgentProgress | null;\n /** Answer the pending question and let the turn continue. */\n readonly answer: (answer: { optionId?: string; text?: string }) => void;\n /**\n * Whether the last turn that moved the table can still be put back.\n *\n * Null when no turn moved it. Re-read every render, because the offer ends\n * the moment anything else changes the view. `blockedCode` is a token the\n * labels translate — the panel never shows a reader a code.\n */\n readonly undo: {\n readonly messageId: string;\n readonly available: boolean;\n readonly blockedCode?: string;\n } | null;\n /** Put that turn back. A no-op once the offer has expired. */\n readonly undoTurn: () => Promise<void>;\n /** Put one action of the last turn back, by its receipt's replay identity. */\n readonly undoAction: (idempotencyKey: string) => Promise<void>;\n /** What the reader said not to ask about again, each with its own name. */\n readonly alwaysAllowed: readonly AssistantAllowance[];\n /** Ask about one of them again from now on. */\n readonly revokeAlwaysAllow: (capability: string) => void;\n /** The suggestions this table can run right now, re-checked every render. */\n readonly suggestions: readonly AssistantSuggestion[];\n /** Send a suggestion's prompt as if the reader had typed it. */\n readonly runSuggestion: (id: string) => Promise<void>;\n readonly open: boolean;\n readonly setOpen: (open: boolean) => void;\n /** The last failure, cleared by the next successful turn. */\n readonly error: string | undefined;\n /**\n * The machine code behind {@link error}, when a turn ended with work\n * pending. A surface with labels turns it into a sentence for the reader;\n * the message beside it is written for whoever is debugging the turn.\n */\n readonly errorCode: string | undefined;\n}\n\n/**\n * Run a table assistant.\n *\n * A thin subscriber to the neutral controller in `@adapttable/ai/assistant`:\n * React supplies the external-store mechanism, the live inputs and the\n * controlled presentation state, and owns none of the lifecycle.\n *\n * @param options - Session, transport and presentation.\n * @returns Everything a panel needs, and nothing about how it looks.\n *\n * @public\n */\nexport function useTableAssistant(\n options: TableAssistantOptions\n): TableAssistantState {\n const { onOpenChange } = options;\n const [uncontrolledOpen, setUncontrolledOpen] = useState(false);\n // The live approval, so a host wires the panel with one prop rather than\n // reaching for feature state itself.\n const approval = useFeatureState(AGENT_APPROVAL_STATE);\n // What the reader has waved through, published by the binding whether or\n // not an approval is open.\n const alwaysAllow = useFeatureState(AGENT_ALWAYS_ALLOW_STATE);\n // The table's own live view, published by `tableAgent`. A host that drives\n // the panel from state of its own passes `contextInputs` and this is unused.\n const viewState = useFeatureState(AGENT_VIEW_STATE);\n // How far a running capability has got, for the same reason: a panel inside\n // the table needs no host wiring to say what the work is doing.\n const progress = useFeatureState(AGENT_PROGRESS_STATE);\n\n // Created once, inert until the mount effect connects it. Constructing a\n // store during render must not open a connection — a render can be thrown\n // away, and Strict Mode throws the first one away on purpose.\n const storeRef = useRef<ReturnType<typeof createTableAssistant> | null>(null);\n const mountRef = useRef<{ superseded: boolean } | null>(null);\n storeRef.current ??= createTableAssistant(\n inputsOf(options, approval, alwaysAllow, viewState, progress)\n );\n const store = storeRef.current;\n\n // Live inputs, every render. The store decides what a change means: a new\n // session resets the conversation, a new transport key reconnects, and an\n // updated catalog or a newly arrived approval does neither.\n useEffect(() => {\n store.update(inputsOf(options, approval, alwaysAllow, viewState, progress));\n });\n\n useEffect(() => {\n const mount = { superseded: false };\n if (mountRef.current) mountRef.current.superseded = true;\n mountRef.current = mount;\n store.connect();\n return () => {\n // React may replay this effect without rendering a replacement store.\n // Release the connection, retaining the inert controller for that next\n // setup. This also hands durable work to the host before unmounting.\n // useSyncExternalStore removes its own subscription on cleanup.\n store.disconnect();\n queueMicrotask(() => {\n if (!mount.superseded) store.dispose();\n });\n };\n }, [store]);\n\n const state = useSyncExternalStore(\n store.subscribe,\n store.getState,\n store.getState\n );\n\n const open = options.open ?? uncontrolledOpen;\n const setOpen = useCallback(\n (next: boolean) => {\n if (options.open === undefined) setUncontrolledOpen(next);\n onOpenChange?.(next);\n },\n [options.open, onOpenChange]\n );\n\n return {\n messages: state.messages,\n draft: state.draft,\n setDraft: store.setDraft,\n send: store.send,\n sendClip: store.sendClip,\n stop: store.stop,\n resume: store.resume,\n interrupted: state.interrupted,\n resumable: state.resumable,\n clear: store.clear,\n status: state.status,\n busy: state.busy,\n approval: approval ?? null,\n progress: state.progress,\n answer: store.answer,\n undo: state.undo\n ? {\n messageId: state.undo.messageId,\n available: state.undo.available,\n ...(state.undo.blocked\n ? { blockedCode: state.undo.blocked.code }\n : {}),\n }\n : null,\n undoTurn: store.undoTurn,\n undoAction: store.undoAction,\n alwaysAllowed: state.alwaysAllowed,\n revokeAlwaysAllow: store.revokeAlwaysAllow,\n suggestions: state.suggestions,\n runSuggestion: store.runSuggestion,\n open,\n setOpen,\n error: state.error,\n errorCode: state.errorCode,\n };\n}\n\n/** The hook's options as the store's live inputs. A projection, not a decision. */\nfunction inputsOf(\n options: TableAssistantOptions,\n approval: AgentApprovalPending | null | undefined,\n alwaysAllow: AgentAlwaysAllowState | null | undefined,\n viewState: AgentViewState | null | undefined,\n progress: AgentProgress | null | undefined\n) {\n // The host's own reader wins; otherwise the table's, which is what makes\n // per-turn undo work without a host lifting page and sort into its state.\n const contextInputs =\n options.contextInputs ??\n (viewState ? () => viewState.read() as AgentContextInputs : undefined);\n return {\n session: options.session,\n transport: options.transport,\n transportKey: options.transportKey,\n suggestions: options.suggestions,\n awaitingApproval: options.awaitingApproval,\n approval: approval ?? null,\n progress: progress ?? null,\n ...(contextInputs ? { contextInputs } : {}),\n ...(options.onDetach ? { onDetach: options.onDetach } : {}),\n ...(options.messages ? { messages: options.messages } : {}),\n ...(options.onMessagesChange\n ? { onMessagesChange: options.onMessagesChange }\n : {}),\n ...(options.conversation === undefined\n ? {}\n : { conversation: options.conversation }),\n ...(options.resumeHandle ? { resumeHandle: options.resumeHandle } : {}),\n // The host's own wins, for the same reason `contextInputs` does: a panel\n // beside the table has no feature state to read.\n ...((options.alwaysAllow ?? alwaysAllow)\n ? {\n alwaysAllowed: (options.alwaysAllow ?? alwaysAllow)?.capabilities,\n onRevokeAlwaysAllow: (options.alwaysAllow ?? alwaysAllow)?.revoke,\n }\n : {}),\n };\n}\n","/**\n * Opt-in table feature — `@adapttable/ai-react`.\n *\n * `@adapttable/ai` stays React-free. This package mounts a provider that\n * drives `@adapttable/ai`'s table agent controller from React: it keeps the\n * controller's inputs current, re-renders on its snapshot and the table's\n * changes, and publishes what the controller holds as feature state.\n */\nimport {\n type AgentSession,\n createTableAgentController,\n TABLE_AGENT_STATE,\n type TableAgentBridge as NeutralBridge,\n type TableAgentController,\n type TableAgentControllerOptions,\n} from \"@adapttable/ai\";\nimport {\n AGENT_ALWAYS_ALLOW_STATE,\n AGENT_APPROVAL_STATE,\n AGENT_PROGRESS_STATE,\n AGENT_VIEW_STATE,\n type AgentApprovalPending,\n type FeatureProviderProps,\n FeatureStateScope,\n type StaticTableFeature,\n useTableRuntime,\n} from \"@adapttable/react/adapter\";\nimport {\n type ReactNode,\n useCallback,\n useDebugValue,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport { flushSync } from \"react-dom\";\n\nexport type { SharedApproval, TableAgentColumnPatch } from \"@adapttable/ai\";\n\n// The bridge contract is `@adapttable/ai`'s — a manifest, a session and a\n// pending approval are what any binding publishes, none of it React. Named\n// here with this binding's own pending shape so every existing import keeps\n// working.\nexport type TableAgentBridge = NeutralBridge<AgentApprovalPending>;\n\n// The live session's key is `@adapttable/ai`'s, so every agent binding\n// publishes and reads the same one.\nexport { TABLE_AGENT_STATE };\n\n/**\n * Options for {@link tableAgent}.\n *\n * The same options `@adapttable/ai`'s table agent controller takes: the\n * runtime half — identity, policy, columns, the host's callbacks and\n * capabilities — plus where updates are published and whether the table is\n * offered to a browser-resident agent.\n *\n * @public\n */\nexport type TableAgentOptions = TableAgentControllerOptions;\n\ninterface TableAgentFeature extends StaticTableFeature {\n readonly options: TableAgentOptions;\n}\n\nfunction TableAgentProvider({\n feature,\n children,\n}: Readonly<FeatureProviderProps>): ReactNode {\n const options = (feature as TableAgentFeature).options;\n const runtime = useTableRuntime();\n const optionsRef = useRef(options);\n optionsRef.current = options;\n const runtimeRef = useRef(runtime);\n runtimeRef.current = runtime;\n // A concrete provider update, rather than an empty `flushSync`, makes React\n // finish controlled-state work already queued by the reader before the\n // session takes its admission snapshot.\n const [admissionTick, setAdmissionTick] = useState(0);\n const flushAdmission = useRef<() => void>(() => undefined);\n flushAdmission.current = () => {\n flushSync(() => {\n setAdmissionTick(admissionTick + 1);\n });\n };\n\n // Built once and never during a render that is thrown away twice: the\n // controller opens nothing until `sync`, which only an effect calls.\n const controllerRef = useRef<TableAgentController | null>(null);\n controllerRef.current ??= createTableAgentController({\n options: optionsRef,\n runtime: runtimeRef,\n flushAdmission: () => {\n flushAdmission.current();\n },\n flush: flushSync,\n });\n const controller = controllerRef.current;\n\n // The table as a store: subscribe where there is one to subscribe to, and\n // read the stamp on every render either way. React re-reads the stamp after\n // it attaches, so a table that moved between the render and the\n // subscription is caught rather than missed. The value is not rendered;\n // re-rendering is the point, because that republishes the manifest.\n const neutralTable = runtime.view()?.neutralTable;\n // The controller subscribes to the table current at the call, so a\n // replaced table is a new subscription.\n const subscribeToTable = useCallback(\n (onStoreChange: () => void) =>\n neutralTable ? controller.subscribeTable(onStoreChange) : () => undefined,\n [controller, neutralTable]\n );\n const stamp = useSyncExternalStore(\n subscribeToTable,\n controller.tableStamp,\n controller.tableStamp\n );\n useDebugValue(stamp);\n\n const state = useSyncExternalStore(\n controller.subscribe,\n controller.getState,\n controller.getState\n );\n\n // Every commit: the controller decides what changed and tells only those\n // who need telling. A layout effect, so a host reading the manifest in its\n // own effects already has this render's.\n useLayoutEffect(() => {\n controller.sync();\n });\n\n // Going away is a close. Strict Mode's setup/cleanup/setup lands here too:\n // the cleanup releases everything, and the next sync sets it up again.\n useEffect(\n () => () => {\n controller.disconnect();\n },\n [controller]\n );\n\n // A new value every render on purpose. The table publishes its runtime\n // while its children render, after this provider has, so a surface below\n // learns what the session now offers only by re-rendering with it — and it\n // re-renders because the value it holds is a different one.\n const session = state.session;\n const published: AgentSession = {\n catalog: () => session.catalog(),\n describe: (key) => session.describe(key),\n execute: (key, args, expectedRevision, idempotencyKey, signal) =>\n session.execute(key, args, expectedRevision, idempotencyKey, signal),\n manifest: () => session.manifest(),\n };\n\n return (\n <FeatureStateScope stateKey={TABLE_AGENT_STATE} value={published}>\n <FeatureStateScope stateKey={AGENT_APPROVAL_STATE} value={state.approval}>\n <FeatureStateScope\n stateKey={AGENT_ALWAYS_ALLOW_STATE}\n value={state.alwaysAllow}\n >\n <FeatureStateScope stateKey={AGENT_VIEW_STATE} value={state.view}>\n <FeatureStateScope\n stateKey={AGENT_PROGRESS_STATE}\n value={state.progress}\n >\n {children}\n </FeatureStateScope>\n </FeatureStateScope>\n </FeatureStateScope>\n </FeatureStateScope>\n </FeatureStateScope>\n );\n}\n\n/**\n * Observe a live table and publish a deterministic capability manifest.\n *\n * Omitting this feature from `features` ships no agent bytes.\n *\n * @public\n */\nexport function tableAgent(options: TableAgentOptions): StaticTableFeature {\n const feature: TableAgentFeature = {\n id: \"table-agent\",\n options,\n provider: { Provider: TableAgentProvider },\n };\n return feature;\n}\n","/**\n * Dictation, as a React hook — `@adapttable/ai-react`.\n *\n * Thin on purpose. The controller in `@adapttable/ai/voice` owns the browser\n * APIs, the permission states and the language choice; this subscribes to it,\n * keeps it alive for the life of the composer, and writes what it hears\n * through the caller's `setDraft` — which is the one channel voice is allowed\n * to use, so a spoken sentence becomes a draft the reader can see and fix\n * rather than a request the table has already acted on.\n *\n * It lives here rather than in `@adapttable/react` because it imports\n * `@adapttable/ai`, and that package must stay out of the base graph. The\n * chrome takes `SpeechInputHandle` — the structural shape this returns —\n * from `@adapttable/react/adapter`, which declares it without importing\n * anything.\n */\n\"use client\";\n\nimport {\n createSpeechInput,\n readRememberedLanguage,\n rememberLanguage,\n type SpeechClip,\n type SpeechInput,\n type SpeechState,\n type VoiceOptions,\n} from \"@adapttable/ai/voice\";\nimport type { SpeechInputHandle } from \"@adapttable/react/adapter\";\nimport {\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\n\n/** How the hook is configured. @public */\nexport interface UseSpeechInputOptions {\n readonly voice?: VoiceOptions;\n /** The table's locale, used when no language list was given. */\n readonly locale?: string;\n /** Where heard text goes. Always the draft, never a send. */\n readonly setDraft: (text: string) => void;\n /** Where a recording goes, in backend mode. */\n readonly onClip?: (clip: SpeechClip) => void;\n}\n\nconst IDLE: SpeechState = { status: \"unsupported\", language: \"\", interim: \"\" };\n\n/**\n * Run dictation for one composer.\n *\n * @param options - Voice configuration and where heard text should go.\n * @returns What the composer needs, or an unavailable handle when voice is off.\n *\n * @public\n */\nexport function useSpeechInput(\n options: UseSpeechInputOptions\n): SpeechInputHandle {\n const { voice, locale, setDraft, onClip } = options;\n // Live callbacks, so the controller is built once and still calls whatever\n // the latest render passed rather than what the first one did.\n const draftRef = useRef(setDraft);\n draftRef.current = setDraft;\n const clipRef = useRef(onClip);\n clipRef.current = onClip;\n\n const enabled = voice !== undefined;\n const mode = voice?.mode ?? \"browser\";\n // A host may construct the same language array on each render. Compare its\n // values so an active recognizer survives those equivalent configurations.\n const languagesKey = JSON.stringify(\n voice?.languages?.length ? voice.languages : [locale ?? \"en-US\"]\n );\n const languages = useMemo(\n () => JSON.parse(languagesKey) as readonly string[],\n [languagesKey]\n );\n const [input, setInput] = useState<SpeechInput | null>(null);\n useEffect(() => {\n if (!enabled) {\n setInput(null);\n return;\n }\n const remembered = readRememberedLanguage();\n const current = createSpeechInput({\n mode,\n languages,\n ...(remembered ? { initialLanguage: remembered } : {}),\n onDraft: (text) => draftRef.current(text),\n onClip: (clip) => clipRef.current?.(clip),\n });\n setInput(current);\n // Every effect setup owns a fresh controller. Strict Mode can clean up\n // and set up again without leaving the composer attached to a disposed one.\n return () => current.dispose();\n }, [enabled, mode, languages]);\n\n const state = useSyncExternalStore(\n (listener) => input?.subscribe(listener) ?? (() => undefined),\n () => input?.getState() ?? IDLE,\n () => IDLE\n );\n\n return {\n // Absent rather than dead: a mic that cannot listen is not drawn.\n available: Boolean(voice && input?.supported()),\n state,\n languages,\n start: () => input?.start(),\n stop: () => input?.stop(),\n setLanguage: (language) => {\n input?.setLanguage(language);\n rememberLanguage(language);\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwRA,SAAgB,kBACd,SACqB;CACrB,MAAM,EAAE,iBAAiB;CACzB,MAAM,CAAC,kBAAkB,uBAAuB,SAAS,KAAK;CAG9D,MAAM,WAAW,gBAAgB,oBAAoB;CAGrD,MAAM,cAAc,gBAAgB,wBAAwB;CAG5D,MAAM,YAAY,gBAAgB,gBAAgB;CAGlD,MAAM,WAAW,gBAAgB,oBAAoB;CAKrD,MAAM,WAAW,OAAuD,IAAI;CAC5E,MAAM,WAAW,OAAuC,IAAI;CAC5D,SAAS,YAAY,qBACnB,SAAS,SAAS,UAAU,aAAa,WAAW,QAA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eACd,SACmB;CACnB,MAAM,EAAE,OAAO,QAAQ,UAAU,WAAW;CAG5C,MAAM,WAAW,OAAO,QAAQ;CAChC,SAAS,UAAU;CACnB,MAAM,UAAU,OAAO,MAAM;CAC7B,QAAQ,UAAU;CAElB,MAAM,UAAU,UAAU,KAAA;CAC1B,MAAM,OAAO,OAAO,QAAQ;CAG5B,MAAM,eAAe,KAAK,UACxB,OAAO,WAAW,SAAS,MAAM,YAAY,CAAC,UAAU,OAAO,CACjE;CACA,MAAM,YAAY,cACV,KAAK,MAAM,YAAY,GAC7B,CAAC,YAAY,CACf;CACA,MAAM,CAAC,OAAO,YAAY,SAA6B,IAAI;CAC3D,gBAAgB;EACd,IAAI,CAAC,SAAS;GACZ,SAAS,IAAI;GACb;EACF;EACA,MAAM,aAAa,uBAAuB;EAC1C,MAAM,UAAU,kBAAkB;GAChC;GACA;GACA,GAAI,aAAa,EAAE,iBAAiB,WAAW,IAAI,CAAC;GACpD,UAAU,SAAS,SAAS,QAAQ,IAAI;GACxC,SAAS,SAAS,QAAQ,UAAU,IAAI;EAC1C,CAAC;EACD,SAAS,OAAO;EAGhB,aAAa,QAAQ,QAAQ;CAC/B,GAAG;EAAC;EAAS;EAAM;CAAS,CAAC;CAE7B,MAAM,QAAQ,sBACX,aAAa,OAAO,UAAU,QAAQ,YAAY,KAAA,UAC7C,OAAO,SAAS,KAAK,YACrB,IACR;CAEA,OAAO;EAEL,WAAW,QAAQ,SAAS,OAAO,UAAU,CAAC;EAC9C;EACA;EACA,aAAa,OAAO,MAAM;EAC1B,YAAY,OAAO,KAAK;EACxB,cAAc,aAAa;GACzB,OAAO,YAAY,QAAQ;GAC3B,iBAAiB,QAAQ;EAC3B;CACF;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/assistant.tsx","../src/react.tsx","../src/useSpeechInput.ts"],"sourcesContent":["/**\n * `@adapttable/ai-react` — the conversation lifecycle, without a UI.\n *\n * This entry owns state and nothing else: no markup, no launcher, no\n * provider client. A host renders its own panel from what the hook returns,\n * and the shipped widget is written against these same public values — which\n * is the only way to be sure it is not required.\n *\n * The rules that shape it:\n *\n * - **One send at a time**, reserved before any await. Two sends racing would\n * interleave two turns' actions against one table.\n * - **A draft survives failure.** Losing what someone typed because a\n * backend was down is worse than the outage.\n * - **A cancelled send is not a cancelled action.** Aborting before the\n * transport answers is clean; aborting after actions began is reported for\n * what it is, and nothing is retried — a mutation whose outcome is unknown\n * is never sent twice.\n * - **A late reply is dropped.** A turn that was stopped, or that belonged\n * to a previous table, never writes into the transcript.\n */\n\"use client\";\n\nimport {\n type AgentContextInputs,\n type AgentSession,\n type AlwaysAllowedState,\n type AssistantAllowance,\n type AssistantAudio,\n type AssistantInterruption,\n type AssistantMessage,\n type AssistantResumeHandle,\n type AssistantStatus,\n type AssistantSuggestion,\n type AssistantTransport,\n type AssistantUndoView,\n createTableAssistant,\n tableAssistantFields,\n tableAssistantInputs,\n} from \"@adapttable/ai\";\nimport {\n AGENT_ALWAYS_ALLOW_STATE,\n AGENT_APPROVAL_STATE,\n AGENT_PROGRESS_STATE,\n AGENT_VIEW_STATE,\n type AgentApprovalPending,\n type AgentProgress,\n useFeatureState,\n} from \"@adapttable/react/adapter\";\nimport {\n useCallback,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\n\n// The hook's own options and state name these, so the entry that publishes\n// the hook publishes them too — a consumer typing a variable from it should\n// not have to reach into another entry point for the pieces.\nexport type {\n ApprovalPolicy,\n AssistantReceiptStatus,\n AssistantReceiptSubject,\n CommitPolicy,\n RowAddressScope,\n WritePolicy,\n} from \"@adapttable/ai\";\nexport type {\n AssistantInterruption,\n AssistantMessage,\n AssistantResumeHandle,\n AssistantStatus,\n AssistantTransport,\n};\nexport type {\n AssistantExchange,\n AssistantQuestion,\n AssistantReceipt,\n AssistantTransportReply,\n AssistantTurnStatus,\n} from \"@adapttable/ai\";\nexport type { AssistantUndoOffer } from \"@adapttable/ai\";\n\n/** How {@link useTableAssistant} is configured. @public */\nexport interface TableAssistantOptions {\n /** The live session. Changing it starts a new conversation. */\n readonly session: AgentSession | undefined;\n /**\n * Where a turn goes. Omit and the assistant stays disconnected.\n *\n * May be a fresh object every render — the controller reads the latest one\n * rather than reconnecting on its identity, so a host is not forced to\n * memoize it.\n */\n readonly transport?: AssistantTransport;\n /**\n * Changes when the transport should be re-established.\n *\n * The conversation resets on a new session, because that is a new table.\n * Swapping one transport for another — a backend for a scripted one — is\n * not visible in the object identity, so a host that does it names the\n * change here. A backend transport must never quietly become a simulated\n * one under the same key.\n */\n readonly transportKey?: string;\n /** Everything authored, filtered live against what the table offers. */\n readonly suggestions?: readonly AssistantSuggestion[];\n /** Controlled panel state. Omit for uncontrolled. */\n readonly open?: boolean;\n /** Called on every open/close request, controlled or not. */\n readonly onOpenChange?: (open: boolean) => void;\n /**\n * Whether a write from this conversation is waiting on a human.\n *\n * `execute` does not return while an approval is open, so the turn looks\n * like thinking from in here. Defaults to whether the table has a write\n * waiting on the reader; a host that renders the approval elsewhere — or\n * wires `bridge.approvals` — passes it so the panel can say what is\n * actually happening. The turn is still in flight and still stoppable.\n */\n readonly awaitingApproval?: boolean;\n /**\n * What the reader has waved through, when the panel is mounted outside the\n * table.\n *\n * A panel inside the table reads this from feature state and needs nothing\n * here. One beside it cannot, so a host wires `bridge.alwaysAllowed` and\n * passes what it publishes — the same arrangement `bridge.approvals` and\n * `bridge.viewInputs` already have. Without it a reader can wave a\n * capability through and have no way to take it back.\n */\n readonly alwaysAllow?: AlwaysAllowedState;\n /**\n * Live view and filter data the manifest does not carry.\n *\n * Read when a turn starts and again when it settles, so per-turn undo can\n * tell what the turn moved. A function rather than a value: a fixed object\n * would report that nothing changed.\n */\n readonly contextInputs?: () => AgentContextInputs;\n /**\n * Work that outlived its connection, handed over the moment it does.\n *\n * Durable recovery starts here and ends outside this package: a host that\n * stores the handle where it survives a reload can offer a resume when the\n * reader comes back, and a host that does nothing loses the work with the\n * page.\n */\n readonly onDetach?: (handle: AssistantResumeHandle) => void;\n /** A handle kept from a previous page, to resume into this one. */\n readonly resumeHandle?: AssistantResumeHandle;\n /**\n * The transcript, when your app owns it.\n *\n * Omit it and the conversation lives in the controller. Supply it to load\n * the last conversation from your own API, append a message that arrived on\n * a socket, or keep it where it survives a reload — pass a new array and the\n * panel shows it. Pair it with `onMessagesChange`.\n */\n readonly messages?: readonly AssistantMessage[];\n /** Told whenever the transcript changes, with the whole of it. */\n readonly onMessagesChange?: (messages: readonly AssistantMessage[]) => void;\n /**\n * How much of the conversation travels with each turn.\n *\n * `\"full\"` (default) sends every earlier message, for a backend that\n * remembers nothing. A number sends that many of the most recent. `0` sends\n * none — the reader's message still travels, and a backend holding its own\n * session supplies the rest. What the reader sees is never trimmed.\n */\n readonly conversation?: \"full\" | number;\n}\n\n/** What a host renders from. @public */\nexport interface TableAssistantState {\n readonly status: AssistantStatus;\n /**\n * Whether a turn is in flight and can still be stopped.\n *\n * Separate from {@link TableAssistantState.status}: a write parked on a\n * human approval reports `awaiting-approval` but is still running, and\n * Stop still ends it.\n */\n readonly busy: boolean;\n readonly messages: readonly AssistantMessage[];\n readonly draft: string;\n readonly setDraft: (draft: string) => void;\n /** Send the draft, or the given text. Resolves when the turn settles. */\n readonly send: (text?: string) => Promise<void>;\n /**\n * Send a recording as the reader's turn — pass it as `onClip` to\n * backend-mode `useSpeechInput`. The transcript the backend returns becomes\n * the reader's message.\n */\n readonly sendClip: (clip: AssistantAudio) => Promise<void>;\n /** Abort the turn in flight. Safe to call when nothing is in flight. */\n readonly stop: () => void;\n /**\n * Rejoin work a released connection left running.\n *\n * A no-op with nothing to rejoin, which is what `resumable` says.\n */\n readonly resume: () => Promise<void>;\n /**\n * What became of the last turn, when no reply ended it.\n *\n * `\"stopped\"` is the reader's own decision; `\"detached\"` is a released\n * connection, where the work may still be running.\n */\n readonly interrupted: AssistantInterruption | undefined;\n /** The work `resume` would rejoin, or nothing. */\n readonly resumable: AssistantResumeHandle | undefined;\n /** Drop the transcript. Refuses while a turn is in flight. */\n readonly clear: () => void;\n /**\n * A write waiting on the reader, or nothing.\n *\n * Hand it to the panel as `approval` and the conversation reviews it —\n * which is where a write asked for in the conversation belongs. The panel\n * draws it only when the approval's presentation names the widget, so\n * passing it costs nothing on a table reviewing elsewhere.\n */\n readonly approval: AgentApprovalPending | null;\n /**\n * How far the capability now running has got, or nothing.\n *\n * Published by the table while a long call works through its rows. It never\n * becomes the receipt: when the turn settles this goes and the receipts say\n * what happened.\n */\n readonly progress: AgentProgress | null;\n /** Answer the pending question and let the turn continue. */\n readonly answer: (answer: { optionId?: string; text?: string }) => void;\n /**\n * Whether the last turn that moved the table can still be put back.\n *\n * Null when no turn moved it. Re-read every render, because the offer ends\n * the moment anything else changes the view. `blockedCode` is a token the\n * labels translate — the panel never shows a reader a code.\n */\n readonly undo: AssistantUndoView | null;\n /** Put that turn back. A no-op once the offer has expired. */\n readonly undoTurn: () => Promise<void>;\n /** Put one action of the last turn back, by its receipt's replay identity. */\n readonly undoAction: (idempotencyKey: string) => Promise<void>;\n /** What the reader said not to ask about again, each with its own name. */\n readonly alwaysAllowed: readonly AssistantAllowance[];\n /** Ask about one of them again from now on. */\n readonly revokeAlwaysAllow: (capability: string) => void;\n /** The suggestions this table can run right now, re-checked every render. */\n readonly suggestions: readonly AssistantSuggestion[];\n /** Send a suggestion's prompt as if the reader had typed it. */\n readonly runSuggestion: (id: string) => Promise<void>;\n readonly open: boolean;\n readonly setOpen: (open: boolean) => void;\n /** The last failure, cleared by the next successful turn. */\n readonly error: string | undefined;\n /**\n * The machine code behind `error`, when a turn ended with work\n * pending. A surface with labels turns it into a sentence for the reader;\n * the message beside it is written for whoever is debugging the turn.\n */\n readonly errorCode: string | undefined;\n}\n\n/**\n * Run a table assistant.\n *\n * A thin subscriber to the neutral controller in `@adapttable/ai/assistant`:\n * React supplies the external-store mechanism, the live inputs and the\n * controlled presentation state, and owns none of the lifecycle.\n *\n * @param options - Session, transport and presentation.\n * @returns Everything a panel needs, and nothing about how it looks.\n *\n * @public\n */\nexport function useTableAssistant(\n options: TableAssistantOptions\n): TableAssistantState {\n const { onOpenChange } = options;\n const [uncontrolledOpen, setUncontrolledOpen] = useState(false);\n // The live approval, so a host wires the panel with one prop rather than\n // reaching for feature state itself.\n const approval = useFeatureState(AGENT_APPROVAL_STATE);\n // What the reader has waved through, published by the binding whether or\n // not an approval is open.\n const alwaysAllow = useFeatureState(AGENT_ALWAYS_ALLOW_STATE);\n // The table's own live view, published by `tableAgent`. A host that drives\n // the panel from state of its own passes `contextInputs` and this is unused.\n const viewState = useFeatureState(AGENT_VIEW_STATE);\n // How far a running capability has got, for the same reason: a panel inside\n // the table needs no host wiring to say what the work is doing.\n const progress = useFeatureState(AGENT_PROGRESS_STATE);\n\n // Created once, inert until the mount effect connects it. Constructing a\n // store during render must not open a connection — a render can be thrown\n // away, and Strict Mode throws the first one away on purpose.\n const storeRef = useRef<ReturnType<typeof createTableAssistant> | null>(null);\n const mountRef = useRef<{ superseded: boolean } | null>(null);\n const table = { approval, alwaysAllow, viewState, progress };\n storeRef.current ??= createTableAssistant(\n tableAssistantInputs(options, table)\n );\n const store = storeRef.current;\n\n // Live inputs, every render. The store decides what a change means: a new\n // session resets the conversation, a new transport key reconnects, and an\n // updated catalog or a newly arrived approval does neither.\n useEffect(() => {\n store.update(tableAssistantInputs(options, table));\n });\n\n useEffect(() => {\n const mount = { superseded: false };\n if (mountRef.current) mountRef.current.superseded = true;\n mountRef.current = mount;\n store.connect();\n return () => {\n // React may replay this effect without rendering a replacement store.\n // Release the connection, retaining the inert controller for that next\n // setup. This also hands durable work to the host before unmounting.\n // useSyncExternalStore removes its own subscription on cleanup.\n store.disconnect();\n queueMicrotask(() => {\n if (!mount.superseded) store.dispose();\n });\n };\n }, [store]);\n\n const state = useSyncExternalStore(\n store.subscribe,\n store.getState,\n store.getState\n );\n\n const open = options.open ?? uncontrolledOpen;\n const setOpen = useCallback(\n (next: boolean) => {\n if (options.open === undefined) setUncontrolledOpen(next);\n onOpenChange?.(next);\n },\n [options.open, onOpenChange]\n );\n\n return {\n ...tableAssistantFields(state, store),\n approval: approval ?? null,\n open,\n setOpen,\n };\n}\n","/**\n * Opt-in table feature — `@adapttable/ai-react`.\n *\n * `@adapttable/ai` stays React-free. This package mounts a provider that\n * drives `@adapttable/ai`'s table agent controller from React: it keeps the\n * controller's inputs current, re-renders on its snapshot and the table's\n * changes, and publishes what the controller holds as feature state.\n */\nimport {\n type AgentSession,\n createTableAgentController,\n TABLE_AGENT_STATE,\n type TableAgentBridge as NeutralBridge,\n type TableAgentController,\n type TableAgentControllerOptions,\n} from \"@adapttable/ai\";\nimport {\n AGENT_ALWAYS_ALLOW_STATE,\n AGENT_APPROVAL_STATE,\n AGENT_PROGRESS_STATE,\n AGENT_VIEW_STATE,\n type AgentApprovalPending,\n type FeatureProviderProps,\n FeatureStateScope,\n type StaticTableFeature,\n useTableRuntime,\n} from \"@adapttable/react/adapter\";\nimport {\n type ReactNode,\n useCallback,\n useDebugValue,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport { flushSync } from \"react-dom\";\n\nexport type { SharedApproval, TableAgentColumnPatch } from \"@adapttable/ai\";\n\n// The bridge contract is `@adapttable/ai`'s — a manifest, a session and a\n// pending approval are what any binding publishes, none of it React. Named\n// here with this binding's own pending shape so every existing import keeps\n// working.\nexport type TableAgentBridge = NeutralBridge<AgentApprovalPending>;\n\n// The live session's key is `@adapttable/ai`'s, so every agent binding\n// publishes and reads the same one.\nexport { TABLE_AGENT_STATE };\n\n/**\n * Options for {@link tableAgent}.\n *\n * The same options `@adapttable/ai`'s table agent controller takes: the\n * runtime half — identity, policy, columns, the host's callbacks and\n * capabilities — plus where updates are published and whether the table is\n * offered to a browser-resident agent.\n *\n * @public\n */\nexport type TableAgentOptions = TableAgentControllerOptions;\n\ninterface TableAgentFeature extends StaticTableFeature {\n readonly options: TableAgentOptions;\n}\n\nfunction TableAgentProvider({\n feature,\n children,\n}: Readonly<FeatureProviderProps>): ReactNode {\n const options = (feature as TableAgentFeature).options;\n const runtime = useTableRuntime();\n const optionsRef = useRef(options);\n optionsRef.current = options;\n const runtimeRef = useRef(runtime);\n runtimeRef.current = runtime;\n // A concrete provider update, rather than an empty `flushSync`, makes React\n // finish controlled-state work already queued by the reader before the\n // session takes its admission snapshot.\n const [admissionTick, setAdmissionTick] = useState(0);\n const flushAdmission = useRef<() => void>(() => undefined);\n flushAdmission.current = () => {\n flushSync(() => {\n setAdmissionTick(admissionTick + 1);\n });\n };\n\n // Built once and never during a render that is thrown away twice: the\n // controller opens nothing until `sync`, which only an effect calls.\n const controllerRef = useRef<TableAgentController | null>(null);\n controllerRef.current ??= createTableAgentController({\n options: optionsRef,\n runtime: runtimeRef,\n flushAdmission: () => {\n flushAdmission.current();\n },\n flush: flushSync,\n });\n const controller = controllerRef.current;\n\n // The table as a store: subscribe where there is one to subscribe to, and\n // read the stamp on every render either way. React re-reads the stamp after\n // it attaches, so a table that moved between the render and the\n // subscription is caught rather than missed. The value is not rendered;\n // re-rendering is the point, because that republishes the manifest.\n const neutralTable = runtime.view()?.neutralTable;\n // The controller subscribes to the table current at the call, so a\n // replaced table is a new subscription.\n const subscribeToTable = useCallback(\n (onStoreChange: () => void) =>\n neutralTable ? controller.subscribeTable(onStoreChange) : () => undefined,\n [controller, neutralTable]\n );\n const stamp = useSyncExternalStore(\n subscribeToTable,\n controller.tableStamp,\n controller.tableStamp\n );\n useDebugValue(stamp);\n\n const state = useSyncExternalStore(\n controller.subscribe,\n controller.getState,\n controller.getState\n );\n\n // Every commit: the controller decides what changed and tells only those\n // who need telling. A layout effect, so a host reading the manifest in its\n // own effects already has this render's.\n useLayoutEffect(() => {\n controller.sync();\n });\n\n // Going away is a close. Strict Mode's setup/cleanup/setup lands here too:\n // the cleanup releases everything, and the next sync sets it up again.\n useEffect(\n () => () => {\n controller.disconnect();\n },\n [controller]\n );\n\n // A new value every render on purpose. The table publishes its runtime\n // while its children render, after this provider has, so a surface below\n // learns what the session now offers only by re-rendering with it — and it\n // re-renders because the value it holds is a different one.\n const session = state.session;\n const published: AgentSession = {\n catalog: () => session.catalog(),\n describe: (key) => session.describe(key),\n execute: (key, args, expectedRevision, idempotencyKey, signal) =>\n session.execute(key, args, expectedRevision, idempotencyKey, signal),\n manifest: () => session.manifest(),\n };\n\n return (\n <FeatureStateScope stateKey={TABLE_AGENT_STATE} value={published}>\n <FeatureStateScope stateKey={AGENT_APPROVAL_STATE} value={state.approval}>\n <FeatureStateScope\n stateKey={AGENT_ALWAYS_ALLOW_STATE}\n value={state.alwaysAllow}\n >\n <FeatureStateScope stateKey={AGENT_VIEW_STATE} value={state.view}>\n <FeatureStateScope\n stateKey={AGENT_PROGRESS_STATE}\n value={state.progress}\n >\n {children}\n </FeatureStateScope>\n </FeatureStateScope>\n </FeatureStateScope>\n </FeatureStateScope>\n </FeatureStateScope>\n );\n}\n\n/**\n * Observe a live table and publish a deterministic capability manifest.\n *\n * Omitting this feature from `features` ships no agent bytes.\n *\n * @public\n */\nexport function tableAgent(options: TableAgentOptions): StaticTableFeature {\n const feature: TableAgentFeature = {\n id: \"table-agent\",\n options,\n provider: { Provider: TableAgentProvider },\n };\n return feature;\n}\n","/**\n * Dictation, as a React hook — `@adapttable/ai-react`.\n *\n * Thin on purpose. The speech session in `@adapttable/ai/voice` owns the\n * browser APIs, the permission states, the language choice and when the\n * microphone is replaced; this subscribes to it, keeps it alive for the life\n * of the composer, and writes what it hears through the caller's `setDraft` —\n * which is the one channel voice is allowed to use, so a spoken sentence\n * becomes a draft the reader can see and fix rather than a request the table\n * has already acted on.\n *\n * It lives here rather than in `@adapttable/react` because it imports\n * `@adapttable/ai`, and that package must stay out of the base graph. The\n * chrome takes `SpeechInputHandle` — the structural shape this returns —\n * from `@adapttable/react/adapter`, which declares it without importing\n * anything.\n */\n\"use client\";\n\nimport {\n createSpeechSession,\n type SpeechClip,\n type VoiceOptions,\n} from \"@adapttable/ai/voice\";\nimport type { SpeechInputHandle } from \"@adapttable/react/adapter\";\nimport { useEffect, useRef, useState, useSyncExternalStore } from \"react\";\n\n/** How the hook is configured. @public */\nexport interface UseSpeechInputOptions {\n readonly voice?: VoiceOptions;\n /** The table's locale, used when no language list was given. */\n readonly locale?: string;\n /** Where heard text goes. Always the draft, never a send. */\n readonly setDraft: (text: string) => void;\n /** Where a recording goes, in backend mode. */\n readonly onClip?: (clip: SpeechClip) => void;\n}\n\n/**\n * Run dictation for one composer.\n *\n * @param options - Voice configuration and where heard text should go.\n * @returns What the composer needs, or an unavailable handle when voice is off.\n *\n * @public\n */\nexport function useSpeechInput(\n options: UseSpeechInputOptions\n): SpeechInputHandle {\n // The latest options, read by the session whenever it needs them, so heard\n // text reaches whatever the latest render passed.\n const latest = useRef(options);\n latest.current = options;\n const [session] = useState(() => createSpeechSession(() => latest.current));\n // Every commit brings the microphone in line with the options; equivalent\n // options keep the one that is listening.\n useEffect(() => {\n session.sync();\n });\n // Strict Mode releases and syncs again, so each setup owns a live controller.\n useEffect(() => () => session.release(), [session]);\n return useSyncExternalStore(\n session.subscribe,\n session.getSnapshot,\n session.getSnapshot\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsRA,SAAgB,kBACd,SACqB;CACrB,MAAM,EAAE,iBAAiB;CACzB,MAAM,CAAC,kBAAkB,uBAAuB,SAAS,KAAK;CAG9D,MAAM,WAAW,gBAAgB,oBAAoB;CAGrD,MAAM,cAAc,gBAAgB,wBAAwB;CAG5D,MAAM,YAAY,gBAAgB,gBAAgB;CAGlD,MAAM,WAAW,gBAAgB,oBAAoB;CAKrD,MAAM,WAAW,OAAuD,IAAI;CAC5E,MAAM,WAAW,OAAuC,IAAI;CAC5D,MAAM,QAAQ;EAAE;EAAU;EAAa;EAAW;CAAS;CAC3D,SAAS,YAAY,qBACnB,qBAAqB,SAAS,KAAK,CACrC;CACA,MAAM,QAAQ,SAAS;CAKvB,gBAAgB;EACd,MAAM,OAAO,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O,CAAC;CAClD,OAAO,qBACL,QAAQ,WACR,QAAQ,aACR,QAAQ,WACV;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adapttable/ai-react",
3
- "version": "0.2.20",
3
+ "version": "0.2.22",
4
4
  "description": "React bindings for AdaptTable AI — tableAgent and useTableAssistant.",
5
5
  "keywords": [
6
6
  "react",
@@ -44,9 +44,8 @@
44
44
  "./package.json": "./package.json"
45
45
  },
46
46
  "dependencies": {
47
- "@adapttable/ai": "0.6.6",
48
- "@adapttable/core": "3.13.1",
49
- "@adapttable/react": "1.9.1",
47
+ "@adapttable/ai": "0.7.1",
48
+ "@adapttable/react": "1.11.0",
50
49
  "react-compiler-runtime": "^1.0.0"
51
50
  },
52
51
  "peerDependencies": {
@@ -54,6 +53,7 @@
54
53
  "react-dom": "^18.0.0 || ^19.0.0"
55
54
  },
56
55
  "devDependencies": {
56
+ "@adapttable/unstyled": "3.5.1",
57
57
  "@testing-library/react": "^16.3.2",
58
58
  "react": "^19.2.8",
59
59
  "react-dom": "^19.2.8"