@adapttable/ai-react 0.1.0

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/dist/index.js ADDED
@@ -0,0 +1,1094 @@
1
+ "use client";
2
+ import { agentColumnsFromNeutral, agentFiltersFromDefs, agentObservation, agentPagination, aggregationsFor, applyAggregations, assertAlwaysAllow, closeTransaction, contractFingerprint, createAgentSession, createApprovalMemory, createTableAssistant, displayProposals, mayAlwaysAllow, monotonicRevision, observationFromNeutral, openTransaction, readRowsFromNeutral, recordDecision, registerWebMcpTools, resolveApproval, resolveRowFromNeutral, revisionToken, settleDecisions, sharedApproval } from "@adapttable/ai";
3
+ import { AGENT_ALWAYS_ALLOW_STATE, AGENT_APPROVAL_STATE, AGENT_PROGRESS_STATE, AGENT_VIEW_STATE, FeatureStateScope, deriveRuntimeOperations, featureStateKey, useFeatureState, useTableRuntime } from "@adapttable/react/adapter";
4
+ import { useCallback, useDebugValue, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
5
+ import { sampleColumns } from "@adapttable/ai/context";
6
+ import { pageSizeOptions } from "@adapttable/core";
7
+ import { flushSync } from "react-dom";
8
+ import { jsx } from "react/jsx-runtime";
9
+ import { createSpeechInput, readRememberedLanguage, rememberLanguage } from "@adapttable/ai/voice";
10
+ //#region src/assistant.tsx
11
+ /**
12
+ * `@adapttable/ai-react` — the conversation lifecycle, without a UI.
13
+ *
14
+ * This entry owns state and nothing else: no markup, no launcher, no
15
+ * provider client. A host renders its own panel from what the hook returns,
16
+ * and the shipped widget is written against these same public values — which
17
+ * is the only way to be sure it is not required.
18
+ *
19
+ * The rules that shape it:
20
+ *
21
+ * - **One send at a time**, reserved before any await. Two sends racing would
22
+ * interleave two turns' actions against one table.
23
+ * - **A draft survives failure.** Losing what someone typed because a
24
+ * backend was down is worse than the outage.
25
+ * - **A cancelled send is not a cancelled action.** Aborting before the
26
+ * transport answers is clean; aborting after actions began is reported for
27
+ * what it is, and nothing is retried — a mutation whose outcome is unknown
28
+ * is never sent twice.
29
+ * - **A late reply is dropped.** A turn that was stopped, or that belonged
30
+ * to a previous table, never writes into the transcript.
31
+ */
32
+ /**
33
+ * Run a table assistant.
34
+ *
35
+ * A thin subscriber to the neutral controller in `@adapttable/ai/assistant`:
36
+ * React supplies the external-store mechanism, the live inputs and the
37
+ * controlled presentation state, and owns none of the lifecycle.
38
+ *
39
+ * @param options - Session, transport and presentation.
40
+ * @returns Everything a panel needs, and nothing about how it looks.
41
+ *
42
+ * @public
43
+ */
44
+ function useTableAssistant(options) {
45
+ const { onOpenChange } = options;
46
+ const [uncontrolledOpen, setUncontrolledOpen] = useState(false);
47
+ const approval = useFeatureState(AGENT_APPROVAL_STATE);
48
+ const alwaysAllow = useFeatureState(AGENT_ALWAYS_ALLOW_STATE);
49
+ const viewState = useFeatureState(AGENT_VIEW_STATE);
50
+ const progress = useFeatureState(AGENT_PROGRESS_STATE);
51
+ const storeRef = useRef(null);
52
+ storeRef.current ??= createTableAssistant(inputsOf(options, approval, alwaysAllow, viewState, progress));
53
+ const store = storeRef.current;
54
+ useEffect(() => {
55
+ store.update(inputsOf(options, approval, alwaysAllow, viewState, progress));
56
+ });
57
+ useEffect(() => {
58
+ store.connect();
59
+ return () => {
60
+ store.dispose();
61
+ storeRef.current = null;
62
+ };
63
+ }, []);
64
+ const state = useSyncExternalStore(store.subscribe, store.getState, store.getState);
65
+ const open = options.open ?? uncontrolledOpen;
66
+ const setOpen = useCallback((next) => {
67
+ if (options.open === void 0) setUncontrolledOpen(next);
68
+ onOpenChange?.(next);
69
+ }, [options.open, onOpenChange]);
70
+ return {
71
+ messages: state.messages,
72
+ draft: state.draft,
73
+ setDraft: store.setDraft,
74
+ send: store.send,
75
+ stop: store.stop,
76
+ resume: store.resume,
77
+ interrupted: state.interrupted,
78
+ resumable: state.resumable,
79
+ clear: store.clear,
80
+ status: state.status,
81
+ busy: state.busy,
82
+ approval: approval ?? null,
83
+ progress: state.progress,
84
+ answer: store.answer,
85
+ undo: state.undo ? {
86
+ messageId: state.undo.messageId,
87
+ available: state.undo.available,
88
+ ...state.undo.blocked ? { blockedCode: state.undo.blocked.code } : {}
89
+ } : null,
90
+ undoTurn: store.undoTurn,
91
+ undoAction: store.undoAction,
92
+ alwaysAllowed: state.alwaysAllowed,
93
+ revokeAlwaysAllow: store.revokeAlwaysAllow,
94
+ suggestions: state.suggestions,
95
+ runSuggestion: store.runSuggestion,
96
+ open,
97
+ setOpen,
98
+ error: state.error,
99
+ errorCode: state.errorCode
100
+ };
101
+ }
102
+ /** The hook's options as the store's live inputs. A projection, not a decision. */
103
+ function inputsOf(options, approval, alwaysAllow, viewState, progress) {
104
+ const contextInputs = options.contextInputs ?? (viewState ? () => viewState.read() : void 0);
105
+ return {
106
+ session: options.session,
107
+ transport: options.transport,
108
+ transportKey: options.transportKey,
109
+ suggestions: options.suggestions,
110
+ awaitingApproval: options.awaitingApproval,
111
+ approval: approval ?? null,
112
+ progress: progress ?? null,
113
+ ...contextInputs ? { contextInputs } : {},
114
+ ...options.onDetach ? { onDetach: options.onDetach } : {},
115
+ ...options.messages ? { messages: options.messages } : {},
116
+ ...options.onMessagesChange ? { onMessagesChange: options.onMessagesChange } : {},
117
+ ...options.conversation === void 0 ? {} : { conversation: options.conversation },
118
+ ...options.resumeHandle ? { resumeHandle: options.resumeHandle } : {},
119
+ ...options.alwaysAllow ?? alwaysAllow ? {
120
+ alwaysAllowed: (options.alwaysAllow ?? alwaysAllow)?.capabilities,
121
+ onRevokeAlwaysAllow: (options.alwaysAllow ?? alwaysAllow)?.revoke
122
+ } : {}
123
+ };
124
+ }
125
+ //#endregion
126
+ //#region src/react.tsx
127
+ /**
128
+ * Opt-in table feature — `@adapttable/ai-react`.
129
+ *
130
+ * `@adapttable/ai` stays React-free. This package mounts a provider that
131
+ * observes the live table and publishes a versioned manifest.
132
+ */
133
+ const PAGE_ONLY_SOURCE = {
134
+ fullDataset: false,
135
+ grouping: false,
136
+ selectAcrossPages: false,
137
+ exportScope: "page",
138
+ totalCount: "loaded"
139
+ };
140
+ /**
141
+ * Feature-state key for the live {@link AgentSession}.
142
+ *
143
+ * @public
144
+ */
145
+ const TABLE_AGENT_STATE = featureStateKey("table-agent");
146
+ function mergeColumn(base, patch) {
147
+ const extra = patch?.[base.id];
148
+ if (!extra) return base;
149
+ return {
150
+ ...base,
151
+ ...extra
152
+ };
153
+ }
154
+ function cellRecord(row, columns, wanted) {
155
+ const record = row && typeof row === "object" ? row : {};
156
+ const cells = {};
157
+ for (const column of columns) {
158
+ if (!column.readable) continue;
159
+ if (wanted && !wanted.includes(column.id)) continue;
160
+ cells[column.id] = record[column.id];
161
+ }
162
+ return cells;
163
+ }
164
+ function viewRevisionStamp(view) {
165
+ const table = view?.neutralTable;
166
+ if (table) return monotonicRevision(table.revisions, void 0).token;
167
+ const rows = view?.rows ?? [];
168
+ const getRowId = view?.getRowId;
169
+ const query = view?.query;
170
+ return JSON.stringify({
171
+ ids: rows.map((row) => getRowId ? getRowId(row) : null),
172
+ payloads: rows,
173
+ page: query?.page ?? 1,
174
+ limit: query?.limit ?? 10,
175
+ search: query?.search ?? "",
176
+ sortBy: query?.sortBy,
177
+ sortDir: query?.sortDir,
178
+ filters: query?.extra,
179
+ groupBy: view?.groupingState?.groupBy,
180
+ aggregateOverrides: view?.groupingState?.aggregateOverrides,
181
+ pinnedColumns: view?.pinning?.columns,
182
+ pinnedRows: view?.pinning?.rows,
183
+ hiddenColumns: view?.columnLayout?.hidden,
184
+ columnOrder: view?.columnLayout?.keys
185
+ });
186
+ }
187
+ function liveReadRows(runtime, columns, query, readMax) {
188
+ const table = runtime.view()?.neutralTable;
189
+ if (table) return readRowsFromNeutral(table, columns, query, readMax);
190
+ const view = runtime.view();
191
+ const rows = (query.scope ?? "visible") === "visible" ? view?.visibleRows ?? view?.rows ?? [] : view?.rows ?? [];
192
+ const getRowId = view?.getRowId ?? (() => "");
193
+ const hidden = columns.filter((column) => !column.readable).map((c) => c.id);
194
+ const limit = Math.max(0, Math.min(query.limit, readMax));
195
+ return {
196
+ rows: rows.slice(query.offset, query.offset + limit).map((row) => ({
197
+ rowKey: getRowId(row),
198
+ cells: cellRecord(row, columns, query.columns)
199
+ })),
200
+ offset: query.offset,
201
+ limit,
202
+ redacted: hidden
203
+ };
204
+ }
205
+ function liveResolveRow(runtime, ref, scope) {
206
+ const table = runtime.view()?.neutralTable;
207
+ if (table) return resolveRowFromNeutral(table, ref);
208
+ const view = runtime.view();
209
+ const rows = scope === "visible" ? view?.visibleRows ?? view?.rows ?? [] : view?.rows ?? [];
210
+ const getRowId = view?.getRowId ?? (() => "");
211
+ if ("rowKey" in ref) return {
212
+ rowKey: ref.rowKey,
213
+ scope
214
+ };
215
+ const row = rows[ref.position - 1];
216
+ if (!row) throw new Error(`no row at 1-based position ${ref.position}`);
217
+ return {
218
+ rowKey: getRowId(row),
219
+ scope: ref.scope,
220
+ position: ref.position
221
+ };
222
+ }
223
+ function findRow(runtime, rowKey) {
224
+ const table = runtime.view()?.neutralTable;
225
+ if (table) return table.rowByKey(rowKey);
226
+ const view = runtime.view();
227
+ const rows = view?.rows ?? [];
228
+ const getRowId = view?.getRowId;
229
+ if (!getRowId) return void 0;
230
+ return rows.find((row) => getRowId(row) === rowKey);
231
+ }
232
+ function stampColumnLayout(columns, layout) {
233
+ if (!layout) return columns;
234
+ const byId = new Map(columns.map((column) => [column.id, column]));
235
+ const hidden = new Set(layout.hidden);
236
+ return (layout.keys.length > 0 ? layout.keys : columns.map((c) => c.id)).map((id) => {
237
+ const existing = byId.get(id);
238
+ const visible = !hidden.has(id);
239
+ if (existing) return {
240
+ ...existing,
241
+ visible
242
+ };
243
+ return {
244
+ id,
245
+ label: id,
246
+ type: "unknown",
247
+ readable: true,
248
+ writable: false,
249
+ sortable: false,
250
+ visible
251
+ };
252
+ });
253
+ }
254
+ function columnsForRuntime(options, runtime) {
255
+ const table = runtime.view()?.neutralTable;
256
+ if (table) return agentColumnsFromNeutral(table, options.columns);
257
+ if (!options.columns) return [];
258
+ return Object.entries(options.columns).map(([id, extra]) => mergeColumn({
259
+ id,
260
+ label: extra.label ?? id,
261
+ type: extra.type ?? "unknown",
262
+ readable: extra.readable ?? true,
263
+ writable: extra.writable ?? false,
264
+ sortable: extra.sortable ?? false
265
+ }, options.columns));
266
+ }
267
+ function observationPolicy(options) {
268
+ const approval = sharedApproval(options.approval);
269
+ return {
270
+ ...options.writePolicy ? { writePolicy: options.writePolicy } : {},
271
+ approval: approval.policy,
272
+ ...approval.presentation ? { presentation: approval.presentation } : {},
273
+ ...options.commit ? { commit: options.commit } : {}
274
+ };
275
+ }
276
+ function observationFromRuntime(options, runtime, revision, apply) {
277
+ const view = runtime.view();
278
+ const table = view?.neutralTable;
279
+ const query = view?.query;
280
+ const ids = runtime.featureIds();
281
+ const pages = serverPagination(view, query);
282
+ if (table) {
283
+ const live = observationFromNeutral(table, options, revision, apply, ids, query ? {
284
+ page: query.page,
285
+ limit: query.limit,
286
+ search: query.search,
287
+ sortBy: query.sortBy,
288
+ sortDir: query.sortDir,
289
+ pinnedColumns: view?.pinning?.columns,
290
+ pinnedRows: view?.pinning?.rows,
291
+ hiddenColumns: view?.columnLayout?.hidden,
292
+ columnOrder: view?.columnLayout?.keys
293
+ } : void 0);
294
+ const sizes = offeredPageSizes(query);
295
+ return {
296
+ ...live,
297
+ columns: stampColumnLayout(live.columns, view?.columnLayout),
298
+ pagination: live.pagination ? {
299
+ ...live.pagination,
300
+ pageSizeOptions: sizes
301
+ } : {
302
+ ...pages,
303
+ pageSizeOptions: sizes
304
+ },
305
+ groupBy: view?.groupingState?.groupBy,
306
+ aggregations: aggregationsFor(aggregationInputs(view, options)),
307
+ availableFilters: agentFiltersFromDefs(view?.filterDefs, view?.filterRegistry, options.columns),
308
+ filters: query?.extra
309
+ };
310
+ }
311
+ const columns = stampColumnLayout(columnsForRuntime(options, runtime).map((column) => mergeColumn(column, options.columns)), view?.columnLayout);
312
+ return agentObservation({
313
+ tableId: options.tableId,
314
+ viewRevision: revision,
315
+ featureIds: ids,
316
+ columns,
317
+ source: view?.sourceCapabilities ?? PAGE_ONLY_SOURCE,
318
+ operations: {
319
+ ...deriveRuntimeOperations(view),
320
+ applyView: apply.applyView !== void 0
321
+ },
322
+ apply: options.apply ?? {},
323
+ policy: observationPolicy(options),
324
+ view: {
325
+ search: query?.search ?? "",
326
+ ...query?.sortBy === void 0 ? {} : { sortBy: query.sortBy },
327
+ ...query?.sortDir === void 0 ? {} : { sortDir: query.sortDir },
328
+ ...view?.groupingState?.groupBy === void 0 ? {} : { groupBy: view.groupingState.groupBy },
329
+ ...view?.pinning?.columns ? { pinnedColumns: view.pinning.columns } : {},
330
+ ...view?.pinning?.rows ? { pinnedRows: view.pinning.rows } : {},
331
+ ...view?.columnLayout?.hidden ? { hiddenColumns: view.columnLayout.hidden } : {},
332
+ ...view?.columnLayout?.keys ? { columnOrder: view.columnLayout.keys } : {},
333
+ ...query?.extra === void 0 ? {} : { filters: query.extra }
334
+ },
335
+ pagination: pages,
336
+ rowAddressScope: "visible",
337
+ readMax: options.readMax ?? 50,
338
+ aggregations: aggregationsFor(aggregationInputs(view, options)),
339
+ availableFilters: agentFiltersFromDefs(view?.filterDefs, view?.filterRegistry, options.columns)
340
+ });
341
+ }
342
+ /**
343
+ * What a server-backed table's pages are, from what the source will say.
344
+ *
345
+ * The total is the server's count for the *current query* — the figure the
346
+ * table's own pagination is computed from — and it is published only when the
347
+ * source claims to have counted. A source that has not counted keeps an
348
+ * unknown total rather than being handed the rows that happen to be loaded,
349
+ * and a short page is the one thing it still proves about its own end.
350
+ */
351
+ /** The sizes the table's own rows-per-page control lists. */
352
+ function offeredPageSizes(query) {
353
+ const limit = query?.limit ?? 10;
354
+ const published = query?.defaultLimit ?? limit;
355
+ return pageSizeOptions([limit, published]);
356
+ }
357
+ function serverPagination(view, query) {
358
+ const counted = (view?.sourceCapabilities ?? PAGE_ONLY_SOURCE).totalCount === "exact";
359
+ const total = query?.total;
360
+ const loaded = view?.rows.length;
361
+ return agentPagination({
362
+ page: query?.page ?? 1,
363
+ pageSize: query?.limit ?? 10,
364
+ pageSizeOptions: offeredPageSizes(query),
365
+ ...counted && total !== void 0 ? { totalRows: total } : {},
366
+ ...loaded === void 0 ? {} : { loadedRows: loaded },
367
+ canJump: query?.setPage !== void 0
368
+ });
369
+ }
370
+ function liveEditCells(runtime, extra, edits) {
371
+ if (extra?.editCells) return extra.editCells(edits);
372
+ const onCellEdit = runtime.view()?.editing?.onCellEdit;
373
+ if (!onCellEdit) throw new Error("editCells is not wired");
374
+ for (const edit of edits) {
375
+ const row = findRow(runtime, edit.rowKey);
376
+ if (!row) throw new Error(`row "${edit.rowKey}" is not in the current view`);
377
+ onCellEdit(row, edit.column, edit.value);
378
+ }
379
+ }
380
+ function liveStageCells(runtime, extra, edits) {
381
+ if (extra?.stageCells) return extra.stageCells(edits);
382
+ const stage = runtime.view()?.editing?.stageCell;
383
+ if (!stage) throw new Error("stageCells is not wired");
384
+ for (const edit of edits) {
385
+ const row = findRow(runtime, edit.rowKey);
386
+ if (!row) throw new Error(`row "${edit.rowKey}" is not in the current view`);
387
+ stage(row, edit.rowKey, edit.column, typeof edit.value === "string" ? edit.value : String(edit.value));
388
+ }
389
+ }
390
+ function liveSetSelection(runtime, extra, ids) {
391
+ extra?.setSelection?.(ids);
392
+ if (!extra?.setSelection) runtime.view()?.selection?.replace(ids);
393
+ }
394
+ function rowScope(ref) {
395
+ return "scope" in ref ? ref.scope : "visible";
396
+ }
397
+ function pickReadRows(runtime, extra, columns, readMax) {
398
+ return (query) => {
399
+ if (extra?.readRows) return extra.readRows(query);
400
+ return liveReadRows(runtime, columns, query, readMax);
401
+ };
402
+ }
403
+ function pickResolveRow(runtime, extra) {
404
+ return (ref) => {
405
+ if (extra?.resolveRow) return extra.resolveRow(ref);
406
+ return liveResolveRow(runtime, ref, rowScope(ref));
407
+ };
408
+ }
409
+ function liveQueryFilters(query) {
410
+ return query ? query : {};
411
+ }
412
+ function applyLiveFilters(query, filters) {
413
+ const live = liveQueryFilters(query);
414
+ if (!live.setExtras && !live.clearExtras) return false;
415
+ if (filters == null) {
416
+ live.clearExtras?.();
417
+ return true;
418
+ }
419
+ if (typeof filters !== "object" || Array.isArray(filters)) throw new TypeError("setFilters requires a filter object");
420
+ if (Object.keys(filters).length === 0) {
421
+ live.clearExtras?.();
422
+ return true;
423
+ }
424
+ live.setExtras?.(filters);
425
+ return true;
426
+ }
427
+ function requireQuery(view, name) {
428
+ const fn = view()?.query?.[name];
429
+ if (!fn) throw new Error(`${name} is not wired`);
430
+ return fn;
431
+ }
432
+ /**
433
+ * What the LIVE TABLE can do, before the host's own callbacks are laid over
434
+ * it.
435
+ *
436
+ * `currentApply` builds `{ ...applyFromRuntime(...), ...options.apply }`, so
437
+ * a callback the host supplied is the one that runs. A guard here that
438
+ * checked for the same callback would be shadowed by that spread and could
439
+ * never fire, which is why the view operations below reach straight for the
440
+ * live table. `extra` still travels to the row, edit, stage and selection
441
+ * helpers, which read it for their own reasons.
442
+ */
443
+ function applyFromRuntime(runtime, options, extra) {
444
+ const columns = columnsForRuntime(options, runtime);
445
+ const readMax = options.readMax ?? 50;
446
+ const view = () => runtime.view();
447
+ return {
448
+ readRows: pickReadRows(runtime, extra, columns, readMax),
449
+ resolveRow: pickResolveRow(runtime, extra),
450
+ setPage: (page) => {
451
+ requireQuery(view, "setPage")(page);
452
+ },
453
+ setLimit: (limit) => {
454
+ requireQuery(view, "setLimit")(limit);
455
+ },
456
+ setSearch: (search) => {
457
+ requireQuery(view, "setSearch")(search);
458
+ },
459
+ setSort: (key, dir) => {
460
+ requireQuery(view, "setSort")(key, dir);
461
+ },
462
+ setGroupBy: (key) => {
463
+ const grouping = view()?.groupingState;
464
+ if (!grouping) throw new Error("setGroupBy is not wired");
465
+ grouping.setGroupBy(key);
466
+ },
467
+ setAggregations: (patch) => {
468
+ applyAggregations(aggregationInputs(view(), options), patch);
469
+ },
470
+ pinColumn: (key, side) => {
471
+ const pinning = view()?.pinning;
472
+ if (!pinning?.setColumnPin) throw new Error("pinColumn is not wired");
473
+ pinning.setColumnPin(key, side);
474
+ },
475
+ hideColumn: (key, hidden) => {
476
+ const layout = view()?.columnLayout;
477
+ if (!layout?.setHidden) throw new Error("hideColumn is not wired");
478
+ layout.setHidden(key, hidden);
479
+ },
480
+ moveColumn: (key, toIndex) => {
481
+ const layout = view()?.columnLayout;
482
+ if (!layout?.move) throw new Error("moveColumn is not wired");
483
+ layout.move(key, toIndex);
484
+ },
485
+ setColumnOrder: (order) => {
486
+ const layout = view()?.columnLayout;
487
+ if (!layout?.setOrder) throw new Error("setColumnOrder is not wired");
488
+ layout.setOrder(order);
489
+ },
490
+ pinRow: (rowKey, side) => {
491
+ const pinning = view()?.pinning;
492
+ if (!pinning?.setRowPin) throw new Error("pinRow is not wired");
493
+ pinning.setRowPin(rowKey, side);
494
+ },
495
+ editCells: (edits) => liveEditCells(runtime, extra, edits),
496
+ stageCells: (edits) => liveStageCells(runtime, extra, edits),
497
+ setSelection: (ids) => liveSetSelection(runtime, extra, ids)
498
+ };
499
+ }
500
+ /**
501
+ * The live view and filter catalog, in the shape the context builder takes.
502
+ *
503
+ * The same values the observation carries, read straight off the runtime so
504
+ * the caller does not have to rebuild an observation to get at them. What the
505
+ * table cannot answer for is simply absent, and the sanitized view names the
506
+ * gap rather than defaulting it.
507
+ */
508
+ /**
509
+ * Column ids whose author asked for live values.
510
+ *
511
+ * The flag is the author's, so it is read from the contract rather than from
512
+ * anything a reader can move. A column the agent may not read is not sampled
513
+ * whatever it says — the sampler refuses it too, and asking twice is cheaper
514
+ * than a read that comes back empty.
515
+ */
516
+ function sampledColumns(session) {
517
+ return session.manifest().columns.filter((column) => column.readable && column.ai?.sample === true).map((column) => column.id);
518
+ }
519
+ function viewInputsFromRuntime(runtime, options, samples) {
520
+ const view = runtime.view();
521
+ const query = view?.query;
522
+ const filters = agentFiltersFromDefs(view?.filterDefs, view?.filterRegistry, options.columns);
523
+ const aggregations = aggregationsFor(aggregationInputs(view, options));
524
+ return {
525
+ ...filters && filters.length > 0 ? { filters } : {},
526
+ ...aggregations ? { aggregations } : {},
527
+ ...Object.keys(samples).length > 0 ? { samples } : {},
528
+ view: {
529
+ ...query?.page === void 0 ? {} : { page: query.page },
530
+ ...query?.limit === void 0 ? {} : { limit: query.limit },
531
+ ...query?.search === void 0 ? {} : { search: query.search },
532
+ ...query?.sortBy ? { sortBy: query.sortBy } : {},
533
+ ...query?.sortDir ? { sortDir: query.sortDir } : {},
534
+ ...view?.groupingState?.groupBy ? { groupBy: view.groupingState.groupBy } : {},
535
+ ...query?.extra ? { filters: query.extra } : {},
536
+ ...view?.pinning?.columns ? { pinnedColumns: view.pinning.columns } : {},
537
+ ...view?.pinning?.rows ? { pinnedRows: view.pinning.rows } : {},
538
+ ...view?.columnLayout?.hidden ? { hiddenColumns: view.columnLayout.hidden } : {},
539
+ ...view?.columnLayout?.keys ? { columnOrder: view.columnLayout.keys } : {}
540
+ }
541
+ };
542
+ }
543
+ /**
544
+ * A row-by-row refusal, with the reader's stated reason when they gave one.
545
+ *
546
+ * The reason travels with the refusal so the receipt and the model-visible
547
+ * result can say why rather than only that.
548
+ */
549
+ function perItemRefusal(transaction, stated) {
550
+ return {
551
+ ...settleDecisions(transaction.decisions, "rejected"),
552
+ ...stated ? { reason: stated } : {}
553
+ };
554
+ }
555
+ /** One comparable string for an exclusion list, order-insensitive. */
556
+ function exclusionKey(keys) {
557
+ return keys ? [...keys].sort((a, b) => a.localeCompare(b)).join("|") : "";
558
+ }
559
+ /**
560
+ * What a capability does to the table, from the live catalog.
561
+ *
562
+ * Read through the session rather than kept in a list here: the definition is
563
+ * the only thing that knows, and item 11 published it on the catalog entry so
564
+ * every surface reads the same answer.
565
+ */
566
+ function capabilityKind(session, capability) {
567
+ if (!session || capability === void 0) return void 0;
568
+ return session.catalog().find((entry) => entry.key === capability)?.kind;
569
+ }
570
+ /**
571
+ * The opt-in list, with an action's own demand for a human applied.
572
+ *
573
+ * The shared configuration is what the binding can see directly; an action
574
+ * that sets `approval: "required"` is read from the custom definition it was
575
+ * declared on, so a capability that must always be confirmed never offers the
576
+ * control however the table was configured.
577
+ */
578
+ function alwaysAllowFor(approval, capabilities, capability) {
579
+ const shared = sharedApproval(approval);
580
+ if (capability === void 0) return shared.alwaysAllow;
581
+ const definition = capabilities?.find((entry) => entry.key === capability);
582
+ return resolveApproval(shared, definition?.ai).alwaysAllow;
583
+ }
584
+ /**
585
+ * How this binding finds what the person in front of the table may see.
586
+ *
587
+ * The lookups are React's — only this side knows how to find a row in a
588
+ * runtime view. What is done with them is not: the enrichment algorithm lives
589
+ * in `@adapttable/ai`, so every binding reports an unreadable column the same
590
+ * way rather than each inventing its own blank cell.
591
+ */
592
+ function readerResolver(runtime, columns) {
593
+ const view = runtime.view();
594
+ const recordFor = (rowKey) => {
595
+ const row = findRow(runtime, rowKey);
596
+ return row && typeof row === "object" ? row : void 0;
597
+ };
598
+ return {
599
+ rowLabel: (rowKey) => {
600
+ const row = findRow(runtime, rowKey);
601
+ return row !== void 0 && view?.rowLabel ? view.rowLabel(row) : void 0;
602
+ },
603
+ cellValue: (rowKey, column) => recordFor(rowKey)?.[column],
604
+ cellText: (rowKey, column, value) => {
605
+ const format = (runtime.view()?.groupingState?.columns?.find((entry) => entry.key === column))?.formatValue;
606
+ const record = recordFor(rowKey);
607
+ if (!format || !record) return void 0;
608
+ return format({
609
+ ...record,
610
+ [column]: value
611
+ });
612
+ },
613
+ readable: (column) => columns?.[column]?.readable !== false,
614
+ columnLabel: (column) => columns?.[column]?.label
615
+ };
616
+ }
617
+ /**
618
+ * The live table's grouping state, as the neutral rules want it.
619
+ *
620
+ * A projection, not a decision: it names where the facts are and which
621
+ * columns the agent may read. What may be offered and what may be set is
622
+ * `@adapttable/ai`'s to answer, so a second binding gets the same answers.
623
+ */
624
+ function aggregationInputs(view, options) {
625
+ return {
626
+ state: view?.groupingState,
627
+ grouping: view?.sourceCapabilities?.grouping,
628
+ allows: (key) => options.columns?.[key]?.readable !== false
629
+ };
630
+ }
631
+ function asCallable(value) {
632
+ if (typeof value !== "function") return void 0;
633
+ return value;
634
+ }
635
+ /**
636
+ * View mutations whose default implementation belongs to this binding.
637
+ *
638
+ * They call React-backed runtime setters. Committing those setters before the
639
+ * call returns lets the session attribute the resulting table revision to the
640
+ * exact apply call that made it. Host overrides are deliberately excluded:
641
+ * only the host can say when its own async callback has settled.
642
+ */
643
+ const BINDING_VIEW_MUTATIONS = /* @__PURE__ */ new Set([
644
+ "setPage",
645
+ "setLimit",
646
+ "setSearch",
647
+ "setSort",
648
+ "setFilters",
649
+ "setGroupBy",
650
+ "setAggregations",
651
+ "pinColumn",
652
+ "hideColumn",
653
+ "moveColumn",
654
+ "setColumnOrder",
655
+ "pinRow",
656
+ "setSelection"
657
+ ]);
658
+ function createRevisionCounter() {
659
+ let token;
660
+ let revision = 1;
661
+ const bumpFromToken = (nextToken) => {
662
+ if (token === void 0) {
663
+ token = nextToken;
664
+ return revision;
665
+ }
666
+ if (token === nextToken) return revision;
667
+ token = nextToken;
668
+ revision += 1;
669
+ return revision;
670
+ };
671
+ return {
672
+ bumpFrom(revisions) {
673
+ return bumpFromToken(revisionToken(revisions));
674
+ },
675
+ bumpFromStamp(stamp) {
676
+ return bumpFromToken(stamp);
677
+ },
678
+ current() {
679
+ return revision;
680
+ }
681
+ };
682
+ }
683
+ function currentApply(options, runtime) {
684
+ const apply = {
685
+ ...applyFromRuntime(runtime, options, options.apply),
686
+ ...options.apply
687
+ };
688
+ apply.setFilters = (filters) => {
689
+ if (options.apply?.setFilters) {
690
+ options.apply.setFilters(filters);
691
+ return;
692
+ }
693
+ if (!applyLiveFilters(runtime.view()?.query, filters)) throw new Error("setFilters is not wired");
694
+ };
695
+ return apply;
696
+ }
697
+ function bindLiveSession(optionsRef, runtimeRef, revisionCounter, flushAdmission, waitForChrome, reportProgress) {
698
+ const apply = new Proxy({}, { get(_target, prop) {
699
+ if (typeof prop !== "string") return void 0;
700
+ if (!(prop in currentApply(optionsRef.current, runtimeRef.current))) return void 0;
701
+ return (...args) => {
702
+ const options = optionsRef.current;
703
+ const fn = asCallable(currentApply(options, runtimeRef.current)[prop]);
704
+ if (!fn) return void 0;
705
+ const host = options.apply;
706
+ if (BINDING_VIEW_MUTATIONS.has(prop) && !asCallable(host?.[prop])) {
707
+ let result;
708
+ flushSync(() => {
709
+ result = fn(...args);
710
+ });
711
+ return result;
712
+ }
713
+ return fn(...args);
714
+ };
715
+ } });
716
+ const observe = () => {
717
+ const options = optionsRef.current;
718
+ if (options.observe) return options.observe();
719
+ const runtimeView = runtimeRef.current.view();
720
+ const table = runtimeView?.neutralTable;
721
+ let viewRevision = revisionCounter.current();
722
+ if (table) viewRevision = revisionCounter.bumpFrom(table.revisions);
723
+ else if (runtimeView) viewRevision = revisionCounter.bumpFromStamp(viewRevisionStamp(runtimeView));
724
+ return observationFromRuntime(options, runtimeRef.current, viewRevision, apply);
725
+ };
726
+ const onApprove = (subject, signal) => {
727
+ const options = optionsRef.current;
728
+ if (options.onApprove) return options.onApprove(subject, signal);
729
+ return waitForChrome.current(subject, signal);
730
+ };
731
+ const inner = createAgentSession({
732
+ observe,
733
+ apply,
734
+ onApprove,
735
+ onProgress: (report) => {
736
+ reportProgress.current(report);
737
+ },
738
+ capabilities: optionsRef.current.capabilities,
739
+ ...optionsRef.current.capabilityApproval ? { capabilityApproval: optionsRef.current.capabilityApproval } : {},
740
+ ...optionsRef.current.excludeCapabilities ? { excludeCapabilities: optionsRef.current.excludeCapabilities } : {}
741
+ });
742
+ return {
743
+ catalog: () => inner.catalog(),
744
+ describe: (key) => inner.describe(key),
745
+ execute: async (key, args, expectedRevision, idempotencyKey, signal) => {
746
+ flushAdmission.current();
747
+ return await inner.execute(key, args, expectedRevision, idempotencyKey, signal);
748
+ },
749
+ manifest: () => inner.manifest()
750
+ };
751
+ }
752
+ /** One open approval, whichever shape the write took. */
753
+ function TableAgentProvider({ feature, children }) {
754
+ const options = feature.options;
755
+ const runtime = useTableRuntime();
756
+ const revisionCounterRef = useRef(createRevisionCounter());
757
+ const optionsRef = useRef(options);
758
+ optionsRef.current = options;
759
+ const runtimeRef = useRef(runtime);
760
+ runtimeRef.current = runtime;
761
+ const [admissionTick, setAdmissionTick] = useState(0);
762
+ const flushAdmission = useRef(() => void 0);
763
+ flushAdmission.current = () => {
764
+ flushSync(() => {
765
+ setAdmissionTick(admissionTick + 1);
766
+ });
767
+ };
768
+ const waitForChrome = useRef(() => Promise.resolve(false));
769
+ const reportProgress = useRef(() => void 0);
770
+ const tableIdRef = useRef(options.tableId);
771
+ const registryKeyOf = (next) => `${exclusionKey(next.excludeCapabilities)}!${JSON.stringify(next.capabilityApproval ?? {})}`;
772
+ const registryRef = useRef(registryKeyOf(options));
773
+ const registryKey = registryKeyOf(options);
774
+ const sessionRef = useRef(null);
775
+ if (tableIdRef.current !== options.tableId || registryRef.current !== registryKey) {
776
+ tableIdRef.current = options.tableId;
777
+ registryRef.current = registryKey;
778
+ sessionRef.current = null;
779
+ revisionCounterRef.current = createRevisionCounter();
780
+ }
781
+ sessionRef.current ??= bindLiveSession(optionsRef, runtimeRef, revisionCounterRef.current, flushAdmission, waitForChrome, reportProgress);
782
+ const session = sessionRef.current;
783
+ const [revocations, setRevocations] = useState(0);
784
+ const [progress, setProgress] = useState(null);
785
+ const [transaction, setTransaction] = useState(null);
786
+ const pendingRef = useRef(null);
787
+ const transactionId = useRef(0);
788
+ const neutralTable = runtime.view()?.neutralTable;
789
+ const readStamp = useCallback(() => neutralTable ? revisionToken(neutralTable.revisions) : viewRevisionStamp(runtime.view()), [neutralTable, runtime]);
790
+ const subscribeToTable = useCallback((onStoreChange) => neutralTable ? neutralTable.subscribe("all", onStoreChange) : () => void 0, [neutralTable]);
791
+ const stamp = useSyncExternalStore(subscribeToTable, readStamp, readStamp);
792
+ useDebugValue(stamp);
793
+ const hostApprove = options.onApprove;
794
+ const approvalMemory = useRef(createApprovalMemory());
795
+ const contractVersion = useCallback(() => contractFingerprint(session.manifest(), session.catalog()), [session]);
796
+ const webmcp = options.webmcp;
797
+ const webmcpVersion = webmcp ? contractVersion() : "";
798
+ useEffect(() => {
799
+ if (!webmcp) return;
800
+ const options = webmcp === true ? {} : webmcp;
801
+ const registration = registerWebMcpTools(session, {
802
+ ...options.exposedTo ? { exposedTo: options.exposedTo } : {},
803
+ onWarning: (warning) => {
804
+ console.warn(`[adapttable] webmcp: ${warning.message}`);
805
+ }
806
+ });
807
+ options.onRegister?.(registration.names);
808
+ return () => {
809
+ registration.dispose();
810
+ options.onRegister?.([]);
811
+ };
812
+ }, [
813
+ session,
814
+ webmcp,
815
+ webmcpVersion
816
+ ]);
817
+ waitForChrome.current = (subject, signal) => {
818
+ if (pendingRef.current) return Promise.reject(/* @__PURE__ */ new Error("an approval is already pending"));
819
+ const capability = subject.kind === "operation" ? subject.capability : void 0;
820
+ if (mayAlwaysAllow({
821
+ capability,
822
+ kind: capabilityKind(session, capability),
823
+ alwaysAllow: alwaysAllowFor(optionsRef.current.approval, optionsRef.current.capabilities, capability)
824
+ }) && capability !== void 0 && approvalMemory.current.allows(capability, contractVersion())) return Promise.resolve(true);
825
+ return new Promise((resolve) => {
826
+ const rows = subject.kind === "rows";
827
+ let settled = false;
828
+ const entry = {
829
+ ...rows ? {} : { capability: subject.capability },
830
+ proposals: rows ? displayProposals(subject.proposals, readerResolver(runtimeRef.current, optionsRef.current.columns)) : [],
831
+ perItem: rows && subject.perItem,
832
+ ...rows ? {} : { operation: {
833
+ capability: subject.capability,
834
+ ...subject.title ? { title: subject.title } : {},
835
+ arguments: subject.arguments
836
+ } },
837
+ resolve: (result) => {
838
+ if (settled) return;
839
+ settled = true;
840
+ if (pendingRef.current === entry) pendingRef.current = null;
841
+ setTransaction(closeTransaction(entry));
842
+ signal?.removeEventListener("abort", onAbort);
843
+ resolve(result);
844
+ }
845
+ };
846
+ const onAbort = () => entry.resolve(false);
847
+ pendingRef.current = entry;
848
+ transactionId.current += 1;
849
+ setTransaction(openTransaction(transactionId.current, entry, subject.presentation));
850
+ if (signal?.aborted) {
851
+ entry.resolve(false);
852
+ return;
853
+ }
854
+ signal?.addEventListener("abort", onAbort, { once: true });
855
+ });
856
+ };
857
+ useEffect(() => () => {
858
+ pendingRef.current?.resolve(false);
859
+ }, []);
860
+ const published = {
861
+ catalog: () => session.catalog(),
862
+ describe: (key) => session.describe(key),
863
+ execute: (key, args, expectedRevision, idempotencyKey, signal) => session.execute(key, args, expectedRevision, idempotencyKey, signal),
864
+ manifest: () => session.manifest()
865
+ };
866
+ const samplesRef = useRef({});
867
+ const viewStateValue = useRef({ read: () => viewInputsFromRuntime(runtimeRef.current, optionsRef.current, samplesRef.current) }).current;
868
+ useEffect(() => {
869
+ options.bridge?.attach?.(session);
870
+ options.bridge?.viewInputs?.(viewStateValue.read);
871
+ }, [
872
+ options.bridge,
873
+ session,
874
+ viewStateValue
875
+ ]);
876
+ const last = useRef("");
877
+ useLayoutEffect(() => {
878
+ const published = session.manifest();
879
+ const encoded = JSON.stringify(published);
880
+ if (encoded === last.current) return;
881
+ last.current = encoded;
882
+ options.bridge?.publish?.(published);
883
+ });
884
+ const sampledKey = sampledColumns(session).join("\0");
885
+ useEffect(() => {
886
+ const wanted = sampledKey === "" ? [] : sampledKey.split("\0");
887
+ if (wanted.length === 0) {
888
+ samplesRef.current = {};
889
+ return;
890
+ }
891
+ const controller = new AbortController();
892
+ sampleColumns(session, wanted, controller.signal).then((values) => {
893
+ if (controller.signal.aborted) return;
894
+ samplesRef.current = values;
895
+ }, () => {
896
+ if (!controller.signal.aborted) samplesRef.current = {};
897
+ });
898
+ return () => controller.abort();
899
+ }, [
900
+ session,
901
+ sampledKey,
902
+ samplesRef
903
+ ]);
904
+ const chromePending = !hostApprove && transaction !== null;
905
+ const approvals = options.bridge?.approvals;
906
+ const approvalsRef = useRef(approvals);
907
+ const announcedRef = useRef(null);
908
+ const publishedRef = useRef(null);
909
+ useEffect(() => {
910
+ const previous = approvalsRef.current;
911
+ if (previous !== approvals) {
912
+ if (announcedRef.current) previous?.(null);
913
+ approvalsRef.current = approvals;
914
+ announcedRef.current = null;
915
+ }
916
+ const next = chromePending ? transaction : null;
917
+ if (announcedRef.current === next) return;
918
+ announcedRef.current = next;
919
+ approvals?.(next ? publishedRef.current : null);
920
+ }, [
921
+ approvals,
922
+ chromePending,
923
+ transaction
924
+ ]);
925
+ useEffect(() => () => {
926
+ if (!announcedRef.current) return;
927
+ announcedRef.current = null;
928
+ approvalsRef.current?.(null);
929
+ }, []);
930
+ const decideAt = (id) => (index, approved) => {
931
+ setTransaction((current) => recordDecision(current, id, index, approved));
932
+ };
933
+ useEffect(() => {
934
+ if (!transaction) return;
935
+ if (transaction.pending.proposals.length === 0) return;
936
+ if (transaction.decisions.includes("pending")) return;
937
+ transaction.pending.resolve(settleDecisions(transaction.decisions, "rejected"));
938
+ }, [transaction]);
939
+ const approvalValue = hostApprove || !transaction ? null : {
940
+ proposals: transaction.pending.proposals,
941
+ ...transaction.pending.operation ? { operation: transaction.pending.operation } : {},
942
+ decisions: transaction.decisions,
943
+ presentation: transaction.presentation,
944
+ ...mayAlwaysAllow({
945
+ capability: transaction.pending.capability,
946
+ kind: capabilityKind(session, transaction.pending.capability),
947
+ alwaysAllow: alwaysAllowFor(optionsRef.current.approval, optionsRef.current.capabilities, transaction.pending.capability)
948
+ }) ? { alwaysAllow: () => {
949
+ const capability = transaction.pending.capability;
950
+ if (capability === void 0) return;
951
+ approvalMemory.current.remember(capability, contractVersion());
952
+ transaction.pending.resolve(true);
953
+ } } : {},
954
+ approve: () => transaction.pending.resolve(transaction.pending.perItem ? settleDecisions(transaction.decisions, "approved") : true),
955
+ reject: (reason) => {
956
+ const stated = typeof reason === "string" ? reason.trim() : void 0;
957
+ if (transaction.pending.perItem) {
958
+ transaction.pending.resolve(perItemRefusal(transaction, stated));
959
+ return;
960
+ }
961
+ transaction.pending.resolve(stated ? {
962
+ approved: [],
963
+ reason: stated
964
+ } : false);
965
+ },
966
+ ...transaction.pending.perItem ? { decideAt: decideAt(transaction.id) } : {}
967
+ };
968
+ publishedRef.current = approvalValue;
969
+ useEffect(() => {
970
+ assertAlwaysAllow(sharedApproval(optionsRef.current.approval).alwaysAllow, session.catalog().map((entry) => entry.key));
971
+ }, [session, stamp]);
972
+ const alwaysAllowValue = useMemo(() => ({
973
+ capabilities: approvalMemory.current.remembered(contractVersion()),
974
+ revoke: (capability) => {
975
+ approvalMemory.current.revoke(capability);
976
+ setRevocations((count) => count + 1);
977
+ }
978
+ }), [
979
+ revocations,
980
+ stamp,
981
+ contractVersion
982
+ ]);
983
+ const alwaysAllowedBridge = optionsRef.current.bridge?.alwaysAllowed;
984
+ useEffect(() => {
985
+ alwaysAllowedBridge?.(alwaysAllowValue);
986
+ }, [alwaysAllowedBridge, alwaysAllowValue]);
987
+ reportProgress.current = (report) => {
988
+ setProgress(report);
989
+ optionsRef.current.bridge?.progress?.(report);
990
+ };
991
+ return /* @__PURE__ */ jsx(FeatureStateScope, {
992
+ stateKey: TABLE_AGENT_STATE,
993
+ value: published,
994
+ children: /* @__PURE__ */ jsx(FeatureStateScope, {
995
+ stateKey: AGENT_APPROVAL_STATE,
996
+ value: approvalValue,
997
+ children: /* @__PURE__ */ jsx(FeatureStateScope, {
998
+ stateKey: AGENT_ALWAYS_ALLOW_STATE,
999
+ value: alwaysAllowValue,
1000
+ children: /* @__PURE__ */ jsx(FeatureStateScope, {
1001
+ stateKey: AGENT_VIEW_STATE,
1002
+ value: viewStateValue,
1003
+ children: /* @__PURE__ */ jsx(FeatureStateScope, {
1004
+ stateKey: AGENT_PROGRESS_STATE,
1005
+ value: progress,
1006
+ children
1007
+ })
1008
+ })
1009
+ })
1010
+ })
1011
+ });
1012
+ }
1013
+ /**
1014
+ * Observe a live table and publish a deterministic capability manifest.
1015
+ *
1016
+ * Omitting this feature from `features` ships no agent bytes.
1017
+ *
1018
+ * @public
1019
+ */
1020
+ function tableAgent(options) {
1021
+ return {
1022
+ id: "table-agent",
1023
+ options,
1024
+ provider: { Provider: TableAgentProvider }
1025
+ };
1026
+ }
1027
+ //#endregion
1028
+ //#region src/useSpeechInput.ts
1029
+ /**
1030
+ * Dictation, as a React hook — `@adapttable/ai-react`.
1031
+ *
1032
+ * Thin on purpose. The controller in `@adapttable/ai/voice` owns the browser
1033
+ * APIs, the permission states and the language choice; this subscribes to it,
1034
+ * keeps it alive for the life of the composer, and writes what it hears
1035
+ * through the caller's `setDraft` — which is the one channel voice is allowed
1036
+ * to use, so a spoken sentence becomes a draft the reader can see and fix
1037
+ * rather than a request the table has already acted on.
1038
+ *
1039
+ * It lives here rather than in `@adapttable/react` because it imports
1040
+ * `@adapttable/ai`, and that package must stay out of the base graph. The
1041
+ * chrome takes `SpeechInputHandle` — the structural shape this returns —
1042
+ * from `@adapttable/react/adapter`, which declares it without importing
1043
+ * anything.
1044
+ */
1045
+ const IDLE = {
1046
+ status: "unsupported",
1047
+ language: "",
1048
+ interim: ""
1049
+ };
1050
+ /**
1051
+ * Run dictation for one composer.
1052
+ *
1053
+ * @param options - Voice configuration and where heard text should go.
1054
+ * @returns What the composer needs, or an unavailable handle when voice is off.
1055
+ *
1056
+ * @public
1057
+ */
1058
+ function useSpeechInput(options) {
1059
+ const { voice, locale, setDraft, onClip } = options;
1060
+ const draftRef = useRef(setDraft);
1061
+ draftRef.current = setDraft;
1062
+ const clipRef = useRef(onClip);
1063
+ clipRef.current = onClip;
1064
+ const languages = voice?.languages?.length ? voice.languages : [locale ?? "en-US"];
1065
+ const inputRef = useRef(null);
1066
+ if (voice && !inputRef.current) inputRef.current = createSpeechInput({
1067
+ mode: voice.mode ?? "browser",
1068
+ languages,
1069
+ ...readRememberedLanguage() ? { initialLanguage: readRememberedLanguage() } : {},
1070
+ onDraft: (text) => draftRef.current(text),
1071
+ onClip: (clip) => clipRef.current?.(clip)
1072
+ });
1073
+ const input = inputRef.current;
1074
+ useEffect(() => () => {
1075
+ input?.dispose();
1076
+ inputRef.current = null;
1077
+ }, [input]);
1078
+ const state = useSyncExternalStore((listener) => input?.subscribe(listener) ?? (() => void 0), () => input?.getState() ?? IDLE, () => IDLE);
1079
+ return {
1080
+ available: Boolean(voice && input?.supported()),
1081
+ state,
1082
+ languages,
1083
+ start: () => input?.start(),
1084
+ stop: () => input?.stop(),
1085
+ setLanguage: (language) => {
1086
+ input?.setLanguage(language);
1087
+ rememberLanguage(language);
1088
+ }
1089
+ };
1090
+ }
1091
+ //#endregion
1092
+ export { TABLE_AGENT_STATE, tableAgent, useSpeechInput, useTableAssistant };
1093
+
1094
+ //# sourceMappingURL=index.js.map