@adapttable/ai-react 0.2.5 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -4,7 +4,6 @@ let _adapttable_ai = require("@adapttable/ai");
4
4
  let _adapttable_react_adapter = require("@adapttable/react/adapter");
5
5
  let react = require("react");
6
6
  let _adapttable_ai_context = require("@adapttable/ai/context");
7
- let _adapttable_core = require("@adapttable/core");
8
7
  let react_dom = require("react-dom");
9
8
  let react_jsx_runtime = require("react/jsx-runtime");
10
9
  let _adapttable_ai_voice = require("@adapttable/ai/voice");
@@ -132,656 +131,17 @@ function inputsOf(options, approval, alwaysAllow, viewState, progress) {
132
131
  * `@adapttable/ai` stays React-free. This package mounts a provider that
133
132
  * observes the live table and publishes a versioned manifest.
134
133
  */
135
- const PAGE_ONLY_SOURCE = {
136
- fullDataset: false,
137
- grouping: false,
138
- selectAcrossPages: false,
139
- exportScope: "page",
140
- totalCount: "loaded"
141
- };
142
134
  /**
143
135
  * Feature-state key for the live {@link AgentSession}.
144
136
  *
145
137
  * @public
146
138
  */
147
139
  const TABLE_AGENT_STATE = (0, _adapttable_react_adapter.featureStateKey)("table-agent");
148
- function mergeColumn(base, patch) {
149
- const extra = patch?.[base.id];
150
- if (!extra) return base;
151
- return {
152
- ...base,
153
- ...extra
154
- };
155
- }
156
- function cellRecord(row, columns, wanted) {
157
- const record = row && typeof row === "object" ? row : {};
158
- const cells = {};
159
- for (const column of columns) {
160
- if (!column.readable) continue;
161
- if (wanted && !wanted.includes(column.id)) continue;
162
- cells[column.id] = record[column.id];
163
- }
164
- return cells;
165
- }
166
- /**
167
- * `JSON.stringify` that never throws on host rows: a BigInt is written as its
168
- * digits with an `n`, and a value that contains itself is written once, not
169
- * followed back in.
170
- */
171
- function stampJson(value) {
172
- const ancestors = [];
173
- return JSON.stringify(value, function replace(_key, next) {
174
- if (typeof next === "bigint") return `${next.toString()}n`;
175
- if (typeof next !== "object" || next === null) return next;
176
- while (ancestors.length > 0 && ancestors.at(-1) !== this) ancestors.pop();
177
- if (ancestors.includes(next)) return void 0;
178
- ancestors.push(next);
179
- return next;
180
- });
181
- }
182
- function viewRevisionStamp(view) {
183
- const table = view?.neutralTable;
184
- if (table) return (0, _adapttable_ai.monotonicRevision)(table.revisions, void 0).token;
185
- const rows = view?.rows ?? [];
186
- const getRowId = view?.getRowId;
187
- const query = view?.query;
188
- return stampJson({
189
- ids: rows.map((row) => getRowId ? getRowId(row) : null),
190
- payloads: rows,
191
- page: query?.page ?? 1,
192
- limit: query?.limit ?? 10,
193
- search: query?.search ?? "",
194
- sortBy: query?.sortBy,
195
- sortDir: query?.sortDir,
196
- filters: query?.extra,
197
- groupBy: view?.groupingState?.groupBy,
198
- aggregateOverrides: view?.groupingState?.aggregateOverrides,
199
- pinnedColumns: view?.pinning?.columns,
200
- pinnedRows: view?.pinning?.rows,
201
- hiddenColumns: view?.columnLayout?.hidden,
202
- columnOrder: view?.columnLayout?.keys
203
- });
204
- }
205
- function liveReadRows(runtime, columns, query, readMax) {
206
- const table = runtime.view()?.neutralTable;
207
- if (table) return (0, _adapttable_ai.readRowsFromNeutral)(table, columns, query, readMax);
208
- const view = runtime.view();
209
- const rows = (query.scope ?? "visible") === "visible" ? view?.visibleRows ?? view?.rows ?? [] : view?.rows ?? [];
210
- const getRowId = view?.getRowId ?? (() => "");
211
- const hidden = columns.filter((column) => !column.readable).map((c) => c.id);
212
- const limit = Math.max(0, Math.min(query.limit, readMax));
213
- return {
214
- rows: rows.slice(query.offset, query.offset + limit).map((row) => ({
215
- rowKey: getRowId(row),
216
- cells: cellRecord(row, columns, query.columns)
217
- })),
218
- offset: query.offset,
219
- limit,
220
- redacted: hidden
221
- };
222
- }
223
- function liveResolveRow(runtime, ref, scope) {
224
- const table = runtime.view()?.neutralTable;
225
- if (table) return (0, _adapttable_ai.resolveRowFromNeutral)(table, ref);
226
- const view = runtime.view();
227
- const rows = scope === "visible" ? view?.visibleRows ?? view?.rows ?? [] : view?.rows ?? [];
228
- const getRowId = view?.getRowId ?? (() => "");
229
- if ("rowKey" in ref) return {
230
- rowKey: ref.rowKey,
231
- scope
232
- };
233
- const row = rows[ref.position - 1];
234
- if (!row) throw new Error(`no row at 1-based position ${ref.position}`);
235
- return {
236
- rowKey: getRowId(row),
237
- scope: ref.scope,
238
- position: ref.position
239
- };
240
- }
241
- function findRow(runtime, rowKey) {
242
- const table = runtime.view()?.neutralTable;
243
- if (table) return table.rowByKey(rowKey);
244
- const view = runtime.view();
245
- const rows = view?.rows ?? [];
246
- const getRowId = view?.getRowId;
247
- if (!getRowId) return void 0;
248
- return rows.find((row) => getRowId(row) === rowKey);
249
- }
250
- function stampColumnLayout(columns, layout) {
251
- if (!layout) return columns;
252
- const byId = new Map(columns.map((column) => [column.id, column]));
253
- const hidden = new Set(layout.hidden);
254
- return (layout.keys.length > 0 ? layout.keys : columns.map((c) => c.id)).map((id) => {
255
- const existing = byId.get(id);
256
- const visible = !hidden.has(id);
257
- if (existing) return {
258
- ...existing,
259
- visible
260
- };
261
- return {
262
- id,
263
- label: id,
264
- type: "unknown",
265
- readable: true,
266
- writable: false,
267
- sortable: false,
268
- visible
269
- };
270
- });
271
- }
272
- function columnsForRuntime(options, runtime) {
273
- const table = runtime.view()?.neutralTable;
274
- if (table) return (0, _adapttable_ai.agentColumnsFromNeutral)(table, options.columns);
275
- if (!options.columns) return [];
276
- return Object.entries(options.columns).map(([id, extra]) => mergeColumn({
277
- id,
278
- label: extra.label ?? id,
279
- type: extra.type ?? "unknown",
280
- readable: extra.readable ?? true,
281
- writable: extra.writable ?? false,
282
- sortable: extra.sortable ?? false
283
- }, options.columns));
284
- }
285
- function observationPolicy(options) {
286
- const approval = (0, _adapttable_ai.sharedApproval)(options.approval);
287
- return {
288
- ...options.writePolicy ? { writePolicy: options.writePolicy } : {},
289
- approval: approval.policy,
290
- ...approval.presentation ? { presentation: approval.presentation } : {},
291
- ...options.commit ? { commit: options.commit } : {}
292
- };
293
- }
294
- function observationFromRuntime(options, runtime, revision, apply) {
295
- const view = runtime.view();
296
- const table = view?.neutralTable;
297
- const query = view?.query;
298
- const ids = runtime.featureIds();
299
- const pages = serverPagination(view, query);
300
- if (table) {
301
- const live = (0, _adapttable_ai.observationFromNeutral)(table, options, revision, apply, ids, query ? {
302
- page: query.page,
303
- limit: query.limit,
304
- search: query.search,
305
- sortBy: query.sortBy,
306
- sortDir: query.sortDir,
307
- pinnedColumns: view?.pinning?.columns,
308
- pinnedRows: view?.pinning?.rows,
309
- hiddenColumns: view?.columnLayout?.hidden,
310
- columnOrder: view?.columnLayout?.keys
311
- } : void 0);
312
- const sizes = offeredPageSizes(query);
313
- return {
314
- ...live,
315
- columns: stampColumnLayout(live.columns, view?.columnLayout),
316
- pagination: live.pagination ? {
317
- ...live.pagination,
318
- pageSizeOptions: sizes
319
- } : {
320
- ...pages,
321
- pageSizeOptions: sizes
322
- },
323
- groupBy: view?.groupingState?.groupBy,
324
- aggregations: (0, _adapttable_ai.aggregationsFor)(aggregationInputs(view, options)),
325
- availableFilters: (0, _adapttable_ai.agentFiltersFromDefs)(view?.filterDefs, view?.filterRegistry, options.columns),
326
- filters: query?.extra
327
- };
328
- }
329
- const columns = stampColumnLayout(columnsForRuntime(options, runtime).map((column) => mergeColumn(column, options.columns)), view?.columnLayout);
330
- return (0, _adapttable_ai.agentObservation)({
331
- tableId: options.tableId,
332
- viewRevision: revision,
333
- featureIds: ids,
334
- columns,
335
- source: view?.sourceCapabilities ?? PAGE_ONLY_SOURCE,
336
- operations: {
337
- ...(0, _adapttable_react_adapter.deriveRuntimeOperations)(view),
338
- applyView: apply.applyView !== void 0
339
- },
340
- apply: options.apply ?? {},
341
- policy: observationPolicy(options),
342
- view: {
343
- search: query?.search ?? "",
344
- ...query?.sortBy === void 0 ? {} : { sortBy: query.sortBy },
345
- ...query?.sortDir === void 0 ? {} : { sortDir: query.sortDir },
346
- ...view?.groupingState?.groupBy === void 0 ? {} : { groupBy: view.groupingState.groupBy },
347
- ...view?.pinning?.columns ? { pinnedColumns: view.pinning.columns } : {},
348
- ...view?.pinning?.rows ? { pinnedRows: view.pinning.rows } : {},
349
- ...view?.columnLayout?.hidden ? { hiddenColumns: view.columnLayout.hidden } : {},
350
- ...view?.columnLayout?.keys ? { columnOrder: view.columnLayout.keys } : {},
351
- ...query?.extra === void 0 ? {} : { filters: query.extra }
352
- },
353
- pagination: pages,
354
- rowAddressScope: "visible",
355
- readMax: options.readMax ?? 50,
356
- aggregations: (0, _adapttable_ai.aggregationsFor)(aggregationInputs(view, options)),
357
- availableFilters: (0, _adapttable_ai.agentFiltersFromDefs)(view?.filterDefs, view?.filterRegistry, options.columns)
358
- });
359
- }
360
- /**
361
- * What a server-backed table's pages are, from what the source will say.
362
- *
363
- * The total is the server's count for the *current query* — the figure the
364
- * table's own pagination is computed from — and it is published only when the
365
- * source claims to have counted. A source that has not counted keeps an
366
- * unknown total rather than being handed the rows that happen to be loaded,
367
- * and a short page is the one thing it still proves about its own end.
368
- */
369
- /** The sizes the table's own rows-per-page control lists. */
370
- function offeredPageSizes(query) {
371
- const limit = query?.limit ?? 10;
372
- const published = query?.defaultLimit ?? limit;
373
- return (0, _adapttable_core.pageSizeOptions)([limit, published]);
374
- }
375
- function serverPagination(view, query) {
376
- const counted = (view?.sourceCapabilities ?? PAGE_ONLY_SOURCE).totalCount === "exact";
377
- const total = query?.total;
378
- const loaded = view?.rows.length;
379
- return (0, _adapttable_ai.agentPagination)({
380
- page: query?.page ?? 1,
381
- pageSize: query?.limit ?? 10,
382
- pageSizeOptions: offeredPageSizes(query),
383
- ...counted && total !== void 0 ? { totalRows: total } : {},
384
- ...loaded === void 0 ? {} : { loadedRows: loaded },
385
- canJump: query?.setPage !== void 0
386
- });
387
- }
388
- function liveEditCells(runtime, extra, edits) {
389
- if (extra?.editCells) return extra.editCells(edits);
390
- const onCellEdit = runtime.view()?.editing?.onCellEdit;
391
- if (!onCellEdit) throw new Error("editCells is not wired");
392
- for (const edit of edits) {
393
- const row = findRow(runtime, edit.rowKey);
394
- if (!row) throw new Error(`row "${edit.rowKey}" is not in the current view`);
395
- onCellEdit(row, edit.column, edit.value);
396
- }
397
- }
398
- function liveStageCells(runtime, extra, edits) {
399
- if (extra?.stageCells) return extra.stageCells(edits);
400
- const stage = runtime.view()?.editing?.stageCell;
401
- if (!stage) throw new Error("stageCells is not wired");
402
- for (const edit of edits) {
403
- const row = findRow(runtime, edit.rowKey);
404
- if (!row) throw new Error(`row "${edit.rowKey}" is not in the current view`);
405
- stage(row, edit.rowKey, edit.column, typeof edit.value === "string" ? edit.value : String(edit.value));
406
- }
407
- }
408
- function liveSetSelection(runtime, extra, ids) {
409
- extra?.setSelection?.(ids);
410
- if (!extra?.setSelection) runtime.view()?.selection?.replace(ids);
411
- }
412
- function rowScope(ref) {
413
- return "scope" in ref ? ref.scope : "visible";
414
- }
415
- function pickReadRows(runtime, extra, columns, readMax) {
416
- return (query) => {
417
- if (extra?.readRows) return extra.readRows(query);
418
- return liveReadRows(runtime, columns, query, readMax);
419
- };
420
- }
421
- function pickResolveRow(runtime, extra) {
422
- return (ref) => {
423
- if (extra?.resolveRow) return extra.resolveRow(ref);
424
- return liveResolveRow(runtime, ref, rowScope(ref));
425
- };
426
- }
427
- function liveQueryFilters(query) {
428
- return query ? query : {};
429
- }
430
- function applyLiveFilters(query, filters) {
431
- const live = liveQueryFilters(query);
432
- if (!live.setExtras && !live.clearExtras) return false;
433
- if (filters == null) {
434
- live.clearExtras?.();
435
- return true;
436
- }
437
- if (typeof filters !== "object" || Array.isArray(filters)) throw new TypeError("setFilters requires a filter object");
438
- if (Object.keys(filters).length === 0) {
439
- live.clearExtras?.();
440
- return true;
441
- }
442
- live.setExtras?.(filters);
443
- return true;
444
- }
445
- function requireQuery(view, name) {
446
- const fn = view()?.query?.[name];
447
- if (!fn) throw new Error(`${name} is not wired`);
448
- return fn;
449
- }
450
- /**
451
- * What the LIVE TABLE can do, before the host's own callbacks are laid over
452
- * it.
453
- *
454
- * `currentApply` builds `{ ...applyFromRuntime(...), ...options.apply }`, so
455
- * a callback the host supplied is the one that runs. A guard here that
456
- * checked for the same callback would be shadowed by that spread and could
457
- * never fire, which is why the view operations below reach straight for the
458
- * live table. `extra` still travels to the row, edit, stage and selection
459
- * helpers, which read it for their own reasons.
460
- */
461
- function applyFromRuntime(runtime, options, extra) {
462
- const columns = columnsForRuntime(options, runtime);
463
- const readMax = options.readMax ?? 50;
464
- const view = () => runtime.view();
465
- return {
466
- readRows: pickReadRows(runtime, extra, columns, readMax),
467
- resolveRow: pickResolveRow(runtime, extra),
468
- setPage: (page) => {
469
- requireQuery(view, "setPage")(page);
470
- },
471
- setLimit: (limit) => {
472
- requireQuery(view, "setLimit")(limit);
473
- },
474
- setSearch: (search) => {
475
- requireQuery(view, "setSearch")(search);
476
- },
477
- setSort: (key, dir) => {
478
- requireQuery(view, "setSort")(key, dir);
479
- },
480
- setGroupBy: (key) => {
481
- const grouping = view()?.groupingState;
482
- if (!grouping) throw new Error("setGroupBy is not wired");
483
- grouping.setGroupBy(key);
484
- },
485
- setAggregations: (patch) => {
486
- (0, _adapttable_ai.applyAggregations)(aggregationInputs(view(), options), patch);
487
- },
488
- pinColumn: (key, side) => {
489
- const pinning = view()?.pinning;
490
- if (!pinning?.setColumnPin) throw new Error("pinColumn is not wired");
491
- pinning.setColumnPin(key, side);
492
- },
493
- hideColumn: (key, hidden) => {
494
- const layout = view()?.columnLayout;
495
- if (!layout?.setHidden) throw new Error("hideColumn is not wired");
496
- layout.setHidden(key, hidden);
497
- },
498
- moveColumn: (key, toIndex) => {
499
- const layout = view()?.columnLayout;
500
- if (!layout?.move) throw new Error("moveColumn is not wired");
501
- layout.move(key, toIndex);
502
- },
503
- setColumnOrder: (order) => {
504
- const layout = view()?.columnLayout;
505
- if (!layout?.setOrder) throw new Error("setColumnOrder is not wired");
506
- layout.setOrder(order);
507
- },
508
- pinRow: (rowKey, side) => {
509
- const pinning = view()?.pinning;
510
- if (!pinning?.setRowPin) throw new Error("pinRow is not wired");
511
- pinning.setRowPin(rowKey, side);
512
- },
513
- editCells: (edits) => liveEditCells(runtime, extra, edits),
514
- stageCells: (edits) => liveStageCells(runtime, extra, edits),
515
- setSelection: (ids) => liveSetSelection(runtime, extra, ids)
516
- };
517
- }
518
- /**
519
- * The live view and filter catalog, in the shape the context builder takes.
520
- *
521
- * The same values the observation carries, read straight off the runtime so
522
- * the caller does not have to rebuild an observation to get at them. What the
523
- * table cannot answer for is simply absent, and the sanitized view names the
524
- * gap rather than defaulting it.
525
- */
526
- /**
527
- * Column ids whose author asked for live values.
528
- *
529
- * The flag is the author's, so it is read from the contract rather than from
530
- * anything a reader can move. A column the agent may not read is not sampled
531
- * whatever it says — the sampler refuses it too, and asking twice is cheaper
532
- * than a read that comes back empty.
533
- */
534
- function sampledColumns(session) {
535
- return session.manifest().columns.filter((column) => column.readable && column.ai?.sample === true).map((column) => column.id);
536
- }
537
- function viewInputsFromRuntime(runtime, options, samples) {
538
- const view = runtime.view();
539
- const query = view?.query;
540
- const filters = (0, _adapttable_ai.agentFiltersFromDefs)(view?.filterDefs, view?.filterRegistry, options.columns);
541
- const aggregations = (0, _adapttable_ai.aggregationsFor)(aggregationInputs(view, options));
542
- return {
543
- ...filters && filters.length > 0 ? { filters } : {},
544
- ...aggregations ? { aggregations } : {},
545
- ...Object.keys(samples).length > 0 ? { samples } : {},
546
- view: {
547
- ...query?.page === void 0 ? {} : { page: query.page },
548
- ...query?.limit === void 0 ? {} : { limit: query.limit },
549
- ...query?.search === void 0 ? {} : { search: query.search },
550
- ...query?.sortBy ? { sortBy: query.sortBy } : {},
551
- ...query?.sortDir ? { sortDir: query.sortDir } : {},
552
- ...view?.groupingState?.groupBy ? { groupBy: view.groupingState.groupBy } : {},
553
- ...query?.extra ? { filters: query.extra } : {},
554
- ...view?.pinning?.columns ? { pinnedColumns: view.pinning.columns } : {},
555
- ...view?.pinning?.rows ? { pinnedRows: view.pinning.rows } : {},
556
- ...view?.columnLayout?.hidden ? { hiddenColumns: view.columnLayout.hidden } : {},
557
- ...view?.columnLayout?.keys ? { columnOrder: view.columnLayout.keys } : {}
558
- }
559
- };
560
- }
561
- /**
562
- * A row-by-row refusal, with the reader's stated reason when they gave one.
563
- *
564
- * The reason travels with the refusal so the receipt and the model-visible
565
- * result can say why rather than only that.
566
- */
567
- function perItemRefusal(transaction, stated) {
568
- return {
569
- ...(0, _adapttable_ai.settleDecisions)(transaction.decisions, "rejected"),
570
- ...stated ? { reason: stated } : {}
571
- };
572
- }
573
- /** One comparable string for an exclusion list, order-insensitive. */
574
- function exclusionKey(keys) {
575
- return keys ? [...keys].sort((a, b) => a.localeCompare(b)).join("|") : "";
576
- }
577
- /**
578
- * What a capability does to the table, from the live catalog.
579
- *
580
- * Read through the session rather than kept in a list here: the definition is
581
- * the only thing that knows, and it is published on the catalog entry so
582
- * every surface reads the same answer.
583
- */
584
- function capabilityKind(session, capability) {
585
- if (!session || capability === void 0) return void 0;
586
- return session.catalog().find((entry) => entry.key === capability)?.kind;
587
- }
588
- /**
589
- * The opt-in list, with an action's own demand for a human applied.
590
- *
591
- * The shared configuration is what the binding can see directly; an action
592
- * that sets `approval: "required"` is read from the custom definition it was
593
- * declared on, so a capability that must always be confirmed never offers the
594
- * control however the table was configured.
595
- */
596
- function alwaysAllowFor(approval, capabilities, capability) {
597
- const shared = (0, _adapttable_ai.sharedApproval)(approval);
598
- if (capability === void 0) return shared.alwaysAllow;
599
- const definition = capabilities?.find((entry) => entry.key === capability);
600
- return (0, _adapttable_ai.resolveApproval)(shared, definition?.ai).alwaysAllow;
601
- }
602
- /**
603
- * How this binding finds what the person in front of the table may see.
604
- *
605
- * The lookups are React's — only this side knows how to find a row in a
606
- * runtime view. What is done with them is not: the enrichment algorithm lives
607
- * in `@adapttable/ai`, so every binding reports an unreadable column the same
608
- * way rather than each inventing its own blank cell.
609
- */
610
- function readerResolver(runtime, columns) {
611
- const view = runtime.view();
612
- const recordFor = (rowKey) => {
613
- const row = findRow(runtime, rowKey);
614
- return row && typeof row === "object" ? row : void 0;
615
- };
616
- return {
617
- rowLabel: (rowKey) => {
618
- const row = findRow(runtime, rowKey);
619
- return row !== void 0 && view?.rowLabel ? view.rowLabel(row) : void 0;
620
- },
621
- cellValue: (rowKey, column) => recordFor(rowKey)?.[column],
622
- cellText: (rowKey, column, value) => {
623
- const format = (runtime.view()?.groupingState?.columns?.find((entry) => entry.key === column))?.formatValue;
624
- const record = recordFor(rowKey);
625
- if (!format || !record) return void 0;
626
- return format({
627
- ...record,
628
- [column]: value
629
- });
630
- },
631
- readable: (column) => columns?.[column]?.readable !== false,
632
- columnLabel: (column) => columns?.[column]?.label
633
- };
634
- }
635
- /**
636
- * The live table's grouping state, as the neutral rules want it.
637
- *
638
- * A projection, not a decision: it names where the facts are and which
639
- * columns the agent may read. What may be offered and what may be set is
640
- * `@adapttable/ai`'s to answer, so a second binding gets the same answers.
641
- */
642
- function aggregationInputs(view, options) {
643
- return {
644
- state: view?.groupingState,
645
- grouping: view?.sourceCapabilities?.grouping,
646
- allows: (key) => options.columns?.[key]?.readable !== false
647
- };
648
- }
649
- function asCallable(value) {
650
- if (typeof value !== "function") return void 0;
651
- return value;
652
- }
653
- /**
654
- * View mutations whose default implementation belongs to this binding.
655
- *
656
- * They call React-backed runtime setters. Committing those setters before the
657
- * call returns lets the session attribute the resulting table revision to the
658
- * exact apply call that made it. Host overrides are deliberately excluded:
659
- * only the host can say when its own async callback has settled.
660
- */
661
- const BINDING_VIEW_MUTATIONS = /* @__PURE__ */ new Set([
662
- "setPage",
663
- "setLimit",
664
- "setSearch",
665
- "setSort",
666
- "setFilters",
667
- "setGroupBy",
668
- "setAggregations",
669
- "pinColumn",
670
- "hideColumn",
671
- "moveColumn",
672
- "setColumnOrder",
673
- "pinRow",
674
- "setSelection"
675
- ]);
676
- function createRevisionCounter() {
677
- let token;
678
- let revision = 1;
679
- const bumpFromToken = (nextToken) => {
680
- if (token === void 0) {
681
- token = nextToken;
682
- return revision;
683
- }
684
- if (token === nextToken) return revision;
685
- token = nextToken;
686
- revision += 1;
687
- return revision;
688
- };
689
- return {
690
- bumpFrom(revisions) {
691
- return bumpFromToken((0, _adapttable_ai.revisionToken)(revisions));
692
- },
693
- bumpFromStamp(stamp) {
694
- return bumpFromToken(stamp);
695
- },
696
- current() {
697
- return revision;
698
- }
699
- };
700
- }
701
- function currentApply(options, runtime) {
702
- const apply = {
703
- ...applyFromRuntime(runtime, options, options.apply),
704
- ...options.apply
705
- };
706
- apply.setFilters = (filters) => {
707
- if (options.apply?.setFilters) {
708
- options.apply.setFilters(filters);
709
- return;
710
- }
711
- if (!applyLiveFilters(runtime.view()?.query, filters)) throw new Error("setFilters is not wired");
712
- };
713
- return apply;
714
- }
715
- function bindLiveSession(optionsRef, runtimeRef, revisionCounter, flushAdmission, waitForChrome, reportProgress) {
716
- const apply = new Proxy({}, { get(_target, prop) {
717
- if (typeof prop !== "string") return void 0;
718
- if (!(prop in currentApply(optionsRef.current, runtimeRef.current))) return void 0;
719
- return (...args) => {
720
- const options = optionsRef.current;
721
- const fn = asCallable(currentApply(options, runtimeRef.current)[prop]);
722
- if (!fn) return void 0;
723
- const host = options.apply;
724
- if (BINDING_VIEW_MUTATIONS.has(prop) && !asCallable(host?.[prop])) {
725
- let result;
726
- (0, react_dom.flushSync)(() => {
727
- result = fn(...args);
728
- });
729
- return result;
730
- }
731
- return fn(...args);
732
- };
733
- } });
734
- const observe = () => {
735
- const options = optionsRef.current;
736
- if (options.observe) return options.observe();
737
- const runtimeView = runtimeRef.current.view();
738
- const table = runtimeView?.neutralTable;
739
- let viewRevision = revisionCounter.current();
740
- if (table) viewRevision = revisionCounter.bumpFrom(table.revisions);
741
- else if (runtimeView) viewRevision = revisionCounter.bumpFromStamp(viewRevisionStamp(runtimeView));
742
- return observationFromRuntime(options, runtimeRef.current, viewRevision, apply);
743
- };
744
- const onApprove = (subject, signal) => {
745
- const options = optionsRef.current;
746
- if (options.onApprove) return options.onApprove(subject, signal);
747
- return waitForChrome.current(subject, signal);
748
- };
749
- const inner = (0, _adapttable_ai.createAgentSession)({
750
- observe,
751
- apply,
752
- onApprove,
753
- onProgress: (report) => {
754
- reportProgress.current(report);
755
- },
756
- capabilities: [...optionsRef.current.capabilities ?? [], ...(0, _adapttable_ai.tableActionCapabilities)(runtimeRef.current.view()?.actions, {
757
- actions: () => runtimeRef.current.view()?.actions,
758
- rowFor: (rowKey) => {
759
- const view = runtimeRef.current.view();
760
- return view?.rows.find((row) => view.getRowId(row) === rowKey);
761
- },
762
- selectedIds: () => {
763
- const selection = runtimeRef.current.view()?.selection;
764
- return selection ? [...selection.selectedIds] : void 0;
765
- }
766
- })],
767
- ...optionsRef.current.capabilityApproval ? { capabilityApproval: optionsRef.current.capabilityApproval } : {},
768
- ...optionsRef.current.excludeCapabilities ? { excludeCapabilities: optionsRef.current.excludeCapabilities } : {}
769
- });
770
- return {
771
- catalog: () => inner.catalog(),
772
- describe: (key) => inner.describe(key),
773
- execute: async (key, args, expectedRevision, idempotencyKey, signal) => {
774
- flushAdmission.current();
775
- return await inner.execute(key, args, expectedRevision, idempotencyKey, signal);
776
- },
777
- manifest: () => inner.manifest()
778
- };
779
- }
780
140
  /** One open approval, whichever shape the write took. */
781
141
  function TableAgentProvider({ feature, children }) {
782
142
  const options = feature.options;
783
143
  const runtime = (0, _adapttable_react_adapter.useTableRuntime)();
784
- const revisionCounterRef = (0, react.useRef)(createRevisionCounter());
144
+ const revisionCounterRef = (0, react.useRef)((0, _adapttable_ai.createRevisionCounter)());
785
145
  const optionsRef = (0, react.useRef)(options);
786
146
  optionsRef.current = options;
787
147
  const runtimeRef = (0, react.useRef)(runtime);
@@ -796,7 +156,7 @@ function TableAgentProvider({ feature, children }) {
796
156
  const waitForChrome = (0, react.useRef)(() => Promise.resolve(false));
797
157
  const reportProgress = (0, react.useRef)(() => void 0);
798
158
  const tableIdRef = (0, react.useRef)(options.tableId);
799
- const registryKeyOf = (next) => `${exclusionKey(next.excludeCapabilities)}!${JSON.stringify(next.capabilityApproval ?? {})}!${(0, _adapttable_ai.tableActionSignature)(runtime.view()?.actions)}`;
159
+ const registryKeyOf = (next) => `${(0, _adapttable_ai.exclusionKey)(next.excludeCapabilities)}!${JSON.stringify(next.capabilityApproval ?? {})}!${(0, _adapttable_ai.tableActionSignature)(runtime.view()?.actions)}`;
800
160
  const registryRef = (0, react.useRef)(registryKeyOf(options));
801
161
  const registryKey = registryKeyOf(options);
802
162
  const sessionRef = (0, react.useRef)(null);
@@ -804,9 +164,17 @@ function TableAgentProvider({ feature, children }) {
804
164
  tableIdRef.current = options.tableId;
805
165
  registryRef.current = registryKey;
806
166
  sessionRef.current = null;
807
- revisionCounterRef.current = createRevisionCounter();
167
+ revisionCounterRef.current = (0, _adapttable_ai.createRevisionCounter)();
808
168
  }
809
- sessionRef.current ??= bindLiveSession(optionsRef, runtimeRef, revisionCounterRef.current, flushAdmission, waitForChrome, reportProgress);
169
+ sessionRef.current ??= (0, _adapttable_ai.bindLiveSession)({
170
+ options: optionsRef,
171
+ runtime: runtimeRef,
172
+ revisions: revisionCounterRef.current,
173
+ flushAdmission,
174
+ waitForChrome,
175
+ reportProgress,
176
+ flush: react_dom.flushSync
177
+ });
810
178
  const session = sessionRef.current;
811
179
  const [revocations, setRevocations] = (0, react.useState)(0);
812
180
  const [progress, setProgress] = (0, react.useState)(null);
@@ -814,7 +182,7 @@ function TableAgentProvider({ feature, children }) {
814
182
  const pendingRef = (0, react.useRef)(null);
815
183
  const transactionId = (0, react.useRef)(0);
816
184
  const neutralTable = runtime.view()?.neutralTable;
817
- const readStamp = (0, react.useCallback)(() => neutralTable ? (0, _adapttable_ai.revisionToken)(neutralTable.revisions) : viewRevisionStamp(runtime.view()), [neutralTable, runtime]);
185
+ const readStamp = (0, react.useCallback)(() => neutralTable ? (0, _adapttable_ai.revisionToken)(neutralTable.revisions) : (0, _adapttable_ai.viewRevisionStamp)(runtime.view()), [neutralTable, runtime]);
818
186
  const subscribeToTable = (0, react.useCallback)((onStoreChange) => neutralTable ? neutralTable.subscribe("all", onStoreChange) : () => void 0, [neutralTable]);
819
187
  const stamp = (0, react.useSyncExternalStore)(subscribeToTable, readStamp, readStamp);
820
188
  (0, react.useDebugValue)(stamp);
@@ -847,15 +215,15 @@ function TableAgentProvider({ feature, children }) {
847
215
  const capability = subject.kind === "operation" ? subject.capability : void 0;
848
216
  if ((0, _adapttable_ai.mayAlwaysAllow)({
849
217
  capability,
850
- kind: capabilityKind(session, capability),
851
- alwaysAllow: alwaysAllowFor(optionsRef.current.approval, optionsRef.current.capabilities, capability)
218
+ kind: (0, _adapttable_ai.capabilityKind)(session, capability),
219
+ alwaysAllow: (0, _adapttable_ai.alwaysAllowFor)(optionsRef.current.approval, optionsRef.current.capabilities, capability)
852
220
  }) && capability !== void 0 && approvalMemory.current.allows(capability, contractVersion())) return Promise.resolve(true);
853
221
  return new Promise((resolve) => {
854
222
  const rows = subject.kind === "rows";
855
223
  let settled = false;
856
224
  const entry = {
857
225
  ...rows ? {} : { capability: subject.capability },
858
- proposals: rows ? (0, _adapttable_ai.displayProposals)(subject.proposals, readerResolver(runtimeRef.current, optionsRef.current.columns)) : [],
226
+ proposals: rows ? (0, _adapttable_ai.displayProposals)(subject.proposals, (0, _adapttable_ai.readerResolver)(runtimeRef.current, optionsRef.current.columns)) : [],
859
227
  perItem: rows && subject.perItem,
860
228
  ...rows ? {} : { operation: {
861
229
  capability: subject.capability,
@@ -892,7 +260,7 @@ function TableAgentProvider({ feature, children }) {
892
260
  manifest: () => session.manifest()
893
261
  };
894
262
  const samplesRef = (0, react.useRef)({});
895
- const viewStateValue = (0, react.useRef)({ read: () => viewInputsFromRuntime(runtimeRef.current, optionsRef.current, samplesRef.current) }).current;
263
+ const viewStateValue = (0, react.useRef)({ read: () => (0, _adapttable_ai.viewInputsFromRuntime)(runtimeRef.current, optionsRef.current, samplesRef.current) }).current;
896
264
  (0, react.useEffect)(() => {
897
265
  options.bridge?.attach?.(session);
898
266
  options.bridge?.viewInputs?.(viewStateValue.read);
@@ -909,7 +277,7 @@ function TableAgentProvider({ feature, children }) {
909
277
  last.current = encoded;
910
278
  options.bridge?.publish?.(published);
911
279
  });
912
- const sampledKey = sampledColumns(session).join("\0");
280
+ const sampledKey = (0, _adapttable_ai.sampledColumns)(session).join("\0");
913
281
  (0, react.useEffect)(() => {
914
282
  const wanted = sampledKey === "" ? [] : sampledKey.split("\0");
915
283
  if (wanted.length === 0) {
@@ -971,8 +339,8 @@ function TableAgentProvider({ feature, children }) {
971
339
  presentation: transaction.presentation,
972
340
  ...(0, _adapttable_ai.mayAlwaysAllow)({
973
341
  capability: transaction.pending.capability,
974
- kind: capabilityKind(session, transaction.pending.capability),
975
- alwaysAllow: alwaysAllowFor(optionsRef.current.approval, optionsRef.current.capabilities, 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)
976
344
  }) ? { alwaysAllow: () => {
977
345
  const capability = transaction.pending.capability;
978
346
  if (capability === void 0) return;
@@ -983,7 +351,7 @@ function TableAgentProvider({ feature, children }) {
983
351
  reject: (reason) => {
984
352
  const stated = typeof reason === "string" ? reason.trim() : void 0;
985
353
  if (transaction.pending.perItem) {
986
- transaction.pending.resolve(perItemRefusal(transaction, stated));
354
+ transaction.pending.resolve((0, _adapttable_ai.perItemRefusal)(transaction, stated));
987
355
  return;
988
356
  }
989
357
  transaction.pending.resolve(stated ? {