# Agent Tools URL: /editor/agent-tools # Agent Tools [#agent-tools] `arrange_workbench` is Tau's tool for changing what a person sees in the editor. It writes the [portable workbench records](/editor/workbench-records); the page applies them live when the project is open. The tool is available to Tau's agent and to external agents through Tau Host's MCP endpoint, including Codex in Tau Desktop. ## Arrange a view [#arrange-a-view] This input creates a named view of an existing project file and shows it immediately: ```json { "views": [ { "id": "front", "name": "Front", "entryPath": "main.scad", "camera": { "kind": "preset", "preset": "front" } } ] } ``` A view can instead use `{ "kind": "look", "direction": [0, -1, 0] }`; the direction points from the model toward the camera. Other view fields include `fieldOfView` (0 means orthographic), `upDirection`, display toggles, `grid.unit`, section cuts, and pinned measurements. Section and measurement lengths use metres in the model frame. `entries` changes a file's render timeout and component visibility for all its views. `open` adds and activates a view, utility pane, or file tab. A file tab can request markdown `preview` or `source`; opening into a hidden workbench lane reveals it. `close` removes a tab and deletes a closed view's record. `viewer` and `workbench` replace their respective group trees when a full arrangement is intended. `lanes` sets chat and workbench lane intent. Omitted keys retain their current values; a supplied list or lane tree replaces that list or tree. The tool does not control window pixel widths, focus, print approval, physical starts, revision actions, installs, or machine binding. ## Preserve the person's arrangement [#preserve-the-persons-arrangement] The per-turn workbench snapshot includes the layout digest and visible state. Pass its `layoutDigest` as `basedOn` when the change depends on the arrangement you read: ```json { "basedOn": "sha256:", "open": [{ "kind": "file", "path": "docs/review.md", "presentation": "preview" }] } ``` The placeholder is the snapshot digest, not literal input. A stale `basedOn` at the first layout read returns `RECORD_CONFLICT` before writes; a later per-record checked-write conflict may leave earlier writes. Without `basedOn`, it rereads and retries conflicts against current bytes. The tool validates paths and records, then writes at the **live project root** during candidate and MCP turns. An `INVALID_RECORD` refusal preserves the existing file for correction. The other refusal codes are `VALIDATION_ERROR` and `FILE_NOT_FOUND`. A successful result says `status: "written"` and lists record paths with their new and previous digests plus the tabs a window will show. `written` confirms record persistence, which may leave bytes unchanged, rather than that the person has already seen it. The native chat card names the arrangement and shows **Written**, **Shown**, or **Shown partly**; **Restore** is visible without expanding a disclosure. A debug-only pane such as `kernel` or `console` can leave a visible placeholder and appear in the next turn's `refused` snapshot. Read [External Agents](/editor/external-agents) for host setup and [Workbench Records](/editor/workbench-records) for the package codecs and file shapes. # External Agents URL: /editor/external-agents An external agent is a coding CLI you already have installed. Tau starts it, gives it the project, and shows its work in the chat — it does not resell it. ## Supported CLIs [#supported-clis] | Agent | Adapter | CLI | Minimum CLI | | ----------- | ---------------------------------------------- | -------- | ----------- | | Codex | `@agentclientprotocol/codex-acp` 1.7.0 | `codex` | 0.148.0 | | Claude Code | `@agentclientprotocol/claude-agent-acp` 0.70.0 | `claude` | none pinned | | Grok Build | Native ACP (no adapter package) | `grok` | 1.0.41 | An older CLI is refused before the turn starts, naming the version it found. Codex is the qualified path; Claude Code and Grok Build are offered, but their authenticated live turns are not yet qualified. For Grok Build, follow the [official installation instructions](https://docs.x.ai/build/overview), then run `grok login` on the host machine. Tau starts `grok --no-auto-update agent stdio` using that local login. Its native ACP handshake has been verified without credentials. Agents run on a Tau Host: Tau Desktop, or `tau serve` paired with the browser. A browser tab with no host refuses the turn rather than quietly answering it with Tau. Each agent keeps its own configuration directory — `CODEX_HOME`, `CLAUDE_CONFIG_DIR`, or `GROK_HOME`. Tau credentials and provider API keys never reach the child process. ## Where the agent works [#where-the-agent-works] Each chat picks a revision mode, and every turn is recorded as a revision either way. * **Direct** — the agent works in the project folder itself. Its edits are the files you are looking at. * **Candidate** — the host materializes a checkout, the agent works there, and the result comes back as a branch you can review and merge. Tau Desktop and `tau serve` offer both. Chat and run records under `.tau/chats` and `.tau/runs` refuse agent writes; the revision store is hidden. [Workbench records](/editor/workbench-records) differ: `arrange_workbench` writes at the live project root, including candidate turns. The editor applies them, and the card offers Restore. ## What reaches the vendor [#what-reaches-the-vendor] The agent is the vendor's own client, so what it reads it may send. In direct mode that is your project tree. The CAD context Tau adds — the kernel, the open files, the model state — rides the session's first prompt as embedded resources, and is transmitted the same way. ## Billing and sign-in [#billing-and-sign-in] The vendor bills the account you signed that CLI into. Tau charges no credits for an external turn and quotes no price for one: the chat footer names the agent, the model and the vendor's own usage report. Tau surfaces a login; it never brokers one. A logged-out agent refuses with the methods it offers — a terminal command such as `codex login`, or a verification page and code — and the chat shows exactly that. # Editor URL: /editor The Tau editor is a parametric CAD workspace that runs in the browser at [tau.new](https://tau.new). You describe geometry in code, and the editor renders it as you work. A project opens as a dockable panel layout: * **Code editor** — a Monaco editor with code completion. * **3D viewport** — renders the model, with camera, grid, measurement, and section-view controls. * **AI chat** — an assistant that reads and edits project files and runs CAD tools directly. * **Files** — a project file tree with export to standard CAD formats. Geometry evaluation runs on the [Tau runtime](/runtime), which you can also embed in your own applications. Read the runtime documentation to learn the kernels and modeling APIs behind the editor. # Workbench Records URL: /editor/workbench-records # Workbench Records [#workbench-records] `@taucad/workbench` defines the portable files that describe a Tau project's viewer and workbench. The package has no React or Dockview dependency; a host owns file writes, and an open Tau window applies valid changes to the visible workspace. | Live project file | What it controls | | -------------------------------- | ----------------------------------------------------------------------------------------------------- | | `.tau/workbench/layout.json` | Chat and workbench lane intent, viewer groups, and workbench tabs. | | `.tau/workbench/views/.json` | One named viewer view: entry file, camera, display, grid unit, section cuts, and pinned measurements. | | `.tau/workbench/entries.json` | Render timeout and component visibility shared by every view of each entry file. | These version-1 records belong to the **live project root**, including when an agent's code turn works in a candidate checkout. The layout records group weights, not window pixel widths or keyboard focus. Device choices stay local to the window. Named-layout and device schemas are exported for future file shapes; neither has a runtime writer in this release. ## Read a view [#read-a-view] Use the package's path helpers and strict codecs when integrating a file-capable host. A `read` result never rewrites the bytes it received. ```typescript import { workbenchPaths, workbenchRecords } from '@taucad/workbench'; const path = workbenchPaths.view('front'); // .tau/workbench/views/front.json const text = workbenchRecords.view.serialize({ version: 1, entryPath: 'main.scad', name: 'Front', camera: { kind: 'preset', preset: 'front' }, }); const result = workbenchRecords.view.read(new TextEncoder().encode(text)); if (result.status !== 'current') throw new Error(result.message); console.log(path, result.record.name); // .tau/workbench/views/front.json Front ``` `workbenchRecords.layout`, `.view`, and `.entries` validate and serialize the three live shapes. Serialization sorts keys, uses two-space indentation and ends with a newline. A record may be at most 64 KiB. A malformed or unsupported older shape returns `INVALID_RECORD`; a higher `version` returns `NEWER_RECORD`. Both return `invalid-preserved`: keep the original bytes for a person's correction or update instead of replacing them with defaults. Invalid layout bytes offer Reset in the editor; a newer layout asks the person to update Tau without offering Reset. ## How changes appear [#how-changes-appear] A named view such as `Front` appears as `Front · main.scad`. Preset and `look` cameras frame the model; a `look` direction points from the model toward the camera, so `[0, -1, 0]` looks from the front. Lengths in section cuts and measurements are metres in the model frame. The editor adopts record changes from another window or an external file edit, and preserves invalid and newer bytes. Closing a view tab deletes its view record. For changes that depend on the person's current arrangement, use [arrange\_workbench](/editor/agent-tools): it validates the request, writes with checked preconditions, reports conflicts and offers Restore on its chat card. Read [External Agents](/editor/external-agents) for the host and candidate-checkout boundary. # Bundler API URL: /runtime/api/bundler Bundlers resolve imports, transpile code, and produce executable bundles for JS/TS kernel inputs. ## Types [#types] **`EsbuildOptions`** — Public esbuild plugin options. - **`extensions`** (`string[] | undefined`, optional) **`BundlerPlugin`** — Registration object for a bundler plugin. Returned by the package-named alias such as `esbuild` from `@taucad/esbuild`, bound to the canonical `plugin` export. - **`permissions`** (`RuntimePluginPermissions | undefined`, optional) — Declarative review metadata; runtime execution does not enforce these permissions. - **`id`** (`Id`, required) — Unique identifier for this bundler - **`extensions`** (`readonly string[]`, required) — File extensions this bundler handles - **`options`** (`Record | undefined`, optional) — Bundler-specific options **`BundlerDefinition`** — Definition for a bundler module loaded via defineBundler(). Bundler modules are ES modules dynamically imported by the worker runtime. The bundler owns both bundling AND execution because the execution model is inherently tied to the bundler's output format. Detection (detectImports) and production (bundle) are separate operations: - detectImports: discovers what bare specifiers are used (no modules needed) - bundle: produces runnable code (modules must be registered first) This separation eliminates the chicken-and-egg problem: detection runs without modules registered, then the framework selects and initializes the kernel (which registers real modules), then bundle() produces code. Type parameters are inferred automatically: - Context from initialize() return type - Options from optionsSchema (when provided) - **`name`** (`string`, required) — Human-readable bundler name, used in logs and error messages - **`version`** (`string`, required) — Semantic version string for cache-key computation and diagnostics - **`extensions`** (`string[]`, required) — File extensions this bundler handles (e.g., ['ts', 'js', 'tsx', 'jsx']). - **`optionsSchema`** (`z.ZodType> | undefined`, optional) — Zod schema for validating and typing bundler options. Options type is inferred from this schema. - **`initialize`** (`(options: Options, runtime: BundlerInitRuntime) => Promise`, required) — Initialize the bundler. Receives user-provided options plus framework runtime services. - **`detectImports`** (`(input: BundleInput, runtime: BundlerRuntime, context: Context) => Promise`, required) — Detect which bare-specifier modules are imported transitively. Resolves relative imports normally but marks bare specifiers as external. Returns detected modules and project dependencies without producing runnable code. This is the primary mechanism for kernel selection -- no module stubs required. - **`bundle`** (`(input: BundleInput, runtime: BundlerRuntime, context: Context) => Promise`, required) — Produce runnable code with all registered modules resolved. Called AFTER kernel selection and initialization (modules are registered). - **`execute`** (`(input: { code: string; }, runtime: BundlerRuntime, context: Context) => Promise`, required) — Execute bundled code (tied to this bundler's output format). - **`registerModule`** (`(input: { name: string; module: BuiltinModule; }, context: Context) => void`, required) — Register a builtin module for resolution during bundle(). - **`clearExecutionCache`** (`((code: string | undefined, context: Context) => void) | undefined`, optional) — Invalidate cached execution results after source changes. - **`onDispose`** (`((context: Context) => Promise) | undefined`, optional) — Clean up bundler resources (e.g., esbuild.stop()). **`BundlerServices`** — Operation-scoped services supplied to bundler work. - **`signal`** (`AbortSignal`, required) — Cancellation signal owned by the active runtime operation. Fresh for each operation; pass it to cancellable APIs and do not retain it. **`KernelBundler`** — Bundler service exposed to kernels. - **`bundle`** (`(entryPath: string) => Promise`, required) - **`resolveDependencies`** (`(entryPath: string) => Promise`, required) - **`registerModule`** (`(name: string, entry: BuiltinModule) => void`, required) **`BundleResult`** — Result of bundling one entry and its transitive dependencies. - **`code`** (`string`, required) - **`sourceMap`** (`string | undefined`, optional) - **`issues`** (`KernelIssue[]`, required) - **`success`** (`boolean`, required) - **`dependencies`** (`string[]`, required) - **`unresolvedPaths`** (`string[]`, required) ## esbuild [#esbuild] `esbuild()` installs the default esbuild-wasm bundler toolkit. Use `esbuildBundler(options)` only when configuring the role factory directly. Both handle `ts`, `js`, `tsx`, `jsx` by default. ## defineBundler [#definebundler] `defineBundler` creates a `BundlerPluginFactory` from a configuration object. Required methods: `initialize`, `detectImports`, `bundle`, `execute`, `registerModule`. Optional: `clearExecutionCache`, `onDispose`. Operation methods use `(input, runtime, context)`: a `BundleInput`, a `BundlerServices` carrying a fresh operation-scoped `AbortSignal`, and the persistent context returned by `initialize` (which receives a `BundlerInitServices`). `detectImports` returns a `DetectImportsResult`; `execute` returns an `ExecuteResult`. `entryPath` and returned dependency paths are canonical root-relative [runtime paths](/runtime/concepts/path-namespaces). ## Usage [#usage] ```typescript import { createRuntimeClient } from '@taucad/runtime'; import { fromMemoryFs } from '@taucad/runtime/filesystem'; import { inProcessTransport } from '@taucad/runtime/transport/in-process'; import { defineRuntime } from '@taucad/runtime/worker'; import { replicad } from '@taucad/replicad'; import { esbuild } from '@taucad/esbuild'; const runtime = defineRuntime({ plugins: [replicad(), esbuild()], }); const client = createRuntimeClient({ transport: inProcessTransport({ runtime, fileSystem: fromMemoryFs() }), }); ``` ## Related [#related] * [Configure the Bundler](/runtime/guides/bundler-configuration) * [Cooperate with Cancellation](/runtime/guides/cooperate-with-cancellation) * [Plugin System](/runtime/concepts/plugin-system) * [Path Namespaces](/runtime/concepts/path-namespaces) # Client API URL: /runtime/api/client # Client API [#client-api] `createRuntimeClient` connects a transport to a worker-owned runtime definition. Each `RuntimeDocument` owns its evaluation, view subscriptions, and committed export source. ## createRuntimeClient [#createruntimeclient] **`RuntimeClientOptions`** — Runtime client options, including the selected transport. - **`transport`** (`Transport`, required) - **`operationTimeout`** (`number | undefined`, optional) - **`config`** (`RuntimeConfigProvider> | RuntimeConfigProvider & RuntimeForClient> | undefined`, optional) **`RuntimeClientOptionsWithTransport`** — Options for one document client. - **`transport`** (`Transport`, required) - **`operationTimeout`** (`number | undefined`, optional) - **`config`** (`RuntimeConfigProvider> | RuntimeConfigProvider & RuntimeForClient> | undefined`, optional) **`RuntimeClient`** — Public document client; each open document owns its view subscriptions and export pin. - **`machines`** (`RuntimeTransportFacet`, required) - **`jobs`** (`Readonly<{ available: false; reason: "not-granted" | "unsupported"; }>`, required) - **`transport`** (`{ id: TransportId; descriptor: TransportDescriptor>; }`, required) - **`capabilities`** (`RuntimeCapabilities, ClientMiddleware, ClientTranscoders> | undefined`, required) - **`lifecycleState`** (`RuntimeLifecycleState`, required) - **`connect`** (`() => Promise`, required) - **`open`** (`>>(input: OpenInput>) => RuntimeDocument, ClientMiddleware, ClientTranscoders>`, required) - **`describe`** (`>>(input: { source: RuntimeSource; resolution?: ParameterResolutionOptions; signal?: AbortSignal; }) => Promise`, required) - **`setOperationTimeout`** (`(milliseconds: number) => void`, required) - **`setTranscodeTimeout`** (`(milliseconds: number) => void`, required) - **`routesFor`** (`(format: Format) => ReadonlyArray, ClientMiddleware, ClientTranscoders, Format & KnownTargetFormats, ClientTranscoders>>>`, required) - **`bestRouteFor`** (`(format: Format, options?: { kernelId?: string; content?: RuntimeContentInput; }) => ExportRoute, ClientMiddleware, ClientTranscoders, Format & KnownTargetFormats, ClientTranscoders>> | undefined`, required) - **`snapshotSource`** (`>>(input: { source: RuntimeSource; additionalPaths?: ReadonlyArray<{ path: string; required: boolean; }>; signal?: AbortSignal; }) => Promise`, required) - **`transcode`** (`(input: RuntimeTranscodeInput>) => Promise`, required) - **`on`** (`, ClientMiddleware, ClientTranscoders>>(event: Event, handler: ClientEventHandlers, ClientMiddleware, ClientTranscoders>[Event], options?: { signal?: AbortSignal; }) => () => void`, required) - **`terminate`** (`() => void`, required) - **`shutdown`** (`() => Promise`, required) | Option | Default | Contract | | ------------------ | ---------------- | -------------------------------------------------------------------------------------------- | | `transport` | required | A wired transport plugin; materialized once per client. | | `operationTimeout` | `0` | Milliseconds; zero disables. Positive values require a transport that can enforce deadlines. | | `config` | schema-dependent | Boot configuration, or a sync/async provider; inferred from the runtime definition. | ### Usage [#usage] ```typescript import { createRuntimeClient } from '@taucad/runtime/client'; import { fromMemoryFs } from '@taucad/runtime/filesystem'; import { inProcessTransport } from '@taucad/runtime/transport/in-process'; import { defineRuntime } from '@taucad/runtime/worker'; import { replicad } from '@taucad/replicad'; import { esbuild } from '@taucad/esbuild'; const runtime = defineRuntime({ plugins: [replicad(), esbuild()] }); const client = createRuntimeClient({ transport: inProcessTransport({ runtime, fileSystem: fromMemoryFs() }), }); const document = client.open({ source: { files: { 'main.ts': 'import { makeBox } from "replicad"; export default () => makeBox([0,0,0],[1,1,1]);' }, }, }); try { const outcome = await document.evaluation(); if (!outcome.superseded && outcome.evaluation.success) { const view = document.view('model'); try { const rendered = await view.rendering(); if (!rendered.superseded && rendered.rendering.success) { console.log(rendered.rendering.artifact.mimeType, rendered.rendering.hash); } const exported = await document.export('glb'); if (exported.success) { console.log(exported.files[0].name, exported.files[0].bytes.byteLength); } } finally { view.close(); } } } finally { document.close(); await client.shutdown(); } ``` Worker-backed clients import `typeof runtime` as a type witness and use `createWebWorkerClientOptions` or the corresponding Node/Electron transport factory. Executable plugins remain in `defineRuntime` at the host boundary. See [Transport API](/runtime/api/transport). ## Sources and Opening [#sources-and-opening] **`RuntimeSource`** — A document source. - **`files`** (`Files | undefined`, optional) - **`path`** (`string | undefined`, optional) - **`entry`** (`Extract | (Extract & string) | undefined`, optional) **`FilesystemRuntimeSource`** — Root-relative filesystem-backed source. - **`path`** (`string`, required) - **`files`** (`undefined`, optional) - **`entry`** (`undefined`, optional) **`InlineRuntimeSource`** — Inline source with a required entry when multiple literal files are supplied. - **`files`** (`Files`, required) - **`path`** (`undefined`, optional) - **`entry`** (`Extract | (Extract & string) | undefined`, optional) **`OpenInput`** — Opening a source also starts its first evaluation. - **`source`** (`({ source: RuntimeSource; parameters?: Readonly>; stage?: Readonly | string>>; watch?: boolean; signal?: AbortSignal; } & EvaluateOptionsField)["source"]`, required) - **`parameters`** (`({ source: RuntimeSource; parameters?: Readonly>; stage?: Readonly | string>>; watch?: boolean; signal?: AbortSignal; } & EvaluateOptionsField)["parameters"] | undefined`, optional) - **`stage`** (`({ source: RuntimeSource; parameters?: Readonly>; stage?: Readonly | string>>; watch?: boolean; signal?: AbortSignal; } & EvaluateOptionsField)["stage"] | undefined`, optional) - **`watch`** (`({ source: RuntimeSource; parameters?: Readonly>; stage?: Readonly | string>>; watch?: boolean; signal?: AbortSignal; } & EvaluateOptionsField)["watch"] | undefined`, optional) - **`signal`** (`({ source: RuntimeSource; parameters?: Readonly>; stage?: Readonly | string>>; watch?: boolean; signal?: AbortSignal; } & EvaluateOptionsField)["signal"] | undefined`, optional) - **`evaluateOptions`** (`({ source: RuntimeSource; parameters?: Readonly>; stage?: Readonly | string>>; watch?: boolean; signal?: AbortSignal; } & EvaluateOptionsField)["evaluateOptions"] | undefined`, optional) `RuntimeSourceFiles` maps canonical root-relative paths to `RuntimeSourceContent` (text or owned bytes). A single inline file may omit `entry`; multiple literal files require an `entry` matching a key. `source.path` names a file inside the transport's filesystem. See [Path Namespaces](/runtime/concepts/path-namespaces). `open(input)` returns synchronously and starts evaluation, connecting lazily. `watch` defaults to `true`; staged bytes are applied before evaluation. `parameters` are model inputs; `evaluateOptions` belong to the selected kernel. Required kernel option schemas remain required through concrete runtime inference. An opening `signal` closes the document when aborted. `describe({ source, resolution?, signal? })` finds the kernel and parameter manifest without evaluating a model. Its `resolution` is the parameter owner's `ParameterResolutionOptions`. ## RuntimeDocument [#runtimedocument] **`RuntimeDocument`** — A document owns evaluation, view subscriptions and exports. - **`id`** (`string`, required) - **`view`** (`{ (): ViewSubscription, Readonly<{ options?: never; instance?: never; content?: never; }>>; >(id: Id, ...request: RequestArguments>>): ViewSubscription>; }`, required) - **`export`** (` | ExportExtensions | ReachableTarget>(target: Target, ...request: RequestArguments>>) => Promise>>`, required) - **`evaluation`** (`(options?: { signal?: AbortSignal; }) => Promise, ExportIds>>>`, required) - **`update`** (`(update: DocumentUpdate & EvaluateOptionsUpdateField) => Promise, ExportIds>>>`, required) - **`on`** (`{ (event: "described", handler: (description: Description) => void, options?: { signal?: AbortSignal; }): () => void; (event: "evaluated", handler: (evaluation: Evaluation, ExportIds>) => void, options?: { signal?: AbortSignal; }): () => void; (event: "progress", handler: (progress: { phase: string; detail?: Record; }) => void, options?: { signal?: AbortSignal; }): () => void; (event: "status", handler: (status: DocumentStatus) => void, options?: { signal?: AbortSignal; }): () => void; }`, required) - **`close`** (`() => void`, required) **`DocumentUpdate`** — Input to a document update; transient changes never replace committed source. - **`parameters`** (`Readonly> | undefined`, optional) - **`evaluateOptions`** (`Readonly> | undefined`, optional) - **`transient`** (`boolean | undefined`, optional) - **`stage`** (`Readonly>> | undefined`, optional) **`UpdateOutcome`** — Supersession is an ordinary result, while cancellation and timeout reject. - **`superseded`** (`boolean`, required) `evaluation()` reads the current evaluation. `update()` replaces supplied parameter/evaluation option state and optionally stages files. A transient update cannot stage files and never replaces the committed export source. A newer admitted update resolves displaced work as `{ superseded: true }`. Document events are `described` (`Description`), `evaluated` (`Evaluation`), `progress` (`{ phase, detail? }`), and `status` (`DocumentStatus`: `evaluating`, `ready`, `error`, `closed`). `on` returns an unsubscribe function and accepts an optional subscription signal. `close()` is idempotent and closes owned views. ## ViewSubscription [#viewsubscription] **`ViewSubscription`** — A live view that follows each evaluation until closed. - **`view`** (`Id | undefined`, required) - **`request`** (`Request`, required) - **`on`** (`{ (event: "rendered", handler: (rendering: Rendering) => void, options?: { signal?: AbortSignal; }): () => void; (event: "status", handler: (status: ViewStatus) => void, options?: { signal?: AbortSignal; }): () => void; }`, required) - **`rendering`** (`(options?: { signal?: AbortSignal; }) => Promise>`, required) - **`update`** (`(request: Partial) => Promise>`, required) - **`close`** (`() => void`, required) **`DocumentViewRequest`** — View request inferred from the document's registered kernels. - **`options`** (`Readonly> | undefined`, optional) - **`instance`** (`string | null | undefined`, optional) - **`content`** (`Readonly<{ readonly includeEdges?: boolean | undefined; readonly includeTopology?: boolean | undefined; }> | undefined`, optional) **`ViewUpdateOutcome`** — Result of changing one view request. - **`superseded`** (`boolean`, required) `document.view()` follows the first offered view with default options. `document.view(id, request)` selects a declared view and its schema-inferred `options`, supported framework `content`, and optional `instance`. An instance is a named projection such as a schematic sheet; it is separate from a camera angle. `instance: null` resets an instance-capable view to the first offered instance. `rendering()` reads a projection; `update(request)` patches that subscription's request. Each subscription independently follows document evaluations. `rendered` carries `Rendering`; `status` carries `ViewStatus` (`rendering`, `ready`, `error`, `closed`). Closing a subscription releases it without closing its document. Successful evaluations may offer no views. Inspect `evaluation.views` before requesting a default projection. An unknown view produces `VIEW_UNKNOWN`; a declared but unavailable view produces `VIEW_UNAVAILABLE`. A valid evaluation can still contain error-severity issues; inspect every issue before treating the model as clean. ## Exporting [#exporting] **`DocumentExportRequest`** — Direct export request inferred from the document's registered kernels. - **`options`** (`Readonly> | undefined`, optional) - **`content`** (`Readonly<{ readonly includeEdges?: boolean | undefined; readonly includeTopology?: boolean | undefined; }> | undefined`, optional) - **`signal`** (`AbortSignal | undefined`, optional) **`ExportResult`** — An export from the pinned committed evaluation. - **`success`** (`boolean`, required) - **`issues`** (`readonly KernelIssue[]`, required) - **`sourceRevision`** (`Readonly<{ entry: string; files: Readonly>; }> | undefined`, optional) `document.export(target, request?)` exports the pinned committed evaluation, independently of active view options and transient edits. `target` is an export ID, an unambiguous extension, or an available transcoder target. Concrete runtimes infer required `options` and supported `content` for that target; dynamic runtimes validate them at the worker. Success provides a nonempty ordered `files` tuple, `exportId`, `evaluationId`, and optional `sourceRevision`. `WideViewRequest` and `WideExportRequest` describe dynamic requests whose option/content validation occurs at the worker. `routesFor(format)` returns routes in manifest order after connection. `bestRouteFor(format, { kernelId?, content? })` filters by kernel/content, then prefers BRep fidelity and direct routes. Check `Evaluation.exports` for the current model's offered direct exports; static declarations do not guarantee a result offers every export. `client.transcode({ from, to, files, options, signal? })` converts caller-owned files without opening a document. Its `TranscodeResult` uses `data`; document `ExportResult` uses `files`. ## Boot Configuration [#boot-configuration] A configured `defineRuntime` receives `RuntimeConfigOutput` from its Zod schema. The client accepts `RuntimeConfigInput` via `RuntimeConfigProvider`: a value or sync/async provider. Required schemas make `config` required; schemas accepting `undefined` make it optional. Static definitions reject `config`. Invalid configuration rejects with `RuntimeConfigError` (`RUNTIME_CONFIG_INVALID`); use `isRuntimeConfigError` to narrow it. The worker subpath exports `createRuntimeWorker`, `CreateRuntimeWorkerOptions`, `resolveRuntimeDefinition`, `RuntimeDefinition`, `RuntimeDefinitionOptions`, `AnyRuntimeDefinition`, and the projections `RuntimeKernels`, `RuntimeMiddleware`, `RuntimeBundlers`, `RuntimeTranscoders`. Node's `createNodeClient` accepts `NodeRuntimeClientOptions` and selects `fromNodeFs(projectPath)` or `fromMemoryFs()`. ## Source Snapshots [#source-snapshots] `snapshotSource` accepts `RuntimeSourceSnapshotInput`: source, optional `additionalPaths` (`RuntimeSourceSnapshotAdditionalPath`: path plus required flag), and signal. `RuntimeSourceSnapshotResult` contains `RuntimeSourceSnapshotData`: `entryPath`, `kernelId`, unresolved paths, and `RuntimeSourceSnapshotFile` records of owned bytes, hashes, and `RuntimeSourceSnapshotFileRole` (`entry`, `kernel-dependency`, `middleware-dependency`, `additional`). It collects source closure without geometry computation. ## Deadlines and Errors [#deadlines-and-errors] `setOperationTimeout(milliseconds)` synchronously changes the deadline for subsequent operations. Zero disables it; negative or nonfinite values are rejected. It covers description, evaluation, view rendering, and document exports. `setTranscodeTimeout(milliseconds)` separately sets direct conversion deadlines; the default is `60_000`. Existing operations retain their admitted deadline. | Error | Stable code | Meaning | | ------------------------ | --------------------------- | --------------------------------------------------------------------------- | | `OperationAbortedError` | `RUNTIME_OPERATION_ABORTED` | Explicit cancellation or reading a closed handle. | | `OperationTimeoutError` | `RUNTIME_OPERATION_TIMEOUT` | The admitted wall-clock deadline expired; `phase` identifies the operation. | | `RuntimeTerminatedError` | `RUNTIME_TERMINATED` | Explicit client termination or transport loss; pending operations reject. | `RuntimeTerminatedError.causeKind` is a `RuntimeTerminatedCause`: `explicit`, `transport-closed`, or `operation-timeout`. Its optional `detail` is `RuntimeTerminatedDetail`, preserving host exit phase, exit code, reason, resource release and stderr tail when available. Pending and subsequent operations retain the first terminal failure. `SharedPoolEntryNotFoundError` identifies unavailable pooled bytes; narrow it with `isSharedPoolEntryNotFoundError`. Use `isOperationAbortedError`, `isOperationTimeoutError`, or `isRuntimeTerminatedError` across realms. Model failures resolve as `success: false` with `KernelIssue` records. Supersession resolves normally; it is separate from operational rejection. A noncooperative isolated host may be terminated after bounded deadline recovery; create a new client after termination. ## Client Lifecycle and Events [#client-lifecycle-and-events] `RuntimeLifecycleState` advances through `unconnected`, `connecting`, `connected`, and `terminated`. `connect()` is idempotent and takes no arguments; explicit connection allows capability discovery before opening a document. `terminate()` initiates teardown; `shutdown()` awaits transport closure. Both settle owned pending work and remove subscriptions. | Client event | Payload | | -------------- | ------------------------------------------------ | | `capabilities` | `CapabilitiesManifest` | | `state` | `idle`, `busy`, or `error`, with optional detail | | `log` | `LogEntry` | | `telemetry` | `TelemetryBatch` | | `error` | Connection-scoped `KernelIssue` records | Model/projection events belong to documents/views. `LogEntry` includes level (`LogLevel`; `logLevels`), timestamp, message, optional `LogOrigin` and data. `RuntimeCapabilities` combines the manifest with transport information. `machines` and `jobs` expose availability facets; inspect the facet before accessing its client. ## Related [#related] * [Live Rendering](/runtime/guides/live-rendering) * [Handle Errors](/runtime/guides/error-handling) * [Transport API](/runtime/api/transport) * [Core Types](/runtime/api/types) # Compute Reuse API URL: /runtime/api/compute-store # Compute Reuse API [#compute-reuse-api] Import compute contracts from `@taucad/runtime/types`, IndexedDB and memory factories from `@taucad/runtime/host`, and SQLite factories from `@taucad/runtime/node`. A `ComputeBinding` is `off`, `memory`, or `durable` with an opaque `ComputeStore`. `off` installs no reuse hook; a library omission defaults to memory. Only the owning host creates a durable store handle, using `fromIndexedDb` or `fromSqlite`. ## Store sessions [#store-sessions] `ComputeStoreEngine.open` yields a fresh `ComputeStoreSession` for one workspace. The session exposes batched `get`, `put`, `pin`, `release`, and `close`; it carries a `ComputeGeneration` that changes on clear. `ComputeStoreEntry` couples a canonical action and action digest to bytes, content digest, media type, required content, and byte-exact or equivalent determinism. `ComputeGetInput` bounds requested digests and fetch size; `ComputeGetResult` separates returned entries from missing, poisoned, or budget-omitted identities. `ComputePutInput` publishes a batch with a generation and disposable or required durability. `ComputePutResult` reports committed entries, conflicts, quota, unavailable storage, or a stale generation. Equivalent divergence keeps the first writer; byte-exact divergence poisons the identity. A stale generation means the caller must not treat old reusable bytes as current. `ComputePinInput` and `ComputePinResult` promote known entries to required durability. Required work needs an authorized `ComputeRetention` owner; `no-durable-storage` is not a success. `ComputeReleaseInput` releases that owner's recovered roots. Host-only `ComputeStoreControl` offers inspect, clear, and collection. `ComputeStoreReport` separates logical and pinned bytes from physical byte measurements whose status may be unsupported. ## Kernel scope and resident cache [#kernel-scope-and-resident-cache] `KernelComputeCapability` is the kernel-facing reuse contract. A runtime opens it with `OpenComputeScopeInput` and closes with `CloseComputeScopeInput`; cancellation publishes nothing. `ComputeAnnouncement` identifies an action and provisional cost synchronously. `ComputeAnnounceResult` records admission; `ComputeWarmInput` and `ComputeWarmResult` provide a bounded fetch after authority checks. `ComputeScopeReceipt` settles once as `ComputeScopeSettlement`; `ComputeReuseScope` owns the per-operation tail. `BuildReuse` distinguishes eligible work from a reasoned ineligible result. A kernel's `ResidentCacheBinding` imports and exports native entries within its own lifetime. `ResidentExportEntry` has a content identity; `ResidentCacheStats` reports logical charges, codec bytes, and unsupported native-memory measurements separately. The host store is not a native-object cache. ## Backends and channels [#backends-and-channels] `createMemoryComputeEngine` returns a `MemoryComputeEngine` for non-durable use. `createIndexedDbComputeEngine` accepts `IndexedDbComputeEngineOptions` and returns an `IndexedDbComputeEngine`; `createSqliteComputeEngine` likewise takes `SqliteComputeEngineOptions` and returns a `SqliteComputeEngine`. `fromIndexedDb` and `fromSqlite` wrap authority-owned backends as opaque store bindings. `connectComputeStoreChannel` and `exposeComputeStoreChannel` connect a session over a host-controlled channel. The Node SQLite worker path uses `connectSqliteComputeStoreWorker`, `SqliteComputeWorker`, `serveSqliteComputeStoreWorker`, `SqliteComputeWorkerConnect`, and `sqliteComputeWorkerConnectType`. These carry store requests; they do not grant filesystem authority by themselves. ## Related [#related] * [Transport API](/runtime/api/transport) * [Runtime architecture](/runtime/concepts/architecture) # Configuration API URL: /runtime/api/configuration # Configuration API [#configuration-api] Import the configuration contracts from `@taucad/runtime/configuration`. The Zod quantity helper has its own `@taucad/runtime/configuration/zod` entry point. A configuration has a trusted Standard Schema for validation and a bounded, serializable manifest for display and transport. The manifest's form hints do not validate submitted values. ## Definition and validation [#definition-and-validation] `defineConfiguration` accepts a `ConfigurationSource`: an `id`, `version`, Standard Schema, optional defaults, and restricted UI metadata. Non-Standard-JSON schemas also require a JSON Schema converter. It returns a `ConfigurationDefinition` containing the frozen `ConfigurationManifestV1`, canonical manifest text, diagnostics, schema, and asynchronous `manifestDigest()`. `validateConfiguration` takes `ValidateConfigurationInput`: definition, matching manifest digest, monotonically tracked form revision, raw value, explicit RFC 6901 pointers, and optional abort signal. `ValidateConfigurationResult` is discriminated by `type`: `valid` carries the parsed output and effective digest; `invalid` carries `ConfigurationIssue` values with code, message, and pointer. Keep the returned revision and digest with the form result so a late validation cannot overwrite a newer edit. `admitConfigurationManifest` parses an untrusted manifest into `ConfigurationAdmissionResult`, including cosmetic `ConfigurationAdmissionDiagnostic` entries. Admission checks the wire shape; it does not replace authoritative validation against the trusted definition. `admitJsonSchema` bounds and admits the `JsonSchema` used by the manifest and provider descriptors. ## Native parameter projection and UI hints [#native-parameter-projection-and-ui-hints] `ConfigurationManifestV1.parameters` has input and output `ConfigurationNativeProjection` values. A `usable` projection carries a `ParameterDeclaration` (exported from `@taucad/runtime/kernel`); an `unsupported` projection carries defaults and `ConfigurationNativeProjectionDiagnostic` reasons. Inspect the status before presenting a native parameter editor. The manifest also carries a draft-07 legacy projection. `RestrictedRjsfUiSchemaV1` wraps a JSON-only `RestrictedUiNodeV1`. Its `RestrictedUiWidgetV1` values are `color`, `radio`, `segmented`, `select`, `slider`, `textarea`, and `toggle`. `configurationIconIds` is the admitted icon vocabulary; `ConfigurationIconId` types its members. Unsupported icon hints produce a compatibility diagnostic rather than granting executable behavior. Import `quantity` and `QuantitySchemaOptions` from `@taucad/runtime/configuration/zod` to declare unit-bearing numeric fields. Import `quantityKinds` from `@taucad/units/quantity` for the reviewed quantity-kind identities. Use the declared units at the authority boundary, not a UI-only conversion. Import `SourceRevision` and `GetParameterDeclarationsResult` from `@taucad/runtime/types`. The former identifies the source state used by a runtime operation; the latter carries declarations resolved for that source. Consumers should not reuse them after the source changes. ## Related [#related] * [Kernel parameter declarations](/runtime/api/kernels) * [Custom kernel guide](/runtime/guides/custom-kernel) # Electron Runtime API URL: /runtime/api/electron # Electron Runtime API [#electron-runtime-api] Electron entry points are process-specific: `@taucad/runtime/electron/main`, `/preload`, `/renderer`, and `/utility`. Main owns the utility fork and releases its lease; the renderer receives a transferred port rather than permission to spawn a process. Import `getIsolationStatus` from `@taucad/runtime/cross-origin-isolation` to check whether the host has the isolation needed for shared-memory capabilities before enabling such a topology. ## Main broker and exits [#main-broker-and-exits] `registerElectronRuntimeMain` installs the IPC broker. An optional `ElectronRuntimeForkResolver` maps a sanitized renderer context to an application-owned utility entry, environment allowlist values, rooted filesystem port, and compute binding. `ElectronRuntimeMainConnectInput` is the privileged main-process request; the resulting `ElectronRuntimeMainConnection` owns a port, an exit promise, and idempotent disposal. `ElectronRuntimeHostExit` distinguishes a main-requested release from an unexplained process exit and may include bounded stderr. `ElectronRuntimeUtilityExit` adds the broker host id. `ElectronRuntimeUtilityLimitError` refuses a fork beyond the configured cap; it does not represent a crashed worker. ## Port relay and utility client [#port-relay-and-utility-client] `relayElectronPorts` installs the preload bridge. `awaitElectronRelayedPort` waits for the renderer's matching request and transferred port. `electronUtilityMainClient` accepts `ElectronUtilityMainClientOptions` for a main-brokered port used by another utility; `electronUtilityMainTransport` wraps that client as a transport plugin. The `/utility` export `serveElectronFileSystemBridgePort` and the `/filesystem` export `createFileSystemBridgePort` connect a host-minted rooted filesystem capability over an admitted port. A port alone is not a filesystem path grant. ## Related [#related] * [Transport API](/runtime/api/transport) * [Embedding in a host](/runtime/guides/embedding-in-a-host) # Filesystem API URL: /runtime/api/filesystem Runtime supports Node.js, browser, memory, confined fs-compatible, and cross-worker bridge filesystems. ## Filesystem Types [#filesystem-types] **`RuntimeFileSystemBase`** — Base filesystem interface for runtime backends. Aliases the canonical {@link FileSystemProvider} from `@taucad/filesystem` augmented with an optional `watch` subscription. Filesystem backends authored for the runtime (e.g. `fromFsLike`, `fromMemoryFs`, `fromNodeFs`) implement this shape; the runtime upgrades it into a {@link KernelFileSystem} at the worker boundary via the runtime's internal decorator. Paths are canonical and root-relative within the supplied runtime filesystem; `''` refers to that filesystem's root. - **`id`** (`string`, required) - **`capabilities`** (`ProviderCapabilities`, required) - **`supportsHeadListing`** (`true | undefined`, optional) — Explicit opt-in to head-only listing; absent on exact-only legacy providers. - **`readdirWithStats`** (`{ (path: string): Promise; (path: string, options: { readonly content: "head"; }): Promise>>; } | undefined`, optional) — Optional batched listing. Omission returns exact metadata; `head` omits unknown line counts. - **`readFile`** (`{ (path: string): Promise>; (path: string, encoding: "utf8"): Promise; }`, required) - **`writeFile`** (`(path: string, data: Uint8Array | string) => Promise`, required) — Persist a file, creating any missing parent directories. - **`writeFileChecked`** (`((input: Omit) => Promise) | undefined`, optional) — Atomically check current bytes and replace one file when this provider owns a real authority fence. - **`deleteFileChecked`** (`((input: { path: string; preconditions: readonly FileWritePrecondition[]; }) => Promise) | undefined`, optional) — Atomically check current bytes and delete one file under the same authority fence. - **`appendFile`** (`((path: string, data: Uint8Array | string) => Promise) | undefined`, optional) — Append bytes in enqueue order, creating the file and missing parent directories when absent. - **`readdir`** (`(path: string) => Promise`, required) - **`stat`** (`(path: string) => Promise`, required) - **`mkdir`** (`(path: string, options?: { recursive?: boolean; }) => Promise`, required) - **`unlink`** (`(path: string) => Promise`, required) - **`rmdir`** (`(path: string) => Promise`, required) - **`rename`** (`(from: string, to: string) => Promise`, required) - **`exists`** (`(path: string) => Promise`, required) - **`lstat`** (`(path: string) => Promise`, required) - **`getFileMode`** (`((path: string) => Promise) | undefined`, optional) — Read a regular file's Git-compatible executable mode when the backend exposes it. - **`setFileMode`** (`((path: string, mode: FileMode) => Promise) | undefined`, optional) — Apply a Git-compatible regular-file mode without exposing an unrestricted chmod seam. - **`dispose`** (`() => void`, required) - **`readFileStream`** (`((path: string, options?: FileReadStreamOptions) => ReadableStream>) | undefined`, optional) — Optional streaming read. When present, service routes through this instead of buffered readFile. - **`readdirEntries`** (`((path: string) => Promise) | undefined`, optional) — Optional readdir carrying entry kinds. When present, tree walks skip the stat-per-child. - **`refresh`** (`((prefixes?: readonly string[]) => Promise) | undefined`, optional) — Refresh provider projections after an out-of-band mutation. Pass the absolute paths whose subtrees changed to scope the invalidation; omit them to drop everything. - **`observe`** (`((listener: (facts: readonly ExternalChangeFact[]) => void) => Promise<(() => void) | undefined>) | undefined`, optional) — Report this root's own external changes. Declared only by a backend that can observe itself; the authority falls back to bounded snapshot polling for one that cannot, so capability presence — never backend identity — decides how a root is watched (charter D13). Resolves with a disposer, or with `undefined` when observation exists in principle but could not be armed here and polling must cover the root. A rejection means the root has no fallback and its derivatives are stale. - **`watch`** (`((request: RuntimeWatchRequest, handler: (event: RuntimeWatchEvent) => void) => () => void) | undefined`, optional) — Subscribe to filesystem change events for the given paths. Returns an unsubscribe function. Events are filtered server-side. **`KernelFileSystem`** — Enhanced filesystem interface seen inside kernel/bundler/middleware code. Extends the base primitives with higher-level helper methods built from the primitives by the runtime's internal decorator. Provider watch stays on the transport boundary and is not exposed through this kernel-facing facade. Distinct from the consumer-facing opaque `RuntimeFileSystem` value (`#filesystem/runtime-filesystem.js`) produced by `from*` factories and handed to a transport plugin's `client({ fileSystem })`; the transport unwraps the opaque value and upgrades the backing `RuntimeFileSystemBase` inside the runtime worker. Renamed from `RuntimeFileSystem` (R14) to disambiguate from the consumer-facing opaque brand. The `KernelFileSystem` name is exported only from the kernel-author subpath `@taucad/runtime/kernel`; the consumer barrel reserves `RuntimeFileSystem` for the opaque value. All methods operate on paths within the supplied runtime filesystem. - **`id`** (`string`, required) - **`capabilities`** (`ProviderCapabilities`, required) - **`supportsHeadListing`** (`true | undefined`, optional) — Explicit opt-in to head-only listing; absent on exact-only legacy providers. - **`readdirWithStats`** (`{ (path: string): Promise; (path: string, options: { readonly content: "head"; }): Promise>>; } | undefined`, optional) — Optional batched listing. Omission returns exact metadata; `head` omits unknown line counts. - **`readFile`** (`{ (path: string): Promise>; (path: string, encoding: "utf8"): Promise; }`, required) - **`writeFile`** (`(path: string, data: Uint8Array | string) => Promise`, required) — Persist a file, creating any missing parent directories. - **`writeFileChecked`** (`((input: Omit) => Promise) | undefined`, optional) — Atomically check current bytes and replace one file when this provider owns a real authority fence. - **`deleteFileChecked`** (`((input: { path: string; preconditions: readonly FileWritePrecondition[]; }) => Promise) | undefined`, optional) — Atomically check current bytes and delete one file under the same authority fence. - **`appendFile`** (`((path: string, data: Uint8Array | string) => Promise) | undefined`, optional) — Append bytes in enqueue order, creating the file and missing parent directories when absent. - **`readdir`** (`(path: string) => Promise`, required) - **`stat`** (`(path: string) => Promise`, required) - **`mkdir`** (`(path: string, options?: { recursive?: boolean; }) => Promise`, required) - **`unlink`** (`(path: string) => Promise`, required) - **`rmdir`** (`(path: string) => Promise`, required) - **`rename`** (`(from: string, to: string) => Promise`, required) - **`exists`** (`(path: string) => Promise`, required) - **`lstat`** (`(path: string) => Promise`, required) - **`getFileMode`** (`((path: string) => Promise) | undefined`, optional) — Read a regular file's Git-compatible executable mode when the backend exposes it. - **`setFileMode`** (`((path: string, mode: FileMode) => Promise) | undefined`, optional) — Apply a Git-compatible regular-file mode without exposing an unrestricted chmod seam. - **`dispose`** (`() => void`, required) - **`readFileStream`** (`((path: string, options?: FileReadStreamOptions) => ReadableStream>) | undefined`, optional) — Optional streaming read. When present, service routes through this instead of buffered readFile. - **`readdirEntries`** (`((path: string) => Promise) | undefined`, optional) — Optional readdir carrying entry kinds. When present, tree walks skip the stat-per-child. - **`refresh`** (`((prefixes?: readonly string[]) => Promise) | undefined`, optional) — Refresh provider projections after an out-of-band mutation. Pass the absolute paths whose subtrees changed to scope the invalidation; omit them to drop everything. - **`observe`** (`((listener: (facts: readonly ExternalChangeFact[]) => void) => Promise<(() => void) | undefined>) | undefined`, optional) — Report this root's own external changes. Declared only by a backend that can observe itself; the authority falls back to bounded snapshot polling for one that cannot, so capability presence — never backend identity — decides how a root is watched (charter D13). Resolves with a disposer, or with `undefined` when observation exists in principle but could not be armed here and polling must cover the root. A rejection means the root has no fallback and its derivatives are stale. - **`readFiles`** (`(paths: string[]) => Promise>>`, required) — Batch-read multiple files as binary. Default: `Promise.all(paths.map(readFile))`. - **`readdirContents`** (`(directoryPath: string) => Promise>>`, required) — Read all file contents in a directory (skips subdirectories). - **`readdirStat`** (`(directoryPath: string) => Promise`, required) — Get stat information for all entries in a directory. - **`ensureDir`** (`(path: string) => Promise`, required) — Ensure a directory exists, creating parents as needed. Default: `mkdir(path, { recursive: true })`. **`RuntimeFileSystem`** — Opaque consumer-facing filesystem handle. Reaching into the value to inspect the underlying handle is a type error: the brand is unexported, so consumer code cannot construct a matching value. _No properties._ **`FsLike`** — Minimal interface for any fs-compatible object with a `promises` namespace. Matches the shape of `fs` from BrowserFS, memfs, and similar libraries without importing them directly. Uses `ArrayBuffer`-backed bytes at the runtime boundary so transfer ownership remains explicit and does not accidentally include shared memory. - **`promises`** (`{ readFile(path: string, encoding: "utf8"): Promise; readFile(path: string): Promise>; writeFile(path: string, data: Uint8Array | string): Promise; mkdir(path: string, options?: { recursive?: boolean; }): Promise; readdir(path: string): Promise; unlink(path: string): Promise; rmdir(path: string): Promise; rename(oldPath: string, newPath: string): Promise; stat(path: string): Promise; lstat(path: string): Promise; }`, required) — Filesystem methods that receive paths within this already-confined filesystem. Runtime `/` is its root. Kernel I/O methods use the shared entry and event types: `FileEntry`, `FileStat`, `FileStatEntry`, `FileTreeEntry`, and `FileStatus` describe listings and stats; watch callbacks receive `ChangeEvent` values carrying a `ChangeEventStat`. `isRuntimeFileSystem` guards an opaque handle; `isNotFoundError` classifies read failures; `runtimeFileSystemSchema` is the Zod validator for the kernel-facing method surface. ## Constructors [#constructors] | Function | Import Path | Description | | ---------------------------- | ------------------------------------ | --------------------------------------------------------- | | `fromNodeFs(basePath)` | `@taucad/runtime/filesystem/node` | Node.js filesystem rooted at `basePath` | | `fromBrowserFs(root)` | `@taucad/runtime/filesystem/browser` | Browser directory handle used as the runtime root | | `fromMemoryFs(files?)` | `@taucad/runtime/filesystem` | In-memory Map-backed filesystem, optionally seeded | | `fromFsLike(fs)` | `@taucad/runtime/filesystem` | An already-confined virtual filesystem | | `fromFileSystemBridge(open)` | `@taucad/runtime/filesystem` | A fresh rooted bridge connection for each runtime binding | Every constructor establishes the root of the [runtime-path namespace](/runtime/concepts/path-namespaces). Filesystem method arguments are root-relative, so `main.ts` refers to a file beneath the supplied root and `''` refers to the root itself. ## Bridge Types [#bridge-types] **`FileSystemBridge`** — Handle returned by {@link createFileSystemBridge}: same-isolate {@link Port} for bridge clients. - **`port`** (`Port`, required) — Wire-agnostic port for RPC clients in this isolate. - **`dispose`** (`() => void`, required) **`FileSystemBridgeOptions`** — Options for configuring the filesystem bridge message type. - **`messageType`** (`string | undefined`, optional) - **`uiCoalescingWindow`** (`number | undefined`, optional) — Coalescing window for UI-bound fileChanged events (default: 500). Milliseconds. - **`createCoalescer`** (`CoalescerFactory | undefined`, optional) — Factory for creating a change event coalescer. When provided, events from `changeEventBus` are batched before broadcasting to bridge clients. When omitted, events pass through without batching. - **`root`** (`string | undefined`, optional) — The workspace surface: no root, and therefore no view to name. Project mount to expose as `/` for this connection. The root is consumed by the filesystem server when the connection is accepted; it is never forwarded to runtime calls. - **`consumer`** (`RootedBridgeConsumer | undefined`, optional) — Which surface this rooted connection reads; required beside a root (CI2). **`ExposeFileSystemHandle`** — Handle returned by {@link exposeFileSystem} for managing bridge connections and cleanup. - **`cleanup`** (`() => void`, required) - **`activePorts`** (`Set`, required) - **`serverHandles`** (`Map`, required) `fromFileSystemBridge` returns a `FileSystemBridgeConnection`; `BridgePort` and `BridgeServerHandle` support host adapters. ## Bridge Utilities [#bridge-utilities] For cross-worker filesystem access, `@taucad/runtime/filesystem` provides the filesystem-specific authority boundary: | Function | Description | | ------------------------------------------ | --------------------------------------------------------------------------------------------------- | | `exposeFileSystem(handlers, options?)` | Listen in the filesystem-owning worker; expose an authority as `workspaceBridgeService(service)`. | | `openFileSystemBridge(worker, options?)` | Open a fresh scoped connection for `fromFileSystemBridge`; use this for runtime transport wiring. | | `createFileSystemBridge(worker, options?)` | Open a managed filesystem bridge when the current isolate also needs to call filesystem methods. | | `createFileSystemBridgeProxy(bridge)` | Create the validated filesystem proxy from the managed bridge returned by `createFileSystemBridge`. | ## Bridge Usage [#bridge-usage] Trusted host code selects an authority route once and supplies a connection factory. The runtime sees only the rooted project's writable local namespace: ```typescript import { fromFileSystemBridge, openFileSystemBridge } from '@taucad/runtime/filesystem'; const fileManagerWorker = new Worker(new URL('./file-manager.worker.ts', import.meta.url), { type: 'module' }); const fileSystem = fromFileSystemBridge(() => openFileSystemBridge(fileManagerWorker, { root: '/projects/widget', consumer: 'agent' }), ); ``` A `root` always names the surface it serves. There is no default: an absent or unknown `consumer` is refused, and the connection answers `ROOT_UNAVAILABLE`. | `consumer` | Surface | | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | | `'working-copy'` | The checkout's own files, with no overlays composed above them. Trusted host composition only. | | `'user'` | What a person sees in the file tree: host-written records included, the control plane hidden. | | `'agent'` | What an agent sees: records readable but not writable, the control plane hidden. A runtime that renders agent-authored code names this one too. | Inside runtime, `main.ts`, `.tau/cache/**`, and `node_modules/**` all belong to that rooted capability. The runtime receives no project id or authority-global root and performs no authorization checks; filesystem reachability is the authority boundary. `fromFsLike(fs)` follows the same local-path contract but assumes `fs` is already confined. Use `fromNodeFs(hostRoot)` for raw Node.js access so the adapter can enforce lexical and symlink containment. ## Related [#related] * [Set Up the Filesystem](/runtime/guides/filesystem-setup) * [Worker Model](/runtime/concepts/worker-model) * [Path Namespaces](/runtime/concepts/path-namespaces) * [API: Client](/runtime/api/client) * [API: Types](/runtime/api/types) * [RPC Wire Spec](https://github.com/taucad/tau/blob/main/docs/architecture/rpc-wire-spec.md) # Framework Integrations API URL: /runtime/api/frameworks Framework helpers package Tau's required build, header, worker, and host-process invariants behind stable configuration seams that hold across every qualified framework version. ## Vite and React Router [#vite-and-react-router] `tauRuntime(options?){:ts}` returns an array of Vite plugins. Vite flattens nested plugin arrays, so place the result directly in `plugins` without spreading it: ```typescript import { reactRouter } from '@react-router/dev/vite'; import { tauRuntime } from '@taucad/runtime/vite'; import { defineConfig } from 'vite'; export default defineConfig({ plugins: [tauRuntime(), reactRouter()], }); ``` **`RuntimePluginOptions`** — Options for the {@link tauRuntime} Vite plugin. - **`crossOriginIsolation`** (`boolean | undefined`, optional) — Skip the cross-origin-isolation middleware. Set to `false` when the host already serves COOP/COEP headers (e.g. via Express middleware or platform headers). Defaults to `true`. **`RuntimeVitePlugin`** — Version-neutral public shape of a Vite plugin returned by Tau factories. Hook types remain internal so consumers can use the same factory with every supported Vite major without importing Tau's development-time Vite types. - **`name`** (`string`, required) `tauRuntime()` includes cross-origin-isolation middleware by default. Set `crossOriginIsolation: false` only when the production host owns those headers; the lower-level `crossOriginIsolation()` export installs only Vite dev/preview headers. React Router SSR response code applies the canonical headers: ```typescript import { applyHandleRequestHeaders } from '@taucad/runtime/react-router'; export function applyRuntimeHeaders(responseHeaders: Headers): void { applyHandleRequestHeaders(responseHeaders); } ``` Express and Connect hosts mount the server adapter without a cast: ```typescript import express from 'express'; import { coiMiddleware } from '@taucad/runtime/cross-origin-isolation/express'; const app = express(); app.use(coiMiddleware()); ``` `@taucad/runtime/cross-origin-isolation` also exports the raw header maps and appliers — `documentHeaders`, `subresourceHeaders`, `applyDocumentHeaders`, `applySubresourceHeaders` — plus the `IsolationStatus` / `IsolationFailureReason` diagnostic types for custom hosts. ## Next.js [#nextjs] `withTauRuntime()` composes application headers and bundler configuration into a `NextRuntimeConfig`. The same call configures Next.js 15's supported Webpack production path and Next.js 16's Turbopack path. ```typescript import { withTauRuntime } from '@taucad/runtime/nextjs/config'; export default withTauRuntime({ output: 'standalone', }); ``` **`NextConfig`** - **`allowedDevOrigins`** (`string[] | undefined`, optional) - **`exportPathMap`** (`((defaultMap: ExportPathMap, ctx: { dev: boolean; dir: string; outDir: string | null; distDir: string; buildId: string; }) => Promise | ExportPathMap) | undefined`, optional) - **`i18n`** (`I18NConfig | null | undefined`, optional) — Internationalization configuration Tags: @see [Internationalization docs](https://nextjs.org/docs/advanced-features/i18n-routing) - **`typescript`** (`TypeScriptConfig | undefined`, optional) Tags: @see [Next.js TypeScript documentation](https://nextjs.org/docs/app/api-reference/config/typescript) - **`typedRoutes`** (`boolean | undefined`, optional) — Enable type checking for Link and Router.push, etc. This feature requires TypeScript in your project. Tags: @see [Typed Links documentation](https://nextjs.org/docs/app/api-reference/config/typescript#statically-typed-links) - **`headers`** (`(() => Promise | Header[]) | undefined`, optional) — Headers allow you to set custom HTTP headers for an incoming request path. Tags: @see [Headers configuration documentation](https://nextjs.org/docs/app/api-reference/config/next-config-js/headers) - **`rewrites`** (`(() => Promise | Rewrite[] | { beforeFiles?: Rewrite[]; afterFiles?: Rewrite[]; fallback?: Rewrite[]; }) | undefined`, optional) — Rewrites allow you to map an incoming request path to a different destination path. Tags: @see [Rewrites configuration documentation](https://nextjs.org/docs/app/api-reference/config/next-config-js/rewrites) - **`redirects`** (`(() => Promise | Redirect[]) | undefined`, optional) — Redirects allow you to redirect an incoming request path to a different destination path. Tags: @see [Redirects configuration documentation](https://nextjs.org/docs/app/api-reference/config/next-config-js/redirects) - **`excludeDefaultMomentLocales`** (`boolean | undefined`, optional) Tags: @see [Moment.js locales excluded by default](https://nextjs.org/docs/upgrading#momentjs-locales-excluded-by-default) - **`webpack`** (`NextJsWebpackConfig | null | undefined`, optional) — Before continuing to add custom webpack configuration to your application make sure Next.js doesn't already support your use-case Tags: @see [Custom Webpack Config documentation](https://nextjs.org/docs/app/api-reference/config/next-config-js/webpack) - **`trailingSlash`** (`boolean | undefined`, optional, default `false`) — By default Next.js will redirect urls with trailing slashes to their counterpart without a trailing slash. Tags: @see [Trailing Slash Configuration](https://nextjs.org/docs/app/api-reference/config/next-config-js/trailingSlash) - **`env`** (`Record | undefined`, optional) — Next.js comes with built-in support for environment variables Tags: @see [Environment Variables documentation](https://nextjs.org/docs/app/api-reference/config/next-config-js/env) - **`distDir`** (`string | undefined`, optional) — Destination directory (defaults to `.next`) - **`cleanDistDir`** (`boolean | undefined`, optional) — The build output directory (defaults to `.next`) is now cleared by default except for the Next.js caches. - **`assetPrefix`** (`string | undefined`, optional) — To set up a CDN, you can set up an asset prefix and configure your CDN's origin to resolve to the domain that Next.js is hosted on. Tags: @see [CDN Support with Asset Prefix](https://nextjs.org/docs/app/api-reference/config/next-config-js/assetPrefix) - **`cacheHandler`** (`string | undefined`, optional) — The default cache handler for the Pages and App Router uses the filesystem cache. This requires no configuration, however, you can customize the cache handler if you prefer. Tags: @see [Configuring Caching](https://nextjs.org/docs/app/building-your-application/deploying#configuring-caching) and the [API Reference](https://nextjs.org/docs/app/api-reference/next-config-js/incrementalCacheHandlerPath). - **`adapterPath`** (`string | undefined`, optional) — Path to a custom adapter module for deployment platform integration. Can also be set via the `NEXT_ADAPTER_PATH` environment variable. - **`cacheHandlers`** (`{ [handlerName: string]: string | undefined; default?: string; remote?: string; static?: string; } | undefined`, optional) - **`cacheMaxMemorySize`** (`number | undefined`, optional) — Configure the in-memory cache size in bytes. Defaults to 50 MB. If `cacheMaxMemorySize: 0`, this disables in-memory caching entirely. Tags: @see [Configuring Caching](https://nextjs.org/docs/app/building-your-application/deploying#configuring-caching). - **`useFileSystemPublicRoutes`** (`boolean | undefined`, optional, default `true`) — By default, `Next` will serve each file in the `pages` folder under a pathname matching the filename. To disable this behavior and prevent routing based set this to `true`. Tags: @see [Disabling file-system routing](https://nextjs.org/docs/advanced-features/custom-server#disabling-file-system-routing) - **`generateBuildId`** (`(() => string | null | Promise) | undefined`, optional) Tags: @see [Configuring the build ID](https://nextjs.org/docs/app/api-reference/config/next-config-js/generateBuildId) - **`generateEtags`** (`boolean | undefined`, optional) Tags: @see [Disabling ETag Configuration](https://nextjs.org/docs/app/api-reference/config/next-config-js/generateEtags) - **`pageExtensions`** (`string[] | undefined`, optional) Tags: @see [Including non-page files in the pages directory](https://nextjs.org/docs/app/api-reference/config/next-config-js/pageExtensions) - **`instrumentationClientInject`** (`string[] | undefined`, optional) — Module specifiers that are required for side effects on the client before hydration, in array order, ahead of the user's `instrumentation-client.{ts,js}`. Each entry may be a bare npm package name or a path relative to the project root. - **`compress`** (`boolean | undefined`, optional) Tags: @see [Compression documentation](https://nextjs.org/docs/app/api-reference/config/next-config-js/compress) - **`poweredByHeader`** (`boolean | undefined`, optional) Tags: @see [Disabling x-powered-by](https://nextjs.org/docs/app/api-reference/config/next-config-js/poweredByHeader) - **`images`** (`Partial | undefined`, optional) Tags: @see [Using the Image Component](https://nextjs.org/docs/app/api-reference/next-config-js/images) - **`devIndicators`** (`false | { position?: "top-left" | "top-right" | "bottom-left" | "bottom-right"; } | undefined`, optional) — Configure indicators in development environment - **`onDemandEntries`** (`{ maxInactiveAge?: number; pagesBufferLength?: number; } | undefined`, optional) — Next.js exposes some options that give you some control over how the server will dispose or keep in memory built pages in development. Tags: @see [Configuring `onDemandEntries`](https://nextjs.org/docs/app/api-reference/config/next-config-js/onDemandEntries) - **`deploymentId`** (`string | undefined`, optional) — A unique identifier for a deployment that will be included in each request's query string or header. - **`supportsImmutableAssets`** (`boolean | undefined`, optional) — Whether the deployment environment supports immutable assets (assets deployed to `_next/static/immutable` don't need a `?dpl` parameter and can be safely requested across deployments.) - **`basePath`** (`string | undefined`, optional) — Deploy a Next.js application under a sub-path of a domain Tags: @see [Base path configuration](https://nextjs.org/docs/app/api-reference/config/next-config-js/basePath) - **`sassOptions`** (`{ [key: string]: any; implementation?: string; } | undefined`, optional) Tags: @see [Customizing sass options](https://nextjs.org/docs/app/api-reference/next-config-js/sassOptions) - **`productionBrowserSourceMaps`** (`boolean | undefined`, optional) — Enable browser source map generation during the production build Tags: @see [Source Maps](https://nextjs.org/docs/advanced-features/source-maps) - **`reactCompiler`** (`boolean | ReactCompilerOptions | undefined`, optional) — Enable {@link https://nextjs.org/docs/app/api-reference/config/next-config-js/reactCompiler React Compiler in Next.js}. Configuration accepts partial config object of the Compiler. If provided, the Compiler will be enabled. - **`reactProductionProfiling`** (`boolean | undefined`, optional) — Enable react profiling in production - **`reactStrictMode`** (`boolean | null | undefined`, optional) — The Next.js runtime is Strict Mode-compliant. Tags: @see [React Strict Mode](https://nextjs.org/docs/app/api-reference/config/next-config-js/reactStrictMode) - **`reactMaxHeadersLength`** (`number | undefined`, optional) — The maximum length of the headers that are emitted by React and added to the response. Tags: @see [React Max Headers Length](https://nextjs.org/docs/app/api-reference/config/next-config-js/reactMaxHeadersLength) - **`httpAgentOptions`** (`{ keepAlive?: boolean; } | undefined`, optional) — Next.js enables HTTP Keep-Alive by default. You may want to disable HTTP Keep-Alive for certain `fetch()` calls or globally. Tags: @see [Disabling HTTP Keep-Alive](https://nextjs.org/docs/app/api-reference/next-config-js/httpAgentOptions) - **`staticPageGenerationTimeout`** (`number | undefined`, optional, default `60`) — Timeout after waiting to generate static pages in seconds - **`crossOrigin`** (`"anonymous" | "use-credentials" | undefined`, optional) — Add `"crossorigin"` attribute to generated `