/** * 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), }, ] }