@adapttable/ai-react 0.2.7 → 0.2.9
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 +23 -0
- package/dist/index.cjs +26 -231
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -28
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.ts +6 -28
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +28 -233
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,28 @@
|
|
|
1
1
|
# @adapttable/ai-react
|
|
2
2
|
|
|
3
|
+
## 0.2.9
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 4613ab6: `tableAgent` runs on `createTableAgentController` from `@adapttable/ai`. Its API is unchanged.
|
|
8
|
+
- Updated dependencies [4613ab6]
|
|
9
|
+
- Updated dependencies [73d62b5]
|
|
10
|
+
- Updated dependencies [8c6aeda]
|
|
11
|
+
- Updated dependencies [6bec4e8]
|
|
12
|
+
- Updated dependencies [1bce1a4]
|
|
13
|
+
- @adapttable/core@3.6.0
|
|
14
|
+
- @adapttable/ai@0.4.0
|
|
15
|
+
- @adapttable/react@1.3.6
|
|
16
|
+
|
|
17
|
+
## 0.2.8
|
|
18
|
+
|
|
19
|
+
### Patch Changes
|
|
20
|
+
|
|
21
|
+
- Updated dependencies [e5615bd]
|
|
22
|
+
- @adapttable/core@3.5.0
|
|
23
|
+
- @adapttable/react@1.3.5
|
|
24
|
+
- @adapttable/ai@0.3.2
|
|
25
|
+
|
|
3
26
|
## 0.2.7
|
|
4
27
|
|
|
5
28
|
### Patch Changes
|
package/dist/index.cjs
CHANGED
|
@@ -3,7 +3,6 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
|
3
3
|
let _adapttable_ai = require("@adapttable/ai");
|
|
4
4
|
let _adapttable_react_adapter = require("@adapttable/react/adapter");
|
|
5
5
|
let react = require("react");
|
|
6
|
-
let _adapttable_ai_context = require("@adapttable/ai/context");
|
|
7
6
|
let react_dom = require("react-dom");
|
|
8
7
|
let react_jsx_runtime = require("react/jsx-runtime");
|
|
9
8
|
let _adapttable_ai_voice = require("@adapttable/ai/voice");
|
|
@@ -129,7 +128,9 @@ function inputsOf(options, approval, alwaysAllow, viewState, progress) {
|
|
|
129
128
|
* Opt-in table feature — `@adapttable/ai-react`.
|
|
130
129
|
*
|
|
131
130
|
* `@adapttable/ai` stays React-free. This package mounts a provider that
|
|
132
|
-
*
|
|
131
|
+
* drives `@adapttable/ai`'s table agent controller from React: it keeps the
|
|
132
|
+
* controller's inputs current, re-renders on its snapshot and the table's
|
|
133
|
+
* changes, and publishes what the controller holds as feature state.
|
|
133
134
|
*/
|
|
134
135
|
/**
|
|
135
136
|
* Feature-state key for the live {@link AgentSession}.
|
|
@@ -137,11 +138,9 @@ function inputsOf(options, approval, alwaysAllow, viewState, progress) {
|
|
|
137
138
|
* @public
|
|
138
139
|
*/
|
|
139
140
|
const TABLE_AGENT_STATE = (0, _adapttable_react_adapter.featureStateKey)("table-agent");
|
|
140
|
-
/** One open approval, whichever shape the write took. */
|
|
141
141
|
function TableAgentProvider({ feature, children }) {
|
|
142
142
|
const options = feature.options;
|
|
143
143
|
const runtime = (0, _adapttable_react_adapter.useTableRuntime)();
|
|
144
|
-
const revisionCounterRef = (0, react.useRef)((0, _adapttable_ai.createRevisionCounter)());
|
|
145
144
|
const optionsRef = (0, react.useRef)(options);
|
|
146
145
|
optionsRef.current = options;
|
|
147
146
|
const runtimeRef = (0, react.useRef)(runtime);
|
|
@@ -153,252 +152,48 @@ function TableAgentProvider({ feature, children }) {
|
|
|
153
152
|
setAdmissionTick(admissionTick + 1);
|
|
154
153
|
});
|
|
155
154
|
};
|
|
156
|
-
const
|
|
157
|
-
|
|
158
|
-
const tableIdRef = (0, react.useRef)(options.tableId);
|
|
159
|
-
const registryKeyOf = (next) => `${(0, _adapttable_ai.exclusionKey)(next.excludeCapabilities)}!${JSON.stringify(next.capabilityApproval ?? {})}!${(0, _adapttable_ai.tableActionSignature)(runtime.view()?.actions)}`;
|
|
160
|
-
const registryRef = (0, react.useRef)(registryKeyOf(options));
|
|
161
|
-
const registryKey = registryKeyOf(options);
|
|
162
|
-
const sessionRef = (0, react.useRef)(null);
|
|
163
|
-
if (tableIdRef.current !== options.tableId || registryRef.current !== registryKey) {
|
|
164
|
-
tableIdRef.current = options.tableId;
|
|
165
|
-
registryRef.current = registryKey;
|
|
166
|
-
sessionRef.current = null;
|
|
167
|
-
revisionCounterRef.current = (0, _adapttable_ai.createRevisionCounter)();
|
|
168
|
-
}
|
|
169
|
-
sessionRef.current ??= (0, _adapttable_ai.bindLiveSession)({
|
|
155
|
+
const controllerRef = (0, react.useRef)(null);
|
|
156
|
+
controllerRef.current ??= (0, _adapttable_ai.createTableAgentController)({
|
|
170
157
|
options: optionsRef,
|
|
171
158
|
runtime: runtimeRef,
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
reportProgress,
|
|
159
|
+
flushAdmission: () => {
|
|
160
|
+
flushAdmission.current();
|
|
161
|
+
},
|
|
176
162
|
flush: react_dom.flushSync
|
|
177
163
|
});
|
|
178
|
-
const
|
|
179
|
-
const [revocations, setRevocations] = (0, react.useState)(0);
|
|
180
|
-
const [progress, setProgress] = (0, react.useState)(null);
|
|
181
|
-
const [transaction, setTransaction] = (0, react.useState)(null);
|
|
182
|
-
const pendingRef = (0, react.useRef)(null);
|
|
183
|
-
const transactionId = (0, react.useRef)(0);
|
|
164
|
+
const controller = controllerRef.current;
|
|
184
165
|
const neutralTable = runtime.view()?.neutralTable;
|
|
185
|
-
const
|
|
186
|
-
const
|
|
187
|
-
const stamp = (0, react.useSyncExternalStore)(subscribeToTable, readStamp, readStamp);
|
|
166
|
+
const subscribeToTable = (0, react.useCallback)((onStoreChange) => neutralTable ? controller.subscribeTable(onStoreChange) : () => void 0, [controller, neutralTable]);
|
|
167
|
+
const stamp = (0, react.useSyncExternalStore)(subscribeToTable, controller.tableStamp, controller.tableStamp);
|
|
188
168
|
(0, react.useDebugValue)(stamp);
|
|
189
|
-
const
|
|
190
|
-
const approvalMemory = (0, react.useRef)((0, _adapttable_ai.createApprovalMemory)());
|
|
191
|
-
const contractVersion = (0, react.useCallback)(() => (0, _adapttable_ai.contractFingerprint)(session.manifest(), session.catalog()), [session]);
|
|
192
|
-
const webmcp = options.webmcp;
|
|
193
|
-
const webmcpVersion = webmcp ? contractVersion() : "";
|
|
194
|
-
(0, react.useEffect)(() => {
|
|
195
|
-
if (!webmcp) return;
|
|
196
|
-
const options = webmcp === true ? {} : webmcp;
|
|
197
|
-
const registration = (0, _adapttable_ai.registerWebMcpTools)(session, {
|
|
198
|
-
...options.exposedTo ? { exposedTo: options.exposedTo } : {},
|
|
199
|
-
onWarning: (warning) => {
|
|
200
|
-
console.warn(`[adapttable] webmcp: ${warning.message}`);
|
|
201
|
-
}
|
|
202
|
-
});
|
|
203
|
-
options.onRegister?.(registration.names);
|
|
204
|
-
return () => {
|
|
205
|
-
registration.dispose();
|
|
206
|
-
options.onRegister?.([]);
|
|
207
|
-
};
|
|
208
|
-
}, [
|
|
209
|
-
session,
|
|
210
|
-
webmcp,
|
|
211
|
-
webmcpVersion
|
|
212
|
-
]);
|
|
213
|
-
waitForChrome.current = (subject, signal) => {
|
|
214
|
-
if (pendingRef.current) return Promise.reject(/* @__PURE__ */ new Error("an approval is already pending"));
|
|
215
|
-
const capability = subject.kind === "operation" ? subject.capability : void 0;
|
|
216
|
-
if ((0, _adapttable_ai.mayAlwaysAllow)({
|
|
217
|
-
capability,
|
|
218
|
-
kind: (0, _adapttable_ai.capabilityKind)(session, capability),
|
|
219
|
-
alwaysAllow: (0, _adapttable_ai.alwaysAllowFor)(optionsRef.current.approval, optionsRef.current.capabilities, capability)
|
|
220
|
-
}) && capability !== void 0 && approvalMemory.current.allows(capability, contractVersion())) return Promise.resolve(true);
|
|
221
|
-
return new Promise((resolve) => {
|
|
222
|
-
const rows = subject.kind === "rows";
|
|
223
|
-
let settled = false;
|
|
224
|
-
const entry = {
|
|
225
|
-
...rows ? {} : { capability: subject.capability },
|
|
226
|
-
proposals: rows ? (0, _adapttable_ai.displayProposals)(subject.proposals, (0, _adapttable_ai.readerResolver)(runtimeRef.current, optionsRef.current.columns)) : [],
|
|
227
|
-
perItem: rows && subject.perItem,
|
|
228
|
-
...rows ? {} : { operation: {
|
|
229
|
-
capability: subject.capability,
|
|
230
|
-
...subject.title ? { title: subject.title } : {},
|
|
231
|
-
arguments: subject.arguments
|
|
232
|
-
} },
|
|
233
|
-
resolve: (result) => {
|
|
234
|
-
if (settled) return;
|
|
235
|
-
settled = true;
|
|
236
|
-
if (pendingRef.current === entry) pendingRef.current = null;
|
|
237
|
-
setTransaction((0, _adapttable_ai.closeTransaction)(entry));
|
|
238
|
-
signal?.removeEventListener("abort", onAbort);
|
|
239
|
-
resolve(result);
|
|
240
|
-
}
|
|
241
|
-
};
|
|
242
|
-
const onAbort = () => entry.resolve(false);
|
|
243
|
-
pendingRef.current = entry;
|
|
244
|
-
transactionId.current += 1;
|
|
245
|
-
setTransaction((0, _adapttable_ai.openTransaction)(transactionId.current, entry, subject.presentation));
|
|
246
|
-
if (signal?.aborted) {
|
|
247
|
-
entry.resolve(false);
|
|
248
|
-
return;
|
|
249
|
-
}
|
|
250
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
251
|
-
});
|
|
252
|
-
};
|
|
253
|
-
(0, react.useEffect)(() => () => {
|
|
254
|
-
pendingRef.current?.resolve(false);
|
|
255
|
-
}, []);
|
|
256
|
-
const published = {
|
|
257
|
-
catalog: () => session.catalog(),
|
|
258
|
-
describe: (key) => session.describe(key),
|
|
259
|
-
execute: (key, args, expectedRevision, idempotencyKey, signal) => session.execute(key, args, expectedRevision, idempotencyKey, signal),
|
|
260
|
-
manifest: () => session.manifest()
|
|
261
|
-
};
|
|
262
|
-
const samplesRef = (0, react.useRef)({});
|
|
263
|
-
const viewStateValue = (0, react.useRef)({ read: () => (0, _adapttable_ai.viewInputsFromRuntime)(runtimeRef.current, optionsRef.current, samplesRef.current) }).current;
|
|
264
|
-
(0, react.useEffect)(() => {
|
|
265
|
-
options.bridge?.attach?.(session);
|
|
266
|
-
options.bridge?.viewInputs?.(viewStateValue.read);
|
|
267
|
-
}, [
|
|
268
|
-
options.bridge,
|
|
269
|
-
session,
|
|
270
|
-
viewStateValue
|
|
271
|
-
]);
|
|
272
|
-
const last = (0, react.useRef)("");
|
|
169
|
+
const state = (0, react.useSyncExternalStore)(controller.subscribe, controller.getState, controller.getState);
|
|
273
170
|
(0, react.useLayoutEffect)(() => {
|
|
274
|
-
|
|
275
|
-
const encoded = JSON.stringify(published);
|
|
276
|
-
if (encoded === last.current) return;
|
|
277
|
-
last.current = encoded;
|
|
278
|
-
options.bridge?.publish?.(published);
|
|
171
|
+
controller.sync();
|
|
279
172
|
});
|
|
280
|
-
const sampledKey = (0, _adapttable_ai.sampledColumns)(session).join("\0");
|
|
281
|
-
(0, react.useEffect)(() => {
|
|
282
|
-
const wanted = sampledKey === "" ? [] : sampledKey.split("\0");
|
|
283
|
-
if (wanted.length === 0) {
|
|
284
|
-
samplesRef.current = {};
|
|
285
|
-
return;
|
|
286
|
-
}
|
|
287
|
-
const controller = new AbortController();
|
|
288
|
-
(0, _adapttable_ai_context.sampleColumns)(session, wanted, controller.signal).then((values) => {
|
|
289
|
-
if (controller.signal.aborted) return;
|
|
290
|
-
samplesRef.current = values;
|
|
291
|
-
}, () => {
|
|
292
|
-
if (!controller.signal.aborted) samplesRef.current = {};
|
|
293
|
-
});
|
|
294
|
-
return () => controller.abort();
|
|
295
|
-
}, [
|
|
296
|
-
session,
|
|
297
|
-
sampledKey,
|
|
298
|
-
samplesRef
|
|
299
|
-
]);
|
|
300
|
-
const chromePending = !hostApprove && transaction !== null;
|
|
301
|
-
const approvals = options.bridge?.approvals;
|
|
302
|
-
const approvalsRef = (0, react.useRef)(approvals);
|
|
303
|
-
const announcedRef = (0, react.useRef)(null);
|
|
304
|
-
const publishedRef = (0, react.useRef)(null);
|
|
305
|
-
(0, react.useEffect)(() => {
|
|
306
|
-
const previous = approvalsRef.current;
|
|
307
|
-
if (previous !== approvals) {
|
|
308
|
-
if (announcedRef.current) previous?.(null);
|
|
309
|
-
approvalsRef.current = approvals;
|
|
310
|
-
announcedRef.current = null;
|
|
311
|
-
}
|
|
312
|
-
const next = chromePending ? transaction : null;
|
|
313
|
-
if (announcedRef.current === next) return;
|
|
314
|
-
announcedRef.current = next;
|
|
315
|
-
approvals?.(next ? publishedRef.current : null);
|
|
316
|
-
}, [
|
|
317
|
-
approvals,
|
|
318
|
-
chromePending,
|
|
319
|
-
transaction
|
|
320
|
-
]);
|
|
321
173
|
(0, react.useEffect)(() => () => {
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
}, []);
|
|
326
|
-
const decideAt = (id) => (index, approved) => {
|
|
327
|
-
setTransaction((current) => (0, _adapttable_ai.recordDecision)(current, id, index, approved));
|
|
328
|
-
};
|
|
329
|
-
(0, react.useEffect)(() => {
|
|
330
|
-
if (!transaction) return;
|
|
331
|
-
if (transaction.pending.proposals.length === 0) return;
|
|
332
|
-
if (transaction.decisions.includes("pending")) return;
|
|
333
|
-
transaction.pending.resolve((0, _adapttable_ai.settleDecisions)(transaction.decisions, "rejected"));
|
|
334
|
-
}, [transaction]);
|
|
335
|
-
const approvalValue = hostApprove || !transaction ? null : {
|
|
336
|
-
proposals: transaction.pending.proposals,
|
|
337
|
-
...transaction.pending.operation ? { operation: transaction.pending.operation } : {},
|
|
338
|
-
decisions: transaction.decisions,
|
|
339
|
-
presentation: transaction.presentation,
|
|
340
|
-
...(0, _adapttable_ai.mayAlwaysAllow)({
|
|
341
|
-
capability: transaction.pending.capability,
|
|
342
|
-
kind: (0, _adapttable_ai.capabilityKind)(session, transaction.pending.capability),
|
|
343
|
-
alwaysAllow: (0, _adapttable_ai.alwaysAllowFor)(optionsRef.current.approval, optionsRef.current.capabilities, transaction.pending.capability)
|
|
344
|
-
}) ? { alwaysAllow: () => {
|
|
345
|
-
const capability = transaction.pending.capability;
|
|
346
|
-
if (capability === void 0) return;
|
|
347
|
-
approvalMemory.current.remember(capability, contractVersion());
|
|
348
|
-
transaction.pending.resolve(true);
|
|
349
|
-
} } : {},
|
|
350
|
-
approve: () => transaction.pending.resolve(transaction.pending.perItem ? (0, _adapttable_ai.settleDecisions)(transaction.decisions, "approved") : true),
|
|
351
|
-
reject: (reason) => {
|
|
352
|
-
const stated = typeof reason === "string" ? reason.trim() : void 0;
|
|
353
|
-
if (transaction.pending.perItem) {
|
|
354
|
-
transaction.pending.resolve((0, _adapttable_ai.perItemRefusal)(transaction, stated));
|
|
355
|
-
return;
|
|
356
|
-
}
|
|
357
|
-
transaction.pending.resolve(stated ? {
|
|
358
|
-
approved: [],
|
|
359
|
-
reason: stated
|
|
360
|
-
} : false);
|
|
361
|
-
},
|
|
362
|
-
...transaction.pending.perItem ? { decideAt: decideAt(transaction.id) } : {}
|
|
363
|
-
};
|
|
364
|
-
publishedRef.current = approvalValue;
|
|
365
|
-
(0, react.useEffect)(() => {
|
|
366
|
-
(0, _adapttable_ai.assertAlwaysAllow)((0, _adapttable_ai.sharedApproval)(optionsRef.current.approval).alwaysAllow, session.catalog().map((entry) => entry.key));
|
|
367
|
-
}, [session, stamp]);
|
|
368
|
-
const alwaysAllowValue = (0, react.useMemo)(() => ({
|
|
369
|
-
capabilities: approvalMemory.current.remembered(contractVersion()),
|
|
370
|
-
revoke: (capability) => {
|
|
371
|
-
approvalMemory.current.revoke(capability);
|
|
372
|
-
setRevocations((count) => count + 1);
|
|
373
|
-
}
|
|
374
|
-
}), [
|
|
375
|
-
revocations,
|
|
376
|
-
stamp,
|
|
377
|
-
contractVersion
|
|
378
|
-
]);
|
|
379
|
-
const alwaysAllowedBridge = optionsRef.current.bridge?.alwaysAllowed;
|
|
380
|
-
(0, react.useEffect)(() => {
|
|
381
|
-
alwaysAllowedBridge?.(alwaysAllowValue);
|
|
382
|
-
}, [alwaysAllowedBridge, alwaysAllowValue]);
|
|
383
|
-
reportProgress.current = (report) => {
|
|
384
|
-
setProgress(report);
|
|
385
|
-
optionsRef.current.bridge?.progress?.(report);
|
|
386
|
-
};
|
|
174
|
+
controller.disconnect();
|
|
175
|
+
}, [controller]);
|
|
176
|
+
const session = state.session;
|
|
387
177
|
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_adapttable_react_adapter.FeatureStateScope, {
|
|
388
178
|
stateKey: TABLE_AGENT_STATE,
|
|
389
|
-
value:
|
|
179
|
+
value: {
|
|
180
|
+
catalog: () => session.catalog(),
|
|
181
|
+
describe: (key) => session.describe(key),
|
|
182
|
+
execute: (key, args, expectedRevision, idempotencyKey, signal) => session.execute(key, args, expectedRevision, idempotencyKey, signal),
|
|
183
|
+
manifest: () => session.manifest()
|
|
184
|
+
},
|
|
390
185
|
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_adapttable_react_adapter.FeatureStateScope, {
|
|
391
186
|
stateKey: _adapttable_react_adapter.AGENT_APPROVAL_STATE,
|
|
392
|
-
value:
|
|
187
|
+
value: state.approval,
|
|
393
188
|
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_adapttable_react_adapter.FeatureStateScope, {
|
|
394
189
|
stateKey: _adapttable_react_adapter.AGENT_ALWAYS_ALLOW_STATE,
|
|
395
|
-
value:
|
|
190
|
+
value: state.alwaysAllow,
|
|
396
191
|
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_adapttable_react_adapter.FeatureStateScope, {
|
|
397
192
|
stateKey: _adapttable_react_adapter.AGENT_VIEW_STATE,
|
|
398
|
-
value:
|
|
193
|
+
value: state.view,
|
|
399
194
|
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_adapttable_react_adapter.FeatureStateScope, {
|
|
400
195
|
stateKey: _adapttable_react_adapter.AGENT_PROGRESS_STATE,
|
|
401
|
-
value: progress,
|
|
196
|
+
value: state.progress,
|
|
402
197
|
children
|
|
403
198
|
})
|
|
404
199
|
})
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["useState","useFeatureState","AGENT_APPROVAL_STATE","AGENT_ALWAYS_ALLOW_STATE","AGENT_VIEW_STATE","AGENT_PROGRESS_STATE","useRef","createTableAssistant","useSyncExternalStore","useCallback","featureStateKey","useTableRuntime","useRef","createRevisionCounter","useState","exclusionKey","tableActionSignature","bindLiveSession","flushSync","useCallback","revisionToken","viewRevisionStamp","useSyncExternalStore","createApprovalMemory","contractFingerprint","registerWebMcpTools","mayAlwaysAllow","capabilityKind","alwaysAllowFor","displayProposals","readerResolver","closeTransaction","openTransaction","viewInputsFromRuntime","sampledColumns","sampleColumns","recordDecision","settleDecisions","perItemRefusal","sharedApproval","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 AssistantAudio,\n type AssistantInterruption,\n type AssistantMessage,\n type AssistantResumeHandle,\n type AssistantStatus,\n type AssistantSuggestion,\n type AssistantTransport,\n createTableAssistant,\n} from \"@adapttable/ai\";\nimport {\n AGENT_ALWAYS_ALLOW_STATE,\n AGENT_APPROVAL_STATE,\n AGENT_PROGRESS_STATE,\n AGENT_VIEW_STATE,\n type AgentAlwaysAllowState,\n type AgentApprovalPending,\n type AgentProgress,\n type AgentViewState,\n useFeatureState,\n} from \"@adapttable/react/adapter\";\nimport {\n useCallback,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\n\n// The hook's own options and state name these, so the entry that publishes\n// the hook publishes them too — a consumer typing a variable from it should\n// not have to reach into another entry point for the pieces.\nexport type {\n ApprovalPolicy,\n AssistantReceiptStatus,\n AssistantReceiptSubject,\n CommitPolicy,\n RowAddressScope,\n WritePolicy,\n} from \"@adapttable/ai\";\nexport type {\n AssistantInterruption,\n AssistantMessage,\n AssistantResumeHandle,\n AssistantStatus,\n AssistantTransport,\n};\nexport type {\n AssistantExchange,\n AssistantQuestion,\n AssistantReceipt,\n AssistantTransportReply,\n AssistantTurnStatus,\n} from \"@adapttable/ai\";\nexport type { AssistantUndoOffer } from \"@adapttable/ai\";\n\n/** How {@link useTableAssistant} is configured. @public */\nexport interface TableAssistantOptions {\n /** The live session. Changing it starts a new conversation. */\n readonly session: AgentSession | undefined;\n /**\n * Where a turn goes. Omit and the assistant stays disconnected.\n *\n * May be a fresh object every render — the controller reads the latest one\n * rather than reconnecting on its identity, so a host is not forced to\n * memoize it.\n */\n readonly transport?: AssistantTransport;\n /**\n * Changes when the transport should be re-established.\n *\n * The conversation resets on a new session, because that is a new table.\n * Swapping one transport for another — a backend for a scripted one — is\n * not visible in the object identity, so a host that does it names the\n * change here. A backend transport must never quietly become a simulated\n * one under the same key.\n */\n readonly transportKey?: string;\n /** Everything authored, filtered live against what the table offers. */\n readonly suggestions?: readonly AssistantSuggestion[];\n /** Controlled panel state. Omit for uncontrolled. */\n readonly open?: boolean;\n /** Called on every open/close request, controlled or not. */\n readonly onOpenChange?: (open: boolean) => void;\n /**\n * Whether a write from this conversation is waiting on a human.\n *\n * `execute` does not return while an approval is open, so the turn looks\n * like thinking from in here. A host that renders the approval — or wires\n * `bridge.approvals` — passes it back so the panel can say what is\n * actually happening. The turn is still in flight and still stoppable.\n */\n readonly awaitingApproval?: boolean;\n /**\n * What the reader has waved through, when the panel is mounted outside the\n * table.\n *\n * A panel inside the table reads this from feature state and needs nothing\n * here. One beside it cannot, so a host wires `bridge.alwaysAllowed` and\n * passes what it publishes — the same arrangement `bridge.approvals` and\n * `bridge.viewInputs` already have. Without it a reader can wave a\n * capability through and have no way to take it back.\n */\n readonly alwaysAllow?: AlwaysAllowedState;\n /**\n * Live view and filter data the manifest does not carry.\n *\n * Read when a turn starts and again when it settles, so per-turn undo can\n * tell what the turn moved. A function rather than a value: a fixed object\n * would report that nothing changed.\n */\n readonly contextInputs?: () => AgentContextInputs;\n /**\n * Work that outlived its connection, handed over the moment it does.\n *\n * Durable recovery starts here and ends outside this package: a host that\n * stores the handle where it survives a reload can offer a resume when the\n * reader comes back, and a host that does nothing loses the work with the\n * page.\n */\n readonly onDetach?: (handle: AssistantResumeHandle) => void;\n /** A handle kept from a previous page, to resume into this one. */\n readonly resumeHandle?: AssistantResumeHandle;\n /**\n * The transcript, when your app owns it.\n *\n * Omit it and the conversation lives in the controller. Supply it to load\n * the last conversation from your own API, append a message that arrived on\n * a socket, or keep it where it survives a reload — pass a new array and the\n * panel shows it. Pair it with `onMessagesChange`.\n */\n readonly messages?: readonly AssistantMessage[];\n /** Told whenever the transcript changes, with the whole of it. */\n readonly onMessagesChange?: (messages: readonly AssistantMessage[]) => void;\n /**\n * How much of the conversation travels with each turn.\n *\n * `\"full\"` (default) sends every earlier message, for a backend that\n * remembers nothing. A number sends that many of the most recent. `0` sends\n * none — the reader's message still travels, and a backend holding its own\n * session supplies the rest. What the reader sees is never trimmed.\n */\n readonly conversation?: \"full\" | number;\n}\n\n/** What a host renders from. @public */\nexport interface TableAssistantState {\n readonly status: AssistantStatus;\n /**\n * Whether a turn is in flight and can still be stopped.\n *\n * Separate from {@link TableAssistantState.status}: a write parked on a\n * human approval reports `awaiting-approval` but is still running, and\n * Stop still ends it.\n */\n readonly busy: boolean;\n readonly messages: readonly AssistantMessage[];\n readonly draft: string;\n readonly setDraft: (draft: string) => void;\n /** Send the draft, or the given text. Resolves when the turn settles. */\n readonly send: (text?: string) => Promise<void>;\n /**\n * Send a recording as the reader's turn — pass it as `onClip` to\n * backend-mode `useSpeechInput`. The transcript the backend returns becomes\n * the reader's message.\n */\n readonly sendClip: (clip: AssistantAudio) => Promise<void>;\n /** Abort the turn in flight. Safe to call when nothing is in flight. */\n readonly stop: () => void;\n /**\n * Rejoin work a released connection left running.\n *\n * A no-op with nothing to rejoin, which is what `resumable` says.\n */\n readonly resume: () => Promise<void>;\n /**\n * What became of the last turn, when no reply ended it.\n *\n * `\"stopped\"` is the reader's own decision; `\"detached\"` is a released\n * connection, where the work may still be running.\n */\n readonly interrupted: AssistantInterruption | undefined;\n /** The work `resume` would rejoin, or nothing. */\n readonly resumable: AssistantResumeHandle | undefined;\n /** Drop the transcript. Refuses while a turn is in flight. */\n readonly clear: () => void;\n /**\n * A write waiting on the reader, or nothing.\n *\n * Hand it to the panel as `approval` and the conversation reviews it —\n * which is where a write asked for in the conversation belongs. The panel\n * draws it only when the approval's presentation names the widget, so\n * passing it costs nothing on a table reviewing elsewhere.\n */\n readonly approval: AgentApprovalPending | null;\n /**\n * How far the capability now running has got, or nothing.\n *\n * Published by the table while a long call works through its rows. It never\n * becomes the receipt: when the turn settles this goes and the receipts say\n * what happened.\n */\n readonly progress: AgentProgress | null;\n /** Answer the pending question and let the turn continue. */\n readonly answer: (answer: { optionId?: string; text?: string }) => void;\n /**\n * Whether the last turn that moved the table can still be put back.\n *\n * Null when no turn moved it. Re-read every render, because the offer ends\n * the moment anything else changes the view. `blockedCode` is a token the\n * labels translate — the panel never shows a reader a code.\n */\n readonly undo: {\n readonly messageId: string;\n readonly available: boolean;\n readonly blockedCode?: string;\n } | null;\n /** Put that turn back. A no-op once the offer has expired. */\n readonly undoTurn: () => Promise<void>;\n /** Put one action of the last turn back, by its receipt's replay identity. */\n readonly undoAction: (idempotencyKey: string) => Promise<void>;\n /** What the reader said not to ask about again, each with its own name. */\n readonly alwaysAllowed: readonly AssistantAllowance[];\n /** Ask about one of them again from now on. */\n readonly revokeAlwaysAllow: (capability: string) => void;\n /** The suggestions this table can run right now, re-checked every render. */\n readonly suggestions: readonly AssistantSuggestion[];\n /** Send a suggestion's prompt as if the reader had typed it. */\n readonly runSuggestion: (id: string) => Promise<void>;\n readonly open: boolean;\n readonly setOpen: (open: boolean) => void;\n /** The last failure, cleared by the next successful turn. */\n readonly error: string | undefined;\n /**\n * The machine code behind {@link error}, when a turn ended with work\n * pending. A surface with labels turns it into a sentence for the reader;\n * the message beside it is written for whoever is debugging the turn.\n */\n readonly errorCode: string | undefined;\n}\n\n/**\n * Run a table assistant.\n *\n * A thin subscriber to the neutral controller in `@adapttable/ai/assistant`:\n * React supplies the external-store mechanism, the live inputs and the\n * controlled presentation state, and owns none of the lifecycle.\n *\n * @param options - Session, transport and presentation.\n * @returns Everything a panel needs, and nothing about how it looks.\n *\n * @public\n */\nexport function useTableAssistant(\n options: TableAssistantOptions\n): TableAssistantState {\n const { onOpenChange } = options;\n const [uncontrolledOpen, setUncontrolledOpen] = useState(false);\n // The live approval, so a host wires the panel with one prop rather than\n // reaching for feature state itself.\n const approval = useFeatureState(AGENT_APPROVAL_STATE);\n // What the reader has waved through, published by the binding whether or\n // not an approval is open.\n const alwaysAllow = useFeatureState(AGENT_ALWAYS_ALLOW_STATE);\n // The table's own live view, published by `tableAgent`. A host that drives\n // the panel from state of its own passes `contextInputs` and this is unused.\n const viewState = useFeatureState(AGENT_VIEW_STATE);\n // How far a running capability has got, for the same reason: a panel inside\n // the table needs no host wiring to say what the work is doing.\n const progress = useFeatureState(AGENT_PROGRESS_STATE);\n\n // Created once, inert until the mount effect connects it. Constructing a\n // store during render must not open a connection — a render can be thrown\n // away, and Strict Mode throws the first one away on purpose.\n const storeRef = useRef<ReturnType<typeof createTableAssistant> | null>(null);\n 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 sendClip: store.sendClip,\n stop: store.stop,\n resume: store.resume,\n interrupted: state.interrupted,\n resumable: state.resumable,\n clear: store.clear,\n status: state.status,\n busy: state.busy,\n approval: approval ?? null,\n progress: state.progress,\n answer: store.answer,\n undo: state.undo\n ? {\n messageId: state.undo.messageId,\n available: state.undo.available,\n ...(state.undo.blocked\n ? { blockedCode: state.undo.blocked.code }\n : {}),\n }\n : null,\n undoTurn: store.undoTurn,\n undoAction: store.undoAction,\n alwaysAllowed: state.alwaysAllowed,\n revokeAlwaysAllow: store.revokeAlwaysAllow,\n suggestions: state.suggestions,\n runSuggestion: store.runSuggestion,\n open,\n setOpen,\n error: state.error,\n errorCode: state.errorCode,\n };\n}\n\n/** The hook's options as the store's live inputs. A projection, not a decision. */\nfunction inputsOf(\n options: TableAssistantOptions,\n approval: AgentApprovalPending | null | undefined,\n alwaysAllow: AgentAlwaysAllowState | null | undefined,\n viewState: AgentViewState | null | undefined,\n progress: AgentProgress | null | undefined\n) {\n // The host's own reader wins; otherwise the table's, which is what makes\n // per-turn undo work without a host lifting page and sort into its state.\n const contextInputs =\n options.contextInputs ??\n (viewState ? () => viewState.read() as AgentContextInputs : undefined);\n return {\n session: options.session,\n transport: options.transport,\n transportKey: options.transportKey,\n suggestions: options.suggestions,\n awaitingApproval: options.awaitingApproval,\n approval: approval ?? null,\n progress: progress ?? null,\n ...(contextInputs ? { contextInputs } : {}),\n ...(options.onDetach ? { onDetach: options.onDetach } : {}),\n ...(options.messages ? { messages: options.messages } : {}),\n ...(options.onMessagesChange\n ? { onMessagesChange: options.onMessagesChange }\n : {}),\n ...(options.conversation === undefined\n ? {}\n : { conversation: options.conversation }),\n ...(options.resumeHandle ? { resumeHandle: options.resumeHandle } : {}),\n // The host's own wins, for the same reason `contextInputs` does: a panel\n // beside the table has no feature state to read.\n ...((options.alwaysAllow ?? alwaysAllow)\n ? {\n alwaysAllowed: (options.alwaysAllow ?? alwaysAllow)?.capabilities,\n onRevokeAlwaysAllow: (options.alwaysAllow ?? alwaysAllow)?.revoke,\n }\n : {}),\n };\n}\n","/**\n * Opt-in table feature — `@adapttable/ai-react`.\n *\n * `@adapttable/ai` stays React-free. This package mounts a provider that\n * observes the live table and publishes a versioned manifest.\n */\nimport {\n type AgentContextInputs,\n type AgentSession,\n alwaysAllowFor,\n type ApprovalResult,\n type ApprovalSubject,\n type ApprovalTransaction,\n assertAlwaysAllow,\n bindLiveSession,\n capabilityKind,\n closeTransaction,\n contractFingerprint,\n createApprovalMemory,\n createRevisionCounter,\n displayProposals,\n exclusionKey,\n mayAlwaysAllow,\n openTransaction,\n type PendingApproval,\n perItemRefusal,\n readerResolver,\n recordDecision,\n registerWebMcpTools,\n revisionToken,\n sampledColumns,\n settleDecisions,\n sharedApproval,\n tableActionSignature,\n type TableAgentBridge as NeutralBridge,\n type TableAgentRuntimeOptions,\n viewInputsFromRuntime,\n viewRevisionStamp,\n} from \"@adapttable/ai\";\nimport { sampleColumns } from \"@adapttable/ai/context\";\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 type FeatureProviderProps,\n featureStateKey,\n FeatureStateScope,\n type StaticTableFeature,\n useTableRuntime,\n} from \"@adapttable/react/adapter\";\nimport {\n type ReactNode,\n useCallback,\n useDebugValue,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport { flushSync } from \"react-dom\";\n\nexport type { SharedApproval, TableAgentColumnPatch } from \"@adapttable/ai\";\n\n// The bridge contract is `@adapttable/ai`'s — a manifest, a session and a\n// pending approval are what any binding publishes, none of it React. Named\n// here with this binding's own pending shape so every existing import keeps\n// working.\nexport type TableAgentBridge = NeutralBridge<AgentApprovalPending>;\n\n/**\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 * The runtime half — identity, policy, columns, the host's callbacks and\n * capabilities — is `@adapttable/ai`'s {@link TableAgentRuntimeOptions}. This\n * binding adds where it publishes updates and whether it offers the table to a\n * browser-resident agent.\n *\n * @public\n */\nexport interface TableAgentOptions extends TableAgentRuntimeOptions {\n /** Host callbacks for manifest and session attach. */\n readonly bridge?: TableAgentBridge;\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\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 ?? {})}!${tableActionSignature(runtime.view()?.actions)}`;\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 options: optionsRef,\n runtime: runtimeRef,\n revisions: revisionCounterRef.current,\n flushAdmission,\n waitForChrome,\n reportProgress,\n flush: flushSync,\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwRA,SAAgB,kBACd,SACqB;CACrB,MAAM,EAAE,iBAAiB;CACzB,MAAM,CAAC,kBAAkB,wBAAA,GAAuBA,MAAAA,SAAAA,CAAS,KAAK;CAG9D,MAAM,YAAA,GAAWC,0BAAAA,gBAAAA,CAAgBC,0BAAAA,oBAAoB;CAGrD,MAAM,eAAA,GAAcD,0BAAAA,gBAAAA,CAAgBE,0BAAAA,wBAAwB;CAG5D,MAAM,aAAA,GAAYF,0BAAAA,gBAAAA,CAAgBG,0BAAAA,gBAAgB;CAGlD,MAAM,YAAA,GAAWH,0BAAAA,gBAAAA,CAAgBI,0BAAAA,oBAAoB;CAKrD,MAAM,YAAA,GAAWC,MAAAA,OAAAA,CAAuD,IAAI;CAC5E,SAAS,aAAA,GAAYC,eAAAA,qBAAAA,CACnB,SAAS,SAAS,UAAU,aAAa,WAAW,QAAQ,CAC9D;CACA,MAAM,QAAQ,SAAS;CAKvB,CAAA,GAAA,MAAA,UAAA,OAAgB;EACd,MAAM,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,aAAa,OAAO,MAAM;EAC1B,YAAY,OAAO,KAAK;EACxB,cAAc,aAAa;GACzB,OAAO,YAAY,QAAQ;GAC3B,CAAA,GAAA,qBAAA,iBAAA,CAAiB,QAAQ;EAC3B;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["useState","useFeatureState","AGENT_APPROVAL_STATE","AGENT_ALWAYS_ALLOW_STATE","AGENT_VIEW_STATE","AGENT_PROGRESS_STATE","useRef","createTableAssistant","useSyncExternalStore","useCallback","featureStateKey","useTableRuntime","useRef","useState","createTableAgentController","flushSync","useCallback","useSyncExternalStore","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 AssistantAudio,\n type AssistantInterruption,\n type AssistantMessage,\n type AssistantResumeHandle,\n type AssistantStatus,\n type AssistantSuggestion,\n type AssistantTransport,\n createTableAssistant,\n} from \"@adapttable/ai\";\nimport {\n AGENT_ALWAYS_ALLOW_STATE,\n AGENT_APPROVAL_STATE,\n AGENT_PROGRESS_STATE,\n AGENT_VIEW_STATE,\n type AgentAlwaysAllowState,\n type AgentApprovalPending,\n type AgentProgress,\n type AgentViewState,\n useFeatureState,\n} from \"@adapttable/react/adapter\";\nimport {\n useCallback,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\n\n// The hook's own options and state name these, so the entry that publishes\n// the hook publishes them too — a consumer typing a variable from it should\n// not have to reach into another entry point for the pieces.\nexport type {\n ApprovalPolicy,\n AssistantReceiptStatus,\n AssistantReceiptSubject,\n CommitPolicy,\n RowAddressScope,\n WritePolicy,\n} from \"@adapttable/ai\";\nexport type {\n AssistantInterruption,\n AssistantMessage,\n AssistantResumeHandle,\n AssistantStatus,\n AssistantTransport,\n};\nexport type {\n AssistantExchange,\n AssistantQuestion,\n AssistantReceipt,\n AssistantTransportReply,\n AssistantTurnStatus,\n} from \"@adapttable/ai\";\nexport type { AssistantUndoOffer } from \"@adapttable/ai\";\n\n/** How {@link useTableAssistant} is configured. @public */\nexport interface TableAssistantOptions {\n /** The live session. Changing it starts a new conversation. */\n readonly session: AgentSession | undefined;\n /**\n * Where a turn goes. Omit and the assistant stays disconnected.\n *\n * May be a fresh object every render — the controller reads the latest one\n * rather than reconnecting on its identity, so a host is not forced to\n * memoize it.\n */\n readonly transport?: AssistantTransport;\n /**\n * Changes when the transport should be re-established.\n *\n * The conversation resets on a new session, because that is a new table.\n * Swapping one transport for another — a backend for a scripted one — is\n * not visible in the object identity, so a host that does it names the\n * change here. A backend transport must never quietly become a simulated\n * one under the same key.\n */\n readonly transportKey?: string;\n /** Everything authored, filtered live against what the table offers. */\n readonly suggestions?: readonly AssistantSuggestion[];\n /** Controlled panel state. Omit for uncontrolled. */\n readonly open?: boolean;\n /** Called on every open/close request, controlled or not. */\n readonly onOpenChange?: (open: boolean) => void;\n /**\n * Whether a write from this conversation is waiting on a human.\n *\n * `execute` does not return while an approval is open, so the turn looks\n * like thinking from in here. A host that renders the approval — or wires\n * `bridge.approvals` — passes it back so the panel can say what is\n * actually happening. The turn is still in flight and still stoppable.\n */\n readonly awaitingApproval?: boolean;\n /**\n * What the reader has waved through, when the panel is mounted outside the\n * table.\n *\n * A panel inside the table reads this from feature state and needs nothing\n * here. One beside it cannot, so a host wires `bridge.alwaysAllowed` and\n * passes what it publishes — the same arrangement `bridge.approvals` and\n * `bridge.viewInputs` already have. Without it a reader can wave a\n * capability through and have no way to take it back.\n */\n readonly alwaysAllow?: AlwaysAllowedState;\n /**\n * Live view and filter data the manifest does not carry.\n *\n * Read when a turn starts and again when it settles, so per-turn undo can\n * tell what the turn moved. A function rather than a value: a fixed object\n * would report that nothing changed.\n */\n readonly contextInputs?: () => AgentContextInputs;\n /**\n * Work that outlived its connection, handed over the moment it does.\n *\n * Durable recovery starts here and ends outside this package: a host that\n * stores the handle where it survives a reload can offer a resume when the\n * reader comes back, and a host that does nothing loses the work with the\n * page.\n */\n readonly onDetach?: (handle: AssistantResumeHandle) => void;\n /** A handle kept from a previous page, to resume into this one. */\n readonly resumeHandle?: AssistantResumeHandle;\n /**\n * The transcript, when your app owns it.\n *\n * Omit it and the conversation lives in the controller. Supply it to load\n * the last conversation from your own API, append a message that arrived on\n * a socket, or keep it where it survives a reload — pass a new array and the\n * panel shows it. Pair it with `onMessagesChange`.\n */\n readonly messages?: readonly AssistantMessage[];\n /** Told whenever the transcript changes, with the whole of it. */\n readonly onMessagesChange?: (messages: readonly AssistantMessage[]) => void;\n /**\n * How much of the conversation travels with each turn.\n *\n * `\"full\"` (default) sends every earlier message, for a backend that\n * remembers nothing. A number sends that many of the most recent. `0` sends\n * none — the reader's message still travels, and a backend holding its own\n * session supplies the rest. What the reader sees is never trimmed.\n */\n readonly conversation?: \"full\" | number;\n}\n\n/** What a host renders from. @public */\nexport interface TableAssistantState {\n readonly status: AssistantStatus;\n /**\n * Whether a turn is in flight and can still be stopped.\n *\n * Separate from {@link TableAssistantState.status}: a write parked on a\n * human approval reports `awaiting-approval` but is still running, and\n * Stop still ends it.\n */\n readonly busy: boolean;\n readonly messages: readonly AssistantMessage[];\n readonly draft: string;\n readonly setDraft: (draft: string) => void;\n /** Send the draft, or the given text. Resolves when the turn settles. */\n readonly send: (text?: string) => Promise<void>;\n /**\n * Send a recording as the reader's turn — pass it as `onClip` to\n * backend-mode `useSpeechInput`. The transcript the backend returns becomes\n * the reader's message.\n */\n readonly sendClip: (clip: AssistantAudio) => Promise<void>;\n /** Abort the turn in flight. Safe to call when nothing is in flight. */\n readonly stop: () => void;\n /**\n * Rejoin work a released connection left running.\n *\n * A no-op with nothing to rejoin, which is what `resumable` says.\n */\n readonly resume: () => Promise<void>;\n /**\n * What became of the last turn, when no reply ended it.\n *\n * `\"stopped\"` is the reader's own decision; `\"detached\"` is a released\n * connection, where the work may still be running.\n */\n readonly interrupted: AssistantInterruption | undefined;\n /** The work `resume` would rejoin, or nothing. */\n readonly resumable: AssistantResumeHandle | undefined;\n /** Drop the transcript. Refuses while a turn is in flight. */\n readonly clear: () => void;\n /**\n * A write waiting on the reader, or nothing.\n *\n * Hand it to the panel as `approval` and the conversation reviews it —\n * which is where a write asked for in the conversation belongs. The panel\n * draws it only when the approval's presentation names the widget, so\n * passing it costs nothing on a table reviewing elsewhere.\n */\n readonly approval: AgentApprovalPending | null;\n /**\n * How far the capability now running has got, or nothing.\n *\n * Published by the table while a long call works through its rows. It never\n * becomes the receipt: when the turn settles this goes and the receipts say\n * what happened.\n */\n readonly progress: AgentProgress | null;\n /** Answer the pending question and let the turn continue. */\n readonly answer: (answer: { optionId?: string; text?: string }) => void;\n /**\n * Whether the last turn that moved the table can still be put back.\n *\n * Null when no turn moved it. Re-read every render, because the offer ends\n * the moment anything else changes the view. `blockedCode` is a token the\n * labels translate — the panel never shows a reader a code.\n */\n readonly undo: {\n readonly messageId: string;\n readonly available: boolean;\n readonly blockedCode?: string;\n } | null;\n /** Put that turn back. A no-op once the offer has expired. */\n readonly undoTurn: () => Promise<void>;\n /** Put one action of the last turn back, by its receipt's replay identity. */\n readonly undoAction: (idempotencyKey: string) => Promise<void>;\n /** What the reader said not to ask about again, each with its own name. */\n readonly alwaysAllowed: readonly AssistantAllowance[];\n /** Ask about one of them again from now on. */\n readonly revokeAlwaysAllow: (capability: string) => void;\n /** The suggestions this table can run right now, re-checked every render. */\n readonly suggestions: readonly AssistantSuggestion[];\n /** Send a suggestion's prompt as if the reader had typed it. */\n readonly runSuggestion: (id: string) => Promise<void>;\n readonly open: boolean;\n readonly setOpen: (open: boolean) => void;\n /** The last failure, cleared by the next successful turn. */\n readonly error: string | undefined;\n /**\n * The machine code behind {@link error}, when a turn ended with work\n * pending. A surface with labels turns it into a sentence for the reader;\n * the message beside it is written for whoever is debugging the turn.\n */\n readonly errorCode: string | undefined;\n}\n\n/**\n * Run a table assistant.\n *\n * A thin subscriber to the neutral controller in `@adapttable/ai/assistant`:\n * React supplies the external-store mechanism, the live inputs and the\n * controlled presentation state, and owns none of the lifecycle.\n *\n * @param options - Session, transport and presentation.\n * @returns Everything a panel needs, and nothing about how it looks.\n *\n * @public\n */\nexport function useTableAssistant(\n options: TableAssistantOptions\n): TableAssistantState {\n const { onOpenChange } = options;\n const [uncontrolledOpen, setUncontrolledOpen] = useState(false);\n // The live approval, so a host wires the panel with one prop rather than\n // reaching for feature state itself.\n const approval = useFeatureState(AGENT_APPROVAL_STATE);\n // What the reader has waved through, published by the binding whether or\n // not an approval is open.\n const alwaysAllow = useFeatureState(AGENT_ALWAYS_ALLOW_STATE);\n // The table's own live view, published by `tableAgent`. A host that drives\n // the panel from state of its own passes `contextInputs` and this is unused.\n const viewState = useFeatureState(AGENT_VIEW_STATE);\n // How far a running capability has got, for the same reason: a panel inside\n // the table needs no host wiring to say what the work is doing.\n const progress = useFeatureState(AGENT_PROGRESS_STATE);\n\n // Created once, inert until the mount effect connects it. Constructing a\n // store during render must not open a connection — a render can be thrown\n // away, and Strict Mode throws the first one away on purpose.\n const storeRef = useRef<ReturnType<typeof createTableAssistant> | null>(null);\n 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 sendClip: store.sendClip,\n stop: store.stop,\n resume: store.resume,\n interrupted: state.interrupted,\n resumable: state.resumable,\n clear: store.clear,\n status: state.status,\n busy: state.busy,\n approval: approval ?? null,\n progress: state.progress,\n answer: store.answer,\n undo: state.undo\n ? {\n messageId: state.undo.messageId,\n available: state.undo.available,\n ...(state.undo.blocked\n ? { blockedCode: state.undo.blocked.code }\n : {}),\n }\n : null,\n undoTurn: store.undoTurn,\n undoAction: store.undoAction,\n alwaysAllowed: state.alwaysAllowed,\n revokeAlwaysAllow: store.revokeAlwaysAllow,\n suggestions: state.suggestions,\n runSuggestion: store.runSuggestion,\n open,\n setOpen,\n error: state.error,\n errorCode: state.errorCode,\n };\n}\n\n/** The hook's options as the store's live inputs. A projection, not a decision. */\nfunction inputsOf(\n options: TableAssistantOptions,\n approval: AgentApprovalPending | null | undefined,\n alwaysAllow: AgentAlwaysAllowState | null | undefined,\n viewState: AgentViewState | null | undefined,\n progress: AgentProgress | null | undefined\n) {\n // The host's own reader wins; otherwise the table's, which is what makes\n // per-turn undo work without a host lifting page and sort into its state.\n const contextInputs =\n options.contextInputs ??\n (viewState ? () => viewState.read() as AgentContextInputs : undefined);\n return {\n session: options.session,\n transport: options.transport,\n transportKey: options.transportKey,\n suggestions: options.suggestions,\n awaitingApproval: options.awaitingApproval,\n approval: approval ?? null,\n progress: progress ?? null,\n ...(contextInputs ? { contextInputs } : {}),\n ...(options.onDetach ? { onDetach: options.onDetach } : {}),\n ...(options.messages ? { messages: options.messages } : {}),\n ...(options.onMessagesChange\n ? { onMessagesChange: options.onMessagesChange }\n : {}),\n ...(options.conversation === undefined\n ? {}\n : { conversation: options.conversation }),\n ...(options.resumeHandle ? { resumeHandle: options.resumeHandle } : {}),\n // The host's own wins, for the same reason `contextInputs` does: a panel\n // beside the table has no feature state to read.\n ...((options.alwaysAllow ?? alwaysAllow)\n ? {\n alwaysAllowed: (options.alwaysAllow ?? alwaysAllow)?.capabilities,\n onRevokeAlwaysAllow: (options.alwaysAllow ?? alwaysAllow)?.revoke,\n }\n : {}),\n };\n}\n","/**\n * Opt-in table feature — `@adapttable/ai-react`.\n *\n * `@adapttable/ai` stays React-free. This package mounts a provider that\n * drives `@adapttable/ai`'s table agent controller from React: it keeps the\n * controller's inputs current, re-renders on its snapshot and the table's\n * changes, and publishes what the controller holds as feature state.\n */\nimport {\n type AgentSession,\n createTableAgentController,\n type TableAgentBridge as NeutralBridge,\n type TableAgentController,\n type TableAgentControllerOptions,\n} from \"@adapttable/ai\";\nimport {\n AGENT_ALWAYS_ALLOW_STATE,\n AGENT_APPROVAL_STATE,\n AGENT_PROGRESS_STATE,\n AGENT_VIEW_STATE,\n type AgentApprovalPending,\n type FeatureProviderProps,\n featureStateKey,\n FeatureStateScope,\n type StaticTableFeature,\n useTableRuntime,\n} from \"@adapttable/react/adapter\";\nimport {\n type ReactNode,\n useCallback,\n useDebugValue,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport { flushSync } from \"react-dom\";\n\nexport type { SharedApproval, TableAgentColumnPatch } from \"@adapttable/ai\";\n\n// The bridge contract is `@adapttable/ai`'s — a manifest, a session and a\n// pending approval are what any binding publishes, none of it React. Named\n// here with this binding's own pending shape so every existing import keeps\n// working.\nexport type TableAgentBridge = NeutralBridge<AgentApprovalPending>;\n\n/**\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 * The same options `@adapttable/ai`'s table agent controller takes: the\n * runtime half — identity, policy, columns, the host's callbacks and\n * capabilities — plus where updates are published and whether the table is\n * offered to a browser-resident agent.\n *\n * @public\n */\nexport type TableAgentOptions = TableAgentControllerOptions;\n\ninterface TableAgentFeature extends StaticTableFeature {\n readonly options: TableAgentOptions;\n}\n\nfunction TableAgentProvider({\n feature,\n children,\n}: Readonly<FeatureProviderProps>): ReactNode {\n const options = (feature as TableAgentFeature).options;\n const runtime = useTableRuntime();\n const optionsRef = useRef(options);\n optionsRef.current = options;\n const runtimeRef = useRef(runtime);\n runtimeRef.current = runtime;\n // A concrete provider update, rather than an empty `flushSync`, makes React\n // finish controlled-state work already queued by the reader before the\n // session takes its admission snapshot.\n const [admissionTick, setAdmissionTick] = useState(0);\n const flushAdmission = useRef<() => void>(() => undefined);\n flushAdmission.current = () => {\n flushSync(() => {\n setAdmissionTick(admissionTick + 1);\n });\n };\n\n // Built once and never during a render that is thrown away twice: the\n // controller opens nothing until `sync`, which only an effect calls.\n const controllerRef = useRef<TableAgentController | null>(null);\n controllerRef.current ??= createTableAgentController({\n options: optionsRef,\n runtime: runtimeRef,\n flushAdmission: () => {\n flushAdmission.current();\n },\n flush: flushSync,\n });\n const controller = controllerRef.current;\n\n // The table as a store: subscribe where there is one to subscribe to, and\n // read the stamp on every render either way. React re-reads the stamp after\n // it attaches, so a table that moved between the render and the\n // subscription is caught rather than missed. The value is not rendered;\n // re-rendering is the point, because that republishes the manifest.\n const neutralTable = runtime.view()?.neutralTable;\n // The controller subscribes to the table current at the call, so a\n // replaced table is a new subscription.\n const subscribeToTable = useCallback(\n (onStoreChange: () => void) =>\n neutralTable ? controller.subscribeTable(onStoreChange) : () => undefined,\n [controller, neutralTable]\n );\n const stamp = useSyncExternalStore(\n subscribeToTable,\n controller.tableStamp,\n controller.tableStamp\n );\n useDebugValue(stamp);\n\n const state = useSyncExternalStore(\n controller.subscribe,\n controller.getState,\n controller.getState\n );\n\n // Every commit: the controller decides what changed and tells only those\n // who need telling. A layout effect, so a host reading the manifest in its\n // own effects already has this render's.\n useLayoutEffect(() => {\n controller.sync();\n });\n\n // Going away is a close. Strict Mode's setup/cleanup/setup lands here too:\n // the cleanup releases everything, and the next sync sets it up again.\n useEffect(\n () => () => {\n controller.disconnect();\n },\n [controller]\n );\n\n // A new value every render on purpose. The table publishes its runtime\n // while its children render, after this provider has, so a surface below\n // learns what the session now offers only by re-rendering with it — and it\n // re-renders because the value it holds is a different one.\n const session = state.session;\n const published: AgentSession = {\n catalog: () => session.catalog(),\n describe: (key) => session.describe(key),\n execute: (key, args, expectedRevision, idempotencyKey, signal) =>\n session.execute(key, args, expectedRevision, idempotencyKey, signal),\n manifest: () => session.manifest(),\n };\n\n return (\n <FeatureStateScope stateKey={TABLE_AGENT_STATE} value={published}>\n <FeatureStateScope stateKey={AGENT_APPROVAL_STATE} value={state.approval}>\n <FeatureStateScope\n stateKey={AGENT_ALWAYS_ALLOW_STATE}\n value={state.alwaysAllow}\n >\n <FeatureStateScope stateKey={AGENT_VIEW_STATE} value={state.view}>\n <FeatureStateScope\n stateKey={AGENT_PROGRESS_STATE}\n value={state.progress}\n >\n {children}\n </FeatureStateScope>\n </FeatureStateScope>\n </FeatureStateScope>\n </FeatureStateScope>\n </FeatureStateScope>\n );\n}\n\n/**\n * Observe a live table and publish a deterministic capability manifest.\n *\n * Omitting this feature from `features` ships no agent bytes.\n *\n * @public\n */\nexport function tableAgent(options: TableAgentOptions): StaticTableFeature {\n const feature: TableAgentFeature = {\n id: \"table-agent\",\n options,\n provider: { Provider: TableAgentProvider },\n };\n return feature;\n}\n","/**\n * Dictation, as a React hook — `@adapttable/ai-react`.\n *\n * Thin on purpose. The controller in `@adapttable/ai/voice` owns the browser\n * APIs, the permission states and the language choice; this subscribes to it,\n * keeps it alive for the life of the composer, and writes what it hears\n * through the caller's `setDraft` — which is the one channel voice is allowed\n * to use, so a spoken sentence becomes a draft the reader can see and fix\n * rather than a request the table has already acted on.\n *\n * It lives here rather than in `@adapttable/react` because it imports\n * `@adapttable/ai`, and that package must stay out of the base graph. The\n * chrome takes `SpeechInputHandle` — the structural shape this returns —\n * from `@adapttable/react/adapter`, which declares it without importing\n * anything.\n */\n\"use client\";\n\nimport {\n createSpeechInput,\n readRememberedLanguage,\n rememberLanguage,\n type SpeechClip,\n type SpeechInput,\n type SpeechState,\n type VoiceOptions,\n} from \"@adapttable/ai/voice\";\nimport type { SpeechInputHandle } from \"@adapttable/react/adapter\";\nimport { 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwRA,SAAgB,kBACd,SACqB;CACrB,MAAM,EAAE,iBAAiB;CACzB,MAAM,CAAC,kBAAkB,wBAAA,GAAuBA,MAAAA,SAAAA,CAAS,KAAK;CAG9D,MAAM,YAAA,GAAWC,0BAAAA,gBAAAA,CAAgBC,0BAAAA,oBAAoB;CAGrD,MAAM,eAAA,GAAcD,0BAAAA,gBAAAA,CAAgBE,0BAAAA,wBAAwB;CAG5D,MAAM,aAAA,GAAYF,0BAAAA,gBAAAA,CAAgBG,0BAAAA,gBAAgB;CAGlD,MAAM,YAAA,GAAWH,0BAAAA,gBAAAA,CAAgBI,0BAAAA,oBAAoB;CAKrD,MAAM,YAAA,GAAWC,MAAAA,OAAAA,CAAuD,IAAI;CAC5E,SAAS,aAAA,G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,SAAS;CAEvB,CAAA,GAAA,MAAA,UAAA,aACc;EACV,OAAO,QAAQ;EAGf,SAAS,UAAU;CACrB,GACA,CAAC,KAAK,CACR;CAEA,MAAM,SAAA,GAAQC,MAAAA,qBAAAA,EACX,aAAa,OAAO,UAAU,QAAQ,YAAY,KAAA,UAC7C,OAAO,SAAS,KAAK,YACrB,IACR;CAEA,OAAO;EAEL,WAAW,QAAQ,SAAS,OAAO,UAAU,CAAC;EAC9C;EACA;EACA,aAAa,OAAO,MAAM;EAC1B,YAAY,OAAO,KAAK;EACxB,cAAc,aAAa;GACzB,OAAO,YAAY,QAAQ;GAC3B,CAAA,GAAA,qBAAA,iBAAA,CAAiB,QAAQ;EAC3B;CACF;AACF"}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
import { AgentContextInputs, AgentSession, AlwaysAllowedState, AssistantAllowance, AssistantAnswer, AssistantAudio, AssistantInterruption, AssistantInterruption as AssistantInterruption$1, AssistantMessage, AssistantQuestion, AssistantResumeHandle, AssistantResumeHandle as AssistantResumeHandle$1, AssistantStatus, AssistantSuggestion, AssistantSuggestion as AssistantSuggestion$1, AssistantTransport, SharedApproval, TableAgentBridge as TableAgentBridge$1, TableAgentColumnPatch,
|
|
2
|
+
import { AgentContextInputs, AgentSession, AlwaysAllowedState, AssistantAllowance, AssistantAnswer, AssistantAudio, AssistantInterruption, AssistantInterruption as AssistantInterruption$1, AssistantMessage, AssistantQuestion, AssistantResumeHandle, AssistantResumeHandle as AssistantResumeHandle$1, AssistantStatus, AssistantSuggestion, AssistantSuggestion as AssistantSuggestion$1, AssistantTransport, SharedApproval, TableAgentBridge as TableAgentBridge$1, TableAgentColumnPatch, TableAgentControllerOptions, TableAssistantSnapshot, TableAssistantStore } from "@adapttable/ai";
|
|
3
3
|
import { AgentApprovalPending, AgentProgress, SpeechInputHandle, StaticTableFeature } from "@adapttable/react/adapter";
|
|
4
4
|
import { SpeechClip, VoiceOptions } from "@adapttable/ai/voice";
|
|
5
5
|
//#region src/assistant.d.ts
|
|
@@ -214,36 +214,14 @@ declare const TABLE_AGENT_STATE: import("@adapttable/core/binding").FeatureState
|
|
|
214
214
|
/**
|
|
215
215
|
* Options for {@link tableAgent}.
|
|
216
216
|
*
|
|
217
|
-
* The
|
|
218
|
-
*
|
|
219
|
-
*
|
|
220
|
-
* browser-resident agent.
|
|
217
|
+
* The same options `@adapttable/ai`'s table agent controller takes: the
|
|
218
|
+
* runtime half — identity, policy, columns, the host's callbacks and
|
|
219
|
+
* capabilities — plus where updates are published and whether the table is
|
|
220
|
+
* offered to a browser-resident agent.
|
|
221
221
|
*
|
|
222
222
|
* @public
|
|
223
223
|
*/
|
|
224
|
-
|
|
225
|
-
/** Host callbacks for manifest and session attach. */
|
|
226
|
-
readonly bridge?: TableAgentBridge;
|
|
227
|
-
/**
|
|
228
|
-
* Offer this table's capabilities to a browser-resident agent.
|
|
229
|
-
*
|
|
230
|
-
* `true` offers everything the session permits; an object narrows the
|
|
231
|
-
* surface. It narrows only — a capability the table excludes stays
|
|
232
|
-
* unavailable, and a browser confirmation is in addition to the table's own
|
|
233
|
-
* approval rather than instead of it. Does nothing in a browser without the
|
|
234
|
-
* API, and nothing on a server.
|
|
235
|
-
*/
|
|
236
|
-
readonly webmcp?: true | {
|
|
237
|
-
readonly exposedTo?: readonly string[];
|
|
238
|
-
/**
|
|
239
|
-
* Told what was registered, and told `[]` when the registration goes.
|
|
240
|
-
*
|
|
241
|
-
* For a surface that lists the tools a browser agent can see. Nothing
|
|
242
|
-
* depends on it: a page that does not care never passes it.
|
|
243
|
-
*/
|
|
244
|
-
readonly onRegister?: (names: readonly string[]) => void;
|
|
245
|
-
};
|
|
246
|
-
}
|
|
224
|
+
type TableAgentOptions = TableAgentControllerOptions;
|
|
247
225
|
/**
|
|
248
226
|
* Observe a live table and publish a deterministic capability manifest.
|
|
249
227
|
*
|
package/dist/index.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"sources":["../src/assistant.tsx","../src/react.tsx","../src/useSpeechInput.ts"],"mappings":";;;;;;UAoFiB;;WAEN,SAAS;;;;;;;;WAQT,YAAY;;;;;;;;;;WAUZ;;WAEA,uBAAuB;;WAEvB;;WAEA,gBAAgB;;;;;;;;;WAShB;;;;;;;;;;;WAWA,cAAc;;;;;;;;WAQd,sBAAsB;;;;;;;;;WAStB,YAAY,QAAQ;;WAEpB,eAAe;;;;;;;;;WASf,oBAAoB;;WAEpB,oBAAoB,mBAAmB;;;;;;;;;WASvC;;;UAIM;WACN,QAAQ;;;;;;;;WAQR;WACA,mBAAmB;WACnB;WACA,WAAW;;WAEX,OAAO,kBAAkB;;;;;;WAMzB,WAAW,MAAM,mBAAmB;;WAEpC;;;;;;WAMA,cAAc;;;;;;;WAOd,aAAa;;WAEb,WAAW;;WAEX;;;;;;;;;WASA,UAAU;;;;;;;;WAQV,UAAU;;WAEV,SAAS;IAAU;IAAmB;;;;;;;;;WAQtC;aACE;aACA;aACA;;;WAGF,gBAAgB;;WAEhB,aAAa,2BAA2B;;WAExC,wBAAwB;;WAExB,oBAAoB;;WAEpB,sBAAsB;;WAEtB,gBAAgB,eAAe;WAC/B;WACA,UAAU;;WAEV;;;;;;WAMA;;;;;;;;;;;;;;iBAeK,kBACd,SAAS,wBACR;;;
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../src/assistant.tsx","../src/react.tsx","../src/useSpeechInput.ts"],"mappings":";;;;;;UAoFiB;;WAEN,SAAS;;;;;;;;WAQT,YAAY;;;;;;;;;;WAUZ;;WAEA,uBAAuB;;WAEvB;;WAEA,gBAAgB;;;;;;;;;WAShB;;;;;;;;;;;WAWA,cAAc;;;;;;;;WAQd,sBAAsB;;;;;;;;;WAStB,YAAY,QAAQ;;WAEpB,eAAe;;;;;;;;;WASf,oBAAoB;;WAEpB,oBAAoB,mBAAmB;;;;;;;;;WASvC;;;UAIM;WACN,QAAQ;;;;;;;;WAQR;WACA,mBAAmB;WACnB;WACA,WAAW;;WAEX,OAAO,kBAAkB;;;;;;WAMzB,WAAW,MAAM,mBAAmB;;WAEpC;;;;;;WAMA,cAAc;;;;;;;WAOd,aAAa;;WAEb,WAAW;;WAEX;;;;;;;;;WASA,UAAU;;;;;;;;WAQV,UAAU;;WAEV,SAAS;IAAU;IAAmB;;;;;;;;;WAQtC;aACE;aACA;aACA;;;WAGF,gBAAgB;;WAEhB,aAAa,2BAA2B;;WAExC,wBAAwB;;WAExB,oBAAoB;;WAEpB,sBAAsB;;WAEtB,gBAAgB,eAAe;WAC/B;WACA,UAAU;;WAEV;;;;;;WAMA;;;;;;;;;;;;;;iBAeK,kBACd,SAAS,wBACR;;;KC7OS,mBAAmB,mBAAc;;;;;;cAOhC,sDAAiB,gBAAA;;;;;;;;;;;KAYlB,oBAAoB;;;;;;;;iBA2HhB,WAAW,SAAS,oBAAoB;;;;UC5JvC;WACN,QAAQ;;WAER;;WAEA,WAAW;;WAEX,UAAU,MAAM;;;;;;;;;;iBAaX,eACd,SAAS,wBACR"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
import { AgentContextInputs, AgentSession, AlwaysAllowedState, AssistantAllowance, AssistantAnswer, AssistantAudio, AssistantInterruption, AssistantInterruption as AssistantInterruption$1, AssistantMessage, AssistantQuestion, AssistantResumeHandle, AssistantResumeHandle as AssistantResumeHandle$1, AssistantStatus, AssistantSuggestion, AssistantSuggestion as AssistantSuggestion$1, AssistantTransport, SharedApproval, TableAgentBridge as TableAgentBridge$1, TableAgentColumnPatch,
|
|
2
|
+
import { AgentContextInputs, AgentSession, AlwaysAllowedState, AssistantAllowance, AssistantAnswer, AssistantAudio, AssistantInterruption, AssistantInterruption as AssistantInterruption$1, AssistantMessage, AssistantQuestion, AssistantResumeHandle, AssistantResumeHandle as AssistantResumeHandle$1, AssistantStatus, AssistantSuggestion, AssistantSuggestion as AssistantSuggestion$1, AssistantTransport, SharedApproval, TableAgentBridge as TableAgentBridge$1, TableAgentColumnPatch, TableAgentControllerOptions, TableAssistantSnapshot, TableAssistantStore } from "@adapttable/ai";
|
|
3
3
|
import { AgentApprovalPending, AgentProgress, SpeechInputHandle, StaticTableFeature } from "@adapttable/react/adapter";
|
|
4
4
|
import { SpeechClip, VoiceOptions } from "@adapttable/ai/voice";
|
|
5
5
|
//#region src/assistant.d.ts
|
|
@@ -214,36 +214,14 @@ declare const TABLE_AGENT_STATE: import("@adapttable/core/binding").FeatureState
|
|
|
214
214
|
/**
|
|
215
215
|
* Options for {@link tableAgent}.
|
|
216
216
|
*
|
|
217
|
-
* The
|
|
218
|
-
*
|
|
219
|
-
*
|
|
220
|
-
* browser-resident agent.
|
|
217
|
+
* The same options `@adapttable/ai`'s table agent controller takes: the
|
|
218
|
+
* runtime half — identity, policy, columns, the host's callbacks and
|
|
219
|
+
* capabilities — plus where updates are published and whether the table is
|
|
220
|
+
* offered to a browser-resident agent.
|
|
221
221
|
*
|
|
222
222
|
* @public
|
|
223
223
|
*/
|
|
224
|
-
|
|
225
|
-
/** Host callbacks for manifest and session attach. */
|
|
226
|
-
readonly bridge?: TableAgentBridge;
|
|
227
|
-
/**
|
|
228
|
-
* Offer this table's capabilities to a browser-resident agent.
|
|
229
|
-
*
|
|
230
|
-
* `true` offers everything the session permits; an object narrows the
|
|
231
|
-
* surface. It narrows only — a capability the table excludes stays
|
|
232
|
-
* unavailable, and a browser confirmation is in addition to the table's own
|
|
233
|
-
* approval rather than instead of it. Does nothing in a browser without the
|
|
234
|
-
* API, and nothing on a server.
|
|
235
|
-
*/
|
|
236
|
-
readonly webmcp?: true | {
|
|
237
|
-
readonly exposedTo?: readonly string[];
|
|
238
|
-
/**
|
|
239
|
-
* Told what was registered, and told `[]` when the registration goes.
|
|
240
|
-
*
|
|
241
|
-
* For a surface that lists the tools a browser agent can see. Nothing
|
|
242
|
-
* depends on it: a page that does not care never passes it.
|
|
243
|
-
*/
|
|
244
|
-
readonly onRegister?: (names: readonly string[]) => void;
|
|
245
|
-
};
|
|
246
|
-
}
|
|
224
|
+
type TableAgentOptions = TableAgentControllerOptions;
|
|
247
225
|
/**
|
|
248
226
|
* Observe a live table and publish a deterministic capability manifest.
|
|
249
227
|
*
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/assistant.tsx","../src/react.tsx","../src/useSpeechInput.ts"],"mappings":";;;;;;UAoFiB;;WAEN,SAAS;;;;;;;;WAQT,YAAY;;;;;;;;;;WAUZ;;WAEA,uBAAuB;;WAEvB;;WAEA,gBAAgB;;;;;;;;;WAShB;;;;;;;;;;;WAWA,cAAc;;;;;;;;WAQd,sBAAsB;;;;;;;;;WAStB,YAAY,QAAQ;;WAEpB,eAAe;;;;;;;;;WASf,oBAAoB;;WAEpB,oBAAoB,mBAAmB;;;;;;;;;WASvC;;;UAIM;WACN,QAAQ;;;;;;;;WAQR;WACA,mBAAmB;WACnB;WACA,WAAW;;WAEX,OAAO,kBAAkB;;;;;;WAMzB,WAAW,MAAM,mBAAmB;;WAEpC;;;;;;WAMA,cAAc;;;;;;;WAOd,aAAa;;WAEb,WAAW;;WAEX;;;;;;;;;WASA,UAAU;;;;;;;;WAQV,UAAU;;WAEV,SAAS;IAAU;IAAmB;;;;;;;;;WAQtC;aACE;aACA;aACA;;;WAGF,gBAAgB;;WAEhB,aAAa,2BAA2B;;WAExC,wBAAwB;;WAExB,oBAAoB;;WAEpB,sBAAsB;;WAEtB,gBAAgB,eAAe;WAC/B;WACA,UAAU;;WAEV;;;;;;WAMA;;;;;;;;;;;;;;iBAeK,kBACd,SAAS,wBACR;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/assistant.tsx","../src/react.tsx","../src/useSpeechInput.ts"],"mappings":";;;;;;UAoFiB;;WAEN,SAAS;;;;;;;;WAQT,YAAY;;;;;;;;;;WAUZ;;WAEA,uBAAuB;;WAEvB;;WAEA,gBAAgB;;;;;;;;;WAShB;;;;;;;;;;;WAWA,cAAc;;;;;;;;WAQd,sBAAsB;;;;;;;;;WAStB,YAAY,QAAQ;;WAEpB,eAAe;;;;;;;;;WASf,oBAAoB;;WAEpB,oBAAoB,mBAAmB;;;;;;;;;WASvC;;;UAIM;WACN,QAAQ;;;;;;;;WAQR;WACA,mBAAmB;WACnB;WACA,WAAW;;WAEX,OAAO,kBAAkB;;;;;;WAMzB,WAAW,MAAM,mBAAmB;;WAEpC;;;;;;WAMA,cAAc;;;;;;;WAOd,aAAa;;WAEb,WAAW;;WAEX;;;;;;;;;WASA,UAAU;;;;;;;;WAQV,UAAU;;WAEV,SAAS;IAAU;IAAmB;;;;;;;;;WAQtC;aACE;aACA;aACA;;;WAGF,gBAAgB;;WAEhB,aAAa,2BAA2B;;WAExC,wBAAwB;;WAExB,oBAAoB;;WAEpB,sBAAsB;;WAEtB,gBAAgB,eAAe;WAC/B;WACA,UAAU;;WAEV;;;;;;WAMA;;;;;;;;;;;;;;iBAeK,kBACd,SAAS,wBACR;;;KC7OS,mBAAmB,mBAAc;;;;;;cAOhC,sDAAiB,gBAAA;;;;;;;;;;;KAYlB,oBAAoB;;;;;;;;iBA2HhB,WAAW,SAAS,oBAAoB;;;;UC5JvC;WACN,QAAQ;;WAER;;WAEA,WAAW;;WAEX,UAAU,MAAM;;;;;;;;;;iBAaX,eACd,SAAS,wBACR"}
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import {
|
|
2
|
+
import { createTableAgentController, createTableAssistant } from "@adapttable/ai";
|
|
3
3
|
import { AGENT_ALWAYS_ALLOW_STATE, AGENT_APPROVAL_STATE, AGENT_PROGRESS_STATE, AGENT_VIEW_STATE, FeatureStateScope, featureStateKey, useFeatureState, useTableRuntime } from "@adapttable/react/adapter";
|
|
4
|
-
import { useCallback, useDebugValue, useEffect, useLayoutEffect,
|
|
5
|
-
import { sampleColumns } from "@adapttable/ai/context";
|
|
4
|
+
import { useCallback, useDebugValue, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore } from "react";
|
|
6
5
|
import { flushSync } from "react-dom";
|
|
7
6
|
import { jsx } from "react/jsx-runtime";
|
|
8
7
|
import { createSpeechInput, readRememberedLanguage, rememberLanguage } from "@adapttable/ai/voice";
|
|
@@ -128,7 +127,9 @@ function inputsOf(options, approval, alwaysAllow, viewState, progress) {
|
|
|
128
127
|
* Opt-in table feature — `@adapttable/ai-react`.
|
|
129
128
|
*
|
|
130
129
|
* `@adapttable/ai` stays React-free. This package mounts a provider that
|
|
131
|
-
*
|
|
130
|
+
* drives `@adapttable/ai`'s table agent controller from React: it keeps the
|
|
131
|
+
* controller's inputs current, re-renders on its snapshot and the table's
|
|
132
|
+
* changes, and publishes what the controller holds as feature state.
|
|
132
133
|
*/
|
|
133
134
|
/**
|
|
134
135
|
* Feature-state key for the live {@link AgentSession}.
|
|
@@ -136,11 +137,9 @@ function inputsOf(options, approval, alwaysAllow, viewState, progress) {
|
|
|
136
137
|
* @public
|
|
137
138
|
*/
|
|
138
139
|
const TABLE_AGENT_STATE = featureStateKey("table-agent");
|
|
139
|
-
/** One open approval, whichever shape the write took. */
|
|
140
140
|
function TableAgentProvider({ feature, children }) {
|
|
141
141
|
const options = feature.options;
|
|
142
142
|
const runtime = useTableRuntime();
|
|
143
|
-
const revisionCounterRef = useRef(createRevisionCounter());
|
|
144
143
|
const optionsRef = useRef(options);
|
|
145
144
|
optionsRef.current = options;
|
|
146
145
|
const runtimeRef = useRef(runtime);
|
|
@@ -152,252 +151,48 @@ function TableAgentProvider({ feature, children }) {
|
|
|
152
151
|
setAdmissionTick(admissionTick + 1);
|
|
153
152
|
});
|
|
154
153
|
};
|
|
155
|
-
const
|
|
156
|
-
|
|
157
|
-
const tableIdRef = useRef(options.tableId);
|
|
158
|
-
const registryKeyOf = (next) => `${exclusionKey(next.excludeCapabilities)}!${JSON.stringify(next.capabilityApproval ?? {})}!${tableActionSignature(runtime.view()?.actions)}`;
|
|
159
|
-
const registryRef = useRef(registryKeyOf(options));
|
|
160
|
-
const registryKey = registryKeyOf(options);
|
|
161
|
-
const sessionRef = useRef(null);
|
|
162
|
-
if (tableIdRef.current !== options.tableId || registryRef.current !== registryKey) {
|
|
163
|
-
tableIdRef.current = options.tableId;
|
|
164
|
-
registryRef.current = registryKey;
|
|
165
|
-
sessionRef.current = null;
|
|
166
|
-
revisionCounterRef.current = createRevisionCounter();
|
|
167
|
-
}
|
|
168
|
-
sessionRef.current ??= bindLiveSession({
|
|
154
|
+
const controllerRef = useRef(null);
|
|
155
|
+
controllerRef.current ??= createTableAgentController({
|
|
169
156
|
options: optionsRef,
|
|
170
157
|
runtime: runtimeRef,
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
reportProgress,
|
|
158
|
+
flushAdmission: () => {
|
|
159
|
+
flushAdmission.current();
|
|
160
|
+
},
|
|
175
161
|
flush: flushSync
|
|
176
162
|
});
|
|
177
|
-
const
|
|
178
|
-
const [revocations, setRevocations] = useState(0);
|
|
179
|
-
const [progress, setProgress] = useState(null);
|
|
180
|
-
const [transaction, setTransaction] = useState(null);
|
|
181
|
-
const pendingRef = useRef(null);
|
|
182
|
-
const transactionId = useRef(0);
|
|
163
|
+
const controller = controllerRef.current;
|
|
183
164
|
const neutralTable = runtime.view()?.neutralTable;
|
|
184
|
-
const
|
|
185
|
-
const
|
|
186
|
-
const stamp = useSyncExternalStore(subscribeToTable, readStamp, readStamp);
|
|
165
|
+
const subscribeToTable = useCallback((onStoreChange) => neutralTable ? controller.subscribeTable(onStoreChange) : () => void 0, [controller, neutralTable]);
|
|
166
|
+
const stamp = useSyncExternalStore(subscribeToTable, controller.tableStamp, controller.tableStamp);
|
|
187
167
|
useDebugValue(stamp);
|
|
188
|
-
const
|
|
189
|
-
const approvalMemory = useRef(createApprovalMemory());
|
|
190
|
-
const contractVersion = useCallback(() => contractFingerprint(session.manifest(), session.catalog()), [session]);
|
|
191
|
-
const webmcp = options.webmcp;
|
|
192
|
-
const webmcpVersion = webmcp ? contractVersion() : "";
|
|
193
|
-
useEffect(() => {
|
|
194
|
-
if (!webmcp) return;
|
|
195
|
-
const options = webmcp === true ? {} : webmcp;
|
|
196
|
-
const registration = registerWebMcpTools(session, {
|
|
197
|
-
...options.exposedTo ? { exposedTo: options.exposedTo } : {},
|
|
198
|
-
onWarning: (warning) => {
|
|
199
|
-
console.warn(`[adapttable] webmcp: ${warning.message}`);
|
|
200
|
-
}
|
|
201
|
-
});
|
|
202
|
-
options.onRegister?.(registration.names);
|
|
203
|
-
return () => {
|
|
204
|
-
registration.dispose();
|
|
205
|
-
options.onRegister?.([]);
|
|
206
|
-
};
|
|
207
|
-
}, [
|
|
208
|
-
session,
|
|
209
|
-
webmcp,
|
|
210
|
-
webmcpVersion
|
|
211
|
-
]);
|
|
212
|
-
waitForChrome.current = (subject, signal) => {
|
|
213
|
-
if (pendingRef.current) return Promise.reject(/* @__PURE__ */ new Error("an approval is already pending"));
|
|
214
|
-
const capability = subject.kind === "operation" ? subject.capability : void 0;
|
|
215
|
-
if (mayAlwaysAllow({
|
|
216
|
-
capability,
|
|
217
|
-
kind: capabilityKind(session, capability),
|
|
218
|
-
alwaysAllow: alwaysAllowFor(optionsRef.current.approval, optionsRef.current.capabilities, capability)
|
|
219
|
-
}) && capability !== void 0 && approvalMemory.current.allows(capability, contractVersion())) return Promise.resolve(true);
|
|
220
|
-
return new Promise((resolve) => {
|
|
221
|
-
const rows = subject.kind === "rows";
|
|
222
|
-
let settled = false;
|
|
223
|
-
const entry = {
|
|
224
|
-
...rows ? {} : { capability: subject.capability },
|
|
225
|
-
proposals: rows ? displayProposals(subject.proposals, readerResolver(runtimeRef.current, optionsRef.current.columns)) : [],
|
|
226
|
-
perItem: rows && subject.perItem,
|
|
227
|
-
...rows ? {} : { operation: {
|
|
228
|
-
capability: subject.capability,
|
|
229
|
-
...subject.title ? { title: subject.title } : {},
|
|
230
|
-
arguments: subject.arguments
|
|
231
|
-
} },
|
|
232
|
-
resolve: (result) => {
|
|
233
|
-
if (settled) return;
|
|
234
|
-
settled = true;
|
|
235
|
-
if (pendingRef.current === entry) pendingRef.current = null;
|
|
236
|
-
setTransaction(closeTransaction(entry));
|
|
237
|
-
signal?.removeEventListener("abort", onAbort);
|
|
238
|
-
resolve(result);
|
|
239
|
-
}
|
|
240
|
-
};
|
|
241
|
-
const onAbort = () => entry.resolve(false);
|
|
242
|
-
pendingRef.current = entry;
|
|
243
|
-
transactionId.current += 1;
|
|
244
|
-
setTransaction(openTransaction(transactionId.current, entry, subject.presentation));
|
|
245
|
-
if (signal?.aborted) {
|
|
246
|
-
entry.resolve(false);
|
|
247
|
-
return;
|
|
248
|
-
}
|
|
249
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
250
|
-
});
|
|
251
|
-
};
|
|
252
|
-
useEffect(() => () => {
|
|
253
|
-
pendingRef.current?.resolve(false);
|
|
254
|
-
}, []);
|
|
255
|
-
const published = {
|
|
256
|
-
catalog: () => session.catalog(),
|
|
257
|
-
describe: (key) => session.describe(key),
|
|
258
|
-
execute: (key, args, expectedRevision, idempotencyKey, signal) => session.execute(key, args, expectedRevision, idempotencyKey, signal),
|
|
259
|
-
manifest: () => session.manifest()
|
|
260
|
-
};
|
|
261
|
-
const samplesRef = useRef({});
|
|
262
|
-
const viewStateValue = useRef({ read: () => viewInputsFromRuntime(runtimeRef.current, optionsRef.current, samplesRef.current) }).current;
|
|
263
|
-
useEffect(() => {
|
|
264
|
-
options.bridge?.attach?.(session);
|
|
265
|
-
options.bridge?.viewInputs?.(viewStateValue.read);
|
|
266
|
-
}, [
|
|
267
|
-
options.bridge,
|
|
268
|
-
session,
|
|
269
|
-
viewStateValue
|
|
270
|
-
]);
|
|
271
|
-
const last = useRef("");
|
|
168
|
+
const state = useSyncExternalStore(controller.subscribe, controller.getState, controller.getState);
|
|
272
169
|
useLayoutEffect(() => {
|
|
273
|
-
|
|
274
|
-
const encoded = JSON.stringify(published);
|
|
275
|
-
if (encoded === last.current) return;
|
|
276
|
-
last.current = encoded;
|
|
277
|
-
options.bridge?.publish?.(published);
|
|
170
|
+
controller.sync();
|
|
278
171
|
});
|
|
279
|
-
const sampledKey = sampledColumns(session).join("\0");
|
|
280
|
-
useEffect(() => {
|
|
281
|
-
const wanted = sampledKey === "" ? [] : sampledKey.split("\0");
|
|
282
|
-
if (wanted.length === 0) {
|
|
283
|
-
samplesRef.current = {};
|
|
284
|
-
return;
|
|
285
|
-
}
|
|
286
|
-
const controller = new AbortController();
|
|
287
|
-
sampleColumns(session, wanted, controller.signal).then((values) => {
|
|
288
|
-
if (controller.signal.aborted) return;
|
|
289
|
-
samplesRef.current = values;
|
|
290
|
-
}, () => {
|
|
291
|
-
if (!controller.signal.aborted) samplesRef.current = {};
|
|
292
|
-
});
|
|
293
|
-
return () => controller.abort();
|
|
294
|
-
}, [
|
|
295
|
-
session,
|
|
296
|
-
sampledKey,
|
|
297
|
-
samplesRef
|
|
298
|
-
]);
|
|
299
|
-
const chromePending = !hostApprove && transaction !== null;
|
|
300
|
-
const approvals = options.bridge?.approvals;
|
|
301
|
-
const approvalsRef = useRef(approvals);
|
|
302
|
-
const announcedRef = useRef(null);
|
|
303
|
-
const publishedRef = useRef(null);
|
|
304
|
-
useEffect(() => {
|
|
305
|
-
const previous = approvalsRef.current;
|
|
306
|
-
if (previous !== approvals) {
|
|
307
|
-
if (announcedRef.current) previous?.(null);
|
|
308
|
-
approvalsRef.current = approvals;
|
|
309
|
-
announcedRef.current = null;
|
|
310
|
-
}
|
|
311
|
-
const next = chromePending ? transaction : null;
|
|
312
|
-
if (announcedRef.current === next) return;
|
|
313
|
-
announcedRef.current = next;
|
|
314
|
-
approvals?.(next ? publishedRef.current : null);
|
|
315
|
-
}, [
|
|
316
|
-
approvals,
|
|
317
|
-
chromePending,
|
|
318
|
-
transaction
|
|
319
|
-
]);
|
|
320
172
|
useEffect(() => () => {
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
}, []);
|
|
325
|
-
const decideAt = (id) => (index, approved) => {
|
|
326
|
-
setTransaction((current) => recordDecision(current, id, index, approved));
|
|
327
|
-
};
|
|
328
|
-
useEffect(() => {
|
|
329
|
-
if (!transaction) return;
|
|
330
|
-
if (transaction.pending.proposals.length === 0) return;
|
|
331
|
-
if (transaction.decisions.includes("pending")) return;
|
|
332
|
-
transaction.pending.resolve(settleDecisions(transaction.decisions, "rejected"));
|
|
333
|
-
}, [transaction]);
|
|
334
|
-
const approvalValue = hostApprove || !transaction ? null : {
|
|
335
|
-
proposals: transaction.pending.proposals,
|
|
336
|
-
...transaction.pending.operation ? { operation: transaction.pending.operation } : {},
|
|
337
|
-
decisions: transaction.decisions,
|
|
338
|
-
presentation: transaction.presentation,
|
|
339
|
-
...mayAlwaysAllow({
|
|
340
|
-
capability: transaction.pending.capability,
|
|
341
|
-
kind: capabilityKind(session, transaction.pending.capability),
|
|
342
|
-
alwaysAllow: alwaysAllowFor(optionsRef.current.approval, optionsRef.current.capabilities, transaction.pending.capability)
|
|
343
|
-
}) ? { alwaysAllow: () => {
|
|
344
|
-
const capability = transaction.pending.capability;
|
|
345
|
-
if (capability === void 0) return;
|
|
346
|
-
approvalMemory.current.remember(capability, contractVersion());
|
|
347
|
-
transaction.pending.resolve(true);
|
|
348
|
-
} } : {},
|
|
349
|
-
approve: () => transaction.pending.resolve(transaction.pending.perItem ? settleDecisions(transaction.decisions, "approved") : true),
|
|
350
|
-
reject: (reason) => {
|
|
351
|
-
const stated = typeof reason === "string" ? reason.trim() : void 0;
|
|
352
|
-
if (transaction.pending.perItem) {
|
|
353
|
-
transaction.pending.resolve(perItemRefusal(transaction, stated));
|
|
354
|
-
return;
|
|
355
|
-
}
|
|
356
|
-
transaction.pending.resolve(stated ? {
|
|
357
|
-
approved: [],
|
|
358
|
-
reason: stated
|
|
359
|
-
} : false);
|
|
360
|
-
},
|
|
361
|
-
...transaction.pending.perItem ? { decideAt: decideAt(transaction.id) } : {}
|
|
362
|
-
};
|
|
363
|
-
publishedRef.current = approvalValue;
|
|
364
|
-
useEffect(() => {
|
|
365
|
-
assertAlwaysAllow(sharedApproval(optionsRef.current.approval).alwaysAllow, session.catalog().map((entry) => entry.key));
|
|
366
|
-
}, [session, stamp]);
|
|
367
|
-
const alwaysAllowValue = useMemo(() => ({
|
|
368
|
-
capabilities: approvalMemory.current.remembered(contractVersion()),
|
|
369
|
-
revoke: (capability) => {
|
|
370
|
-
approvalMemory.current.revoke(capability);
|
|
371
|
-
setRevocations((count) => count + 1);
|
|
372
|
-
}
|
|
373
|
-
}), [
|
|
374
|
-
revocations,
|
|
375
|
-
stamp,
|
|
376
|
-
contractVersion
|
|
377
|
-
]);
|
|
378
|
-
const alwaysAllowedBridge = optionsRef.current.bridge?.alwaysAllowed;
|
|
379
|
-
useEffect(() => {
|
|
380
|
-
alwaysAllowedBridge?.(alwaysAllowValue);
|
|
381
|
-
}, [alwaysAllowedBridge, alwaysAllowValue]);
|
|
382
|
-
reportProgress.current = (report) => {
|
|
383
|
-
setProgress(report);
|
|
384
|
-
optionsRef.current.bridge?.progress?.(report);
|
|
385
|
-
};
|
|
173
|
+
controller.disconnect();
|
|
174
|
+
}, [controller]);
|
|
175
|
+
const session = state.session;
|
|
386
176
|
return /* @__PURE__ */ jsx(FeatureStateScope, {
|
|
387
177
|
stateKey: TABLE_AGENT_STATE,
|
|
388
|
-
value:
|
|
178
|
+
value: {
|
|
179
|
+
catalog: () => session.catalog(),
|
|
180
|
+
describe: (key) => session.describe(key),
|
|
181
|
+
execute: (key, args, expectedRevision, idempotencyKey, signal) => session.execute(key, args, expectedRevision, idempotencyKey, signal),
|
|
182
|
+
manifest: () => session.manifest()
|
|
183
|
+
},
|
|
389
184
|
children: /* @__PURE__ */ jsx(FeatureStateScope, {
|
|
390
185
|
stateKey: AGENT_APPROVAL_STATE,
|
|
391
|
-
value:
|
|
186
|
+
value: state.approval,
|
|
392
187
|
children: /* @__PURE__ */ jsx(FeatureStateScope, {
|
|
393
188
|
stateKey: AGENT_ALWAYS_ALLOW_STATE,
|
|
394
|
-
value:
|
|
189
|
+
value: state.alwaysAllow,
|
|
395
190
|
children: /* @__PURE__ */ jsx(FeatureStateScope, {
|
|
396
191
|
stateKey: AGENT_VIEW_STATE,
|
|
397
|
-
value:
|
|
192
|
+
value: state.view,
|
|
398
193
|
children: /* @__PURE__ */ jsx(FeatureStateScope, {
|
|
399
194
|
stateKey: AGENT_PROGRESS_STATE,
|
|
400
|
-
value: progress,
|
|
195
|
+
value: state.progress,
|
|
401
196
|
children
|
|
402
197
|
})
|
|
403
198
|
})
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/assistant.tsx","../src/react.tsx","../src/useSpeechInput.ts"],"sourcesContent":["/**\n * `@adapttable/ai-react` — the conversation lifecycle, without a UI.\n *\n * This entry owns state and nothing else: no markup, no launcher, no\n * provider client. A host renders its own panel from what the hook returns,\n * and the shipped widget is written against these same public values — which\n * is the only way to be sure it is not required.\n *\n * The rules that shape it:\n *\n * - **One send at a time**, reserved before any await. Two sends racing would\n * interleave two turns' actions against one table.\n * - **A draft survives failure.** Losing what someone typed because a\n * backend was down is worse than the outage.\n * - **A cancelled send is not a cancelled action.** Aborting before the\n * transport answers is clean; aborting after actions began is reported for\n * what it is, and nothing is retried — a mutation whose outcome is unknown\n * is never sent twice.\n * - **A late reply is dropped.** A turn that was stopped, or that belonged\n * to a previous table, never writes into the transcript.\n */\n\"use client\";\n\nimport {\n type AgentContextInputs,\n type AgentSession,\n type AlwaysAllowedState,\n type AssistantAllowance,\n type AssistantAudio,\n type AssistantInterruption,\n type AssistantMessage,\n type AssistantResumeHandle,\n type AssistantStatus,\n type AssistantSuggestion,\n type AssistantTransport,\n createTableAssistant,\n} from \"@adapttable/ai\";\nimport {\n AGENT_ALWAYS_ALLOW_STATE,\n AGENT_APPROVAL_STATE,\n AGENT_PROGRESS_STATE,\n AGENT_VIEW_STATE,\n type AgentAlwaysAllowState,\n type AgentApprovalPending,\n type AgentProgress,\n type AgentViewState,\n useFeatureState,\n} from \"@adapttable/react/adapter\";\nimport {\n useCallback,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\n\n// The hook's own options and state name these, so the entry that publishes\n// the hook publishes them too — a consumer typing a variable from it should\n// not have to reach into another entry point for the pieces.\nexport type {\n ApprovalPolicy,\n AssistantReceiptStatus,\n AssistantReceiptSubject,\n CommitPolicy,\n RowAddressScope,\n WritePolicy,\n} from \"@adapttable/ai\";\nexport type {\n AssistantInterruption,\n AssistantMessage,\n AssistantResumeHandle,\n AssistantStatus,\n AssistantTransport,\n};\nexport type {\n AssistantExchange,\n AssistantQuestion,\n AssistantReceipt,\n AssistantTransportReply,\n AssistantTurnStatus,\n} from \"@adapttable/ai\";\nexport type { AssistantUndoOffer } from \"@adapttable/ai\";\n\n/** How {@link useTableAssistant} is configured. @public */\nexport interface TableAssistantOptions {\n /** The live session. Changing it starts a new conversation. */\n readonly session: AgentSession | undefined;\n /**\n * Where a turn goes. Omit and the assistant stays disconnected.\n *\n * May be a fresh object every render — the controller reads the latest one\n * rather than reconnecting on its identity, so a host is not forced to\n * memoize it.\n */\n readonly transport?: AssistantTransport;\n /**\n * Changes when the transport should be re-established.\n *\n * The conversation resets on a new session, because that is a new table.\n * Swapping one transport for another — a backend for a scripted one — is\n * not visible in the object identity, so a host that does it names the\n * change here. A backend transport must never quietly become a simulated\n * one under the same key.\n */\n readonly transportKey?: string;\n /** Everything authored, filtered live against what the table offers. */\n readonly suggestions?: readonly AssistantSuggestion[];\n /** Controlled panel state. Omit for uncontrolled. */\n readonly open?: boolean;\n /** Called on every open/close request, controlled or not. */\n readonly onOpenChange?: (open: boolean) => void;\n /**\n * Whether a write from this conversation is waiting on a human.\n *\n * `execute` does not return while an approval is open, so the turn looks\n * like thinking from in here. A host that renders the approval — or wires\n * `bridge.approvals` — passes it back so the panel can say what is\n * actually happening. The turn is still in flight and still stoppable.\n */\n readonly awaitingApproval?: boolean;\n /**\n * What the reader has waved through, when the panel is mounted outside the\n * table.\n *\n * A panel inside the table reads this from feature state and needs nothing\n * here. One beside it cannot, so a host wires `bridge.alwaysAllowed` and\n * passes what it publishes — the same arrangement `bridge.approvals` and\n * `bridge.viewInputs` already have. Without it a reader can wave a\n * capability through and have no way to take it back.\n */\n readonly alwaysAllow?: AlwaysAllowedState;\n /**\n * Live view and filter data the manifest does not carry.\n *\n * Read when a turn starts and again when it settles, so per-turn undo can\n * tell what the turn moved. A function rather than a value: a fixed object\n * would report that nothing changed.\n */\n readonly contextInputs?: () => AgentContextInputs;\n /**\n * Work that outlived its connection, handed over the moment it does.\n *\n * Durable recovery starts here and ends outside this package: a host that\n * stores the handle where it survives a reload can offer a resume when the\n * reader comes back, and a host that does nothing loses the work with the\n * page.\n */\n readonly onDetach?: (handle: AssistantResumeHandle) => void;\n /** A handle kept from a previous page, to resume into this one. */\n readonly resumeHandle?: AssistantResumeHandle;\n /**\n * The transcript, when your app owns it.\n *\n * Omit it and the conversation lives in the controller. Supply it to load\n * the last conversation from your own API, append a message that arrived on\n * a socket, or keep it where it survives a reload — pass a new array and the\n * panel shows it. Pair it with `onMessagesChange`.\n */\n readonly messages?: readonly AssistantMessage[];\n /** Told whenever the transcript changes, with the whole of it. */\n readonly onMessagesChange?: (messages: readonly AssistantMessage[]) => void;\n /**\n * How much of the conversation travels with each turn.\n *\n * `\"full\"` (default) sends every earlier message, for a backend that\n * remembers nothing. A number sends that many of the most recent. `0` sends\n * none — the reader's message still travels, and a backend holding its own\n * session supplies the rest. What the reader sees is never trimmed.\n */\n readonly conversation?: \"full\" | number;\n}\n\n/** What a host renders from. @public */\nexport interface TableAssistantState {\n readonly status: AssistantStatus;\n /**\n * Whether a turn is in flight and can still be stopped.\n *\n * Separate from {@link TableAssistantState.status}: a write parked on a\n * human approval reports `awaiting-approval` but is still running, and\n * Stop still ends it.\n */\n readonly busy: boolean;\n readonly messages: readonly AssistantMessage[];\n readonly draft: string;\n readonly setDraft: (draft: string) => void;\n /** Send the draft, or the given text. Resolves when the turn settles. */\n readonly send: (text?: string) => Promise<void>;\n /**\n * Send a recording as the reader's turn — pass it as `onClip` to\n * backend-mode `useSpeechInput`. The transcript the backend returns becomes\n * the reader's message.\n */\n readonly sendClip: (clip: AssistantAudio) => Promise<void>;\n /** Abort the turn in flight. Safe to call when nothing is in flight. */\n readonly stop: () => void;\n /**\n * Rejoin work a released connection left running.\n *\n * A no-op with nothing to rejoin, which is what `resumable` says.\n */\n readonly resume: () => Promise<void>;\n /**\n * What became of the last turn, when no reply ended it.\n *\n * `\"stopped\"` is the reader's own decision; `\"detached\"` is a released\n * connection, where the work may still be running.\n */\n readonly interrupted: AssistantInterruption | undefined;\n /** The work `resume` would rejoin, or nothing. */\n readonly resumable: AssistantResumeHandle | undefined;\n /** Drop the transcript. Refuses while a turn is in flight. */\n readonly clear: () => void;\n /**\n * A write waiting on the reader, or nothing.\n *\n * Hand it to the panel as `approval` and the conversation reviews it —\n * which is where a write asked for in the conversation belongs. The panel\n * draws it only when the approval's presentation names the widget, so\n * passing it costs nothing on a table reviewing elsewhere.\n */\n readonly approval: AgentApprovalPending | null;\n /**\n * How far the capability now running has got, or nothing.\n *\n * Published by the table while a long call works through its rows. It never\n * becomes the receipt: when the turn settles this goes and the receipts say\n * what happened.\n */\n readonly progress: AgentProgress | null;\n /** Answer the pending question and let the turn continue. */\n readonly answer: (answer: { optionId?: string; text?: string }) => void;\n /**\n * Whether the last turn that moved the table can still be put back.\n *\n * Null when no turn moved it. Re-read every render, because the offer ends\n * the moment anything else changes the view. `blockedCode` is a token the\n * labels translate — the panel never shows a reader a code.\n */\n readonly undo: {\n readonly messageId: string;\n readonly available: boolean;\n readonly blockedCode?: string;\n } | null;\n /** Put that turn back. A no-op once the offer has expired. */\n readonly undoTurn: () => Promise<void>;\n /** Put one action of the last turn back, by its receipt's replay identity. */\n readonly undoAction: (idempotencyKey: string) => Promise<void>;\n /** What the reader said not to ask about again, each with its own name. */\n readonly alwaysAllowed: readonly AssistantAllowance[];\n /** Ask about one of them again from now on. */\n readonly revokeAlwaysAllow: (capability: string) => void;\n /** The suggestions this table can run right now, re-checked every render. */\n readonly suggestions: readonly AssistantSuggestion[];\n /** Send a suggestion's prompt as if the reader had typed it. */\n readonly runSuggestion: (id: string) => Promise<void>;\n readonly open: boolean;\n readonly setOpen: (open: boolean) => void;\n /** The last failure, cleared by the next successful turn. */\n readonly error: string | undefined;\n /**\n * The machine code behind {@link error}, when a turn ended with work\n * pending. A surface with labels turns it into a sentence for the reader;\n * the message beside it is written for whoever is debugging the turn.\n */\n readonly errorCode: string | undefined;\n}\n\n/**\n * Run a table assistant.\n *\n * A thin subscriber to the neutral controller in `@adapttable/ai/assistant`:\n * React supplies the external-store mechanism, the live inputs and the\n * controlled presentation state, and owns none of the lifecycle.\n *\n * @param options - Session, transport and presentation.\n * @returns Everything a panel needs, and nothing about how it looks.\n *\n * @public\n */\nexport function useTableAssistant(\n options: TableAssistantOptions\n): TableAssistantState {\n const { onOpenChange } = options;\n const [uncontrolledOpen, setUncontrolledOpen] = useState(false);\n // The live approval, so a host wires the panel with one prop rather than\n // reaching for feature state itself.\n const approval = useFeatureState(AGENT_APPROVAL_STATE);\n // What the reader has waved through, published by the binding whether or\n // not an approval is open.\n const alwaysAllow = useFeatureState(AGENT_ALWAYS_ALLOW_STATE);\n // The table's own live view, published by `tableAgent`. A host that drives\n // the panel from state of its own passes `contextInputs` and this is unused.\n const viewState = useFeatureState(AGENT_VIEW_STATE);\n // How far a running capability has got, for the same reason: a panel inside\n // the table needs no host wiring to say what the work is doing.\n const progress = useFeatureState(AGENT_PROGRESS_STATE);\n\n // Created once, inert until the mount effect connects it. Constructing a\n // store during render must not open a connection — a render can be thrown\n // away, and Strict Mode throws the first one away on purpose.\n const storeRef = useRef<ReturnType<typeof createTableAssistant> | null>(null);\n 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 sendClip: store.sendClip,\n stop: store.stop,\n resume: store.resume,\n interrupted: state.interrupted,\n resumable: state.resumable,\n clear: store.clear,\n status: state.status,\n busy: state.busy,\n approval: approval ?? null,\n progress: state.progress,\n answer: store.answer,\n undo: state.undo\n ? {\n messageId: state.undo.messageId,\n available: state.undo.available,\n ...(state.undo.blocked\n ? { blockedCode: state.undo.blocked.code }\n : {}),\n }\n : null,\n undoTurn: store.undoTurn,\n undoAction: store.undoAction,\n alwaysAllowed: state.alwaysAllowed,\n revokeAlwaysAllow: store.revokeAlwaysAllow,\n suggestions: state.suggestions,\n runSuggestion: store.runSuggestion,\n open,\n setOpen,\n error: state.error,\n errorCode: state.errorCode,\n };\n}\n\n/** The hook's options as the store's live inputs. A projection, not a decision. */\nfunction inputsOf(\n options: TableAssistantOptions,\n approval: AgentApprovalPending | null | undefined,\n alwaysAllow: AgentAlwaysAllowState | null | undefined,\n viewState: AgentViewState | null | undefined,\n progress: AgentProgress | null | undefined\n) {\n // The host's own reader wins; otherwise the table's, which is what makes\n // per-turn undo work without a host lifting page and sort into its state.\n const contextInputs =\n options.contextInputs ??\n (viewState ? () => viewState.read() as AgentContextInputs : undefined);\n return {\n session: options.session,\n transport: options.transport,\n transportKey: options.transportKey,\n suggestions: options.suggestions,\n awaitingApproval: options.awaitingApproval,\n approval: approval ?? null,\n progress: progress ?? null,\n ...(contextInputs ? { contextInputs } : {}),\n ...(options.onDetach ? { onDetach: options.onDetach } : {}),\n ...(options.messages ? { messages: options.messages } : {}),\n ...(options.onMessagesChange\n ? { onMessagesChange: options.onMessagesChange }\n : {}),\n ...(options.conversation === undefined\n ? {}\n : { conversation: options.conversation }),\n ...(options.resumeHandle ? { resumeHandle: options.resumeHandle } : {}),\n // The host's own wins, for the same reason `contextInputs` does: a panel\n // beside the table has no feature state to read.\n ...((options.alwaysAllow ?? alwaysAllow)\n ? {\n alwaysAllowed: (options.alwaysAllow ?? alwaysAllow)?.capabilities,\n onRevokeAlwaysAllow: (options.alwaysAllow ?? alwaysAllow)?.revoke,\n }\n : {}),\n };\n}\n","/**\n * Opt-in table feature — `@adapttable/ai-react`.\n *\n * `@adapttable/ai` stays React-free. This package mounts a provider that\n * observes the live table and publishes a versioned manifest.\n */\nimport {\n type AgentContextInputs,\n type AgentSession,\n alwaysAllowFor,\n type ApprovalResult,\n type ApprovalSubject,\n type ApprovalTransaction,\n assertAlwaysAllow,\n bindLiveSession,\n capabilityKind,\n closeTransaction,\n contractFingerprint,\n createApprovalMemory,\n createRevisionCounter,\n displayProposals,\n exclusionKey,\n mayAlwaysAllow,\n openTransaction,\n type PendingApproval,\n perItemRefusal,\n readerResolver,\n recordDecision,\n registerWebMcpTools,\n revisionToken,\n sampledColumns,\n settleDecisions,\n sharedApproval,\n tableActionSignature,\n type TableAgentBridge as NeutralBridge,\n type TableAgentRuntimeOptions,\n viewInputsFromRuntime,\n viewRevisionStamp,\n} from \"@adapttable/ai\";\nimport { sampleColumns } from \"@adapttable/ai/context\";\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 type FeatureProviderProps,\n featureStateKey,\n FeatureStateScope,\n type StaticTableFeature,\n useTableRuntime,\n} from \"@adapttable/react/adapter\";\nimport {\n type ReactNode,\n useCallback,\n useDebugValue,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport { flushSync } from \"react-dom\";\n\nexport type { SharedApproval, TableAgentColumnPatch } from \"@adapttable/ai\";\n\n// The bridge contract is `@adapttable/ai`'s — a manifest, a session and a\n// pending approval are what any binding publishes, none of it React. Named\n// here with this binding's own pending shape so every existing import keeps\n// working.\nexport type TableAgentBridge = NeutralBridge<AgentApprovalPending>;\n\n/**\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 * The runtime half — identity, policy, columns, the host's callbacks and\n * capabilities — is `@adapttable/ai`'s {@link TableAgentRuntimeOptions}. This\n * binding adds where it publishes updates and whether it offers the table to a\n * browser-resident agent.\n *\n * @public\n */\nexport interface TableAgentOptions extends TableAgentRuntimeOptions {\n /** Host callbacks for manifest and session attach. */\n readonly bridge?: TableAgentBridge;\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\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 ?? {})}!${tableActionSignature(runtime.view()?.actions)}`;\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 options: optionsRef,\n runtime: runtimeRef,\n revisions: revisionCounterRef.current,\n flushAdmission,\n waitForChrome,\n reportProgress,\n flush: flushSync,\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwRA,SAAgB,kBACd,SACqB;CACrB,MAAM,EAAE,iBAAiB;CACzB,MAAM,CAAC,kBAAkB,uBAAuB,SAAS,KAAK;CAG9D,MAAM,WAAW,gBAAgB,oBAAoB;CAGrD,MAAM,cAAc,gBAAgB,wBAAwB;CAG5D,MAAM,YAAY,gBAAgB,gBAAgB;CAGlD,MAAM,WAAW,gBAAgB,oBAAoB;CAKrD,MAAM,WAAW,OAAuD,IAAI;CAC5E,SAAS,YAAY,qBACnB,SAAS,SAAS,UAAU,aAAa,WAAW,QAAQ,CAC9D;CACA,MAAM,QAAQ,SAAS;CAKvB,gBAAgB;EACd,MAAM,OAAO,SAAS,SAAS,UAAU,aAAa,WAAW,QAAQ,CAAC;CAC5E,CAAC;CAED,gBAAgB;EACd,MAAM,QAAQ;EACd,aAAa;GACX,MAAM,QAAQ;GAId,SAAS,UAAU;EACrB;CAIF,GAAG,CAAC,CAAC;CAEL,MAAM,QAAQ,qBACZ,MAAM,WACN,MAAM,UACN,MAAM,QACR;CAEA,MAAM,OAAO,QAAQ,QAAQ;CAC7B,MAAM,UAAU,aACb,SAAkB;EACjB,IAAI,QAAQ,SAAS,KAAA,GAAW,oBAAoB,IAAI;EACxD,eAAe,IAAI;CACrB,GACA,CAAC,QAAQ,MAAM,YAAY,CAC7B;CAEA,OAAO;EACL,UAAU,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AC;EAC9C;EACA;EACA,aAAa,OAAO,MAAM;EAC1B,YAAY,OAAO,KAAK;EACxB,cAAc,aAAa;GACzB,OAAO,YAAY,QAAQ;GAC3B,iBAAiB,QAAQ;EAC3B;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/assistant.tsx","../src/react.tsx","../src/useSpeechInput.ts"],"sourcesContent":["/**\n * `@adapttable/ai-react` — the conversation lifecycle, without a UI.\n *\n * This entry owns state and nothing else: no markup, no launcher, no\n * provider client. A host renders its own panel from what the hook returns,\n * and the shipped widget is written against these same public values — which\n * is the only way to be sure it is not required.\n *\n * The rules that shape it:\n *\n * - **One send at a time**, reserved before any await. Two sends racing would\n * interleave two turns' actions against one table.\n * - **A draft survives failure.** Losing what someone typed because a\n * backend was down is worse than the outage.\n * - **A cancelled send is not a cancelled action.** Aborting before the\n * transport answers is clean; aborting after actions began is reported for\n * what it is, and nothing is retried — a mutation whose outcome is unknown\n * is never sent twice.\n * - **A late reply is dropped.** A turn that was stopped, or that belonged\n * to a previous table, never writes into the transcript.\n */\n\"use client\";\n\nimport {\n type AgentContextInputs,\n type AgentSession,\n type AlwaysAllowedState,\n type AssistantAllowance,\n type AssistantAudio,\n type AssistantInterruption,\n type AssistantMessage,\n type AssistantResumeHandle,\n type AssistantStatus,\n type AssistantSuggestion,\n type AssistantTransport,\n createTableAssistant,\n} from \"@adapttable/ai\";\nimport {\n AGENT_ALWAYS_ALLOW_STATE,\n AGENT_APPROVAL_STATE,\n AGENT_PROGRESS_STATE,\n AGENT_VIEW_STATE,\n type AgentAlwaysAllowState,\n type AgentApprovalPending,\n type AgentProgress,\n type AgentViewState,\n useFeatureState,\n} from \"@adapttable/react/adapter\";\nimport {\n useCallback,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\n\n// The hook's own options and state name these, so the entry that publishes\n// the hook publishes them too — a consumer typing a variable from it should\n// not have to reach into another entry point for the pieces.\nexport type {\n ApprovalPolicy,\n AssistantReceiptStatus,\n AssistantReceiptSubject,\n CommitPolicy,\n RowAddressScope,\n WritePolicy,\n} from \"@adapttable/ai\";\nexport type {\n AssistantInterruption,\n AssistantMessage,\n AssistantResumeHandle,\n AssistantStatus,\n AssistantTransport,\n};\nexport type {\n AssistantExchange,\n AssistantQuestion,\n AssistantReceipt,\n AssistantTransportReply,\n AssistantTurnStatus,\n} from \"@adapttable/ai\";\nexport type { AssistantUndoOffer } from \"@adapttable/ai\";\n\n/** How {@link useTableAssistant} is configured. @public */\nexport interface TableAssistantOptions {\n /** The live session. Changing it starts a new conversation. */\n readonly session: AgentSession | undefined;\n /**\n * Where a turn goes. Omit and the assistant stays disconnected.\n *\n * May be a fresh object every render — the controller reads the latest one\n * rather than reconnecting on its identity, so a host is not forced to\n * memoize it.\n */\n readonly transport?: AssistantTransport;\n /**\n * Changes when the transport should be re-established.\n *\n * The conversation resets on a new session, because that is a new table.\n * Swapping one transport for another — a backend for a scripted one — is\n * not visible in the object identity, so a host that does it names the\n * change here. A backend transport must never quietly become a simulated\n * one under the same key.\n */\n readonly transportKey?: string;\n /** Everything authored, filtered live against what the table offers. */\n readonly suggestions?: readonly AssistantSuggestion[];\n /** Controlled panel state. Omit for uncontrolled. */\n readonly open?: boolean;\n /** Called on every open/close request, controlled or not. */\n readonly onOpenChange?: (open: boolean) => void;\n /**\n * Whether a write from this conversation is waiting on a human.\n *\n * `execute` does not return while an approval is open, so the turn looks\n * like thinking from in here. A host that renders the approval — or wires\n * `bridge.approvals` — passes it back so the panel can say what is\n * actually happening. The turn is still in flight and still stoppable.\n */\n readonly awaitingApproval?: boolean;\n /**\n * What the reader has waved through, when the panel is mounted outside the\n * table.\n *\n * A panel inside the table reads this from feature state and needs nothing\n * here. One beside it cannot, so a host wires `bridge.alwaysAllowed` and\n * passes what it publishes — the same arrangement `bridge.approvals` and\n * `bridge.viewInputs` already have. Without it a reader can wave a\n * capability through and have no way to take it back.\n */\n readonly alwaysAllow?: AlwaysAllowedState;\n /**\n * Live view and filter data the manifest does not carry.\n *\n * Read when a turn starts and again when it settles, so per-turn undo can\n * tell what the turn moved. A function rather than a value: a fixed object\n * would report that nothing changed.\n */\n readonly contextInputs?: () => AgentContextInputs;\n /**\n * Work that outlived its connection, handed over the moment it does.\n *\n * Durable recovery starts here and ends outside this package: a host that\n * stores the handle where it survives a reload can offer a resume when the\n * reader comes back, and a host that does nothing loses the work with the\n * page.\n */\n readonly onDetach?: (handle: AssistantResumeHandle) => void;\n /** A handle kept from a previous page, to resume into this one. */\n readonly resumeHandle?: AssistantResumeHandle;\n /**\n * The transcript, when your app owns it.\n *\n * Omit it and the conversation lives in the controller. Supply it to load\n * the last conversation from your own API, append a message that arrived on\n * a socket, or keep it where it survives a reload — pass a new array and the\n * panel shows it. Pair it with `onMessagesChange`.\n */\n readonly messages?: readonly AssistantMessage[];\n /** Told whenever the transcript changes, with the whole of it. */\n readonly onMessagesChange?: (messages: readonly AssistantMessage[]) => void;\n /**\n * How much of the conversation travels with each turn.\n *\n * `\"full\"` (default) sends every earlier message, for a backend that\n * remembers nothing. A number sends that many of the most recent. `0` sends\n * none — the reader's message still travels, and a backend holding its own\n * session supplies the rest. What the reader sees is never trimmed.\n */\n readonly conversation?: \"full\" | number;\n}\n\n/** What a host renders from. @public */\nexport interface TableAssistantState {\n readonly status: AssistantStatus;\n /**\n * Whether a turn is in flight and can still be stopped.\n *\n * Separate from {@link TableAssistantState.status}: a write parked on a\n * human approval reports `awaiting-approval` but is still running, and\n * Stop still ends it.\n */\n readonly busy: boolean;\n readonly messages: readonly AssistantMessage[];\n readonly draft: string;\n readonly setDraft: (draft: string) => void;\n /** Send the draft, or the given text. Resolves when the turn settles. */\n readonly send: (text?: string) => Promise<void>;\n /**\n * Send a recording as the reader's turn — pass it as `onClip` to\n * backend-mode `useSpeechInput`. The transcript the backend returns becomes\n * the reader's message.\n */\n readonly sendClip: (clip: AssistantAudio) => Promise<void>;\n /** Abort the turn in flight. Safe to call when nothing is in flight. */\n readonly stop: () => void;\n /**\n * Rejoin work a released connection left running.\n *\n * A no-op with nothing to rejoin, which is what `resumable` says.\n */\n readonly resume: () => Promise<void>;\n /**\n * What became of the last turn, when no reply ended it.\n *\n * `\"stopped\"` is the reader's own decision; `\"detached\"` is a released\n * connection, where the work may still be running.\n */\n readonly interrupted: AssistantInterruption | undefined;\n /** The work `resume` would rejoin, or nothing. */\n readonly resumable: AssistantResumeHandle | undefined;\n /** Drop the transcript. Refuses while a turn is in flight. */\n readonly clear: () => void;\n /**\n * A write waiting on the reader, or nothing.\n *\n * Hand it to the panel as `approval` and the conversation reviews it —\n * which is where a write asked for in the conversation belongs. The panel\n * draws it only when the approval's presentation names the widget, so\n * passing it costs nothing on a table reviewing elsewhere.\n */\n readonly approval: AgentApprovalPending | null;\n /**\n * How far the capability now running has got, or nothing.\n *\n * Published by the table while a long call works through its rows. It never\n * becomes the receipt: when the turn settles this goes and the receipts say\n * what happened.\n */\n readonly progress: AgentProgress | null;\n /** Answer the pending question and let the turn continue. */\n readonly answer: (answer: { optionId?: string; text?: string }) => void;\n /**\n * Whether the last turn that moved the table can still be put back.\n *\n * Null when no turn moved it. Re-read every render, because the offer ends\n * the moment anything else changes the view. `blockedCode` is a token the\n * labels translate — the panel never shows a reader a code.\n */\n readonly undo: {\n readonly messageId: string;\n readonly available: boolean;\n readonly blockedCode?: string;\n } | null;\n /** Put that turn back. A no-op once the offer has expired. */\n readonly undoTurn: () => Promise<void>;\n /** Put one action of the last turn back, by its receipt's replay identity. */\n readonly undoAction: (idempotencyKey: string) => Promise<void>;\n /** What the reader said not to ask about again, each with its own name. */\n readonly alwaysAllowed: readonly AssistantAllowance[];\n /** Ask about one of them again from now on. */\n readonly revokeAlwaysAllow: (capability: string) => void;\n /** The suggestions this table can run right now, re-checked every render. */\n readonly suggestions: readonly AssistantSuggestion[];\n /** Send a suggestion's prompt as if the reader had typed it. */\n readonly runSuggestion: (id: string) => Promise<void>;\n readonly open: boolean;\n readonly setOpen: (open: boolean) => void;\n /** The last failure, cleared by the next successful turn. */\n readonly error: string | undefined;\n /**\n * The machine code behind {@link error}, when a turn ended with work\n * pending. A surface with labels turns it into a sentence for the reader;\n * the message beside it is written for whoever is debugging the turn.\n */\n readonly errorCode: string | undefined;\n}\n\n/**\n * Run a table assistant.\n *\n * A thin subscriber to the neutral controller in `@adapttable/ai/assistant`:\n * React supplies the external-store mechanism, the live inputs and the\n * controlled presentation state, and owns none of the lifecycle.\n *\n * @param options - Session, transport and presentation.\n * @returns Everything a panel needs, and nothing about how it looks.\n *\n * @public\n */\nexport function useTableAssistant(\n options: TableAssistantOptions\n): TableAssistantState {\n const { onOpenChange } = options;\n const [uncontrolledOpen, setUncontrolledOpen] = useState(false);\n // The live approval, so a host wires the panel with one prop rather than\n // reaching for feature state itself.\n const approval = useFeatureState(AGENT_APPROVAL_STATE);\n // What the reader has waved through, published by the binding whether or\n // not an approval is open.\n const alwaysAllow = useFeatureState(AGENT_ALWAYS_ALLOW_STATE);\n // The table's own live view, published by `tableAgent`. A host that drives\n // the panel from state of its own passes `contextInputs` and this is unused.\n const viewState = useFeatureState(AGENT_VIEW_STATE);\n // How far a running capability has got, for the same reason: a panel inside\n // the table needs no host wiring to say what the work is doing.\n const progress = useFeatureState(AGENT_PROGRESS_STATE);\n\n // Created once, inert until the mount effect connects it. Constructing a\n // store during render must not open a connection — a render can be thrown\n // away, and Strict Mode throws the first one away on purpose.\n const storeRef = useRef<ReturnType<typeof createTableAssistant> | null>(null);\n 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 sendClip: store.sendClip,\n stop: store.stop,\n resume: store.resume,\n interrupted: state.interrupted,\n resumable: state.resumable,\n clear: store.clear,\n status: state.status,\n busy: state.busy,\n approval: approval ?? null,\n progress: state.progress,\n answer: store.answer,\n undo: state.undo\n ? {\n messageId: state.undo.messageId,\n available: state.undo.available,\n ...(state.undo.blocked\n ? { blockedCode: state.undo.blocked.code }\n : {}),\n }\n : null,\n undoTurn: store.undoTurn,\n undoAction: store.undoAction,\n alwaysAllowed: state.alwaysAllowed,\n revokeAlwaysAllow: store.revokeAlwaysAllow,\n suggestions: state.suggestions,\n runSuggestion: store.runSuggestion,\n open,\n setOpen,\n error: state.error,\n errorCode: state.errorCode,\n };\n}\n\n/** The hook's options as the store's live inputs. A projection, not a decision. */\nfunction inputsOf(\n options: TableAssistantOptions,\n approval: AgentApprovalPending | null | undefined,\n alwaysAllow: AgentAlwaysAllowState | null | undefined,\n viewState: AgentViewState | null | undefined,\n progress: AgentProgress | null | undefined\n) {\n // The host's own reader wins; otherwise the table's, which is what makes\n // per-turn undo work without a host lifting page and sort into its state.\n const contextInputs =\n options.contextInputs ??\n (viewState ? () => viewState.read() as AgentContextInputs : undefined);\n return {\n session: options.session,\n transport: options.transport,\n transportKey: options.transportKey,\n suggestions: options.suggestions,\n awaitingApproval: options.awaitingApproval,\n approval: approval ?? null,\n progress: progress ?? null,\n ...(contextInputs ? { contextInputs } : {}),\n ...(options.onDetach ? { onDetach: options.onDetach } : {}),\n ...(options.messages ? { messages: options.messages } : {}),\n ...(options.onMessagesChange\n ? { onMessagesChange: options.onMessagesChange }\n : {}),\n ...(options.conversation === undefined\n ? {}\n : { conversation: options.conversation }),\n ...(options.resumeHandle ? { resumeHandle: options.resumeHandle } : {}),\n // The host's own wins, for the same reason `contextInputs` does: a panel\n // beside the table has no feature state to read.\n ...((options.alwaysAllow ?? alwaysAllow)\n ? {\n alwaysAllowed: (options.alwaysAllow ?? alwaysAllow)?.capabilities,\n onRevokeAlwaysAllow: (options.alwaysAllow ?? alwaysAllow)?.revoke,\n }\n : {}),\n };\n}\n","/**\n * Opt-in table feature — `@adapttable/ai-react`.\n *\n * `@adapttable/ai` stays React-free. This package mounts a provider that\n * drives `@adapttable/ai`'s table agent controller from React: it keeps the\n * controller's inputs current, re-renders on its snapshot and the table's\n * changes, and publishes what the controller holds as feature state.\n */\nimport {\n type AgentSession,\n createTableAgentController,\n type TableAgentBridge as NeutralBridge,\n type TableAgentController,\n type TableAgentControllerOptions,\n} from \"@adapttable/ai\";\nimport {\n AGENT_ALWAYS_ALLOW_STATE,\n AGENT_APPROVAL_STATE,\n AGENT_PROGRESS_STATE,\n AGENT_VIEW_STATE,\n type AgentApprovalPending,\n type FeatureProviderProps,\n featureStateKey,\n FeatureStateScope,\n type StaticTableFeature,\n useTableRuntime,\n} from \"@adapttable/react/adapter\";\nimport {\n type ReactNode,\n useCallback,\n useDebugValue,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport { flushSync } from \"react-dom\";\n\nexport type { SharedApproval, TableAgentColumnPatch } from \"@adapttable/ai\";\n\n// The bridge contract is `@adapttable/ai`'s — a manifest, a session and a\n// pending approval are what any binding publishes, none of it React. Named\n// here with this binding's own pending shape so every existing import keeps\n// working.\nexport type TableAgentBridge = NeutralBridge<AgentApprovalPending>;\n\n/**\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 * The same options `@adapttable/ai`'s table agent controller takes: the\n * runtime half — identity, policy, columns, the host's callbacks and\n * capabilities — plus where updates are published and whether the table is\n * offered to a browser-resident agent.\n *\n * @public\n */\nexport type TableAgentOptions = TableAgentControllerOptions;\n\ninterface TableAgentFeature extends StaticTableFeature {\n readonly options: TableAgentOptions;\n}\n\nfunction TableAgentProvider({\n feature,\n children,\n}: Readonly<FeatureProviderProps>): ReactNode {\n const options = (feature as TableAgentFeature).options;\n const runtime = useTableRuntime();\n const optionsRef = useRef(options);\n optionsRef.current = options;\n const runtimeRef = useRef(runtime);\n runtimeRef.current = runtime;\n // A concrete provider update, rather than an empty `flushSync`, makes React\n // finish controlled-state work already queued by the reader before the\n // session takes its admission snapshot.\n const [admissionTick, setAdmissionTick] = useState(0);\n const flushAdmission = useRef<() => void>(() => undefined);\n flushAdmission.current = () => {\n flushSync(() => {\n setAdmissionTick(admissionTick + 1);\n });\n };\n\n // Built once and never during a render that is thrown away twice: the\n // controller opens nothing until `sync`, which only an effect calls.\n const controllerRef = useRef<TableAgentController | null>(null);\n controllerRef.current ??= createTableAgentController({\n options: optionsRef,\n runtime: runtimeRef,\n flushAdmission: () => {\n flushAdmission.current();\n },\n flush: flushSync,\n });\n const controller = controllerRef.current;\n\n // The table as a store: subscribe where there is one to subscribe to, and\n // read the stamp on every render either way. React re-reads the stamp after\n // it attaches, so a table that moved between the render and the\n // subscription is caught rather than missed. The value is not rendered;\n // re-rendering is the point, because that republishes the manifest.\n const neutralTable = runtime.view()?.neutralTable;\n // The controller subscribes to the table current at the call, so a\n // replaced table is a new subscription.\n const subscribeToTable = useCallback(\n (onStoreChange: () => void) =>\n neutralTable ? controller.subscribeTable(onStoreChange) : () => undefined,\n [controller, neutralTable]\n );\n const stamp = useSyncExternalStore(\n subscribeToTable,\n controller.tableStamp,\n controller.tableStamp\n );\n useDebugValue(stamp);\n\n const state = useSyncExternalStore(\n controller.subscribe,\n controller.getState,\n controller.getState\n );\n\n // Every commit: the controller decides what changed and tells only those\n // who need telling. A layout effect, so a host reading the manifest in its\n // own effects already has this render's.\n useLayoutEffect(() => {\n controller.sync();\n });\n\n // Going away is a close. Strict Mode's setup/cleanup/setup lands here too:\n // the cleanup releases everything, and the next sync sets it up again.\n useEffect(\n () => () => {\n controller.disconnect();\n },\n [controller]\n );\n\n // A new value every render on purpose. The table publishes its runtime\n // while its children render, after this provider has, so a surface below\n // learns what the session now offers only by re-rendering with it — and it\n // re-renders because the value it holds is a different one.\n const session = state.session;\n const published: AgentSession = {\n catalog: () => session.catalog(),\n describe: (key) => session.describe(key),\n execute: (key, args, expectedRevision, idempotencyKey, signal) =>\n session.execute(key, args, expectedRevision, idempotencyKey, signal),\n manifest: () => session.manifest(),\n };\n\n return (\n <FeatureStateScope stateKey={TABLE_AGENT_STATE} value={published}>\n <FeatureStateScope stateKey={AGENT_APPROVAL_STATE} value={state.approval}>\n <FeatureStateScope\n stateKey={AGENT_ALWAYS_ALLOW_STATE}\n value={state.alwaysAllow}\n >\n <FeatureStateScope stateKey={AGENT_VIEW_STATE} value={state.view}>\n <FeatureStateScope\n stateKey={AGENT_PROGRESS_STATE}\n value={state.progress}\n >\n {children}\n </FeatureStateScope>\n </FeatureStateScope>\n </FeatureStateScope>\n </FeatureStateScope>\n </FeatureStateScope>\n );\n}\n\n/**\n * Observe a live table and publish a deterministic capability manifest.\n *\n * Omitting this feature from `features` ships no agent bytes.\n *\n * @public\n */\nexport function tableAgent(options: TableAgentOptions): StaticTableFeature {\n const feature: TableAgentFeature = {\n id: \"table-agent\",\n options,\n provider: { Provider: TableAgentProvider },\n };\n return feature;\n}\n","/**\n * Dictation, as a React hook — `@adapttable/ai-react`.\n *\n * Thin on purpose. The controller in `@adapttable/ai/voice` owns the browser\n * APIs, the permission states and the language choice; this subscribes to it,\n * keeps it alive for the life of the composer, and writes what it hears\n * through the caller's `setDraft` — which is the one channel voice is allowed\n * to use, so a spoken sentence becomes a draft the reader can see and fix\n * rather than a request the table has already acted on.\n *\n * It lives here rather than in `@adapttable/react` because it imports\n * `@adapttable/ai`, and that package must stay out of the base graph. The\n * chrome takes `SpeechInputHandle` — the structural shape this returns —\n * from `@adapttable/react/adapter`, which declares it without importing\n * anything.\n */\n\"use client\";\n\nimport {\n createSpeechInput,\n readRememberedLanguage,\n rememberLanguage,\n type SpeechClip,\n type SpeechInput,\n type SpeechState,\n type VoiceOptions,\n} from \"@adapttable/ai/voice\";\nimport type { SpeechInputHandle } from \"@adapttable/react/adapter\";\nimport { 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwRA,SAAgB,kBACd,SACqB;CACrB,MAAM,EAAE,iBAAiB;CACzB,MAAM,CAAC,kBAAkB,uBAAuB,SAAS,KAAK;CAG9D,MAAM,WAAW,gBAAgB,oBAAoB;CAGrD,MAAM,cAAc,gBAAgB,wBAAwB;CAG5D,MAAM,YAAY,gBAAgB,gBAAgB;CAGlD,MAAM,WAAW,gBAAgB,oBAAoB;CAKrD,MAAM,WAAW,OAAuD,IAAI;CAC5E,SAAS,YAAY,qBACnB,SAAS,SAAS,UAAU,aAAa,WAAW,QAAQ,CAC9D;CACA,MAAM,QAAQ,SAAS;CAKvB,gBAAgB;EACd,MAAM,OAAO,SAAS,SAAS,UAAU,aAAa,WAAW,QAAQ,CAAC;CAC5E,CAAC;CAED,gBAAgB;EACd,MAAM,QAAQ;EACd,aAAa;GACX,MAAM,QAAQ;GAId,SAAS,UAAU;EACrB;CAIF,GAAG,CAAC,CAAC;CAEL,MAAM,QAAQ,qBACZ,MAAM,WACN,MAAM,UACN,MAAM,QACR;CAEA,MAAM,OAAO,QAAQ,QAAQ;CAC7B,MAAM,UAAU,aACb,SAAkB;EACjB,IAAI,QAAQ,SAAS,KAAA,GAAW,oBAAoB,IAAI;EACxD,eAAe,IAAI;CACrB,GACA,CAAC,QAAQ,MAAM,YAAY,C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rB,GACA,CAAC,KAAK,CACR;CAEA,MAAM,QAAQ,sBACX,aAAa,OAAO,UAAU,QAAQ,YAAY,KAAA,UAC7C,OAAO,SAAS,KAAK,YACrB,IACR;CAEA,OAAO;EAEL,WAAW,QAAQ,SAAS,OAAO,UAAU,CAAC;EAC9C;EACA;EACA,aAAa,OAAO,MAAM;EAC1B,YAAY,OAAO,KAAK;EACxB,cAAc,aAAa;GACzB,OAAO,YAAY,QAAQ;GAC3B,iBAAiB,QAAQ;EAC3B;CACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@adapttable/ai-react",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.9",
|
|
4
4
|
"description": "React bindings for AdaptTable AI — tableAgent and useTableAssistant.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"react",
|
|
@@ -44,9 +44,9 @@
|
|
|
44
44
|
"./package.json": "./package.json"
|
|
45
45
|
},
|
|
46
46
|
"dependencies": {
|
|
47
|
-
"@adapttable/ai": "0.
|
|
48
|
-
"@adapttable/core": "3.
|
|
49
|
-
"@adapttable/react": "1.3.
|
|
47
|
+
"@adapttable/ai": "0.4.0",
|
|
48
|
+
"@adapttable/core": "3.6.0",
|
|
49
|
+
"@adapttable/react": "1.3.6",
|
|
50
50
|
"react-compiler-runtime": "^1.0.0"
|
|
51
51
|
},
|
|
52
52
|
"peerDependencies": {
|