# programs

> Carry small JavaScript programs in inert script tags and run them outside the browser with checked file, git, or public network calls.

Source: https://clayjs.com/docs/plugins/programs/

Carry small JavaScript programs inside an HTML document and run them on the person's computer through HTML Clay's built-in `programs` helper on the [wire](https://clayjs.com/docs/plugins/wire/). Each program lives in an inert `<script type="text/x-clay-program">` tag and runs outside the browser in a separate worker process with Goja, reaching files, git history, or public web addresses only through host calls that HTML Clay checks against the program's declared level and the document's trust tier.

## Loading

```html
<script src="https://clayjs.com/v1/clay.js?plugins=programs"></script>
```

Adding `?plugins=programs` attaches `clay.programs` and loads `wire` automatically. The plugin loads in `view`, `edit` and `draft` mode, and stays active across live mode switches so readers in view mode can run a page's programs too.

In `draft` mode ([visitor drafts](https://clayjs.com/docs/guide/free-documents/)), `wire` is dropped, so `clay.programs.run()` resolves immediately with `programs_unavailable` and sends nothing, while `clay.programs.list()` still reads the page's tags.

On a [blockeditor](https://clayjs.com/docs/plugins/blockeditor/) document, naming `programs` moves `wire` out of the late wave into the main plugin wave so `clay.programs` can send as soon as `clay.ready` resolves. In HTML Clay, carried programs run under the AI Editing switch, and any document that carries a `<script type="text/x-clay-program">` tag or loads `plugins=programs` in its first 2.5 MiB on disk (or has run a program in the current session) refuses relayed live-sync snapshots from other tabs.

## Declaring programs

Place each program in an HTML `<script type="text/x-clay-program">` tag outside `<template>`, `<noscript>` and foreign namespaces such as `<svg>`:

```html
<script type="text/x-clay-program" name="release-notes" can="read">
async function main(input, clay) {
  const commits = await clay.git.log({ max: input?.max ?? 20 });
  return { count: commits.length, commits };
}
</script>
```

### Names and limits

- **Valid names:** `name` must be 1 to 32 lowercase ASCII letters, digits and hyphens, with no leading or trailing hyphen (`/^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/`).
- **Reserved names:** `ai-tools`, `ai-edit`, `programs` and `document-trust` are refused by both ClayJS and HTML Clay (`list()` skips them and `run()` refuses them with `invalid_request`). HTML Clay also reserves its built-in helper names (`file-search`, `file-convert` and `folder-watch`).
- **No duplicate names:** if two tags in a document share the same `name`, both are refused (`level: null` in `list()`, and `program_invalid` from the host) so it is always clear which code runs.
- **Scan limits:** HTML Clay reads program tags from the first 2.5 MiB (`2,621,440` bytes) of the saved file, up to 8 program tags per document, and up to 256 KiB of UTF-8 text per tag. Tags past 2.5 MiB, cut across the 2.5 MiB mark, larger than 256 KiB, or past the eighth tag are refused on run with `program_not_read` (and tags over 256 KiB or past the eighth show `level: null` in `clay.programs.list()`).

### Capabilities (`can`)

The `can` attribute takes whitespace-separated words (case-insensitive) that set one of three levels:

| `can` attribute | Resolved `level` | What the program may reach |
|---|---|---|
| omitted, `""`, `"read"`, `"git"`, `"read git"` | `"read"` | Read files and git history in a folder the person chooses. |
| `"change"` (alone or with `"read"` or `"git"`) | `"change"` | Read files, read git history, and write files in the chosen folder. |
| `"internet"` | `"internet"` | Fetch public `http:` and `https:` addresses. Asks for no folder and reaches no files or git. |

A program never gets both the internet and local files: combining `internet` with `read`, `git` or `change` is refused (`level: null` in `list()`, `program_invalid` on run). Split network fetches and local file work into two separate programs instead. Any unknown word in `can` (for example `write` instead of `change`) is also refused with `program_invalid`.

## Page API (`clay.programs`)

`clay.programs.run()` sends the program's name and JSON input to the host, never its code. HTML Clay reads the `<script type="text/x-clay-program">` tag from the saved file on disk, verifies the trust of those exact bytes, prompts for a folder when the level needs one (sharing the page's remembered folder with `clay.ai`), re-reads the file after the prompt (`program_changed` if anything in the program tags or trust tier changed while waiting), and runs a stored copy. Unsaved DOM edits to a program tag never run until the document is saved. Only one carried program runs per document at a time (`helper_busy` if another is already running).

### `clay.programs.list()`

Returns `[{ name, can, level }]` in document order, one entry per valid, unreserved program name in the HTML document:

- `name`: the tag's `name` attribute.
- `can`: the tag's `can` attribute, trimmed (`""` when absent).
- `level`: `"read"`, `"change"` or `"internet"`, or `null` when the tag will be refused (unknown `can` word, `internet` combined with file words, duplicate `name`, tag over 256 KiB, or tag after the first 8). `level` reports what the tag asks for, not whether the document's trust tier permits it.

### `clay.programs.available()`

`await clay.programs.available()` checks `/_/meta` through `clay.wire.helpers()` for the `programs` helper and resolves to `"ready"`, `"denied"` or `"unavailable"`, or `null` when `wire` is absent or the host does not run carried programs.

### `clay.programs.run(name, options)`

Starts the named program and returns `{ id, state, done, cancel }` immediately. `done` always resolves to an outcome object and never rejects.

| Option | Default | What it does |
|---|---|---|
| `input` | `null` | Any JSON value (`object`, `array`, `string`, `number`, `boolean` or `null`), up to 256 KiB serialized. |
| `folder` | `"remembered"` | `"remembered"` or `"choose"`. Ignored at the `"internet"` level, which uses no folder. |
| `onLog` | optional | Callback `(text)` receiving streamed `console` output chunks (at most one frame up to 16 KiB every 100 ms, up to 1 MiB per run). |
| `onStatus` | optional | Callback `({ text, phase })` receiving `"asking"` (waiting up to 5 minutes for folder choice), `"starting"`, and `"working"` (from `clay.status()`, throttled to every 100 ms). Console lines go only to `onLog`. |
| `signal` | optional | `AbortSignal`. Aborting sends `wire/cancel` and terminates the worker process group. |

`await handle.done` resolves to:

```js
{ state, program, data, log, logCut, outputs, folder, grant, error }
```

- `state`: `"done"`, `"cancelled"` or `"error"`.
- `program`: the program name on `"done"`, otherwise `null`.
- `data`: the JSON value returned by `main` (`undefined` becomes `null`; capped at 768 KiB serialized), otherwise `null`.
- `log`: up to the last 16 KiB of `console` output on `"done"` (`""` otherwise).
- `logCut`: `true` when console output exceeded the 16 KiB kept in `log` or the 1 MiB stream limit.
- `outputs`: map of each `clay.output(name, text)` artifact to `{ name, bytes, text() }`. ClayJS starts fetching each run file from `/_/wire/runs/<run>/files/<id>` as soon as the run finishes (kept for 5 minutes and checked with `Document-URL` and `Save-Token`); `await outputs[name].text()` resolves to the string or rejects with `code: "output_unavailable"`.
- `folder`: `{ name }` (base name of the chosen folder, never its path) when the program ran with a folder, or `null`.
- `grant`: `{ level, remembered }` on `"done"`, or `null`.
- `error`: `null` on `"done"`, or `{ code, message }` on `"error"` and `"cancelled"`.

Pre-run and worker error codes on `outcome.error.code`: `invalid_request`, `programs_unavailable`, `helper_off`, `helper_not_granted`, `helper_busy`, `helper_cancelled`, `helper_timeout`, `program_missing`, `program_not_read`, `program_invalid`, `level_unavailable`, `program_changed`, `program_failed`, `program_timeout` (5-minute run limit), `program_memory` (256 MiB worker cap), `program_crashed`, `result_too_large` (return value over 768 KiB), `folder_missing`, `store_failed`, `worker_failed`, plus any uncaught host-call error code below.

## Inside a program

A program is plain JavaScript compiled by Goja with an event loop, a 256 MiB memory cap, a 10,000-frame call stack limit, a 5-minute deadline, and a limit of 10,000 host calls per run.

### Entry point and `require`

Define a top-level `main(input, clay)` function (`async function main(input, clay)` or a `function`, `const`, `let` or `var` binding). HTML Clay calls `main(input, clay)` and awaits its return value, which must serialize to JSON within 768 KiB. `clay` is also a global (`globalThis.clay`), so helper modules reach it without threading it through arguments. A program without `main` or with a syntax error fails with `program_invalid`.

Programs cannot use ES module `import` or `export` syntax (using either fails with `program_invalid`). To share code across programs in the same page, put CommonJS exports on `exports` or `module.exports` in another `<script type="text/x-clay-program">` tag and load it with `require("./name")` (or `require("name")` / `require("name.js")`). `require` loads only sibling program tags from the same document, never the entry tag itself, files on disk, or Node built-in modules.

### `clay.files` (`read` and `change` levels)

Paths must be relative `/`-separated paths inside the chosen folder. Leading `/`, `..`, backslashes, drive letters, symlinks anywhere along the path, non-regular files (such as FIFOs or devices), and Windows 8.3 short-name segments (`~` followed by a digit, such as `GIT~1`) are refused with `call_refused` or `not_a_file`.

Repository metadata directories (`.git`, `.hg`, `.svn`, matched with case-folding, stripped trailing dots/spaces, and stripped HFS+ ignorable characters) are blocked on every file call (`call_refused` on read or write, and omitted from `list()`). Read repository history through `clay.git` instead.

- `await clay.files.read(path)`: reads a regular UTF-8 text file up to 4 MiB and returns its string. Binary or non-UTF-8 files reject with `not_text` (`not_found` when absent, `too_large` over 4 MiB).
- `await clay.files.list(path)`: lists a directory (`""` or `"."` for the root, up to 5,000 entries) sorted by `name`, returning `[{ name, type, size }]` where `type` is `"file"`, `"folder"`, `"link"` or `"other"` (`size` is set on regular files).
- `await clay.files.write(path, text)`: (`change` level only; rejects with `call_refused` on `read`). Writes UTF-8 text atomically via a temporary file rename, creating missing parent folders on the way, up to 4 MiB per file and 32 MiB per run, returning `{ path, bytes }`. Even at the `change` level, writes are blocked (`call_refused`) on configuration and hook paths that other tools execute commands from: `.vscode`, `.idea`, `.claude`, `.codex`, `.cursor`, `.gemini`, `.gitmodules`, `.gitattributes`, `.husky`, and `.github/workflows` (reading these paths remains allowed).

### `clay.git` (`read` and `change` levels)

Git calls read the chosen folder's repository in-process through `go-git` without spawning a `git` subprocess, so repository hooks, diff drivers, filters, and `fsmonitor` never execute.

- `await clay.git.log({ base, head, max })`: commits reachable from `head` (default `"HEAD"`), newest first, up to `max` (default and maximum `500`), returning `[{ hash, subject, author, when }]`. When `base` is set, returns commits in `base..head`; when `base` is omitted, walks history from `head`.
- `await clay.git.diff({ base, head, paths })`: three-dot diff from the merge base of `base` and `head` (`base...head`, `head` defaults to `"HEAD"`), optionally restricted to `paths`, up to 4 MiB of unified diff text (lockfiles, `*.min.js`, `*.min.css`, `*.map`, `**/vendor/**` and `**/node_modules/**` are excluded by default and listed in `skipped`). Returns `{ base, head, mergeBase, text, files, skipped, truncated }` where `files` entries are `{ path, from, status, added, deleted, binary }` and `skipped` entries are `{ path, reason }`.
- `await clay.git.branches()`: local branches then remote-tracking branches (up to 5,000), returning `[{ name, hash, remote, current }]`.
- `await clay.git.status()`: modified and untracked working-tree files (respecting `.gitignore` and `.git/info/exclude`, up to 5,000), returning `[{ path, staging, worktree }]` with short status codes (`"M"`, `"A"`, `"D"`, `"R"`, `"C"`, `"U"`, `"?"`, `" "`).
- `await clay.git.show(revision, path)`: returns the UTF-8 string of `path` at `revision` (up to 4 MiB). Rejects with `not_text` on binary or non-UTF-8 content, `not_found` when absent at that commit, `too_large` over 4 MiB, `call_invalid` on an invalid ref or path, or `git_failed` on repository errors.

### `clay.fetch(url, options)` (`internet` level only)

`await clay.fetch(url, { method, headers, body })` sends an HTTP or HTTPS request to a public internet address (up to 30 seconds, at most 5 redirects, no proxy, no cookies). Every resolved IP on the initial connection and on each redirect must be public: localhost, loopback, link-local, and private network addresses reject with `fetch_refused` (other transport errors reject with `fetch_failed`).

- `method` defaults to `"GET"` (`GET`, `HEAD`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS`).
- `headers` accepts up to 32 request headers; hop-by-hop headers (`Host`, `Connection`, `Content-Length`, `Transfer-Encoding`, `TE`, `Trailer`, `Upgrade`, `Keep-Alive`) and `Proxy-*` headers are refused with `call_invalid`.
- `body` accepts a string up to 1 MiB; responses are capped at 4 MiB each and 32 MiB across the run (`too_large` or `limit`).
- Resolves to `{ status, ok, url, headers, text }`, where `headers` keys are lowercased and repeated response headers are joined with `", "`.

### Output, status, console, and errors

- `await clay.output(name, text)`: keeps a named text file for the page (`name` matching `/^[A-Za-z0-9_-]{1,64}$/`, unique within the run, up to 16 outputs, 4 MiB per file and 8 MiB per run), returning `{ name, url, bytes }`. Use `clay.output` for large Markdown, CSV or patch text that would crowd `main`'s 768 KiB JSON return limit.
- `clay.status(text)`: synchronous call sending progress text (up to 512 bytes) to `options.onStatus` with `phase: "working"`.
- `console.log`, `console.info`, `console.warn`, `console.error`, `console.debug`: join arguments with spaces (strings printed directly, other values JSON-encoded) and stream lines to `options.onLog`.
- Failed host calls reject with an `Error` carrying `.code` (`call_refused`, `call_invalid`, `not_found`, `not_a_file`, `not_text`, `too_large`, `limit`, `git_failed`, `fetch_refused`, `fetch_failed`, `output_refused`, `folder_unreadable`, `program_invalid`). When a program lets that rejection go uncaught, `outcome.error.code` preserves the call's `code`.

## Trust tiers

HTML Clay decides what a document's programs may run from the trust tier of the exact file bytes on disk:

| Tier | Approval before first run | Allowed program levels |
|---|---|---|
| **Mine** (documents you created or trusted) and **Ecosystem** (signed releases) | Ready immediately (still prompts to pick a folder when the page has none remembered). | `read`, `change`, `internet` |
| **Team** (shared team folders) and **Unknown** (downloaded or unverified files) | Prompts once for the document's current code (`helper_not_granted` until allowed; **Don't allow** sets the helper to `denied`). Asks again if the page's code changes. | `read` and `internet` after approval. Any `change` program is refused with `level_unavailable` before asking for a folder. |

To let a downloaded or team document run a `change` program, vouch for it explicitly with `htmlclay trust` in the terminal or **Trust it like a file I made** on the warning dialog.

## Example

```html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Release notes</title>
  <script src="https://clayjs.com/v1/clay.js?plugins=programs"></script>

  <script type="text/x-clay-program" name="format">
  exports.toMarkdown = (commits) =>
    commits.map((c) => `- ${c.subject} (${c.hash.slice(0, 7)})`).join("\n") + "\n";
  </script>

  <script type="text/x-clay-program" name="release-notes" can="read">
  const { toMarkdown } = require("./format");

  async function main(input, clay) {
    clay.status("Reading recent commits");
    const commits = await clay.git.log({ max: input?.max ?? 25 });
    console.log("Found", commits.length, "commits");
    await clay.output("notes", toMarkdown(commits));
    return { count: commits.length };
  }
  </script>
</head>
<body>
  <div clay="freeze">
    <button type="button" id="run">Build release notes</button>
    <p id="status"></p>
    <pre id="notes"></pre>
  </div>

  <script>
    const status = document.getElementById("status");
    const notes = document.getElementById("notes");

    document.getElementById("run").addEventListener("click", async () => {
      await clay.ready;
      const run = clay.programs.run("release-notes", {
        input: { max: 25 },
        onStatus: ({ text }) => { status.textContent = text; },
        onLog: (chunk) => console.log(chunk),
      });
      const outcome = await run.done;
      if (outcome.state !== "done") {
        status.textContent = outcome.error.message;
        return;
      }
      notes.textContent = await outcome.outputs.notes.text();
      status.textContent = `${outcome.data.count} commits from ${outcome.folder.name}`;
    });
  </script>
</body>
</html>
```
