@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/CHANGELOG.md +71 -0
- package/LICENSE +21 -0
- package/README.md +45 -0
- package/dist/index.cjs +1098 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +317 -0
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.ts +317 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1094 -0
- package/dist/index.js.map +1 -0
- package/package.json +76 -0
|
@@ -0,0 +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","featureStateKey","monotonicRevision","readRowsFromNeutral","resolveRowFromNeutral","agentColumnsFromNeutral","sharedApproval","observationFromNeutral","aggregationsFor","agentFiltersFromDefs","agentObservation","deriveRuntimeOperations","pageSizeOptions","agentPagination","settleDecisions","resolveApproval","revisionToken","createAgentSession","useTableRuntime","useRef","useState","useCallback","useSyncExternalStore","createApprovalMemory","contractFingerprint","registerWebMcpTools","mayAlwaysAllow","displayProposals","closeTransaction","openTransaction","sampleColumns","recordDecision","useMemo","FeatureStateScope","AGENT_APPROVAL_STATE","AGENT_ALWAYS_ALLOW_STATE","AGENT_VIEW_STATE","AGENT_PROGRESS_STATE","useRef","createSpeechInput","readRememberedLanguage","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 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 /** 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 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 store.connect();\n return () => {\n store.dispose();\n // A disposed store is never reused. Strict Mode's second setup, and any\n // later remount, builds a fresh one rather than reviving one that has\n // already released its connection.\n storeRef.current = null;\n };\n // Mount and unmount only: every other change reaches the store through\n // `update` above, which is what keeps connection effects out of render.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\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 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 * observes the live table and publishes a versioned manifest.\n */\nimport {\n type AgentApply,\n type AgentCapabilityDefinition,\n type AgentColumn,\n agentColumnsFromNeutral,\n type AgentContextInputs,\n agentFiltersFromDefs,\n type AgentObservation,\n agentObservation,\n type AgentPagination,\n agentPagination,\n type AgentSession,\n type AggregationInputs,\n aggregationsFor,\n applyAggregations,\n type ApprovalResult,\n type ApprovalSubject,\n type ApprovalTransaction,\n assertAlwaysAllow,\n closeTransaction,\n type CommitPolicy,\n contractFingerprint,\n createAgentSession,\n createApprovalMemory,\n displayProposals,\n mayAlwaysAllow,\n monotonicRevision,\n observationFromNeutral,\n openTransaction,\n type PendingApproval,\n type ProposalResolver,\n readRowsFromNeutral,\n recordDecision,\n registerWebMcpTools,\n resolveApproval,\n type ResolvedRow,\n resolveRowFromNeutral,\n revisionToken,\n type RowAddressScope,\n type RowReadQuery,\n type RowRef,\n type RowWindow,\n settleDecisions,\n type SharedApproval,\n sharedApproval,\n type TableAgentBridge as NeutralBridge,\n type TableAgentColumnPatch,\n type WritePolicy,\n} from \"@adapttable/ai\";\nimport { sampleColumns } from \"@adapttable/ai/context\";\nimport { type ActionAiOptions, pageSizeOptions } from \"@adapttable/core\";\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 deriveRuntimeOperations,\n type FeatureProviderProps,\n featureStateKey,\n FeatureStateScope,\n type StaticTableFeature,\n type TableRuntimeView,\n useTableRuntime,\n} from \"@adapttable/react/adapter\";\nimport {\n type ReactNode,\n useCallback,\n useDebugValue,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport { flushSync } from \"react-dom\";\n\nexport type { SharedApproval, TableAgentColumnPatch };\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\nconst PAGE_ONLY_SOURCE = {\n fullDataset: false,\n grouping: false as const,\n selectAcrossPages: false,\n exportScope: \"page\" as const,\n totalCount: \"loaded\" as const,\n};\n\n/**\n * Feature-state key for the live {@link AgentSession}.\n *\n * @public\n */\nexport const TABLE_AGENT_STATE = featureStateKey<AgentSession>(\"table-agent\");\n\n/**\n * Options for {@link tableAgent}.\n *\n * @public\n */\nexport interface TableAgentOptions {\n /** Host-supplied table identity. */\n readonly tableId: string;\n /** Whether host callbacks already authorize writes. */\n readonly writePolicy?: WritePolicy;\n /** When a write must be confirmed. */\n readonly approval?: SharedApproval;\n /** Whether an approved write stages or persists. */\n readonly commit?: CommitPolicy;\n /** Host confirmation. When set, chrome is skipped. */\n readonly onApprove?: (\n subject: ApprovalSubject,\n signal?: AbortSignal\n ) => Promise<ApprovalResult>;\n /** Per-column readability, writability, and labels. */\n readonly columns?: Readonly<Record<string, TableAgentColumnPatch>>;\n /** Largest `rows.read` window. */\n readonly readMax?: number;\n /** Host callbacks for manifest and session attach. */\n readonly bridge?: TableAgentBridge;\n /** Host- or test-supplied observation. Live tables omit this. */\n readonly observe?: () => AgentObservation;\n /** Extra apply callbacks the live table does not already expose. */\n readonly apply?: AgentApply;\n /** Custom governed capabilities for this table. */\n readonly capabilities?: readonly AgentCapabilityDefinition[];\n /**\n * This table's approval policy for individual capabilities, by key.\n *\n * The same shape a row or bulk action carries. An entry **replaces**\n * {@link approval} for that one capability rather than narrowing it:\n * `required` asks on a table that asks for nothing, and `automatic` skips the\n * human on a table that asks for writes. Both directions are deliberate —\n * this is the developer's own answer to \"who confirms this\".\n *\n * It is not the reader's answer. \"Don't ask again\" is `approval.alwaysAllow`\n * plus the approval memory: opt-in per capability, revocable, and reset by a\n * contract change. A capability carrying `required` here keeps asking however\n * often the reader waves it through.\n *\n * Approval decides who confirms an operation, never whether the table offers\n * it: a key the table does not wire, or one in\n * {@link excludeCapabilities}, stays unavailable whatever this says.\n */\n readonly capabilityApproval?: Readonly<Record<string, ActionAiOptions>>;\n /**\n * Capability keys the agent may not use on this table.\n *\n * One list, for built-ins and custom definitions alike. It only ever denies:\n * a key the table does not wire stays unavailable whatever this says, and no\n * entry here can enable a forbidden operation. The table's own controls are\n * untouched — denying `view.setFilters` to the agent leaves a person\n * filtering exactly as before.\n */\n readonly excludeCapabilities?: readonly string[];\n /**\n * Offer this table's capabilities to a browser-resident agent.\n *\n * `true` offers everything the session permits; an object narrows the\n * surface. It narrows only — a capability the table excludes stays\n * unavailable, and a browser confirmation is in addition to the table's own\n * approval rather than instead of it. Does nothing in a browser without the\n * API, and nothing on a server.\n */\n readonly webmcp?:\n | true\n | {\n readonly exposedTo?: readonly string[];\n /**\n * Told what was registered, and told `[]` when the registration goes.\n *\n * For a surface that lists the tools a browser agent can see. Nothing\n * depends on it: a page that does not care never passes it.\n */\n readonly onRegister?: (names: readonly string[]) => void;\n };\n}\n\ninterface TableAgentFeature extends StaticTableFeature {\n readonly options: TableAgentOptions;\n}\n\nfunction mergeColumn(\n base: AgentColumn,\n patch: TableAgentOptions[\"columns\"]\n): AgentColumn {\n const extra = patch?.[base.id];\n if (!extra) return base;\n return { ...base, ...extra };\n}\n\nfunction cellRecord(\n row: unknown,\n columns: readonly AgentColumn[],\n wanted?: readonly string[]\n): Record<string, unknown> {\n const record =\n row && typeof row === \"object\" ? (row as Record<string, unknown>) : {};\n const cells: Record<string, unknown> = {};\n for (const column of columns) {\n if (!column.readable) continue;\n if (wanted && !wanted.includes(column.id)) continue;\n cells[column.id] = record[column.id];\n }\n return cells;\n}\n\nfunction viewRevisionStamp(\n view: TableRuntimeView<unknown> | undefined\n): string {\n const table = view?.neutralTable;\n if (table) return monotonicRevision(table.revisions, undefined).token;\n const rows = view?.rows ?? [];\n const getRowId = view?.getRowId;\n const query = view?.query;\n return JSON.stringify({\n ids: rows.map((row) => (getRowId ? getRowId(row) : null)),\n payloads: rows,\n page: query?.page ?? 1,\n limit: query?.limit ?? 10,\n search: query?.search ?? \"\",\n sortBy: query?.sortBy,\n sortDir: query?.sortDir,\n filters: query?.extra,\n groupBy: view?.groupingState?.groupBy,\n aggregateOverrides: view?.groupingState?.aggregateOverrides,\n pinnedColumns: view?.pinning?.columns,\n pinnedRows: view?.pinning?.rows,\n hiddenColumns: view?.columnLayout?.hidden,\n columnOrder: view?.columnLayout?.keys,\n });\n}\n\nfunction liveReadRows(\n runtime: ReturnType<typeof useTableRuntime>,\n columns: readonly AgentColumn[],\n query: RowReadQuery,\n readMax: number\n): RowWindow {\n const table = runtime.view()?.neutralTable;\n if (table) return readRowsFromNeutral(table, columns, query, readMax);\n const view = runtime.view();\n const scope = query.scope ?? \"visible\";\n const rows =\n scope === \"visible\"\n ? (view?.visibleRows ?? view?.rows ?? [])\n : (view?.rows ?? []);\n const getRowId = view?.getRowId ?? (() => \"\");\n const hidden = columns.filter((column) => !column.readable).map((c) => c.id);\n const limit = Math.max(0, Math.min(query.limit, readMax));\n const sliced = rows.slice(query.offset, query.offset + limit);\n return {\n rows: sliced.map((row) => ({\n rowKey: getRowId(row),\n cells: cellRecord(row, columns, query.columns),\n })),\n offset: query.offset,\n limit,\n redacted: hidden,\n };\n}\n\nfunction liveResolveRow(\n runtime: ReturnType<typeof useTableRuntime>,\n ref: RowRef,\n scope: RowAddressScope\n): ResolvedRow {\n const table = runtime.view()?.neutralTable;\n if (table) return resolveRowFromNeutral(table, ref);\n const view = runtime.view();\n const rows =\n scope === \"visible\"\n ? (view?.visibleRows ?? view?.rows ?? [])\n : (view?.rows ?? []);\n const getRowId = view?.getRowId ?? (() => \"\");\n if (\"rowKey\" in ref) {\n return { rowKey: ref.rowKey, scope };\n }\n const index = ref.position - 1;\n const row = rows[index];\n if (!row) {\n throw new Error(`no row at 1-based position ${ref.position}`);\n }\n return { rowKey: getRowId(row), scope: ref.scope, position: ref.position };\n}\n\nfunction findRow(\n runtime: ReturnType<typeof useTableRuntime>,\n rowKey: string\n): unknown {\n const table = runtime.view()?.neutralTable;\n if (table) return table.rowByKey(rowKey);\n const view = runtime.view();\n const rows = view?.rows ?? [];\n const getRowId = view?.getRowId;\n if (!getRowId) return undefined;\n return rows.find((row) => getRowId(row) === rowKey);\n}\n\nfunction stampColumnLayout(\n columns: readonly AgentColumn[],\n layout: TableRuntimeView<unknown>[\"columnLayout\"]\n): readonly AgentColumn[] {\n if (!layout) return columns;\n const byId = new Map(columns.map((column) => [column.id, column]));\n const hidden = new Set(layout.hidden);\n const keys = layout.keys.length > 0 ? layout.keys : columns.map((c) => c.id);\n return keys.map((id) => {\n const existing = byId.get(id);\n const visible = !hidden.has(id);\n if (existing) return { ...existing, visible };\n return {\n id,\n label: id,\n type: \"unknown\",\n readable: true,\n writable: false,\n sortable: false,\n visible,\n };\n });\n}\n\nfunction columnsForRuntime(\n options: TableAgentOptions,\n runtime: ReturnType<typeof useTableRuntime>\n): readonly AgentColumn[] {\n const table = runtime.view()?.neutralTable;\n if (table) return agentColumnsFromNeutral(table, options.columns);\n if (!options.columns) return [];\n return Object.entries(options.columns).map(([id, extra]) =>\n mergeColumn(\n {\n id,\n label: extra.label ?? id,\n type: extra.type ?? \"unknown\",\n readable: extra.readable ?? true,\n writable: extra.writable ?? false,\n sortable: extra.sortable ?? false,\n },\n options.columns\n )\n );\n}\n\nfunction observationPolicy(options: TableAgentOptions) {\n const approval = sharedApproval(options.approval);\n return {\n ...(options.writePolicy ? { writePolicy: options.writePolicy } : {}),\n approval: approval.policy,\n ...(approval.presentation ? { presentation: approval.presentation } : {}),\n ...(options.commit ? { commit: options.commit } : {}),\n };\n}\n\nfunction observationFromRuntime(\n options: TableAgentOptions,\n runtime: ReturnType<typeof useTableRuntime>,\n revision: number,\n apply: AgentApply\n): AgentObservation {\n const view = runtime.view();\n const table = view?.neutralTable;\n const query = view?.query;\n const ids = runtime.featureIds();\n const pages = serverPagination(view, query);\n if (table) {\n const live = observationFromNeutral(\n table,\n options,\n revision,\n apply,\n ids,\n query\n ? {\n page: query.page,\n limit: query.limit,\n search: query.search,\n sortBy: query.sortBy,\n sortDir: query.sortDir,\n pinnedColumns: view?.pinning?.columns,\n pinnedRows: view?.pinning?.rows,\n hiddenColumns: view?.columnLayout?.hidden,\n columnOrder: view?.columnLayout?.keys,\n }\n : undefined\n );\n const sizes = offeredPageSizes(query);\n return {\n ...live,\n columns: stampColumnLayout(live.columns, view?.columnLayout),\n pagination: live.pagination\n ? { ...live.pagination, pageSizeOptions: sizes }\n : { ...pages, pageSizeOptions: sizes },\n groupBy: view?.groupingState?.groupBy,\n aggregations: aggregationsFor(aggregationInputs(view, options)),\n availableFilters: agentFiltersFromDefs(\n view?.filterDefs,\n view?.filterRegistry,\n options.columns\n ),\n filters: query?.extra,\n };\n }\n const columns = stampColumnLayout(\n columnsForRuntime(options, runtime).map((column) =>\n mergeColumn(column, options.columns)\n ),\n view?.columnLayout\n );\n // What this runtime offers, and what the host wired, projected into the\n // neutral contract. Which of those two makes a capability available is not\n // this binding's rule to hold — it is the same rule for a local engine and\n // for a server, and `agentObservation` is where it lives.\n return agentObservation({\n tableId: options.tableId,\n viewRevision: revision,\n featureIds: ids,\n columns,\n source: view?.sourceCapabilities ?? PAGE_ONLY_SOURCE,\n operations: {\n ...deriveRuntimeOperations(view),\n // `applyView` is the host's alone; no runtime offers it by itself.\n applyView: apply.applyView !== undefined,\n },\n apply: options.apply ?? {},\n policy: observationPolicy(options),\n view: {\n search: query?.search ?? \"\",\n ...(query?.sortBy === undefined ? {} : { sortBy: query.sortBy }),\n ...(query?.sortDir === undefined ? {} : { sortDir: query.sortDir }),\n ...(view?.groupingState?.groupBy === undefined\n ? {}\n : { groupBy: view.groupingState.groupBy }),\n ...(view?.pinning?.columns\n ? { pinnedColumns: view.pinning.columns }\n : {}),\n ...(view?.pinning?.rows ? { pinnedRows: view.pinning.rows } : {}),\n ...(view?.columnLayout?.hidden\n ? { hiddenColumns: view.columnLayout.hidden }\n : {}),\n ...(view?.columnLayout?.keys\n ? { columnOrder: view.columnLayout.keys }\n : {}),\n ...(query?.extra === undefined ? {} : { filters: query.extra }),\n },\n pagination: pages,\n rowAddressScope: \"visible\",\n readMax: options.readMax ?? 50,\n aggregations: aggregationsFor(aggregationInputs(view, options)),\n availableFilters: agentFiltersFromDefs(\n view?.filterDefs,\n view?.filterRegistry,\n options.columns\n ),\n });\n}\n\n/**\n * What a server-backed table's pages are, from what the source will say.\n *\n * The total is the server's count for the *current query* — the figure the\n * table's own pagination is computed from — and it is published only when the\n * source claims to have counted. A source that has not counted keeps an\n * unknown total rather than being handed the rows that happen to be loaded,\n * and a short page is the one thing it still proves about its own end.\n */\n/** The sizes the table's own rows-per-page control lists. */\nfunction offeredPageSizes(\n query: TableRuntimeView<unknown>[\"query\"]\n): readonly number[] {\n const limit = query?.limit ?? 10;\n const published =\n (query as { defaultLimit?: number } | undefined)?.defaultLimit ?? limit;\n return pageSizeOptions([limit, published]);\n}\n\nfunction serverPagination(\n view: TableRuntimeView<unknown> | undefined,\n query: TableRuntimeView<unknown>[\"query\"]\n): AgentPagination {\n const counted =\n (view?.sourceCapabilities ?? PAGE_ONLY_SOURCE).totalCount === \"exact\";\n const total = query?.total;\n const loaded = view?.rows.length;\n return agentPagination({\n page: query?.page ?? 1,\n pageSize: query?.limit ?? 10,\n pageSizeOptions: offeredPageSizes(query),\n ...(counted && total !== undefined ? { totalRows: total } : {}),\n ...(loaded === undefined ? {} : { loadedRows: loaded }),\n // Only a source wired to take a page number can be sent one.\n canJump: query?.setPage !== undefined,\n });\n}\n\nfunction liveEditCells(\n runtime: ReturnType<typeof useTableRuntime>,\n extra: AgentApply | undefined,\n edits: Parameters<NonNullable<AgentApply[\"editCells\"]>>[0]\n): ReturnType<NonNullable<AgentApply[\"editCells\"]>> {\n if (extra?.editCells) return extra.editCells(edits);\n const view = runtime.view();\n const onCellEdit = view?.editing?.onCellEdit;\n if (!onCellEdit) {\n throw new Error(\"editCells is not wired\");\n }\n for (const edit of edits) {\n const row = findRow(runtime, edit.rowKey);\n if (!row) {\n throw new Error(`row \"${edit.rowKey}\" is not in the current view`);\n }\n onCellEdit(row, edit.column, edit.value);\n }\n}\n\nfunction liveStageCells(\n runtime: ReturnType<typeof useTableRuntime>,\n extra: AgentApply | undefined,\n edits: Parameters<NonNullable<AgentApply[\"stageCells\"]>>[0]\n): ReturnType<NonNullable<AgentApply[\"stageCells\"]>> {\n if (extra?.stageCells) return extra.stageCells(edits);\n const view = runtime.view();\n const stage = view?.editing?.stageCell;\n if (!stage) {\n throw new Error(\"stageCells is not wired\");\n }\n for (const edit of edits) {\n const row = findRow(runtime, edit.rowKey);\n if (!row) {\n throw new Error(`row \"${edit.rowKey}\" is not in the current view`);\n }\n stage(\n row,\n edit.rowKey,\n edit.column,\n typeof edit.value === \"string\" ? edit.value : String(edit.value)\n );\n }\n}\n\nfunction liveSetSelection(\n runtime: ReturnType<typeof useTableRuntime>,\n extra: AgentApply | undefined,\n ids: readonly string[] | undefined\n): void {\n extra?.setSelection?.(ids);\n if (!extra?.setSelection) runtime.view()?.selection?.replace(ids);\n}\n\nfunction rowScope(ref: RowRef): RowAddressScope {\n return \"scope\" in ref ? ref.scope : \"visible\";\n}\n\nfunction pickReadRows(\n runtime: ReturnType<typeof useTableRuntime>,\n extra: AgentApply | undefined,\n columns: readonly AgentColumn[],\n readMax: number\n): NonNullable<AgentApply[\"readRows\"]> {\n return (query) => {\n if (extra?.readRows) return extra.readRows(query);\n return liveReadRows(runtime, columns, query, readMax);\n };\n}\n\nfunction pickResolveRow(\n runtime: ReturnType<typeof useTableRuntime>,\n extra: AgentApply | undefined\n): NonNullable<AgentApply[\"resolveRow\"]> {\n return (ref) => {\n if (extra?.resolveRow) return extra.resolveRow(ref);\n return liveResolveRow(runtime, ref, rowScope(ref));\n };\n}\n\ninterface LiveQueryFilters {\n extra?: unknown;\n setExtras?: (extra: Record<string, unknown>) => void;\n clearExtras?: () => void;\n}\n\nfunction liveQueryFilters(\n query: NonNullable<TableRuntimeView[\"query\"]> | undefined\n): LiveQueryFilters {\n return query ? (query as LiveQueryFilters) : {};\n}\n\nfunction applyLiveFilters(\n query: NonNullable<TableRuntimeView[\"query\"]> | undefined,\n filters: unknown\n): boolean {\n const live = liveQueryFilters(query);\n if (!live.setExtras && !live.clearExtras) return false;\n if (filters == null) {\n live.clearExtras?.();\n return true;\n }\n if (typeof filters !== \"object\" || Array.isArray(filters)) {\n throw new TypeError(\"setFilters requires a filter object\");\n }\n if (Object.keys(filters).length === 0) {\n live.clearExtras?.();\n return true;\n }\n live.setExtras?.(filters as Record<string, unknown>);\n return true;\n}\n\nfunction requireQuery<\n K extends \"setPage\" | \"setLimit\" | \"setSearch\" | \"setSort\",\n>(\n view: () => TableRuntimeView<unknown> | undefined,\n name: K\n): NonNullable<NonNullable<TableRuntimeView[\"query\"]>[K]> {\n const fn = view()?.query?.[name];\n if (!fn) {\n throw new Error(`${name} is not wired`);\n }\n return fn;\n}\n\n/**\n * What the LIVE TABLE can do, before the host's own callbacks are laid over\n * it.\n *\n * `currentApply` builds `{ ...applyFromRuntime(...), ...options.apply }`, so\n * a callback the host supplied is the one that runs. A guard here that\n * checked for the same callback would be shadowed by that spread and could\n * never fire, which is why the view operations below reach straight for the\n * live table. `extra` still travels to the row, edit, stage and selection\n * helpers, which read it for their own reasons.\n */\nfunction applyFromRuntime(\n runtime: ReturnType<typeof useTableRuntime>,\n options: TableAgentOptions,\n extra?: AgentApply\n): AgentApply {\n const columns = columnsForRuntime(options, runtime);\n const readMax = options.readMax ?? 50;\n const view = () => runtime.view();\n return {\n readRows: pickReadRows(runtime, extra, columns, readMax),\n resolveRow: pickResolveRow(runtime, extra),\n setPage: (page) => {\n requireQuery(view, \"setPage\")(page);\n },\n setLimit: (limit) => {\n requireQuery(view, \"setLimit\")(limit);\n },\n setSearch: (search) => {\n requireQuery(view, \"setSearch\")(search);\n },\n setSort: (key, dir) => {\n requireQuery(view, \"setSort\")(key, dir);\n },\n setGroupBy: (key) => {\n const grouping = view()?.groupingState;\n if (!grouping) throw new Error(\"setGroupBy is not wired\");\n grouping.setGroupBy(key);\n },\n setAggregations: (patch) => {\n applyAggregations(aggregationInputs(view(), options), patch);\n },\n pinColumn: (key, side) => {\n const pinning = view()?.pinning;\n if (!pinning?.setColumnPin) throw new Error(\"pinColumn is not wired\");\n pinning.setColumnPin(key, side);\n },\n hideColumn: (key, hidden) => {\n const layout = view()?.columnLayout;\n if (!layout?.setHidden) throw new Error(\"hideColumn is not wired\");\n layout.setHidden(key, hidden);\n },\n moveColumn: (key, toIndex) => {\n const layout = view()?.columnLayout;\n if (!layout?.move) throw new Error(\"moveColumn is not wired\");\n layout.move(key, toIndex);\n },\n setColumnOrder: (order) => {\n const layout = view()?.columnLayout;\n if (!layout?.setOrder) throw new Error(\"setColumnOrder is not wired\");\n layout.setOrder(order);\n },\n pinRow: (rowKey, side) => {\n const pinning = view()?.pinning;\n if (!pinning?.setRowPin) throw new Error(\"pinRow is not wired\");\n pinning.setRowPin(rowKey, side);\n },\n editCells: (edits) => liveEditCells(runtime, extra, edits),\n stageCells: (edits) => liveStageCells(runtime, extra, edits),\n setSelection: (ids) => liveSetSelection(runtime, extra, ids),\n };\n}\n\n/**\n * The live view and filter catalog, in the shape the context builder takes.\n *\n * The same values the observation carries, read straight off the runtime so\n * the caller does not have to rebuild an observation to get at them. What the\n * table cannot answer for is simply absent, and the sanitized view names the\n * gap rather than defaulting it.\n */\n/**\n * Column ids whose author asked for live values.\n *\n * The flag is the author's, so it is read from the contract rather than from\n * anything a reader can move. A column the agent may not read is not sampled\n * whatever it says — the sampler refuses it too, and asking twice is cheaper\n * than a read that comes back empty.\n */\nfunction sampledColumns(session: AgentSession): readonly string[] {\n return session\n .manifest()\n .columns.filter((column) => column.readable && column.ai?.sample === true)\n .map((column) => column.id);\n}\n\nfunction viewInputsFromRuntime(\n runtime: ReturnType<typeof useTableRuntime>,\n options: TableAgentOptions,\n samples: Readonly<Record<string, readonly unknown[]>>\n): AgentContextInputs {\n const view = runtime.view();\n const query = view?.query;\n const filters = agentFiltersFromDefs(\n view?.filterDefs,\n view?.filterRegistry,\n options.columns\n );\n // The operations each column takes travel with the contract, not behind a\n // describe call: a caller that has to guess between \"avg\" and \"average\"\n // guesses wrong, and only finds out by being refused.\n const aggregations = aggregationsFor(aggregationInputs(view, options));\n return {\n ...(filters && filters.length > 0 ? { filters } : {}),\n ...(aggregations ? { aggregations } : {}),\n ...(Object.keys(samples).length > 0 ? { samples } : {}),\n view: {\n ...(query?.page === undefined ? {} : { page: query.page }),\n ...(query?.limit === undefined ? {} : { limit: query.limit }),\n ...(query?.search === undefined ? {} : { search: query.search }),\n ...(query?.sortBy ? { sortBy: query.sortBy } : {}),\n ...(query?.sortDir ? { sortDir: query.sortDir } : {}),\n ...(view?.groupingState?.groupBy\n ? { groupBy: view.groupingState.groupBy }\n : {}),\n ...(query?.extra ? { filters: query.extra } : {}),\n ...(view?.pinning?.columns\n ? {\n pinnedColumns: view.pinning.columns,\n }\n : {}),\n ...(view?.pinning?.rows\n ? {\n pinnedRows: view.pinning.rows,\n }\n : {}),\n ...(view?.columnLayout?.hidden\n ? { hiddenColumns: view.columnLayout.hidden }\n : {}),\n ...(view?.columnLayout?.keys\n ? { columnOrder: view.columnLayout.keys }\n : {}),\n },\n };\n}\n\n/**\n * A row-by-row refusal, with the reader's stated reason when they gave one.\n *\n * The reason travels with the refusal so the receipt and the model-visible\n * result can say why rather than only that.\n */\nfunction perItemRefusal(\n transaction: ApprovalTransaction,\n stated: string | undefined\n): ApprovalResult {\n return {\n ...settleDecisions(transaction.decisions, \"rejected\"),\n ...(stated ? { reason: stated } : {}),\n };\n}\n\n/** One comparable string for an exclusion list, order-insensitive. */\nfunction exclusionKey(keys: readonly string[] | undefined): string {\n return keys ? [...keys].sort((a, b) => a.localeCompare(b)).join(\"|\") : \"\";\n}\n\n/**\n * What a capability does to the table, from the live catalog.\n *\n * Read through the session rather than kept in a list here: the definition is\n * the only thing that knows, and item 11 published it on the catalog entry so\n * every surface reads the same answer.\n */\nfunction capabilityKind(\n session: AgentSession | undefined,\n capability: string | undefined\n): AgentCapabilityDefinition[\"kind\"] | undefined {\n if (!session || capability === undefined) return undefined;\n return session.catalog().find((entry) => entry.key === capability)?.kind;\n}\n\n/**\n * The opt-in list, with an action's own demand for a human applied.\n *\n * The shared configuration is what the binding can see directly; an action\n * that sets `approval: \"required\"` is read from the custom definition it was\n * declared on, so a capability that must always be confirmed never offers the\n * control however the table was configured.\n */\nfunction alwaysAllowFor(\n approval: SharedApproval | undefined,\n capabilities: readonly AgentCapabilityDefinition[] | undefined,\n capability: string | undefined\n): readonly string[] {\n const shared = sharedApproval(approval);\n if (capability === undefined) return shared.alwaysAllow;\n const definition = capabilities?.find((entry) => entry.key === capability);\n return resolveApproval(shared, definition?.ai).alwaysAllow;\n}\n\n/**\n * How this binding finds what the person in front of the table may see.\n *\n * The lookups are React's — only this side knows how to find a row in a\n * runtime view. What is done with them is not: the enrichment algorithm lives\n * in `@adapttable/ai`, so every binding reports an unreadable column the same\n * way rather than each inventing its own blank cell.\n */\nfunction readerResolver(\n runtime: ReturnType<typeof useTableRuntime>,\n columns: Readonly<Record<string, TableAgentColumnPatch>> | undefined\n): ProposalResolver {\n const view = runtime.view();\n const recordFor = (rowKey: string): Record<string, unknown> | undefined => {\n const row = findRow(runtime, rowKey);\n return row && typeof row === \"object\"\n ? (row as Record<string, unknown>)\n : undefined;\n };\n return {\n rowLabel: (rowKey) => {\n const row = findRow(runtime, rowKey);\n return row !== undefined && view?.rowLabel\n ? view.rowLabel(row)\n : undefined;\n },\n cellValue: (rowKey, column) => recordFor(rowKey)?.[column],\n // The column's own `formatValue` takes a row, so a proposed value is\n // formatted by asking the column about the row it would produce. That is\n // what makes `170 → 175` read as `$170k → $175k` on the card, in exactly\n // the wording the cells use.\n cellText: (rowKey, column, value) => {\n const definition = runtime\n .view()\n ?.groupingState?.columns?.find((entry) => entry.key === column);\n const format = definition?.formatValue;\n const record = recordFor(rowKey);\n if (!format || !record) return undefined;\n return format({ ...record, [column]: value });\n },\n readable: (column) => columns?.[column]?.readable !== false,\n columnLabel: (column) => columns?.[column]?.label,\n };\n}\n\n/**\n * The live table's grouping state, as the neutral rules want it.\n *\n * A projection, not a decision: it names where the facts are and which\n * columns the agent may read. What may be offered and what may be set is\n * `@adapttable/ai`'s to answer, so a second binding gets the same answers.\n */\nfunction aggregationInputs(\n view: TableRuntimeView<unknown> | undefined,\n options: TableAgentOptions\n): AggregationInputs {\n return {\n state: view?.groupingState,\n grouping: view?.sourceCapabilities?.grouping,\n allows: (key) => options.columns?.[key]?.readable !== false,\n };\n}\n\nfunction asCallable(\n value: unknown\n): ((...input: unknown[]) => unknown) | undefined {\n if (typeof value !== \"function\") return undefined;\n return value as (...input: unknown[]) => unknown;\n}\n\n/**\n * View mutations whose default implementation belongs to this binding.\n *\n * They call React-backed runtime setters. Committing those setters before the\n * call returns lets the session attribute the resulting table revision to the\n * exact apply call that made it. Host overrides are deliberately excluded:\n * only the host can say when its own async callback has settled.\n */\nconst BINDING_VIEW_MUTATIONS: ReadonlySet<string> = new Set([\n \"setPage\",\n \"setLimit\",\n \"setSearch\",\n \"setSort\",\n \"setFilters\",\n \"setGroupBy\",\n \"setAggregations\",\n \"pinColumn\",\n \"hideColumn\",\n \"moveColumn\",\n \"setColumnOrder\",\n \"pinRow\",\n \"setSelection\",\n]);\n\nfunction createRevisionCounter() {\n let token: string | undefined;\n let revision = 1;\n const bumpFromToken = (nextToken: string): number => {\n if (token === undefined) {\n token = nextToken;\n return revision;\n }\n if (token === nextToken) return revision;\n token = nextToken;\n revision += 1;\n return revision;\n };\n return {\n bumpFrom(revisions: {\n data: number;\n view: number;\n schema: number;\n policy: number;\n }) {\n return bumpFromToken(revisionToken(revisions));\n },\n bumpFromStamp(stamp: string) {\n return bumpFromToken(stamp);\n },\n current() {\n return revision;\n },\n };\n}\n\nfunction currentApply(\n options: TableAgentOptions,\n runtime: ReturnType<typeof useTableRuntime>\n): AgentApply {\n const fromRuntime = applyFromRuntime(runtime, options, options.apply);\n const apply: AgentApply = { ...fromRuntime, ...options.apply };\n apply.setFilters = (filters) => {\n if (options.apply?.setFilters) {\n options.apply.setFilters(filters);\n return;\n }\n const applied = applyLiveFilters(runtime.view()?.query, filters);\n if (!applied) {\n throw new Error(\"setFilters is not wired\");\n }\n };\n return apply;\n}\n\nfunction bindLiveSession(\n optionsRef: { current: TableAgentOptions },\n runtimeRef: { current: ReturnType<typeof useTableRuntime> },\n revisionCounter: ReturnType<typeof createRevisionCounter>,\n flushAdmission: { current: () => void },\n waitForChrome: {\n current: (\n subject: ApprovalSubject,\n signal?: AbortSignal\n ) => Promise<ApprovalResult>;\n },\n reportProgress: { current: (report: AgentProgress | null) => void }\n): AgentSession {\n const apply = new Proxy<AgentApply>(\n {},\n {\n get(_target, prop) {\n if (typeof prop !== \"string\") return undefined;\n const live = currentApply(\n optionsRef.current,\n runtimeRef.current\n ) as Record<string, unknown>;\n if (!(prop in live)) return undefined;\n return (...args: unknown[]) => {\n const options = optionsRef.current;\n const latest = currentApply(options, runtimeRef.current) as Record<\n string,\n unknown\n >;\n const fn = asCallable(latest[prop]);\n if (!fn) return undefined;\n const host = options.apply as Record<string, unknown> | undefined;\n if (BINDING_VIEW_MUTATIONS.has(prop) && !asCallable(host?.[prop])) {\n let result: unknown;\n flushSync(() => {\n result = fn(...args);\n });\n return result;\n }\n return fn(...args);\n };\n },\n }\n );\n const observe = () => {\n const options = optionsRef.current;\n if (options.observe) return options.observe();\n const runtimeView = runtimeRef.current.view();\n const table = runtimeView?.neutralTable;\n let viewRevision = revisionCounter.current();\n if (table) viewRevision = revisionCounter.bumpFrom(table.revisions);\n else if (runtimeView) {\n viewRevision = revisionCounter.bumpFromStamp(\n viewRevisionStamp(runtimeView)\n );\n }\n return observationFromRuntime(\n options,\n runtimeRef.current,\n viewRevision,\n apply\n );\n };\n const onApprove = (subject: ApprovalSubject, signal?: AbortSignal) => {\n const options = optionsRef.current;\n if (options.onApprove) return options.onApprove(subject, signal);\n // No second policy decision here. The session already resolved whether a\n // human is asked, for THIS capability, with the action's own override\n // applied — so a table that asks for nothing by default can still mark\n // one action always-ask. Answering \"approved\" on the shared policy alone\n // silently overrode that.\n return waitForChrome.current(subject, signal);\n };\n const inner = createAgentSession({\n observe,\n apply,\n onApprove,\n // Read at call time, like everything else here. The session is built once\n // and a host may wire its bridge on a later render, so what a capability\n // reports is delivered through the ref rather than through whatever was\n // configured when the session was made.\n onProgress: (report) => {\n reportProgress.current(report);\n },\n capabilities: optionsRef.current.capabilities,\n ...(optionsRef.current.capabilityApproval\n ? { capabilityApproval: optionsRef.current.capabilityApproval }\n : {}),\n ...(optionsRef.current.excludeCapabilities\n ? { excludeCapabilities: optionsRef.current.excludeCapabilities }\n : {}),\n });\n return {\n catalog: () => inner.catalog(),\n describe: (key: string) => inner.describe(key),\n execute: async (\n key: string,\n args: unknown,\n expectedRevision: number,\n idempotencyKey: string,\n signal?: AbortSignal\n ) => {\n // React may still hold a reader's earlier controlled-state change. Flush\n // it before the session takes its admission snapshot so that change is\n // refused as foreign, never swept into the revision of the agent call\n // below. The binding-owned mutation itself is flushed in `apply` above.\n flushAdmission.current();\n const result = await inner.execute(\n key,\n args,\n expectedRevision,\n idempotencyKey,\n signal\n );\n return result;\n },\n manifest: () => inner.manifest(),\n };\n}\n\n/** One open approval, whichever shape the write took. */\nfunction TableAgentProvider({\n feature,\n children,\n}: Readonly<FeatureProviderProps>): ReactNode {\n const options = (feature as TableAgentFeature).options;\n const runtime = useTableRuntime();\n const revisionCounterRef = useRef(createRevisionCounter());\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 // The session is built here, before anything reads it. Several callbacks\n // below name it in a dependency array, which React evaluates during render\n // — so a `const` declared after them is read before it exists.\n //\n // `waitForChrome` is a ref whose handler is assigned further down; the\n // session only calls it once a write is actually proposed, so declaring the\n // ref early costs nothing and is what lets the session move up here.\n const waitForChrome = useRef<\n (subject: ApprovalSubject, signal?: AbortSignal) => Promise<ApprovalResult>\n >(() => Promise.resolve(false));\n // The same arrangement for progress: the session is built once and reports\n // through this, and what it reports goes both to the table's own feature\n // state and to a bridge a host wired.\n const reportProgress = useRef<(report: AgentProgress | null) => void>(\n () => undefined\n );\n const tableIdRef = useRef(options.tableId);\n // The registry is resolved when the session is built, so a change to what\n // the agent may use — or to who has to approve it — is a different session,\n // not a different answer from the same one.\n const registryKeyOf = (next: TableAgentOptions): string =>\n `${exclusionKey(next.excludeCapabilities)}!${JSON.stringify(next.capabilityApproval ?? {})}`;\n const registryRef = useRef(registryKeyOf(options));\n const registryKey = registryKeyOf(options);\n const sessionRef = useRef<AgentSession | null>(null);\n if (\n tableIdRef.current !== options.tableId ||\n registryRef.current !== registryKey\n ) {\n tableIdRef.current = options.tableId;\n registryRef.current = registryKey;\n sessionRef.current = null;\n revisionCounterRef.current = createRevisionCounter();\n }\n sessionRef.current ??= bindLiveSession(\n optionsRef,\n runtimeRef,\n revisionCounterRef.current,\n flushAdmission,\n waitForChrome,\n reportProgress\n );\n const session = sessionRef.current;\n // Bumped when the reader takes an allowance back, so the published list is\n // rebuilt. The memory itself is a ref and cannot notify React on its own.\n const [revocations, setRevocations] = useState(0);\n // What a running capability last said about itself, and nothing once it\n // stops. The session reports it through `reportProgress` above.\n const [progress, setProgress] = useState<AgentProgress | null>(null);\n const [transaction, setTransaction] = useState<ApprovalTransaction | null>(\n null\n );\n const pendingRef = useRef<PendingApproval | null>(null);\n const transactionId = useRef(0);\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 — which is what the old\n // dependency-free effect was standing in for. The value is not rendered;\n // re-rendering is the point, because that republishes the manifest.\n const neutralTable = runtime.view()?.neutralTable;\n const readStamp = useCallback(\n () =>\n neutralTable\n ? revisionToken(neutralTable.revisions)\n : viewRevisionStamp(runtime.view()),\n [neutralTable, runtime]\n );\n const subscribeToTable = useCallback(\n (onStoreChange: () => void) =>\n neutralTable\n ? neutralTable.subscribe(\"all\", onStoreChange)\n : () => undefined,\n [neutralTable]\n );\n const stamp = useSyncExternalStore(subscribeToTable, readStamp, readStamp);\n useDebugValue(stamp);\n\n const hostApprove = options.onApprove;\n // What the reader has said not to be asked about again. Scoped to the\n // contract, so it forgets the moment the table is not the one they agreed\n // about.\n const approvalMemory = useRef(createApprovalMemory());\n // The contract the reader agreed about. A label, a permission or a\n // capability changing makes it a different table, and the memory clears.\n const contractVersion = useCallback(\n () => contractFingerprint(session.manifest(), session.catalog()),\n [session]\n );\n\n const webmcp = options.webmcp;\n // Registration belongs to a contract version: a table whose capabilities or\n // columns moved is a different set of tools, so the old ones go and the new\n // ones are offered. Effects never run on the server, which is also where\n // `document` would be missing.\n const webmcpVersion = webmcp ? contractVersion() : \"\";\n useEffect(() => {\n if (!webmcp) return;\n const options = webmcp === true ? {} : webmcp;\n const registration = registerWebMcpTools(session, {\n ...(options.exposedTo ? { exposedTo: options.exposedTo } : {}),\n onWarning: (warning) => {\n // A page whose policy forbids this is configured that way on purpose.\n // Saying so once beats throwing into a render.\n console.warn(`[adapttable] webmcp: ${warning.message}`);\n },\n });\n options.onRegister?.(registration.names);\n return () => {\n registration.dispose();\n // Said plainly rather than left standing: the tools are gone, and a\n // surface listing them would otherwise show a set nothing can call.\n options.onRegister?.([]);\n };\n }, [session, webmcp, webmcpVersion]);\n waitForChrome.current = (subject, signal) => {\n if (pendingRef.current) {\n return Promise.reject(new Error(\"an approval is already pending\"));\n }\n // Consulted only here, after the session has already decided a human\n // would be asked. It can never turn `approval: \"never\"` into a write\n // nobody saw, and it never answers for a write that enumerates rows.\n const capability =\n subject.kind === \"operation\" ? subject.capability : undefined;\n if (\n mayAlwaysAllow({\n capability,\n kind: capabilityKind(session, capability),\n alwaysAllow: alwaysAllowFor(\n optionsRef.current.approval,\n optionsRef.current.capabilities,\n capability\n ),\n }) &&\n capability !== undefined &&\n approvalMemory.current.allows(capability, contractVersion())\n ) {\n return Promise.resolve(true);\n }\n return new Promise<ApprovalResult>((resolve) => {\n // A write is either rows the reader can decide one at a time, or one\n // operation a backend performs whole — \"set every status to Active\"\n // names no rows at all. The session says which; nothing here guesses\n // from the runtime shape of a value.\n const rows = subject.kind === \"rows\";\n let settled = false;\n const entry: PendingApproval = {\n ...(rows ? {} : { capability: subject.capability }),\n // What the reader is shown, resolved from their own table. The\n // model's own `before` values stay in the session and never reach\n // this side.\n proposals: rows\n ? displayProposals(\n subject.proposals,\n readerResolver(runtimeRef.current, optionsRef.current.columns)\n )\n : [],\n perItem: rows && subject.perItem,\n ...(rows\n ? {}\n : {\n operation: {\n capability: subject.capability,\n ...(subject.title ? { title: subject.title } : {}),\n arguments: subject.arguments,\n },\n }),\n // Settled once, whoever gets there first: the reader, an abort, an\n // unmount, or the last row being answered. A second call is a no-op\n // rather than a second answer to one question.\n resolve: (result: ApprovalResult) => {\n if (settled) return;\n settled = true;\n if (pendingRef.current === entry) pendingRef.current = null;\n setTransaction(closeTransaction(entry));\n signal?.removeEventListener(\"abort\", onAbort);\n resolve(result);\n },\n };\n const onAbort = () => entry.resolve(false);\n pendingRef.current = entry;\n // Identity and decisions in one write, so no render ever shows this\n // write's rows beside the last write's answers.\n transactionId.current += 1;\n // Resolved by the session for THIS action, so an override of\n // `ai.approval.presentation` reaches the surface that draws it.\n setTransaction(\n openTransaction(transactionId.current, entry, subject.presentation)\n );\n if (signal?.aborted) {\n entry.resolve(false);\n return;\n }\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n };\n\n useEffect(\n () => () => {\n pendingRef.current?.resolve(false);\n },\n []\n );\n\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 // The live view, as the context builder wants it. Read through a stable\n // callback rather than captured: the store calls it when a turn starts and\n // again when it settles, and a value taken at render time would report that\n // nothing moved between the two — which is exactly what per-turn undo has\n // to be able to tell.\n // Live values for the columns whose author opted in. Read once per contract\n // rather than once per turn: sampling is a read against the table, and a\n // table publishing ten sampled columns must not open ten reads every time\n // somebody types. Held in a ref because the reader below is synchronous —\n // the context builder performs no I/O, which is the rule this keeps.\n const samplesRef = useRef<Readonly<Record<string, readonly unknown[]>>>({});\n const viewStateValue = useRef<AgentViewState>({\n read: () =>\n viewInputsFromRuntime(\n runtimeRef.current,\n optionsRef.current,\n samplesRef.current\n ),\n }).current;\n\n useEffect(() => {\n options.bridge?.attach?.(session);\n // The reader is stable for the life of this feature, so a host takes it\n // once and calls it whenever it needs the view — rather than being pushed\n // a copy on every change and having to keep it in step.\n options.bridge?.viewInputs?.(\n viewStateValue.read as () => AgentContextInputs\n );\n }, [options.bridge, session, viewStateValue]);\n\n const last = useRef<string>(\"\");\n useLayoutEffect(() => {\n const published = session.manifest();\n const encoded = JSON.stringify(published);\n if (encoded === last.current) return;\n last.current = encoded;\n options.bridge?.publish?.(published);\n });\n\n // Sampled once for the set of columns that asked, and again only when that\n // set changes. Abandoned on unmount: a read that comes back to a table the\n // reader has left must not write into it.\n const sampledKey = sampledColumns(session).join(\"\u0000\");\n useEffect(() => {\n const wanted = sampledKey === \"\" ? [] : sampledKey.split(\"\u0000\");\n if (wanted.length === 0) {\n samplesRef.current = {};\n return;\n }\n const controller = new AbortController();\n void sampleColumns(session, wanted, controller.signal).then(\n (values) => {\n if (controller.signal.aborted) return;\n samplesRef.current = values;\n },\n () => {\n // A sample is an illustration, not a result. A table that cannot\n // supply one publishes the author's own examples and nothing else,\n // rather than failing a turn nobody has started.\n if (!controller.signal.aborted) samplesRef.current = {};\n }\n );\n return () => controller.abort();\n }, [session, sampledKey, samplesRef]);\n\n // The chrome path is the only one that parks: with `onApprove` the host\n // answers directly and nothing is ever left open here.\n const chromePending = !hostApprove && transaction !== null;\n\n // Who is listening, and what they were last told.\n //\n // The subscriber is compared by its own identity rather than the bridge's:\n // a host that rebuilds `bridge={{ ... }}` inline on every render still\n // passes the same `approvals` function, and re-announcing an unchanged\n // state on every render is noise a host cannot filter.\n const approvals = options.bridge?.approvals;\n const approvalsRef = useRef(approvals);\n // The transaction last announced, not merely whether one was. A decision\n // taken inside an open approval changes what a subscriber should be\n // holding, and announcing only open-versus-closed left a panel outside the\n // table rendering the state from before the reader touched it.\n const announcedRef = useRef<ApprovalTransaction | null>(null);\n // What a subscriber would be handed right now. Held in a ref because the\n // published value is built below, and the announcement must not care about\n // declaration order.\n const publishedRef = useRef<AgentApprovalPending | null>(null);\n\n useEffect(() => {\n const previous = approvalsRef.current;\n if (previous !== approvals) {\n // A genuinely different subscriber. The one being replaced must not be\n // left believing an approval is still open, and the one arriving has\n // never been told anything.\n if (announcedRef.current) previous?.(null);\n approvalsRef.current = approvals;\n announcedRef.current = null;\n }\n const next = chromePending ? transaction : null;\n if (announcedRef.current === next) return;\n announcedRef.current = next;\n approvals?.(next ? publishedRef.current : null);\n }, [approvals, chromePending, transaction]);\n\n // Going away is a close. Without this the host is left showing \"waiting for\n // you\" for an approval whose provider no longer exists — and resolving the\n // promise below cannot help, because no effect runs after an unmount to\n // announce it. Strict Mode's setup/cleanup/setup lands here too: the\n // cleanup retracts, and the effect above re-announces on the second setup.\n useEffect(\n () => () => {\n if (!announcedRef.current) return;\n announcedRef.current = null;\n approvalsRef.current?.(null);\n },\n []\n );\n\n // A pure state update, bound to the transaction it was made for. A control\n // left over from a settled approval finds a different id and does nothing;\n // a position that is not a row of THIS plan changes nothing either.\n const decideAt = (id: number) => (index: number, approved: boolean) => {\n setTransaction((current) => recordDecision(current, id, index, approved));\n };\n\n // Answering the last row settles the write. This belongs in an effect and\n // not in the updater that produced the decisions: a state updater may be\n // replayed, and replaying one that resolves a promise would answer the\n // session twice.\n useEffect(() => {\n if (!transaction) return;\n // A write that named no rows has no last row to answer. It waits for an\n // explicit whole decision — an empty decision list is not \"everything is\n // decided\", it is \"there was never anything to enumerate\".\n if (transaction.pending.proposals.length === 0) return;\n if (transaction.decisions.includes(\"pending\")) return;\n transaction.pending.resolve(\n settleDecisions(transaction.decisions, \"rejected\")\n );\n }, [transaction]);\n\n // Rebuilt every render on purpose: the published value is what subscribers\n // compare, and memoizing it hides a decision that changed inside it.\n const approvalValue =\n hostApprove || !transaction\n ? null\n : {\n proposals: transaction.pending.proposals,\n ...(transaction.pending.operation\n ? { operation: transaction.pending.operation }\n : {}),\n decisions: transaction.decisions,\n presentation: transaction.presentation,\n // \"Approve remaining\" is what these mean once rows have been\n // decided: a row already refused stays refused, or the control\n // undoes the reader's own work.\n //\n // A write that cannot be split is answered whole — a row move, a\n // custom operation, or one that enumerates no rows at all. Sending\n // positions for one of those reaches the session as a decision it\n // is right to refuse, and an empty list reads as \"approved none\".\n ...(mayAlwaysAllow({\n capability: transaction.pending.capability,\n kind: capabilityKind(session, transaction.pending.capability),\n alwaysAllow: alwaysAllowFor(\n optionsRef.current.approval,\n optionsRef.current.capabilities,\n transaction.pending.capability\n ),\n })\n ? {\n alwaysAllow: () => {\n const capability = transaction.pending.capability;\n if (capability === undefined) return;\n approvalMemory.current.remember(\n capability,\n contractVersion()\n );\n transaction.pending.resolve(true);\n },\n }\n : {}),\n approve: () =>\n transaction.pending.resolve(\n transaction.pending.perItem\n ? settleDecisions(transaction.decisions, \"approved\")\n : true\n ),\n reject: (reason?: string) => {\n // A kit's button is wired `onClick={onReject}`, and the slot\n // contract says the handler takes nothing — so what actually\n // arrives is a click event. The declared type is a claim, not a\n // fact: anything that is not a stated reason is no reason at all.\n const stated =\n typeof reason === \"string\" ? reason.trim() : undefined;\n if (transaction.pending.perItem) {\n transaction.pending.resolve(perItemRefusal(transaction, stated));\n return;\n }\n // A write answered whole is a plain refusal unless the reader\n // said something, in which case an empty approval list carries\n // the words.\n transaction.pending.resolve(\n stated ? { approved: [], reason: stated } : false\n );\n },\n ...(transaction.pending.perItem\n ? { decideAt: decideAt(transaction.id) }\n : {}),\n };\n\n publishedRef.current = approvalValue;\n\n // What the reader has waved through, published whether or not an approval is\n // open — a reader goes looking for the list precisely when nothing is\n // waiting. `remembered` is read during render, and `revocations` is what\n // makes a revoke reach this render rather than the next approval.\n // Checked once per contract, where the configuration first meets a live\n // catalog. A key this table does not offer is a control the developer\n // believes they shipped and the reader never sees, so it is an error rather\n // than a silence — the same treatment `include` gets in the context builder.\n useEffect(() => {\n assertAlwaysAllow(\n sharedApproval(optionsRef.current.approval).alwaysAllow,\n session.catalog().map((entry) => entry.key)\n );\n }, [session, stamp]);\n\n const alwaysAllowValue = useMemo<AgentAlwaysAllowState>(\n () => ({\n capabilities: approvalMemory.current.remembered(contractVersion()),\n revoke: (capability: string) => {\n approvalMemory.current.revoke(capability);\n setRevocations((count) => count + 1);\n },\n }),\n // A revoke, or the table moving — the memory is a ref, so neither tells\n // React on its own, and a contract change is what clears the memory.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [revocations, stamp, contractVersion]\n );\n\n // Published the same way the manifest and the approval are: a panel mounted\n // beside the table cannot read feature state from inside it, so a reader\n // who waved a capability through would have nowhere to take it back.\n const alwaysAllowedBridge = optionsRef.current.bridge?.alwaysAllowed;\n useEffect(() => {\n alwaysAllowedBridge?.(alwaysAllowValue);\n }, [alwaysAllowedBridge, alwaysAllowValue]);\n\n // Both destinations, from the one report: the table's own panel reads the\n // feature state, and a panel mounted outside it reads the bridge. Assigned\n // on every render for the same reason the approval handler is — the session\n // is built once and must not be holding the first render's closure.\n reportProgress.current = (report) => {\n setProgress(report);\n optionsRef.current.bridge?.progress?.(report);\n };\n\n return (\n <FeatureStateScope stateKey={TABLE_AGENT_STATE} value={published}>\n <FeatureStateScope stateKey={AGENT_APPROVAL_STATE} value={approvalValue}>\n <FeatureStateScope\n stateKey={AGENT_ALWAYS_ALLOW_STATE}\n value={alwaysAllowValue}\n >\n <FeatureStateScope stateKey={AGENT_VIEW_STATE} value={viewStateValue}>\n <FeatureStateScope stateKey={AGENT_PROGRESS_STATE} value={progress}>\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 { useEffect, useRef, 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\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 languages = voice?.languages?.length\n ? voice.languages\n : [locale ?? \"en-US\"];\n const inputRef = useRef<SpeechInput | null>(null);\n if (voice && !inputRef.current) {\n inputRef.current = createSpeechInput({\n mode: voice.mode ?? \"browser\",\n languages,\n // Remembered from a previous visit when the browser kept it, and the\n // first offered language otherwise.\n ...(readRememberedLanguage()\n ? { initialLanguage: readRememberedLanguage() }\n : {}),\n onDraft: (text) => draftRef.current(text),\n onClip: (clip) => clipRef.current?.(clip),\n });\n }\n const input = inputRef.current;\n\n useEffect(\n () => () => {\n input?.dispose();\n // A disposed controller is never revived: a remount builds a fresh one,\n // the way the assistant store does.\n inputRef.current = null;\n },\n [input]\n );\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiRA,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;CAG5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Q;EAC3B;CACF;AACF"}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
|
|
2
|
+
import { AgentApply, AgentCapabilityDefinition, AgentContextInputs, AgentObservation, AgentSession, AlwaysAllowedState, ApprovalResult, ApprovalSubject, AssistantAllowance, AssistantAnswer, AssistantInterruption, AssistantInterruption as AssistantInterruption$1, AssistantMessage, AssistantQuestion, AssistantResumeHandle, AssistantResumeHandle as AssistantResumeHandle$1, AssistantStatus, AssistantSuggestion, AssistantSuggestion as AssistantSuggestion$1, AssistantTransport, CommitPolicy, SharedApproval, TableAgentBridge as TableAgentBridge$1, TableAgentColumnPatch, TableAssistantSnapshot, TableAssistantStore, WritePolicy } from "@adapttable/ai";
|
|
3
|
+
import { AgentApprovalPending, AgentProgress, SpeechInputHandle, StaticTableFeature } from "@adapttable/react/adapter";
|
|
4
|
+
import { ActionAiOptions } from "@adapttable/core";
|
|
5
|
+
import { SpeechClip, VoiceOptions } from "@adapttable/ai/voice";
|
|
6
|
+
//#region src/assistant.d.ts
|
|
7
|
+
/** How {@link useTableAssistant} is configured. @public */
|
|
8
|
+
interface TableAssistantOptions {
|
|
9
|
+
/** The live session. Changing it starts a new conversation. */
|
|
10
|
+
readonly session: AgentSession | undefined;
|
|
11
|
+
/**
|
|
12
|
+
* Where a turn goes. Omit and the assistant stays disconnected.
|
|
13
|
+
*
|
|
14
|
+
* May be a fresh object every render — the controller reads the latest one
|
|
15
|
+
* rather than reconnecting on its identity, so a host is not forced to
|
|
16
|
+
* memoize it.
|
|
17
|
+
*/
|
|
18
|
+
readonly transport?: AssistantTransport;
|
|
19
|
+
/**
|
|
20
|
+
* Changes when the transport should be re-established.
|
|
21
|
+
*
|
|
22
|
+
* The conversation resets on a new session, because that is a new table.
|
|
23
|
+
* Swapping one transport for another — a backend for a scripted one — is
|
|
24
|
+
* not visible in the object identity, so a host that does it names the
|
|
25
|
+
* change here. A backend transport must never quietly become a simulated
|
|
26
|
+
* one under the same key.
|
|
27
|
+
*/
|
|
28
|
+
readonly transportKey?: string;
|
|
29
|
+
/** Everything authored, filtered live against what the table offers. */
|
|
30
|
+
readonly suggestions?: readonly AssistantSuggestion$1[];
|
|
31
|
+
/** Controlled panel state. Omit for uncontrolled. */
|
|
32
|
+
readonly open?: boolean;
|
|
33
|
+
/** Called on every open/close request, controlled or not. */
|
|
34
|
+
readonly onOpenChange?: (open: boolean) => void;
|
|
35
|
+
/**
|
|
36
|
+
* Whether a write from this conversation is waiting on a human.
|
|
37
|
+
*
|
|
38
|
+
* `execute` does not return while an approval is open, so the turn looks
|
|
39
|
+
* like thinking from in here. A host that renders the approval — or wires
|
|
40
|
+
* `bridge.approvals` — passes it back so the panel can say what is
|
|
41
|
+
* actually happening. The turn is still in flight and still stoppable.
|
|
42
|
+
*/
|
|
43
|
+
readonly awaitingApproval?: boolean;
|
|
44
|
+
/**
|
|
45
|
+
* What the reader has waved through, when the panel is mounted outside the
|
|
46
|
+
* table.
|
|
47
|
+
*
|
|
48
|
+
* A panel inside the table reads this from feature state and needs nothing
|
|
49
|
+
* here. One beside it cannot, so a host wires `bridge.alwaysAllowed` and
|
|
50
|
+
* passes what it publishes — the same arrangement `bridge.approvals` and
|
|
51
|
+
* `bridge.viewInputs` already have. Without it a reader can wave a
|
|
52
|
+
* capability through and have no way to take it back.
|
|
53
|
+
*/
|
|
54
|
+
readonly alwaysAllow?: AlwaysAllowedState;
|
|
55
|
+
/**
|
|
56
|
+
* Live view and filter data the manifest does not carry.
|
|
57
|
+
*
|
|
58
|
+
* Read when a turn starts and again when it settles, so per-turn undo can
|
|
59
|
+
* tell what the turn moved. A function rather than a value: a fixed object
|
|
60
|
+
* would report that nothing changed.
|
|
61
|
+
*/
|
|
62
|
+
readonly contextInputs?: () => AgentContextInputs;
|
|
63
|
+
/**
|
|
64
|
+
* Work that outlived its connection, handed over the moment it does.
|
|
65
|
+
*
|
|
66
|
+
* Durable recovery starts here and ends outside this package: a host that
|
|
67
|
+
* stores the handle where it survives a reload can offer a resume when the
|
|
68
|
+
* reader comes back, and a host that does nothing loses the work with the
|
|
69
|
+
* page.
|
|
70
|
+
*/
|
|
71
|
+
readonly onDetach?: (handle: AssistantResumeHandle$1) => void;
|
|
72
|
+
/** A handle kept from a previous page, to resume into this one. */
|
|
73
|
+
readonly resumeHandle?: AssistantResumeHandle$1;
|
|
74
|
+
/**
|
|
75
|
+
* The transcript, when your app owns it.
|
|
76
|
+
*
|
|
77
|
+
* Omit it and the conversation lives in the controller. Supply it to load
|
|
78
|
+
* the last conversation from your own API, append a message that arrived on
|
|
79
|
+
* a socket, or keep it where it survives a reload — pass a new array and the
|
|
80
|
+
* panel shows it. Pair it with `onMessagesChange`.
|
|
81
|
+
*/
|
|
82
|
+
readonly messages?: readonly AssistantMessage[];
|
|
83
|
+
/** Told whenever the transcript changes, with the whole of it. */
|
|
84
|
+
readonly onMessagesChange?: (messages: readonly AssistantMessage[]) => void;
|
|
85
|
+
/**
|
|
86
|
+
* How much of the conversation travels with each turn.
|
|
87
|
+
*
|
|
88
|
+
* `"full"` (default) sends every earlier message, for a backend that
|
|
89
|
+
* remembers nothing. A number sends that many of the most recent. `0` sends
|
|
90
|
+
* none — the reader's message still travels, and a backend holding its own
|
|
91
|
+
* session supplies the rest. What the reader sees is never trimmed.
|
|
92
|
+
*/
|
|
93
|
+
readonly conversation?: "full" | number;
|
|
94
|
+
}
|
|
95
|
+
/** What a host renders from. @public */
|
|
96
|
+
interface TableAssistantState {
|
|
97
|
+
readonly status: AssistantStatus;
|
|
98
|
+
/**
|
|
99
|
+
* Whether a turn is in flight and can still be stopped.
|
|
100
|
+
*
|
|
101
|
+
* Separate from {@link TableAssistantState.status}: a write parked on a
|
|
102
|
+
* human approval reports `awaiting-approval` but is still running, and
|
|
103
|
+
* Stop still ends it.
|
|
104
|
+
*/
|
|
105
|
+
readonly busy: boolean;
|
|
106
|
+
readonly messages: readonly AssistantMessage[];
|
|
107
|
+
readonly draft: string;
|
|
108
|
+
readonly setDraft: (draft: string) => void;
|
|
109
|
+
/** Send the draft, or the given text. Resolves when the turn settles. */
|
|
110
|
+
readonly send: (text?: string) => Promise<void>;
|
|
111
|
+
/** Abort the turn in flight. Safe to call when nothing is in flight. */
|
|
112
|
+
readonly stop: () => void;
|
|
113
|
+
/**
|
|
114
|
+
* Rejoin work a released connection left running.
|
|
115
|
+
*
|
|
116
|
+
* A no-op with nothing to rejoin, which is what `resumable` says.
|
|
117
|
+
*/
|
|
118
|
+
readonly resume: () => Promise<void>;
|
|
119
|
+
/**
|
|
120
|
+
* What became of the last turn, when no reply ended it.
|
|
121
|
+
*
|
|
122
|
+
* `"stopped"` is the reader's own decision; `"detached"` is a released
|
|
123
|
+
* connection, where the work may still be running.
|
|
124
|
+
*/
|
|
125
|
+
readonly interrupted: AssistantInterruption$1 | undefined;
|
|
126
|
+
/** The work `resume` would rejoin, or nothing. */
|
|
127
|
+
readonly resumable: AssistantResumeHandle$1 | undefined;
|
|
128
|
+
/** Drop the transcript. Refuses while a turn is in flight. */
|
|
129
|
+
readonly clear: () => void;
|
|
130
|
+
/**
|
|
131
|
+
* A write waiting on the reader, or nothing.
|
|
132
|
+
*
|
|
133
|
+
* Hand it to the panel as `approval` and the conversation reviews it —
|
|
134
|
+
* which is where a write asked for in the conversation belongs. The panel
|
|
135
|
+
* draws it only when the approval's presentation names the widget, so
|
|
136
|
+
* passing it costs nothing on a table reviewing elsewhere.
|
|
137
|
+
*/
|
|
138
|
+
readonly approval: AgentApprovalPending | null;
|
|
139
|
+
/**
|
|
140
|
+
* How far the capability now running has got, or nothing.
|
|
141
|
+
*
|
|
142
|
+
* Published by the table while a long call works through its rows. It never
|
|
143
|
+
* becomes the receipt: when the turn settles this goes and the receipts say
|
|
144
|
+
* what happened.
|
|
145
|
+
*/
|
|
146
|
+
readonly progress: AgentProgress | null;
|
|
147
|
+
/** Answer the pending question and let the turn continue. */
|
|
148
|
+
readonly answer: (answer: {
|
|
149
|
+
optionId?: string;
|
|
150
|
+
text?: string;
|
|
151
|
+
}) => void;
|
|
152
|
+
/**
|
|
153
|
+
* Whether the last turn that moved the table can still be put back.
|
|
154
|
+
*
|
|
155
|
+
* Null when no turn moved it. Re-read every render, because the offer ends
|
|
156
|
+
* the moment anything else changes the view. `blockedCode` is a token the
|
|
157
|
+
* labels translate — the panel never shows a reader a code.
|
|
158
|
+
*/
|
|
159
|
+
readonly undo: {
|
|
160
|
+
readonly messageId: string;
|
|
161
|
+
readonly available: boolean;
|
|
162
|
+
readonly blockedCode?: string;
|
|
163
|
+
} | null;
|
|
164
|
+
/** Put that turn back. A no-op once the offer has expired. */
|
|
165
|
+
readonly undoTurn: () => Promise<void>;
|
|
166
|
+
/** Put one action of the last turn back, by its receipt's replay identity. */
|
|
167
|
+
readonly undoAction: (idempotencyKey: string) => Promise<void>;
|
|
168
|
+
/** What the reader said not to ask about again, each with its own name. */
|
|
169
|
+
readonly alwaysAllowed: readonly AssistantAllowance[];
|
|
170
|
+
/** Ask about one of them again from now on. */
|
|
171
|
+
readonly revokeAlwaysAllow: (capability: string) => void;
|
|
172
|
+
/** The suggestions this table can run right now, re-checked every render. */
|
|
173
|
+
readonly suggestions: readonly AssistantSuggestion$1[];
|
|
174
|
+
/** Send a suggestion's prompt as if the reader had typed it. */
|
|
175
|
+
readonly runSuggestion: (id: string) => Promise<void>;
|
|
176
|
+
readonly open: boolean;
|
|
177
|
+
readonly setOpen: (open: boolean) => void;
|
|
178
|
+
/** The last failure, cleared by the next successful turn. */
|
|
179
|
+
readonly error: string | undefined;
|
|
180
|
+
/**
|
|
181
|
+
* The machine code behind {@link error}, when a turn ended with work
|
|
182
|
+
* pending. A surface with labels turns it into a sentence for the reader;
|
|
183
|
+
* the message beside it is written for whoever is debugging the turn.
|
|
184
|
+
*/
|
|
185
|
+
readonly errorCode: string | undefined;
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Run a table assistant.
|
|
189
|
+
*
|
|
190
|
+
* A thin subscriber to the neutral controller in `@adapttable/ai/assistant`:
|
|
191
|
+
* React supplies the external-store mechanism, the live inputs and the
|
|
192
|
+
* controlled presentation state, and owns none of the lifecycle.
|
|
193
|
+
*
|
|
194
|
+
* @param options - Session, transport and presentation.
|
|
195
|
+
* @returns Everything a panel needs, and nothing about how it looks.
|
|
196
|
+
*
|
|
197
|
+
* @public
|
|
198
|
+
*/
|
|
199
|
+
declare function useTableAssistant(options: TableAssistantOptions): TableAssistantState;
|
|
200
|
+
//#endregion
|
|
201
|
+
//#region src/react.d.ts
|
|
202
|
+
type TableAgentBridge = TableAgentBridge$1<AgentApprovalPending>;
|
|
203
|
+
/**
|
|
204
|
+
* Feature-state key for the live {@link AgentSession}.
|
|
205
|
+
*
|
|
206
|
+
* @public
|
|
207
|
+
*/
|
|
208
|
+
declare const TABLE_AGENT_STATE: import("@adapttable/react/adapter").FeatureStateKey<AgentSession>;
|
|
209
|
+
/**
|
|
210
|
+
* Options for {@link tableAgent}.
|
|
211
|
+
*
|
|
212
|
+
* @public
|
|
213
|
+
*/
|
|
214
|
+
interface TableAgentOptions {
|
|
215
|
+
/** Host-supplied table identity. */
|
|
216
|
+
readonly tableId: string;
|
|
217
|
+
/** Whether host callbacks already authorize writes. */
|
|
218
|
+
readonly writePolicy?: WritePolicy;
|
|
219
|
+
/** When a write must be confirmed. */
|
|
220
|
+
readonly approval?: SharedApproval;
|
|
221
|
+
/** Whether an approved write stages or persists. */
|
|
222
|
+
readonly commit?: CommitPolicy;
|
|
223
|
+
/** Host confirmation. When set, chrome is skipped. */
|
|
224
|
+
readonly onApprove?: (subject: ApprovalSubject, signal?: AbortSignal) => Promise<ApprovalResult>;
|
|
225
|
+
/** Per-column readability, writability, and labels. */
|
|
226
|
+
readonly columns?: Readonly<Record<string, TableAgentColumnPatch>>;
|
|
227
|
+
/** Largest `rows.read` window. */
|
|
228
|
+
readonly readMax?: number;
|
|
229
|
+
/** Host callbacks for manifest and session attach. */
|
|
230
|
+
readonly bridge?: TableAgentBridge;
|
|
231
|
+
/** Host- or test-supplied observation. Live tables omit this. */
|
|
232
|
+
readonly observe?: () => AgentObservation;
|
|
233
|
+
/** Extra apply callbacks the live table does not already expose. */
|
|
234
|
+
readonly apply?: AgentApply;
|
|
235
|
+
/** Custom governed capabilities for this table. */
|
|
236
|
+
readonly capabilities?: readonly AgentCapabilityDefinition[];
|
|
237
|
+
/**
|
|
238
|
+
* This table's approval policy for individual capabilities, by key.
|
|
239
|
+
*
|
|
240
|
+
* The same shape a row or bulk action carries. An entry **replaces**
|
|
241
|
+
* {@link approval} for that one capability rather than narrowing it:
|
|
242
|
+
* `required` asks on a table that asks for nothing, and `automatic` skips the
|
|
243
|
+
* human on a table that asks for writes. Both directions are deliberate —
|
|
244
|
+
* this is the developer's own answer to "who confirms this".
|
|
245
|
+
*
|
|
246
|
+
* It is not the reader's answer. "Don't ask again" is `approval.alwaysAllow`
|
|
247
|
+
* plus the approval memory: opt-in per capability, revocable, and reset by a
|
|
248
|
+
* contract change. A capability carrying `required` here keeps asking however
|
|
249
|
+
* often the reader waves it through.
|
|
250
|
+
*
|
|
251
|
+
* Approval decides who confirms an operation, never whether the table offers
|
|
252
|
+
* it: a key the table does not wire, or one in
|
|
253
|
+
* {@link excludeCapabilities}, stays unavailable whatever this says.
|
|
254
|
+
*/
|
|
255
|
+
readonly capabilityApproval?: Readonly<Record<string, ActionAiOptions>>;
|
|
256
|
+
/**
|
|
257
|
+
* Capability keys the agent may not use on this table.
|
|
258
|
+
*
|
|
259
|
+
* One list, for built-ins and custom definitions alike. It only ever denies:
|
|
260
|
+
* a key the table does not wire stays unavailable whatever this says, and no
|
|
261
|
+
* entry here can enable a forbidden operation. The table's own controls are
|
|
262
|
+
* untouched — denying `view.setFilters` to the agent leaves a person
|
|
263
|
+
* filtering exactly as before.
|
|
264
|
+
*/
|
|
265
|
+
readonly excludeCapabilities?: readonly string[];
|
|
266
|
+
/**
|
|
267
|
+
* Offer this table's capabilities to a browser-resident agent.
|
|
268
|
+
*
|
|
269
|
+
* `true` offers everything the session permits; an object narrows the
|
|
270
|
+
* surface. It narrows only — a capability the table excludes stays
|
|
271
|
+
* unavailable, and a browser confirmation is in addition to the table's own
|
|
272
|
+
* approval rather than instead of it. Does nothing in a browser without the
|
|
273
|
+
* API, and nothing on a server.
|
|
274
|
+
*/
|
|
275
|
+
readonly webmcp?: true | {
|
|
276
|
+
readonly exposedTo?: readonly string[];
|
|
277
|
+
/**
|
|
278
|
+
* Told what was registered, and told `[]` when the registration goes.
|
|
279
|
+
*
|
|
280
|
+
* For a surface that lists the tools a browser agent can see. Nothing
|
|
281
|
+
* depends on it: a page that does not care never passes it.
|
|
282
|
+
*/
|
|
283
|
+
readonly onRegister?: (names: readonly string[]) => void;
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* Observe a live table and publish a deterministic capability manifest.
|
|
288
|
+
*
|
|
289
|
+
* Omitting this feature from `features` ships no agent bytes.
|
|
290
|
+
*
|
|
291
|
+
* @public
|
|
292
|
+
*/
|
|
293
|
+
declare function tableAgent(options: TableAgentOptions): StaticTableFeature;
|
|
294
|
+
//#endregion
|
|
295
|
+
//#region src/useSpeechInput.d.ts
|
|
296
|
+
/** How the hook is configured. @public */
|
|
297
|
+
interface UseSpeechInputOptions {
|
|
298
|
+
readonly voice?: VoiceOptions;
|
|
299
|
+
/** The table's locale, used when no language list was given. */
|
|
300
|
+
readonly locale?: string;
|
|
301
|
+
/** Where heard text goes. Always the draft, never a send. */
|
|
302
|
+
readonly setDraft: (text: string) => void;
|
|
303
|
+
/** Where a recording goes, in backend mode. */
|
|
304
|
+
readonly onClip?: (clip: SpeechClip) => void;
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Run dictation for one composer.
|
|
308
|
+
*
|
|
309
|
+
* @param options - Voice configuration and where heard text should go.
|
|
310
|
+
* @returns What the composer needs, or an unavailable handle when voice is off.
|
|
311
|
+
*
|
|
312
|
+
* @public
|
|
313
|
+
*/
|
|
314
|
+
declare function useSpeechInput(options: UseSpeechInputOptions): SpeechInputHandle;
|
|
315
|
+
//#endregion
|
|
316
|
+
export { type AssistantAnswer, type AssistantInterruption, type AssistantMessage, type AssistantQuestion, type AssistantResumeHandle, type AssistantStatus, type AssistantSuggestion, type SharedApproval, TABLE_AGENT_STATE, type TableAgentBridge, type TableAgentColumnPatch, type TableAgentOptions, type TableAssistantOptions, type TableAssistantSnapshot, type TableAssistantState, type TableAssistantStore, type UseSpeechInputOptions, tableAgent, useSpeechInput, useTableAssistant };
|
|
317
|
+
//# sourceMappingURL=index.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../src/assistant.tsx","../src/react.tsx","../src/useSpeechInput.ts"],"mappings":";;;;;;;UAmFiB;;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;;WAEzB;;;;;;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;;;KCtLS,mBAAmB,mBAAc;;;;;;cAehC,uDAAiB,gBAA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