# zidane/codemode

> A QuickJS sandbox that runs model-written JavaScript with only injected tools as its capabilities.

Import: `import { … } from 'zidane/codemode'`. Source: [src/codemode/index.ts](https://github.com/Tahul/zidane/blob/main/src/codemode/index.ts).

Use `CodemodeSandbox` to let a model write one script that calls many tools, so the intermediate results never enter its context. The script runs in a QuickJS VM in a worker thread, with no timers, network or modules, and needs the optional `quickjs-wasi` package. The render functions turn your tools into TypeScript declarations to show the model.

```ts
import { CodemodeSandbox } from 'zidane/codemode'

interface AddArgs { a: number, b: number }

const sandbox = new CodemodeSandbox({
  tools: [{ name: 'add', execute: (args) => { const { a, b } = args as AddArgs; return a + b } }],
})
const result = await sandbox.execute('return await tools.add({ a: 1, b: 2 })')
if (result.ok)
  console.log(result.value)
await sandbox.close()
```

## Functions

### `codemodeSandboxPaths`

Function.

The paths set with [`setCodemodeSandboxPaths`](https://zidane.si/docs/reference/codemode.md#setCodemodeSandboxPaths).

```ts
function codemodeSandboxPaths(): Readonly<CodemodeSandboxPaths>
```

**Returns** `Readonly<CodemodeSandboxPaths>`

Source: [src/codemode/sandbox-paths.ts:32](https://github.com/Tahul/zidane/blob/main/src/codemode/sandbox-paths.ts#L32)

### `loadQuickJSWasm`

Function.

Read and compile the QuickJS wasm once per path. `path` defaults to the file in the installed
`quickjs-wasi` package (an optional peer dependency); pass it when the file lives elsewhere, for
example embedded in a Bun compiled executable. A failed load is retried on the next call.

```ts
function loadQuickJSWasm(path?: string): Promise<object>
```

**Parameters**

- `path?` (`string`): Path to `quickjs.wasm`. Defaults to the file in the installed `quickjs-wasi` package.

**Returns** `Promise<object>`

Source: [src/codemode/wasm.ts:24](https://github.com/Tahul/zidane/blob/main/src/codemode/wasm.ts#L24)

### `mcpStructuredContentSchema`

Function.

The `structuredContent` schema of an MCP `CallToolResult` output schema (detected by a
`content` array of objects, boolean `isError`, and object `_meta`), `true` when it declares none, or
`undefined` when the schema is not a `CallToolResult`.

```ts
function mcpStructuredContentSchema(
  schema: CodemodeJsonSchema | undefined,
): CodemodeJsonSchema | undefined
```

**Parameters**

- `schema` (`CodemodeJsonSchema | undefined`): Output schema of a tool.

**Returns** `CodemodeJsonSchema | undefined`

Source: [src/codemode/declarations.ts:215](https://github.com/Tahul/zidane/blob/main/src/codemode/declarations.ts#L215)

### `parseCodemodeSource`

Function.

Split an optional first-line `// @options: {...}` from the script. Throws
[`CodemodeSourceError`](https://zidane.si/docs/reference/codemode.md#CodemodeSourceError) for empty input and invalid options.

```ts
function parseCodemodeSource(input: string): ParsedCodemodeSource
```

**Parameters**

- `input` (`string`): Script text, optionally starting with an `// @options:` line.

**Returns** `ParsedCodemodeSource`

**Example**

```ts
import { parseCodemodeSource } from 'zidane/codemode'

const { code, options } = parseCodemodeSource(
  '// @options: {"timeout_ms": 5000}\ntext("hi")',
)
console.log(options.timeoutMs, code)
```

Source: [src/codemode/source.ts:114](https://github.com/Tahul/zidane/blob/main/src/codemode/source.ts#L114)

### `renderDeclarations`

Function.

Render TypeScript declarations for the script-visible API. Tools become members of
`declare const tools`, globals become `declare function` statements, and `ns.member` globals
members of `declare const ns`. Descriptions become doc comments; schemas become types.

```ts
function renderDeclarations(options: RenderDeclarationsOptions): string
```

**Parameters**

- `options` (`RenderDeclarationsOptions`): Tools and globals to render.

**Returns** `string`

**Example**

```ts
import { renderDeclarations } from 'zidane/codemode'

const declarations = renderDeclarations({
  tools: [{
    name: 'read_file',
    description: 'Reads a file.',
    inputSchema: { type: 'object', properties: { path: { type: 'string' } }, required: ['path'] },
    execute: () => '',
  }],
})
console.log(declarations)
```

Source: [src/codemode/declarations.ts:123](https://github.com/Tahul/zidane/blob/main/src/codemode/declarations.ts#L123)

### `renderToolOutputType`

Function.

The type a tool call resolves to: `CallToolResult<T>` for MCP output schemas (needs
[`MCP_TYPESCRIPT_PREAMBLE`](https://zidane.si/docs/reference/codemode.md#MCP_TYPESCRIPT_PREAMBLE)), the schema's type otherwise, and `unknown` without a schema.

```ts
function renderToolOutputType(
  schema: CodemodeJsonSchema | undefined,
  options?: { comments?: boolean },
): string
```

**Parameters**

- `schema` (`CodemodeJsonSchema | undefined`): Output schema of a tool.
- `options?` (`{ comments?: boolean }`, default `{}`): Rendering options.

**Returns** `string`

Source: [src/codemode/declarations.ts:235](https://github.com/Tahul/zidane/blob/main/src/codemode/declarations.ts#L235)

### `renderToolSample`

Function.

A tool's sample: the description followed by the tool's declaration. Used for tool
listings and `ALL_TOOLS` entries.

```ts
function renderToolSample(
  tool: Pick<CodemodeTool, 'name' | 'description' | 'inputSchema' | 'outputSchema'>,
  options?: { inputMaxChars?: number },
): string
```

**Parameters**

- `tool` (`Pick<CodemodeTool, 'name' | 'description' | 'inputSchema' | 'outputSchema'>`): Tool whose description and declaration to render.
- `options?` (`{ inputMaxChars?: number }`, default `{}`): `inputMaxChars` renders longer input types as `unknown`.

**Returns** `string`

Source: [src/codemode/declarations.ts:200](https://github.com/Tahul/zidane/blob/main/src/codemode/declarations.ts#L200)

### `renderToolSignature`

Function.

One tool as a member of the `tools` object: `name(args: T): Promise<R>;` with the
name as the identifier scripts use. Input types longer than `inputMaxChars` render as `unknown`.
A tool that takes a bare string ([`stringArgumentOf`](https://zidane.si/docs/reference/codemode.md#stringArgumentOf)) renders as `name(args: string | T)`.
Tools whose output schema is an MCP `CallToolResult` render as `Promise<CallToolResult<T>>`,
which needs [`MCP_TYPESCRIPT_PREAMBLE`](https://zidane.si/docs/reference/codemode.md#MCP_TYPESCRIPT_PREAMBLE).

```ts
function renderToolSignature(
  tool: Pick<CodemodeTool, 'name' | 'inputSchema' | 'outputSchema'>,
  options?: { comments?: boolean; inputMaxChars?: number },
): string
```

**Parameters**

- `tool` (`Pick<CodemodeTool, 'name' | 'inputSchema' | 'outputSchema'>`): Tool whose name and schemas to render.
- `options?` (`{ comments?: boolean; inputMaxChars?: number }`, default `{}`): Rendering options.

**Returns** `string`

Source: [src/codemode/declarations.ts:163](https://github.com/Tahul/zidane/blob/main/src/codemode/declarations.ts#L163)

### `schemaToType`

Function.

Convert a JSON Schema to a TypeScript type expression: objects on one line (`{ a: string; b?: number; }`) with properties sorted by name,
or one property per line with `//` comments when a property has a description; `Array<T>` for
arrays. Local references (`#/$defs/...`, `#/definitions/...`) resolve against `schema`;
recursive and remote references render as `unknown`. A result longer than `maxChars` renders as
`unknown`.

```ts
function schemaToType(
  schema: CodemodeJsonSchema,
  options?: { comments?: boolean; maxChars?: number },
): string
```

**Parameters**

- `schema` (`CodemodeJsonSchema`): JSON Schema to convert.
- `options?` (`{ comments?: boolean; maxChars?: number }`, default `{}`): Conversion options.

**Returns** `string`

Source: [src/codemode/declarations.ts:290](https://github.com/Tahul/zidane/blob/main/src/codemode/declarations.ts#L290)

### `setCodemodeSandboxPaths`

Function.

Replace the process-wide sandbox paths. Explicit per-sandbox options
(`CodemodeSandboxOptions.workerUrl`, `loadQuickJSWasm(path)`) still win.

```ts
function setCodemodeSandboxPaths(paths: CodemodeSandboxPaths): void
```

**Parameters**

- `paths` (`CodemodeSandboxPaths`): Paths to use; omitted fields fall back to the defaults.

Source: [src/codemode/sandbox-paths.ts:27](https://github.com/Tahul/zidane/blob/main/src/codemode/sandbox-paths.ts#L27)

### `stringArgumentOf`

Function.

The property a bare string argument fills: the schema's only required property, when it is a
string. A script may then call `tools.shell("ls")` for `tools.shell({ command: "ls" })`, or
`tools.shell("ls", { timeout: 5000 })` to pass the other properties too. `undefined` otherwise.

```ts
function stringArgumentOf(schema: CodemodeJsonSchema | undefined): string | undefined
```

**Parameters**

- `schema` (`CodemodeJsonSchema | undefined`): Input schema of a tool.

**Returns** `string | undefined`

Source: [src/codemode/declarations.ts:183](https://github.com/Tahul/zidane/blob/main/src/codemode/declarations.ts#L183)

### `toCodemodeIdentifier`

Function.

The identifier a script uses for a tool: characters that are not valid in a JavaScript
identifier become `_`. `mcp__docs__search` stays as is, `my-tool` becomes `my_tool`.

```ts
function toCodemodeIdentifier(name: string): string
```

**Parameters**

- `name` (`string`): Tool name to convert.

**Returns** `string`

Source: [src/codemode/identifier.ts:7](https://github.com/Tahul/zidane/blob/main/src/codemode/identifier.ts#L7)

## Classes

### `CodemodeSandbox`

Class.

Runs JavaScript in a QuickJS VM (a separate wasm instance) inside a worker
thread. The script sees `tools.<name>(args)` for every registered tool, `ALL_TOOLS`,
the output helpers `text`, `image`, `exit`, and `console.*`, `store`/`load`, and the
configured globals; nothing else (no timers, `fetch`, `process`, `require`, modules).

Each `execute()` gets its own worker and VM; the sandbox only holds the tool
table and defaults. `close()` aborts in-flight executions.

```ts
class CodemodeSandbox
```

**Constructor**

```ts
new CodemodeSandbox(options?: CodemodeSandboxOptions)
```

Creates a sandbox with its tools, globals and defaults. Throws when a global or shortcut name is invalid, reserved or duplicated.

**Parameters**

- `options?` (`CodemodeSandboxOptions`, default `{}`): Tools, globals, timeout, memory limit and worker settings.

**Returns** `CodemodeSandbox`

**Properties**

- `globals` (`CodemodeTool[]`, readonly): Globals the script can call as top-level functions.
- `tools` (`CodemodeTool[]`, readonly): Tools currently registered.

**Methods**

#### `close()`

```ts
close(): Promise<void>
```

Aborts in-flight executions (they resolve with `kind: "aborted"`) and rejects new ones.

**Returns** `Promise<void>`

#### `execute()`

```ts
execute(code: string, options?: CodemodeExecuteOptions): Promise<CodemodeResult>
```

`code` is an async function body: `return` and top-level `await` work.
Script failures come back as `{ ok: false }`. The promise rejects only when the sandbox is closed.
The script can use `store(key, value)` and `load(key)` on `options.store`.

**Parameters**

- `code` (`string`): Script source, run as an async function body.
- `options?` (`CodemodeExecuteOptions`, default `{}`): Per-execution signal, timeout, `store` values and determinism settings.

**Returns** `Promise<CodemodeResult>`

#### `registerTool()`

```ts
registerTool(tool: CodemodeTool): void
```

Throws if a tool with the same name is already registered.

**Parameters**

- `tool` (`CodemodeTool`): Tool to add to the `tools` table.

#### `unregisterTool()`

```ts
unregisterTool(name: string): boolean
```

Removes a tool by name. Returns `true` when it was registered.

**Parameters**

- `name` (`string`): Name of the tool to remove.

**Returns** `boolean`

**Example**

```ts
import { CodemodeSandbox } from 'zidane/codemode'

const sandbox = new CodemodeSandbox({
  tools: [{ name: 'add', execute: args => (args as { a: number, b: number }).a + (args as { a: number, b: number }).b }],
})
const result = await sandbox.execute('return await tools.add({ a: 1, b: 2 })')
if (result.ok)
  console.log(result.value)
```

Source: [src/codemode/runtime/host.ts:433](https://github.com/Tahul/zidane/blob/main/src/codemode/runtime/host.ts#L433)

### `CodemodeSourceError`

Class.

Error thrown when codemode source is empty or its `@options` line is invalid.

```ts
class CodemodeSourceError extends Error
```

**Constructor**

```ts
new CodemodeSourceError(message: string)
```

Creates the error.

**Parameters**

- `message` (`string`): Description of the problem.

**Returns** `CodemodeSourceError`

Source: [src/codemode/source.ts:49](https://github.com/Tahul/zidane/blob/main/src/codemode/source.ts#L49)

### `CodemodeValue`

Class.

A tool result the script reads as `value` and prints as `text`. Printing it (`return r`,
`text(r)`, `console.log(r)`, or an array holding such results) shows `text`, the result as a
direct call returns it, while `r.field` reads `value` as usual. Return one from
`CodemodeTool.execute` when `value` is structured.

```ts
class CodemodeValue
```

**Constructor**

```ts
new CodemodeValue(value: unknown, text: string)
```

**Parameters**

- `value` (`unknown`): What the script receives. Must survive a JSON round trip.
- `text` (`string`): What printing the value shows.

**Returns** `CodemodeValue`

**Properties**

- `[CODEMODE_VALUE]` (`true`, readonly, default `true`): Brands the instance, so `CodemodeValue.is` recognizes one from any copy of this module.
- `text` (`string`, readonly): What printing the value shows.
- `value` (`unknown`, readonly): What the script receives. Must survive a JSON round trip.

**Methods**

#### `CodemodeValue.is()`

```ts
CodemodeValue.is(candidate: unknown): candidate is CodemodeValue
```

Whether `candidate` is a [`CodemodeValue`](https://zidane.si/docs/reference/codemode.md#CodemodeValue), from any copy of this module.

**Parameters**

- `candidate` (`unknown`): Value to check.

**Returns** `candidate is CodemodeValue`

**Example**

```ts
const run: CodemodeTool = {
  name: 'run',
  execute: () => new CodemodeValue({ stdout: 'ok\n', exit_code: 0 }, 'ok\n(exit 0)'),
}
```

Source: [src/codemode/value.ts:18](https://github.com/Tahul/zidane/blob/main/src/codemode/value.ts#L18)

## Constants

### `CODEMODE_OPTIONS_PREFIX`

Constant.

Codemode source format: JavaScript, optionally preceded by one options line.

```js
// @options: {"max_output_tokens": 2000, "timeout_ms": 30000}
const text = await tools.read_file({ path: "package.json" });
text(JSON.parse(text).name);
```

```ts
const CODEMODE_OPTIONS_PREFIX = '// @options:'
```

Source: [src/codemode/source.ts:11](https://github.com/Tahul/zidane/blob/main/src/codemode/source.ts#L11)

### `CODEMODE_SOURCE_GRAMMAR`

Constant.

Lark grammar for providers with grammar-constrained tool input. It only fixes the shape of the
options line; the options JSON and the code are checked by [`parseCodemodeSource`](https://zidane.si/docs/reference/codemode.md#parseCodemodeSource).

```ts
const CODEMODE_SOURCE_GRAMMAR: string
```

Source: [src/codemode/source.ts:22](https://github.com/Tahul/zidane/blob/main/src/codemode/source.ts#L22)

### `DEFAULT_INPUT_SCHEMA_MAX_CHARS`

Constant.

Largest rendered input type, in characters, before it becomes `unknown`.

```ts
const DEFAULT_INPUT_SCHEMA_MAX_CHARS = 16_000
```

Source: [src/codemode/declarations.ts:9](https://github.com/Tahul/zidane/blob/main/src/codemode/declarations.ts#L9)

### `MAX_OUTPUT_CHARS`

Constant.

Output one script may produce with `text()`, `image()`, and `console.*`: characters of text and
base64 image data, and items. The host keeps all output until the script ends, so without a
limit a script that prints in a loop grows the host's memory until it crashes. The item limit
covers loops that print empty strings.

```ts
const MAX_OUTPUT_CHARS: number
```

Source: [src/codemode/runtime/prelude.ts:13](https://github.com/Tahul/zidane/blob/main/src/codemode/runtime/prelude.ts#L13)

### `MAX_OUTPUT_ITEMS`

Constant.

Maximum number of output items one script may produce.

```ts
const MAX_OUTPUT_ITEMS = 100_000
```

Source: [src/codemode/runtime/prelude.ts:15](https://github.com/Tahul/zidane/blob/main/src/codemode/runtime/prelude.ts#L15)

### `MAX_STORE_TOTAL_CHARS`

Constant.

Maximum total size, in characters of JSON, of all values a script writes with `store()` in one execution.

```ts
const MAX_STORE_TOTAL_CHARS: number
```

Source: [src/codemode/runtime/prelude.ts:6](https://github.com/Tahul/zidane/blob/main/src/codemode/runtime/prelude.ts#L6)

### `MAX_STORE_VALUE_CHARS`

Constant.

Maximum size, in characters of JSON, of one value a script writes with `store()`.

```ts
const MAX_STORE_VALUE_CHARS: number
```

Source: [src/codemode/runtime/prelude.ts:4](https://github.com/Tahul/zidane/blob/main/src/codemode/runtime/prelude.ts#L4)

### `MCP_TYPESCRIPT_PREAMBLE`

Constant.

TypeScript types for MCP results, from the MCP `CallToolResult` schema, so `CallToolResult<T>`
declarations can refer to them.

```ts
const MCP_TYPESCRIPT_PREAMBLE = ...
```

Source: [src/codemode/declarations.ts:17](https://github.com/Tahul/zidane/blob/main/src/codemode/declarations.ts#L17)

## Interfaces

### `CodemodeCall`

Interface.

Record of one tool call made by a script.

```ts
interface CodemodeCall
```

**Properties**

- `durationMs` (`number`): Time the call took, in milliseconds.
- `name` (`string`): Name of the tool that was called.
- `seq` (`number`): Same as `CodemodeToolContext.seq` for this call.
- `status` (`CodemodeCallStatus`): How the call ended.

Source: [src/codemode/types.ts:71](https://github.com/Tahul/zidane/blob/main/src/codemode/types.ts#L71)

### `CodemodeDeterminism`

Interface.

Pins the VM's only nondeterministic inputs, the WASI clock and random
source. `Date.now()` returns `nowMs` for the whole run and `Math.random()`
(seeded from the clock by QuickJS) plus WASI `random_get` derive from
`seed`. With these set, a script that sees the same tool results takes the
same path, which is what durable replay needs.

```ts
interface CodemodeDeterminism
```

**Properties**

- `nowMs` (`number`): Fixed value returned by `Date.now()`, in milliseconds since the epoch.
- `seed` (`number`): Seed for `Math.random()` and the WASI random source.

Source: [src/codemode/types.ts:136](https://github.com/Tahul/zidane/blob/main/src/codemode/types.ts#L136)

### `CodemodeError`

Interface.

Failure of a codemode execution.

```ts
interface CodemodeError
```

**Properties**

- `excerpt?` (`string`): Script errors with a location: the offending source line and a `^` under
  the column, so the line can be fixed without counting lines.
- `kind` (`CodemodeErrorKind`): What kind of failure occurred.
- `message` (`string`): Error message.
- `name?` (`string`): Error name from the script, for script errors.
- `stack?` (`string`): Stack trace from the script, for script errors.

Source: [src/codemode/types.ts:94](https://github.com/Tahul/zidane/blob/main/src/codemode/types.ts#L94)

### `CodemodeExecuteOptions`

Interface.

Options for one `CodemodeSandbox.execute` call.

```ts
interface CodemodeExecuteOptions
```

**Properties**

- `determinism?` (`CodemodeDeterminism`): Pin the clock and random source for this execution. See [`CodemodeDeterminism`](https://zidane.si/docs/reference/codemode.md#CodemodeDeterminism).
- `onOutput?` (`(item: CodemodeOutputItem) => void`): Called with each output item as the script produces it, before the execution ends. The
  result still carries every item. A throwing callback is ignored.
- `signal?` (`AbortSignal`): Aborts the execution when signaled. The result is an `aborted` error.
- `store?` (`Readonly<Record<string, unknown>>`): Values the script reads with `load(key)`. Must be JSON-serializable. The script's own
  `store()` calls come back as `result.storeWrites`; persisting them is up to the caller.
- `timeoutMs?` (`number`): Overrides the sandbox default for this execution.
- `trackLines?` (`boolean`): Report the script line of each call as `CodemodeToolContext.line`. Costs one stack
  capture per call. Default: off.

Source: [src/codemode/types.ts:192](https://github.com/Tahul/zidane/blob/main/src/codemode/types.ts#L192)

### `CodemodeSandboxOptions`

Interface.

Options for creating a [`CodemodeSandbox`](https://zidane.si/docs/reference/codemode.md#CodemodeSandbox).

```ts
interface CodemodeSandboxOptions
```

**Properties**

- `globals?` (`CodemodeTool[]`): Functions exposed as top-level identifiers instead of on `tools`, for host helpers such as
  attaching an image to the result. They behave like tools (JSON round trip, promise result)
  but are not recorded in `result.calls`. Names must be identifiers and may not shadow the
  built-in globals (`tools`, `ALL_TOOLS`, `console`, `text`, `image`, `exit`, `globalThis`, `store`, `load`).
- `memoryLimitBytes?` (`number`): Maximum memory the QuickJS VM may allocate. Allocations beyond it fail inside the script as
  `InternalError: out of memory`. Default: no limit beyond wasm32's 4 GiB address space.
- `shortcuts?` (`Record<string, string>`): Global functions that call a tool, by function name: `{ sh: 'shell' }` makes `sh(...args)` the
  same call as `tools.shell(...args)`, recorded like it. Names follow the rules for `globals`; a
  shortcut to a tool the sandbox does not have is not defined.
- `timeoutMs?` (`number`): Overall deadline per execution, including time spent in tools. `Infinity` disables the
  deadline; the execution then only ends when the script settles or is aborted.
  Default: 300000.
- `toolHints?` (`Record<string, string>`): Advice shown when a script reads a `tools` member that does not exist but
  that the host knows, by member name (e.g. `spawn`, which runs outside
  scripts). Replaces the generic "does not exist" message for those names.
- `tools?` (`CodemodeTool[]`): Tools the script calls as `tools.<id>(args)`. Recorded in `result.calls`.
- `wasm?` (`object | Promise<object>`): Compiled `quickjs-wasi/quickjs.wasm`, usually from `loadQuickJSWasm`. Default: the file in
  the installed `quickjs-wasi` package. Pass it when that file is not on disk, for example in a
  Bun compiled executable.
- `workerUrl?` (`string | URL`): Worker entry (`src/codemode/runtime/worker.ts`, `dist/codemode-worker.js`). Default: the
  sibling of this module. Pass it when zidane is re-bundled. Bun compiled executables need
  the relative string specifier of an embedded build entrypoint; other hosts usually use a URL.

Source: [src/codemode/types.ts:144](https://github.com/Tahul/zidane/blob/main/src/codemode/types.ts#L144)

### `CodemodeSandboxPaths`

Interface.

Paths the sandbox uses instead of its defaults.

```ts
interface CodemodeSandboxPaths
```

**Properties**

- `wasmPath?` (`string`): `quickjs.wasm`. Default: the file in the installed `quickjs-wasi` package.
- `workerUrl?` (`URL`): The sandbox worker module. Default: `codemode-worker.js` next to the bundle (`worker.ts` in source).

Source: [src/codemode/sandbox-paths.ts:13](https://github.com/Tahul/zidane/blob/main/src/codemode/sandbox-paths.ts#L13)

### `CodemodeSourceOptions`

Interface.

Options read from the `// @options:` line of a codemode script.

```ts
interface CodemodeSourceOptions
```

**Properties**

- `maxOutputTokens?` (`number`): Token budget for the script's output.
- `timeoutMs?` (`number`): Hard deadline for the whole script in milliseconds, including tool calls.

Source: [src/codemode/source.ts:33](https://github.com/Tahul/zidane/blob/main/src/codemode/source.ts#L33)

### `CodemodeStoreWrites`

Interface.

Keys the script changed with `store()`. Only successful executions report writes.

```ts
interface CodemodeStoreWrites
```

**Properties**

- `delete` (`string[]`): Keys stored as `undefined`.
- `set` (`Record<string, unknown>`): Keys written with a value, mapped to the stored value.

Source: [src/codemode/types.ts:111](https://github.com/Tahul/zidane/blob/main/src/codemode/types.ts#L111)

### `CodemodeTool`

Interface.

A host function a codemode script can call, either as `tools.<id>(args)` or, for globals, as a top-level function.

```ts
interface CodemodeTool
```

**Properties**

- `description?` (`string`): Shown as a doc comment in `renderDeclarations`, and listed in `ALL_TOOLS` for tools.
- `execute` (`(args: unknown, context: CodemodeToolContext) => unknown`): `args` is whatever the script passed, after a JSON round trip; a bare string becomes the
  object `stringArgumentOf(inputSchema)` names. The return value must be JSON-serializable, or a
  `CodemodeValue` to print as text; a thrown error surfaces in the script as an `Error` with the
  same message.
- `inputSchema?` (`CodemodeJsonSchema`): Schema of the single argument. Rendered as the parameter type; `unknown` when omitted.
- `name` (`string`): The script calls tools as `tools.<id>(args)`, where `<id>` is the name with characters that
  are not valid in identifiers replaced by `_` (see `toCodemodeIdentifier`), and also as
  `tools["<name>"](args)`. Globals are called as `<name>(args)` and must be identifiers, or
  `<namespace>.<member>`, which groups them into a frozen namespace object.
- `outputSchema?` (`CodemodeJsonSchema`): Schema of the resolved value. Rendered as the promise type; `unknown` when omitted.
- `signature?` (`string`): Globals only: TypeScript parameter list and return type for `renderDeclarations`, for
  example `(type: string, id?: string): Promise<Model[]>`. Replaces the rendering from the schemas.
- `spread?` (`boolean`): Globals only: `execute` receives all call arguments as an array instead of the first one.

Source: [src/codemode/types.ts:29](https://github.com/Tahul/zidane/blob/main/src/codemode/types.ts#L29)

### `CodemodeToolContext`

Interface.

Context passed to a [`CodemodeTool`](https://zidane.si/docs/reference/codemode.md#CodemodeTool) on each call.

```ts
interface CodemodeToolContext
```

**Properties**

- `line?` (`number`): Script line that made this call (the innermost frame of the script, so a
  call inside a helper reports the helper's line). Only with
  `CodemodeExecuteOptions.trackLines`.
- `seq` (`number`): 1-based position of this call in the order the script issued it, shared
  by tools and globals. The VM is single-threaded and has no timers, so for
  a given script and given results the order is the same on every run:
  durable adapters can key journal entries on it.
- `signal` (`AbortSignal`): Aborted when the script finishes (including unawaited calls), the
  execution times out, the caller aborts, or the sandbox is closed.

Source: [src/codemode/types.ts:4](https://github.com/Tahul/zidane/blob/main/src/codemode/types.ts#L4)

### `ParsedCodemodeSource`

Interface.

Result of [`parseCodemodeSource`](https://zidane.si/docs/reference/codemode.md#parseCodemodeSource).

```ts
interface ParsedCodemodeSource
```

**Properties**

- `code` (`string`): The script with the options line replaced by an empty line, so line numbers are unchanged.
- `options` (`CodemodeSourceOptions`): Options from the options line. Empty when the script has none.

Source: [src/codemode/source.ts:41](https://github.com/Tahul/zidane/blob/main/src/codemode/source.ts#L41)

### `RenderDeclarationsOptions`

Interface.

Options for [`renderDeclarations`](https://zidane.si/docs/reference/codemode.md#renderDeclarations).

```ts
interface RenderDeclarationsOptions
```

**Properties**

- `globals?` (`readonly CodemodeTool[]`): Globals rendered as top-level `declare function` statements or namespace objects.
- `tools?` (`readonly CodemodeTool[]`): Tools rendered as members of `declare const tools`.

Source: [src/codemode/declarations.ts:95](https://github.com/Tahul/zidane/blob/main/src/codemode/declarations.ts#L95)

## Types

### `CodemodeCallStatus`

Type.

Outcome of a tool call: finished (`ok`), threw (`error`) or was aborted before it settled (`cancelled`).

```ts
type CodemodeCallStatus = 'ok' | 'error' | 'cancelled'
```

Source: [src/codemode/types.ts:68](https://github.com/Tahul/zidane/blob/main/src/codemode/types.ts#L68)

### `CodemodeErrorKind`

Type.

Category of a [`CodemodeError`](https://zidane.si/docs/reference/codemode.md#CodemodeError).

```ts
type CodemodeErrorKind = 'script' | 'timeout' | 'aborted' | 'sandbox'
```

Source: [src/codemode/types.ts:83](https://github.com/Tahul/zidane/blob/main/src/codemode/types.ts#L83)

### `CodemodeJsonSchema`

Type.

A JSON Schema document. Only used to render declarations; values are not validated against it.

```ts
type CodemodeJsonSchema = { [key: string]: unknown } | boolean
```

Source: [src/codemode/types.ts:26](https://github.com/Tahul/zidane/blob/main/src/codemode/types.ts#L26)

### `CodemodeOutputItem`

Type.

One item of the script's output, in the order the script produced it: `text()` and `console.*`
produce text items, with `console: true` for `console.*`, and `image()` image items. `data` is base64.

```ts
type CodemodeOutputItem =
  | { console?: true; text: string; type: 'text' }
  | { data: string; mimeType: string; type: 'image' }
```

Source: [src/codemode/types.ts:63](https://github.com/Tahul/zidane/blob/main/src/codemode/types.ts#L63)

### `CodemodeResult`

Type.

`output` is kept for failed executions too, up to the failure. `exit()` completes with `value: undefined`.

```ts
type CodemodeResult =
  | { calls: CodemodeCall[]; ok: true; output: CodemodeOutputItem[]; storeWrites: CodemodeStoreWrites; value: unknown }
  | { calls: CodemodeCall[]; error: CodemodeError; ok: false; output: CodemodeOutputItem[] }
```

Source: [src/codemode/types.ts:119](https://github.com/Tahul/zidane/blob/main/src/codemode/types.ts#L119)

### `CodemodeWasmModule`

Type.

A compiled `WebAssembly.Module` of `quickjs-wasi/quickjs.wasm`. Typed opaquely so callers don't
need the DOM lib for the WebAssembly globals.

```ts
type CodemodeWasmModule = object
```

Source: [src/codemode/wasm.ts:9](https://github.com/Tahul/zidane/blob/main/src/codemode/wasm.ts#L9)
