# ai

> Carry hidden agent instructions in the file, send structured AI requests over a local folder on the wire, or build a copyable terminal prompt.

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

Carry hidden instructions for an AI agent inside the HTML file, send structured requests to the host's `ai-tools` helper over the [wire](https://clayjs.com/docs/plugins/wire/), or turn the same request into a copyable prompt for an agent in a terminal. Asking runs the person's own CLI agent (Claude Code, Codex or `agy`) against a local folder they choose and returns JSON matching your schema, plus optional git diffs and file excerpts expanded by the host. ClayJS never writes the reply into the document on its own: your page receives the data and decides how to apply it.

## Loading

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

Adding `?plugins=ai` attaches `clay.instructions` and `clay.ai`, and loads `wire` automatically. The plugin loads in `view`, `edit` and `draft` mode, and stays active across live mode switches: a reader in view mode can run requests too.

In `draft` mode ([visitor drafts](https://clayjs.com/docs/guide/free-documents/)), ClayJS drops `wire`, so `clay.ai.ask()` resolves immediately with `ai_unavailable` without sending a network request, while `clay.ai.prompt()` still builds a full terminal prompt a visitor can copy.

On a [blockeditor](https://clayjs.com/docs/plugins/blockeditor/) document, `wire` normally loads in the late wave after the editor mounts. Naming `ai` moves `wire` into the main plugin wave so `clay.ai` is ready to send as soon as `clay.ready` resolves. In HTML Clay, any document that carries `<script type="text/x-clay-instructions">`, loads `plugins=ai`, holds a remembered folder, or has sent an `ai-tools` request turns off relayed live-sync snapshots from other tabs.

## `clay.instructions`

Hidden instructions live in inert `<script type="text/x-clay-instructions" name="...">` tags inside the document:

```html
<script type="text/x-clay-instructions" name="review">
Focus on data loss, race conditions, and public API changes.
</script>
```

Browsers ignore the unknown script type, and hosts never parse these tags. ClayJS resolves instruction names on the client and sends `{ name, text }` pairs in the request or embeds them in the copied prompt. Tags without a non-empty `name` attribute are ignored.

| Method | What it does |
|---|---|
| `clay.instructions.get(name)` | Returns the unescaped, trimmed text of the first `<script type="text/x-clay-instructions">` tag with `name`, or `null` when none exists. |
| `clay.instructions.names()` | Returns unique non-empty instruction names in document order (`string[]`). |
| `clay.instructions.set(name, text)` | Updates the first matching tag in place, or appends a new `<script type="text/x-clay-instructions" name="...">` to `<head>`. Returns `true` when this tab can write (`clay.modeLifecycle.canWrite()` is `true` and `clay.isDraftMode` is `false`), and `false` in view mode, in draft mode, or when `name` is empty. |
| `clay.instructions.fromForm(form)` | Reads whitespace-separated names from the `<form>` element's `instructions` attribute, then appends `.value` from each matching `[instructions]` descendant (`<select instructions>`, or checked `<input type="checkbox" instructions>` and `<input type="radio" instructions>`), returning unique non-empty names in order. |

`set(name, text)` makes an ordinary DOM edit to saved content, so autosave and sync carry it. When storing text, `set()` escapes `</script` and `<!--` sequences (and `get()` unescapes them) so instruction prose containing HTML or script snippets survives save and reload without closing the surrounding `<script>` tag early.

```html
<form id="review-form" instructions="review">
  <select instructions>
    <option value="tone-concise" selected>Concise</option>
    <option value="tone-thorough">Thorough</option>
  </select>
  <label><input type="checkbox" instructions value="security" checked> Check security</label>
</form>
```

Calling `clay.instructions.fromForm(form)` on the form above returns `["review", "tone-concise", "security"]`.

## `clay.ai`

### `clay.ai.available()`

`await clay.ai.available()` checks `/_/meta` through `clay.wire.helpers()` for the built-in `ai-tools` helper and resolves to its state (`"ready"`, `"denied"` or `"unavailable"`), or `null` when `wire` is absent or the host does not offer `ai-tools`.

### `clay.ai.schema({ result, omit })`

Builds a JSON Schema object from one entry in the page's `<script type="application/json" data-rules-name="api">` tag:

```js
const shape = clay.ai.schema({ result: "reviews", omit: ["id", "diff"] });
```

- `result` (required `string`): key in the `api` rules object. When `result` names a list rule (`[selector, itemRule]`), `schema()` builds the schema for a single row (`itemRule`); when it names an object or scalar rule, it builds the schema for that value.
- `omit` (`string[]`, default `[]`): top-level field names to exclude from the generated schema, such as fields the page populates itself.

Throws an `Error` with `code: "invalid_request"` when the page has no `api` rules tag or `result` is not a key in it.

### `clay.ai.ask(options)`

`clay.ai.ask(options)` sends one request to the host's `ai-tools` wire helper (`document: "none"`) and returns `{ id, state, done, cancel }` at once. `done` is a `Promise` that always resolves to an outcome object and never rejects. On a client-side validation failure or missing wire, `id` is `null`, `state` is `"error"`, `cancel()` returns `false`, and `done` resolves immediately with the error.

| Option | Default | What it does |
|---|---|---|
| `request` | required | Non-empty prompt string, up to 64 KiB in UTF-8. |
| `instructions` | `[]` | Array of instruction tag names (`string[]`). Deduplicated in order. Up to 128 KiB of UTF-8 text in all (HTML Clay also limits a request to 32 instructions and 128-byte names). |
| `tools` | `"read"` | Access level: `"read"`, `"change"` or `"internet"`. In HTML Clay, `"read"` gives the agent read-only folder tools, `"change"` allows file edits on your own or signed ecosystem documents (downgraded to `"read"` on team or unknown documents, and supported only when the active agent is Claude Code), and `"internet"` is refused with `level_unavailable`. |
| `folder` | `"remembered"` | `"remembered"` reuses the folder previously chosen for this document in HTML Clay (asking once if none is stored); `"choose"` opens the folder picker for a new choice. A page never sends a filesystem path. |
| `sources` | `false` | When `true`, asks the agent to cite git ranges or file line ranges, which HTML Clay expands from disk and git into run files. |
| `schema` | `{ type: "object" }` | Plain JSON Schema object for the answer, up to 64 KiB serialized. Overrides `result` when given. |
| `result`, `omit` | optional | Passed to `clay.ai.schema({ result, omit })` when `schema` is omitted. |
| `engine` | `""` | Agent name (`"claude"`, `"codex"`, `"agy"`, or `""` to use the person's preferred agent in HTML Clay). |
| `onStatus` | optional | Callback `({ text, phase })` for progress updates (`"asking"`, `"starting"`, `"working"`, `"collecting"`). |
| `signal` | optional | `AbortSignal`. Aborting sends `wire/cancel` and resolves `done` with `state: "cancelled"`. |

`await handle.done` resolves to:

```js
{ state, data, sources, folder, grant, engine, model, error }
```

- `state`: `"done"`, `"cancelled"` or `"error"`.
- `data`: parsed JSON value matching the schema when `state` is `"done"`, otherwise `null`.
- `sources`: map of cited source `id` strings to source entries (`{}` when `sources` was `false` or the request did not finish). Each entry carries `{ id, kind, bytes, sha256, truncated, skipped, text() }` plus `base` and `head` when `kind` is `"git"`, or `path` and `lines` (`[firstLine, lastLine]`) when `kind` is `"file"`. ClayJS starts fetching each run file from `/_/wire/runs/<run>/files/<id>` as soon as `done` arrives (HTML Clay keeps run files for 5 minutes and checks `Document-URL` and `Save-Token`); `await entry.text()` resolves to the source string or rejects with `code: "source_unavailable"`.
- `folder`: `{ name }` with the base name of the chosen folder (never its path) on `"done"`, otherwise `null`.
- `grant`: `{ level, remembered }` naming the effective level granted (`"read"` or `"change"`) and whether the folder came from a remembered grant, otherwise `null`.
- `engine`: agent that ran (`"claude"`, `"codex"` or `"agy"`), otherwise `null`.
- `model`: model identifier string used for the run, or `null`.
- `error`: `null` on `"done"`, or `{ code, message }` on `"error"` and `"cancelled"`.

Error codes on `outcome.error.code`:

- Before sending: `invalid_request` (missing or over 64 KiB `request`, bad `tools`/`folder`/`engine`, over 128 KiB total instructions, over 64 KiB schema, or bad `result` rule), `instruction_missing` (an instruction name has no tag on the page), `ai_unavailable` (`clay.wire` is not loaded, as in draft mode).
- From the wire and host: `helper_off` (AI Editing is turned off in HTML Clay), `helper_not_granted` (document is awaiting trust approval or was denied), `helper_busy` (this document already has an AI request running), `helper_cancelled`, `helper_timeout` (no folder chosen within 5 minutes, or the agent exceeded 15 minutes), `duplicate_request`, `invalid_type`, `level_unavailable`, `engine_unsupported`, `engine_failed`, `folder_missing`, `result_invalid`, `source_unsupported`, `source_refused`, `source_too_large`.

### `clay.ai.prompt(options)`

`clay.ai.prompt(options)` formats the same request synchronously as Markdown text for an agent running in a terminal, including the resolved instruction sections, the required JSON Schema, and step-by-step instructions to write the answer back.

| Option | Default | What it does |
|---|---|---|
| `request` | `""` | Prompt text placed at the top when non-empty. |
| `instructions` | `[]` | Instruction tag names resolved through `clay.instructions.get(name)` under `## Instructions`. |
| `schema` or `result`, `omit` | `{ type: "object" }` | Same answer schema options as `clay.ai.ask()`, rendered under `## Answer shape`. |
| `writeBack` | `"auto"` | `"agent"`, `"file"` or `"auto"`. `"auto"` picks `"agent"` when `clay.canEdit` is `true`, `clay.isDraftMode` is `false`, and `location.protocol` is `http:` or `https:`, and picks `"file"` otherwise. |
| `into` | `options.result` | Required when `writeBack` resolves to `"agent"`. Must name a list rule in the page's `api` rules tag (`/^[A-Za-z0-9_$-]+$/`). |
| `fileName` | `"answer.json"` | File name shown in the write-back steps when `writeBack` resolves to `"file"`. |
| `notes` | `""` | Extra Markdown appended at the end under `## Notes from this page` when non-empty. |

In `"agent"` mode, the prompt prints shell commands using `npx -y @panphora/clay-agent data` and `jq` to read the page's current data and append the new JSON object to the `into` list with `--if-match` ETag checking (retrying from the read step on conflict). Calling `prompt({ writeBack: "agent" })` on a non-HTTP(S) address or with an `into` key that does not name a list rule throws an `Error` with `code: "invalid_request"`. Unknown instruction names throw `code: "instruction_missing"`.

## Example

```html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Branch review</title>
  <script src="https://clayjs.com/v1/clay.js?plugins=ai"></script>
  <script type="application/json" data-rules-name="api" data-rules-version="1">
  {
    "reviews": ["#reviews > article", {
      "title": "h2",
      "summary": "p.summary",
      "diff": "pre.diff"
    }]
  }
  </script>
  <script type="text/x-clay-instructions" name="review">
  Summarize what changed on this branch in plain sentences. If sources are enabled, cite a git source with id "branch-diff".
  </script>
</head>
<body>
  <form id="ask-form" instructions="review" clay="freeze">
    <input name="q" value="Review the current branch against main.">
    <button type="submit">Ask agent</button>
    <button type="button" id="copy-prompt">Copy prompt</button>
    <p id="status"></p>
  </form>
  <section id="reviews"></section>

  <script>
    const form = document.getElementById("ask-form");
    const status = document.getElementById("status");

    const buildOptions = () => ({
      request: form.elements.q.value,
      instructions: clay.instructions.fromForm(form),
      result: "reviews",
      omit: ["diff"],
      sources: true,
    });

    form.addEventListener("submit", async (event) => {
      event.preventDefault();
      await clay.ready;
      const run = clay.ai.ask({
        ...buildOptions(),
        onStatus: ({ text }) => { status.textContent = text; },
      });
      const outcome = await run.done;
      if (outcome.state !== "done") {
        status.textContent = outcome.error.message;
        return;
      }
      const patch = outcome.sources["branch-diff"] ? await outcome.sources["branch-diff"].text() : "";
      const card = document.createElement("article");
      const h2 = document.createElement("h2");
      h2.textContent = outcome.data.title;
      const p = document.createElement("p");
      p.className = "summary";
      p.textContent = outcome.data.summary;
      const pre = document.createElement("pre");
      pre.className = "diff";
      pre.textContent = patch;
      card.append(h2, p, pre);
      document.getElementById("reviews").prepend(card);
      status.textContent = `Done (${outcome.engine})`;
    });

    document.getElementById("copy-prompt").addEventListener("click", async () => {
      await clay.ready;
      const text = clay.ai.prompt({ ...buildOptions(), into: "reviews" });
      await navigator.clipboard.writeText(text);
      status.textContent = "Prompt copied.";
    });
  </script>
</body>
</html>
```
