Skip to content

Claude Code is an agentic coding tool that lives in your terminal, understands your codebase, and helps you code faster by executing routine tasks, explaining complex code, and handling git workflows - all through natural language commands.

TypeScript

mods/agents-md: the AGENTS.md project-instructions mod (#95409)

Alice T'Poteata92ea1cdb11a
diff --git a/mods/README.md b/mods/README.md
index 34ccd54c..f80ba955 100644
--- a/mods/README.md
+++ b/mods/README.md
@@ -2,7 +2,7 @@
A mod is a Claude Code plugin whose behaviour lives in a hooks module: one
`register(on, options)` entry that hooks the engine's events as functions
-`($, e, next)`. These three ship inside Claude Code; this folder is their
+`($, e, next)`. These four ship inside Claude Code; this folder is their
source, published as it is built into the binary.
| Mod | What it does | Seated |
@@ -10,6 +10,7 @@ source, published as it is built into the binary.
| [`sec-default`](sec-default) | Keeps an organization's classic hooks, prompt content, managed settings and tool policy out of reach of the plugins a person installs; adds no policy of its own. | Outermost, on a machine with managed settings or for a Team or Enterprise organization, unless managed `prependPlugins` says otherwise |
| [`diff`](diff) | `/diff`: the session's uncommitted changes in a pane beside the transcript, file by file with their hunks, refreshed as Claude edits files and runs commands. | Built in |
| [`telemetry`](telemetry) | Adds `$.telemetry` (`log`, `mark`) in the `engine.create` fold so a plugin can record an event as a first-party analytics row; sends nothing wherever Claude Code's analytics are off. | Built in |
+| [`agents-md`](agents-md) | `AGENTS.md` as project instructions, by one option: loaded where the project has no `CLAUDE.md` of its own (`claude-md-or-agents-md`, the default) or beside it (`claude-md-and-agents-md`), placed and framed exactly as the engine places `CLAUDE.md`, nested ones on a `Read`; or the project's and the person's instruction files dropped and the organization's kept (`managed-only`); or `CLAUDE.md` alone, as the engine reads it (`claude-md`). | Built in |
Each folder is a complete plugin: `.claude-plugin/plugin.json`, a
`hooks/hooks.json` naming the module, and TypeScript under `hooks/` typed
diff --git a/mods/agents-md/.claude-plugin/plugin.json b/mods/agents-md/.claude-plugin/plugin.json
new file mode 100644
index 00000000..fe2c5dcc
--- /dev/null
+++ b/mods/agents-md/.claude-plugin/plugin.json
@@ -0,0 +1,23 @@
+{
+ "name": "agents-md",
+ "version": "0.1.0",
+ "description": "AGENTS.md as project instructions, by one option. Under claude-md-or-agents-md a project with no instruction files of its own gets its AGENTS.md files instead: a prompt.context hook asks $.fs.ancestors for every AGENTS.md and .claude/AGENTS.md from the filesystem root down to the working directory and hands them to the engine as project instruction files, which it renders, announces and withholds from agents exactly as it does CLAUDE.md, skipping any file the engine already loaded by import or link; a tool.call hook on Read attaches the ones under the project root as the engine attaches a nested CLAUDE.md. Under claude-md-and-agents-md every AGENTS.md is loaded beside CLAUDE.md. Under managed-only the project's and the person's instruction files are dropped and the organization's managed ones kept. Under claude-md the engine's walk stands alone. claude-md-or-agents-md is the default.",
+ "author": {
+ "name": "Anthropic"
+ },
+ "userConfig": {
+ "instructionFiles": {
+ "type": "string",
+ "title": "Project instructions",
+ "description": "\"claude-md\": CLAUDE.md only, loaded by the engine as today. \"claude-md-or-agents-md\" (default): a project with no CLAUDE.md of its own gets its AGENTS.md files instead, loaded exactly where and how CLAUDE.md would be. \"claude-md-and-agents-md\": AGENTS.md files are loaded beside CLAUDE.md (a file CLAUDE.md already imports or links to is not loaded twice). \"managed-only\": the project's and your own instruction files are dropped; the organization's managed CLAUDE.md and memory stay.",
+ "required": false,
+ "default": "claude-md-or-agents-md",
+ "options": [
+ "claude-md",
+ "claude-md-or-agents-md",
+ "claude-md-and-agents-md",
+ "managed-only"
+ ]
+ }
+ }
+}
diff --git a/mods/agents-md/README.md b/mods/agents-md/README.md
new file mode 100644
index 00000000..bf825bd0
--- /dev/null
+++ b/mods/agents-md/README.md
@@ -0,0 +1,163 @@
+# agents-md
+
+`AGENTS.md` read the way Claude Code reads `CLAUDE.md`, as a plugin, under
+one option, `instructionFiles`:
+
+- `claude-md`: only `CLAUDE.md` is loaded, by the engine, as today. The plugin
+ adds nothing.
+- `claude-md-or-agents-md` (the default): a project with no instruction files
+ of its own gets its `AGENTS.md` files instead, loaded exactly where and how
+ `CLAUDE.md` would be. "Of its own" is read off what the engine loaded for
+ the context: a `CLAUDE.md`, `.claude/CLAUDE.md` or `CLAUDE.local.md` in any
+ directory from the root down to the working directory leaves the whole
+ project to the engine, and the plugin stays out (the organization's managed
+ file, the person's `~/.claude/CLAUDE.md`, a `.claude/rules` file and an
+ added directory's `CLAUDE.md` do not count, as the nested walk does not see
+ them either). With none, every `AGENTS.md` and `.claude/AGENTS.md` on that
+ path joins the instruction files the engine renders, and a `Read` under a
+ subdirectory attaches that directory's `AGENTS.md` unless a `CLAUDE.md`
+ there claims it.
+- `claude-md-and-agents-md`: every `AGENTS.md` is loaded beside `CLAUDE.md`,
+ up and down the tree; a file `CLAUDE.md` already `@`-imports, or is a link
+ to, is not loaded a second time (compared by path, then by content).
+- `managed-only`: the project's checked-in and private instruction files and
+ the person's own are dropped from the context; the organization's managed
+ `CLAUDE.md` and the engine's memory stay. The engine's nested `CLAUDE.md`
+ attachments on `Read` are not an event yet and still arrive. (The engine's
+ `claudeMdExcludes` setting also exists, for user, project and local files,
+ and applies to the `AGENTS.md` files this plugin reads too.)
+
+How the files reach the model is the engine's doing, not the plugin's:
+`prompt.context` hands a hook the instruction files behind `claudeMd`
+(`{ path, kind, content, parent? }`, kinds `managed`, `user`, `project`,
+`local`, `memory`, in load order) and a hook answers the list changed. The
+engine then renders `claudeMd` from the answered files with its own preamble
+and framing, announces them by name, and keeps only the `managed` ones for an
+agent that omits project instructions (Explore, Plan, a custom agent with
+`omitClaudeMd`). So an `AGENTS.md` this plugin adds as a `project` file is, to
+everything downstream, a project instruction file: same place in the context,
+same framing, same omission rules, same announcement. An organization's
+prepended plugin on `prompt.context` sits above this one and has the last
+word on the files.
+
+`hooks/register.ts` is the module; everything under `hooks/` is its parts,
+importing `claude-code` and one another alone. `tests/` runs under
+`claude plugin test <this folder>`.
+
+## Setting the option
+
+As a built-in its option is the `/config` row "Project instructions", a
+picker over the four values, each described there. By hand it is
+
+```json
+{
+ "pluginConfigs": {
+ "agents-md@builtin": {
+ "options": { "instructionFiles": "claude-md-and-agents-md" }
+ }
+ }
+}
+```
+
+in user settings (`~/.claude/settings.json`), `--settings`, or managed
+settings; a project's `.claude/settings.json` is not read for plugin
+options. Changing it reloads the module, and the next context the engine
+builds (the next turn after the reload, a new conversation, `/clear`, a
+compaction) carries the new mode's files. A hand-typed value outside the
+four is told once in the transcript and reads as the default. `/plugin`
+lists the plugin among the built-ins, where a person can turn it off; with
+it off the engine reads `CLAUDE.md` alone.
+
+The option was first keyed `projectInstructions`, with the values `claude`,
+`agents-fallback`, `both` and `none`. A value still stored under that key is
+honoured for now while `instructionFiles` reads as its default: `none` as
+`managed-only`, `claude` as `claude-md`, `agents-fallback` as
+`claude-md-or-agents-md`, `both` as `claude-md-and-agents-md`, any other
+value as `claude-md` (which adds nothing, never as the default, which loads
+`AGENTS.md`); the first `session.start` of a load says in the transcript how
+it was read. Once `instructionFiles` is set to anything but its default, the
+old key is not read and the transcript says to remove it.
+
+Run from this folder instead (`claude --plugin-dir mods/agents-md`), the
+same entry is keyed `"agents-md"`.
+
+## What it hooks
+
+| event | what the hook does |
+| --- | --- |
+| `session.start` | in every mode: passes the start straight through and floats the usage row for the configured mode, never awaited; the first start of a load logs how a stored `projectInstructions` value is read. The session's start never waits on this plugin |
+| `prompt.context` | under `claude-md-or-agents-md` and `claude-md-and-agents-md`: walks `$.fs.ancestors` for the `AGENTS.md` files above the working directory and answers them as `project` instruction files, each `@` import its own entry after its file, each placed where a project file of its directory stands (root first, before the first deeper project file, else after the last project file, before memory); files the engine already holds by path or by content are left out; under `claude-md-or-agents-md` it answers nothing when the project has a `CLAUDE.md` of its own (among the handed files, else found by a `$.fs.ancestors` walk, so a `CLAUDE.md` the engine loaded and then withheld still counts), and logs which files it loaded once, and again after a move to another project root; handed unknown files (a hook above rewrote the `claudeMd` text) it adds nothing; the first context of a load sends the load row (counts) and the feature mark; under `managed-only` (matcher: a `project`, `local` or `user` file present): answers the list without those kinds |
+| `agent.spawn` on `fork: true` | under `claude-md-or-agents-md` and `claude-md-and-agents-md`: a fork the Agent tool starts shares its parent's prompt prefix, so the parent loop's delivered nested files are copied to the fork's loop and not attached to it again (a `/fork` or `/subtask` fork does not raise `agent.spawn` yet and starts from an empty set, as every fork did before; a fork started in the same tool batch as a `Read` inherits that Read's file although its prefix holds a placeholder for it) |
+| `tool.call` on `Read` | under `claude-md-or-agents-md` and `claude-md-and-agents-md`, for a file under the session's project root (`$.session.root()`, read live, so `/cd`, a host's directory change and worktree moves are followed and a moved root starts the delivered sets and the fallback decision over; a file elsewhere gets nothing, as the engine attaches no nested `CLAUDE.md` there): walks only the directories strictly between the root and the read file (`$.fs.ancestors` with `below: root`, as the engine walks only those for a nested `CLAUDE.md`, never up to the filesystem root again) and attaches their `AGENTS.md` files not yet given to that agent loop, not already among the context's instruction files (by path or, for a project file, by text) and not claimed by a `CLAUDE.md` of the same directory (or imported by one), as `context` after the tool result, framed `Contents of <path>:` byte for byte as the engine frames a nested `CLAUDE.md`, whatever its size; each file once per loop and conversation (the context's recomputation after a compaction or `/clear` starts the count over), the context's files never; a Read that attached files sends the nested row. A `~` or `~/` path is read under the home directory as the Read tool reads it |
+
+## What it calls on `$`
+
+`fs.ancestors` (with each found file's `parts`: the file and its imports
+apart; with `below` on a Read; it finds nothing on a thin client, whose
+workspace files are remote, as the engine's own walk does), `session.root`,
+`session.cwd`, `env.get` (`HOME` and `USERPROFILE`, once per load, the
+profile first on a Windows spelling of the working directory, so a `~/` path
+the model hands a Read resolves where the Read tool reads it), `ui.log`,
+`telemetry.log` and `telemetry.mark`.
+
+`$.telemetry` is the [telemetry](../telemetry) plugin's noun; where that
+plugin is not seated the calls find no noun and are dropped without a trace,
+and nothing else changes.
+
+## What it logs
+
+Counts and closed choices only; no path and no file text. Each row goes
+through `$.telemetry.log`, so it exists only where the telemetry plugin
+does:
+
+| event | when | properties |
+| --- | --- | --- |
+| `agents_md_mode` | once per fresh load, at `session.start` | `mode` (`claude-md` \| `claude-md-or-agents-md` \| `claude-md-and-agents-md` \| `managed-only`), `is_interactive` |
+| `agents_md_load` | the first context of a load, under `claude-md-or-agents-md` and `claude-md-and-agents-md` | `mode`, `file_count` (`AGENTS.md` files handed to the engine), `import_count` (their `@` imports), `total_content_length`, `yielded` (`claude-md-or-agents-md` stood down for a `CLAUDE.md` of the project's own), `walk_failed`; with it one `$.telemetry.mark` for feature `agents_md`: `ok`, or `sad` with reason `walk_failed` |
+| `agents_md_nested` | a Read that attached nested files | `mode`, `file_count` |
+
+## Where it still differs from CLAUDE.md
+
+All of these apply only to the modes that load `AGENTS.md`,
+`claude-md-or-agents-md` (the default) and `claude-md-and-agents-md`. Each
+names a loader fact a plugin cannot reach through the events it has today.
+
+1. Nested files attach on a text `Read` only. The engine also attaches a
+ directory's `CLAUDE.md` for a file `@`-mentioned in the prompt, for the
+ IDE's opened file or selection, and for the `Read` tool's notebook, image
+ and PDF results.
+2. A nested file the plugin attaches is not registered in the loop's
+ read-file state, so after a compaction the engine does not restore it
+ among the recently read files (the plugin attaches it again at the next
+ `Read` under that directory instead), and a change to it mid-session is
+ not re-announced.
+3. `/cd` carries the new tree's `CLAUDE.md` in its own notice; the plugin's
+ files for the new tree arrive in the same next request through the
+ engine's instructions announcement instead.
+4. Paths compare by spelling; the engine resolves a symlinked alias of the
+ working directory before deciding a file is inside it.
+5. `--add-dir` directories contribute no `AGENTS.md`, where the engine can
+ load their `CLAUDE.md`.
+6. `/memory` and the `#` shortcut do not know `AGENTS.md` files, and the
+ engine's own initial-load row does not count them (this plugin's
+ `agents_md_load` row does).
+7. An `@` import outside the working directory inside an `AGENTS.md` is
+ honoured only once the approval the engine asks for a `CLAUDE.md`'s
+ external imports has been given (without it the import is left out, as a
+ `CLAUDE.md`'s is); the approval dialog itself is raised for `CLAUDE.md`
+ imports alone.
+8. A subagent that is not a fork gets a nested `AGENTS.md` at its own first
+ `Read` under that directory even when its parent's loop was already given
+ it; the engine does not hand such a subagent the nested `CLAUDE.md` again.
+ A fork matches the engine on both sides.
+
+## Testing
+
+ claude plugin test mods/agents-md
+
+`tests/register.test.ts` covers the default mode: a project with `AGENTS.md`
+alone gets it as a project instruction file and one transcript line naming
+it, a project with a `CLAUDE.md` of its own is left to the engine without a
+walk, a failed walk leaves the context as handed, and the start hands
+`$.telemetry` the mode row alone where a test seats a provider for that
+noun, and goes on untouched where none is seated.
diff --git a/mods/agents-md/hooks/files/chain-root-of.ts b/mods/agents-md/hooks/files/chain-root-of.ts
new file mode 100644
index 00000000..998c68f8
--- /dev/null
+++ b/mods/agents-md/hooks/files/chain-root-of.ts
@@ -0,0 +1,28 @@
+import type { InstructionFile } from 'claude-code'
+
+/**
+ * The path of the file at the head of an instruction file's `@`-import
+ * chain; the file's own path when nothing imported it.
+ *
+ * Follows `parent` among the given files until a file nothing imported.
+ *
+ * @param file the instruction file
+ * @param byPath the files it may have come through, by path
+ * @returns the chain head's path
+ */
+export function chainRootOf(
+ file: InstructionFile,
+ byPath: ReadonlyMap<string, InstructionFile>,
+): string {
+ const seen = new Set<string>([file.path])
+ let path = file.path
+ let parent = file.parent
+
+ while (parent !== undefined && !seen.has(parent)) {
+ seen.add(parent)
+ path = parent
+ parent = byPath.get(parent)?.parent
+ }
+
+ return path
+}
diff --git a/mods/agents-md/hooks/files/dropped-kinds.ts b/mods/agents-md/hooks/files/dropped-kinds.ts
new file mode 100644
index 00000000..6c78ea78
--- /dev/null
+++ b/mods/agents-md/hooks/files/dropped-kinds.ts
@@ -0,0 +1,12 @@
+import type { InstructionFileKind } from 'claude-code'
+
+/**
+ * The kinds `managed-only` drops: the project's checked-in and private
+ * instruction files and the person's own; what it keeps is the organization's
+ * and memory.
+ */
+export const DROPPED_KINDS: readonly InstructionFileKind[] = [
+ 'project',
+ 'local',
+ 'user',
+]
diff --git a/mods/agents-md/hooks/files/files-of.ts b/mods/agents-md/hooks/files/files-of.ts
new file mode 100644
index 00000000..55cda9af
--- /dev/null
+++ b/mods/agents-md/hooks/files/files-of.ts
@@ -0,0 +1,20 @@
+import type { FsAncestor, InstructionFile } from 'claude-code'
+
+/**
+ * The found AGENTS.md files as project instruction files, one per file and
+ * per file it `@`-imported, in walk and load order.
+ *
+ * An import names the file that brought it as its parent.
+ *
+ * @param found what `$.fs.ancestors` found, root first
+ * @returns the instruction files, kind `project`
+ */
+export const filesOf = (found: readonly FsAncestor[]): InstructionFile[] =>
+ found.flatMap(entry =>
+ entry.parts.map((part, index) => ({
+ path: part.path,
+ kind: 'project' as const,
+ content: part.content,
+ ...(index > 0 && { parent: entry.parts[0]?.path ?? part.path }),
+ })),
+ )
diff --git a/mods/agents-md/hooks/files/index.ts b/mods/agents-md/hooks/files/index.ts
new file mode 100644
index 00000000..a383585c
--- /dev/null
+++ b/mods/agents-md/hooks/files/index.ts
@@ -0,0 +1,12 @@
+export * from './chain-root-of.js'
+export * from './dropped-kinds.js'
+export * from './files-of.js'
+export * from './insertion-index.js'
+export * from './is-claude-file-on-walk.js'
+export * from './is-kept-without-instructions.js'
+export * from './is-project-own.js'
+export * from './project-dir-of.js'
+export * from './unseen-files.js'
+export * from './with-project-files.js'
+
+export * as default from '.'
diff --git a/mods/agents-md/hooks/files/insertion-index.ts b/mods/agents-md/hooks/files/insertion-index.ts
new file mode 100644
index 00000000..8794674b
--- /dev/null
+++ b/mods/agents-md/hooks/files/insertion-index.ts
@@ -0,0 +1,44 @@
+import type { InstructionFile } from 'claude-code'
+
+import Frames from '../frames'
+import { chainRootOf } from './chain-root-of.js'
+import { isProjectOwn } from './is-project-own.js'
+import { projectDirOf } from './project-dir-of.js'
+
+/**
+ * Where a directory's AGENTS.md files go among the files the engine loaded,
+ * as the engine orders project files root first.
+ *
+ * Before the first project file of a deeper directory (an imported file
+ * counts with the file at the head of its chain), else after the last
+ * project file, else before the engine's memory, else at the end.
+ *
+ * @param files the list so far
+ * @param dir the directory the AGENTS.md files stand in
+ * @returns the index to insert at
+ */
+export function insertionIndex(
+ files: readonly InstructionFile[],
+ dir: string,
+): number {
+ const byPath = new Map(files.map(file => [file.path, file]))
+ const deeper = files.findIndex(
+ file =>
+ isProjectOwn(file) &&
+ Frames.isBelow(projectDirOf(chainRootOf(file, byPath)), dir),
+ )
+
+ if (deeper !== -1) {
+ return deeper
+ }
+
+ const lastOwn = files.findLastIndex(isProjectOwn)
+
+ if (lastOwn !== -1) {
+ return lastOwn + 1
+ }
+
+ const memory = files.findIndex(file => file.kind === 'memory')
+
+ return memory === -1 ? files.length : memory
+}
diff --git a/mods/agents-md/hooks/files/is-claude-file-on-walk.ts b/mods/agents-md/hooks/files/is-claude-file-on-walk.ts
new file mode 100644
index 00000000..ef0f8e24
--- /dev/null
+++ b/mods/agents-md/hooks/files/is-claude-file-on-walk.ts
@@ -0,0 +1,39 @@
+import type { InstructionFile } from 'claude-code'
+
+import Frames from '../frames'
+import Names from '../names'
+import { isProjectOwn } from './is-project-own.js'
+import { projectDirOf } from './project-dir-of.js'
+
+/**
+ * Whether a handed instruction file is a CLAUDE.md, `.claude/CLAUDE.md` or
+ * CLAUDE.local.md of a directory on the walk down to the session's root.
+ *
+ * What makes a project "have a CLAUDE.md of its own" for
+ * `claude-md-or-agents-md`, the same files the Read walk asks for; a rules
+ * file, an imported file or an added directory's CLAUDE.md is not one.
+ *
+ * @param file the handed instruction file
+ * @param root the session's project root, absolute
+ * @returns true for the project's own CLAUDE.md files on the walk
+ */
+export function isClaudeFileOnWalk(
+ file: InstructionFile,
+ root: string,
+): boolean {
+ const isOwnClaudeFile =
+ isProjectOwn(file) &&
+ file.parent === undefined &&
+ Names.CLAUDE_NAMES.some(name =>
+ Frames.normalSpellingOf(file.path).endsWith(`/${name}`),
+ )
+
+ if (!isOwnClaudeFile) {
+ return false
+ }
+
+ const dir = projectDirOf(file.path)
+ const spelledRoot = Frames.normalSpellingOf(root)
+
+ return dir === spelledRoot || Frames.isBelow(spelledRoot, dir)
+}
diff --git a/mods/agents-md/hooks/files/is-kept-without-instructions.ts b/mods/agents-md/hooks/files/is-kept-without-instructions.ts
new file mode 100644
index 00000000..39776225
--- /dev/null
+++ b/mods/agents-md/hooks/files/is-kept-without-instructions.ts
@@ -0,0 +1,13 @@
+import type { InstructionFile } from 'claude-code'
+
+import { DROPPED_KINDS } from './dropped-kinds.js'
+
+/**
+ * Whether `managed-only` keeps an instruction file: the organization's managed
+ * files and the engine's memory stay, the project's and the person's go.
+ *
+ * @param file the instruction file
+ * @returns true for a file `managed-only` leaves in place
+ */
+export const isKeptWithoutInstructions = (file: InstructionFile): boolean =>
+ !DROPPED_KINDS.includes(file.kind)
diff --git a/mods/agents-md/hooks/files/is-project-own.ts b/mods/agents-md/hooks/files/is-project-own.ts
new file mode 100644
index 00000000..09c002e9
--- /dev/null
+++ b/mods/agents-md/hooks/files/is-project-own.ts
@@ -0,0 +1,11 @@
+import type { InstructionFile } from 'claude-code'
+
+/**
+ * Whether an instruction file is one of the project's own (checked in or
+ * private), as opposed to the organization's, the person's or memory.
+ *
+ * @param file the instruction file
+ * @returns true for a `project` or `local` file
+ */
+export const isProjectOwn = (file: InstructionFile): boolean =>
+ file.kind === 'project' || file.kind === 'local'
diff --git a/mods/agents-md/hooks/files/project-dir-of.ts b/mods/agents-md/hooks/files/project-dir-of.ts
new file mode 100644
index 00000000..94ae684a
--- /dev/null
+++ b/mods/agents-md/hooks/files/project-dir-of.ts
@@ -0,0 +1,16 @@
+import Frames from '../frames'
+
+/**
+ * The project directory an instruction file speaks for: the directory
+ * holding it, or the one holding its `.claude` folder.
+ *
+ * @param path the file's path, absolute
+ * @returns the directory, in the walk's normal spelling
+ */
+export function projectDirOf(path: string): string {
+ const spelled = Frames.normalSpellingOf(path)
+ const claudeAt = spelled.lastIndexOf('/.claude/')
+ const cut = claudeAt === -1 ? spelled.lastIndexOf('/') : claudeAt
+
+ return cut <= 0 ? '/' : spelled.slice(0, cut)
+}
diff --git a/mods/agents-md/hooks/files/unseen-files.ts b/mods/agents-md/hooks/files/unseen-files.ts
new file mode 100644
index 00000000..f256c268
--- /dev/null
+++ b/mods/agents-md/hooks/files/unseen-files.ts
@@ -0,0 +1,40 @@
+import type { InstructionFile } from 'claude-code'
+
+import Frames from '../frames'
+import { isProjectOwn } from './is-project-own.js'
+
+/**
+ * The candidate files the engine has not already loaded, and no candidate
+ * twice.
+ *
+ * Leaves out one whose path is among the handed files (a CLAUDE.md that
+ * `@`-imports AGENTS.md) or whose text equals a handed project file's (a
+ * CLAUDE.md symlinked to AGENTS.md); other kinds' text does not count.
+ *
+ * @param candidates the AGENTS.md instruction files of a walk
+ * @param handed the files the engine handed the hook
+ * @returns the candidates worth adding, in order
+ */
+export function unseenFiles(
+ candidates: readonly InstructionFile[],
+ handed: readonly InstructionFile[],
+): InstructionFile[] {
+ const paths = new Set(handed.map(file => Frames.normalSpellingOf(file.path)))
+ const texts = new Set(
+ handed.filter(isProjectOwn).map(file => file.content.trim()),
+ )
+ const kept: InstructionFile[] = []
+
+ for (const file of candidates) {
+ const path = Frames.normalSpellingOf(file.path)
+ const text = file.content.trim()
+ const isSeen = paths.has(path) || (text !== '' && texts.has(text))
+
+ if (!isSeen) {
+ paths.add(path)
+ kept.push(file)
+ }
+ }
+
+ return kept
+}
diff --git a/mods/agents-md/hooks/files/with-project-files.ts b/mods/agents-md/hooks/files/with-project-files.ts
new file mode 100644
index 00000000..095727c1
--- /dev/null
+++ b/mods/agents-md/hooks/files/with-project-files.ts
@@ -0,0 +1,37 @@
+import type { InstructionFile } from 'claude-code'
+
+import { chainRootOf } from './chain-root-of.js'
+import { insertionIndex } from './insertion-index.js'
+import { projectDirOf } from './project-dir-of.js'
+
+/**
+ * The engine's instruction files with the AGENTS.md files placed where the
+ * engine would place a project file of their directory; as is when none.
+ *
+ * @param handed the files the engine handed the hook, in its order
+ * @param added the AGENTS.md instruction files to add, root first
+ * @returns the merged list
+ */
+export function withProjectFiles(
+ handed: readonly InstructionFile[],
+ added: readonly InstructionFile[],
+): readonly InstructionFile[] {
+ if (added.length === 0) {
+ return handed
+ }
+
+ const merged = [...handed]
+ const byPath = new Map(added.map(file => [file.path, file]))
+ const byDir = new Map<string, InstructionFile[]>()
+
+ for (const file of added) {
+ const dir = projectDirOf(chainRootOf(file, byPath))
+ byDir.set(dir, [...(byDir.get(dir) ?? []), file])
+ }
+
+ for (const [dir, files] of byDir) {
+ merged.splice(insertionIndex(merged, dir), 0, ...files)
+ }
+
+ return merged
+}
diff --git a/mods/agents-md/hooks/frames/absolute-of.ts b/mods/agents-md/hooks/frames/absolute-of.ts
new file mode 100644
index 00000000..e14ea5d5
--- /dev/null
+++ b/mods/agents-md/hooks/frames/absolute-of.ts
@@ -0,0 +1,33 @@
+/**
+ * A path the model handed a Read, made absolute as the Read tool reads it.
+ *
+ * As given when it is absolute; under the home directory (less any trailing
+ * separator) for `~` or a `~/` spelling when a home is known; else under the
+ * working directory.
+ *
+ * @param path the Read's `file_path` as the model spelled it
+ * @param root the session's working directory, absolute
+ * @param home the home directory, absolute, when the environment names one
+ * @returns the absolute path
+ */
+export function absoluteOf(path: string, root: string, home?: string): string {
+ const isHomeSpelling = path === '~' || path.startsWith('~/')
+
+ if (isHomeSpelling && home !== undefined) {
+ const bare = home.replace(/(?<=.)[\\/]+$/, '')
+
+ return path === '~' ? bare : `${bare}${separatorOf(bare)}${path.slice(2)}`
+ }
+
+ return /^(?:[A-Za-z]:)?[\\/]/.test(path)
+ ? path
+ : `${root}${separatorOf(root)}${path}`
+}
+
+/**
+ * The separator a directory's own spelling uses.
+ *
+ * @param dir an absolute directory
+ * @returns `\` for a backslash spelling, `/` otherwise
+ */
+const separatorOf = (dir: string): string => (dir.includes('\\') ? '\\' : '/')
diff --git a/mods/agents-md/hooks/frames/index.ts b/mods/agents-md/hooks/frames/index.ts
new file mode 100644
index 00000000..4d2639b7
--- /dev/null
+++ b/mods/agents-md/hooks/frames/index.ts
@@ -0,0 +1,8 @@
+export * from './absolute-of.js'
+export * from './is-below.js'
+export * from './is-file-at.js'
+export * from './nested-frame.js'
+export * from './normal-spelling-of.js'
+export * from './outside-claude-dirs.js'
+
+export * as default from '.'
diff --git a/mods/agents-md/hooks/frames/is-below.ts b/mods/agents-md/hooks/frames/is-below.ts
new file mode 100644
index 00000000..3fb1d232
--- /dev/null
+++ b/mods/agents-md/hooks/frames/is-below.ts
@@ -0,0 +1,12 @@
+import { normalSpellingOf } from './normal-spelling-of.js'
+
+/**
+ * Whether a path lies strictly inside a directory, by spelling (no links
+ * followed), as the engine bounds its nested CLAUDE.md walk.
+ *
+ * @param path an absolute path
+ * @param dir an absolute directory
+ * @returns true when `path` is under `dir` and not `dir` itself
+ */
+export const isBelow = (path: string, dir: string): boolean =>
+ normalSpellingOf(path).startsWith(`${normalSpellingOf(dir)}/`)
diff --git a/mods/agents-md/hooks/frames/is-file-at.ts b/mods/agents-md/hooks/frames/is-file-at.ts
new file mode 100644
index 00000000..569704fb
--- /dev/null
+++ b/mods/agents-md/hooks/frames/is-file-at.ts
@@ -0,0 +1,14 @@
+import type { InstructionFile } from 'claude-code'
+
+import { normalSpellingOf } from './normal-spelling-of.js'
+
+/**
+ * Whether an instruction file is the file at a path, however either is
+ * spelled.
+ *
+ * @param file the instruction file
+ * @param path an absolute path
+ * @returns true when both name one path
+ */
+export const isFileAt = (file: InstructionFile, path: string): boolean =>
+ normalSpellingOf(file.path) === normalSpellingOf(path)
diff --git a/mods/agents-md/hooks/frames/nested-frame.ts b/mods/agents-md/hooks/frames/nested-frame.ts
new file mode 100644
index 00000000..57e1a3b9
--- /dev/null
+++ b/mods/agents-md/hooks/frames/nested-frame.ts
@@ -0,0 +1,11 @@
+import type { InstructionFile } from 'claude-code'
+
+/**
+ * An instruction file as a Read attaches it, framed as the engine frames a
+ * nested CLAUDE.md: the text as loaded, trailing newline and all.
+ *
+ * @param file the file
+ * @returns the `Contents of <path>` frame over its text
+ */
+export const nestedFrame = (file: InstructionFile): string =>
+ `Contents of ${file.path}:\n\n${file.content}`
diff --git a/mods/agents-md/hooks/frames/normal-spelling-of.ts b/mods/agents-md/hooks/frames/normal-spelling-of.ts
new file mode 100644
index 00000000..245d95a7
--- /dev/null
+++ b/mods/agents-md/hooks/frames/normal-spelling-of.ts
@@ -0,0 +1,9 @@
+/**
+ * A path with one separator spelling and no trailing separator, so two
+ * spellings of one path compare equal (`C:/repo/x` and `C:\repo\x`).
+ *
+ * @param path an absolute path as a walk or the model spelled it
+ * @returns the path with `/` for every separator, no trailing one
+ */
+export const normalSpellingOf = (path: string): string =>
+ path.replaceAll('\\', '/').replace(/(?<=.)\/+$/, '')
diff --git a/mods/agents-md/hooks/frames/outside-claude-dirs.ts b/mods/agents-md/hooks/frames/outside-claude-dirs.ts
new file mode 100644
index 00000000..a3bbbaf1
--- /dev/null
+++ b/mods/agents-md/hooks/frames/outside-claude-dirs.ts
@@ -0,0 +1,21 @@
+import type { FsAncestor } from 'claude-code'
+
+/**
+ * The AGENTS.md files standing in a directory with no CLAUDE.md of its own,
+ * in walk order.
+ *
+ * Where the engine attaches a directory's CLAUDE.md, that directory's
+ * AGENTS.md is left out rather than merged.
+ *
+ * @param agents the AGENTS.md files of a walk, root first
+ * @param claude the CLAUDE.md files of the same walk
+ * @returns the AGENTS.md files whose directory holds no CLAUDE.md
+ */
+export function outsideClaudeDirs(
+ agents: readonly FsAncestor[],
+ claude: readonly FsAncestor[],
+): readonly FsAncestor[] {
+ const taken = new Set(claude.map(file => file.dir))
+
+ return agents.filter(file => !taken.has(file.dir))
+}
diff --git a/mods/agents-md/hooks/hooks.json b/mods/agents-md/hooks/hooks.json
new file mode 100644
index 00000000..e883fc78
--- /dev/null
+++ b/mods/agents-md/hooks/hooks.json
@@ -0,0 +1,4 @@
+{
+ "description": "AGENTS.md up and down the tree like CLAUDE.md, by the instructionFiles option: under claude-md-or-agents-md (the default; where the project has no CLAUDE.md of its own on the walk) or claude-md-and-agents-md, a prompt.context hook hands every ancestor AGENTS.md to the engine among its instruction files, skipping ones it already loaded, and a tool.call hook on Read attaches the AGENTS.md files of the directories between the project root and a read file, once a conversation and agent loop (an Agent-tool fork inherits its parent's); under managed-only, a prompt.context hook keeps only the organization's managed files and memory; under claude-md, nothing is added; in every mode a session.start hook sends the plugin's usage row through $.telemetry where that noun is seated",
+ "modules": ["./register.ts"]
+}
diff --git a/mods/agents-md/hooks/index.ts b/mods/agents-md/hooks/index.ts
new file mode 100644
index 00000000..b782983d
--- /dev/null
+++ b/mods/agents-md/hooks/index.ts
@@ -0,0 +1,8 @@
+export * from './files'
+export * from './frames'
+export * from './modes'
+export * from './names'
+export * from './register.js'
+export * from './telemetry'
+
+export * as default from '.'
diff --git a/mods/agents-md/hooks/modes/default-mode.ts b/mods/agents-md/hooks/modes/default-mode.ts
new file mode 100644
index 00000000..95422594
--- /dev/null
+++ b/mods/agents-md/hooks/modes/default-mode.ts
@@ -0,0 +1,8 @@
+import type { Mode } from './types'
+
+/**
+ * The mode an unset option reads as: AGENTS.md where the project has no
+ * CLAUDE.md of its own, the engine's CLAUDE.md walk standing alone where it
+ * has one.
+ */
+export const DEFAULT_MODE: Mode = 'claude-md-or-agents-md'
diff --git a/mods/agents-md/hooks/modes/index.ts b/mods/agents-md/hooks/modes/index.ts
new file mode 100644
index 00000000..153128bd
--- /dev/null
+++ b/mods/agents-md/hooks/modes/index.ts
@@ -0,0 +1,7 @@
+export * from './default-mode.js'
+export * from './legacy-mode-of.js'
+export * from './mode-of.js'
+export * from './modes.js'
+export * from './types'
+
+export * as default from '.'
diff --git a/mods/agents-md/hooks/modes/legacy-mode-of.ts b/mods/agents-md/hooks/modes/legacy-mode-of.ts
new file mode 100644
index 00000000..bce1f7f6
--- /dev/null
+++ b/mods/agents-md/hooks/modes/legacy-mode-of.ts
@@ -0,0 +1,33 @@
+import type { Mode } from './types'
+
+/**
+ * Each value the option took under its old key, `projectInstructions`, and
+ * the mode that keeps its meaning.
+ */
+const LEGACY_MODES: Readonly<Record<string, Mode>> = {
+ none: 'managed-only',
+ claude: 'claude-md',
+ 'agents-fallback': 'claude-md-or-agents-md',
+ both: 'claude-md-and-agents-md',
+}
+
+/**
+ * The mode a value stored under the old `projectInstructions` key keeps; a
+ * value it never took reads as `claude-md`, which adds nothing, never as the
+ * default, which loads AGENTS.md.
+ *
+ * COMPAT_BREAK(agents-md-project-instructions): drop the projectInstructions
+ * mapping once stored settings have migrated.
+ *
+ * @param value the `projectInstructions` option as stored
+ * @returns the mode it keeps, undefined when nothing is stored there
+ */
+export function legacyModeOf(value: unknown): Mode | undefined {
+ if (value === undefined) {
+ return undefined
+ }
+
+ return (
+ (typeof value === 'string' ? LEGACY_MODES[value] : undefined) ?? 'claude-md'
+ )
+}
diff --git a/mods/agents-md/hooks/modes/mode-of.ts b/mods/agents-md/hooks/modes/mode-of.ts
new file mode 100644
index 00000000..4dc007a3
--- /dev/null
+++ b/mods/agents-md/hooks/modes/mode-of.ts
@@ -0,0 +1,13 @@
+import { DEFAULT_MODE } from './default-mode.js'
+import { MODES } from './modes.js'
+import type { Mode } from './types'
+
+/**
+ * The mode a stored option names; unset, a typo or a value of another type
+ * names the default.
+ *
+ * @param value the `instructionFiles` option as stored
+ * @returns the mode named, DEFAULT_MODE for anything else
+ */
+export const modeOf = (value: unknown): Mode =>
+ MODES.find(mode => mode === value) ?? DEFAULT_MODE
diff --git a/mods/agents-md/hooks/modes/modes.ts b/mods/agents-md/hooks/modes/modes.ts
new file mode 100644
index 00000000..0fccea61
--- /dev/null
+++ b/mods/agents-md/hooks/modes/modes.ts
@@ -0,0 +1,11 @@
+import type { Mode } from './types'
+
+/**
+ * Every mode, in the order the option's description names them.
+ */
+export const MODES: readonly Mode[] = [
+ 'claude-md',
+ 'claude-md-or-agents-md',
+ 'claude-md-and-agents-md',
+ 'managed-only',
+]
diff --git a/mods/agents-md/hooks/modes/types/index.ts b/mods/agents-md/hooks/modes/types/index.ts
new file mode 100644
index 00000000..77853f71
--- /dev/null
+++ b/mods/agents-md/hooks/modes/types/index.ts
@@ -0,0 +1,3 @@
+export * from './mode'
+
+export * as default from '.'
diff --git a/mods/agents-md/hooks/modes/types/mode/index.ts b/mods/agents-md/hooks/modes/types/mode/index.ts
new file mode 100644
index 00000000..3ff287b3
--- /dev/null
+++ b/mods/agents-md/hooks/modes/types/mode/index.ts
@@ -0,0 +1,3 @@
+export type * from './mode.js'
+
+export * as default from '.'
diff --git a/mods/agents-md/hooks/modes/types/mode/mode.ts b/mods/agents-md/hooks/modes/types/mode/mode.ts
new file mode 100644
index 00000000..db4d336e
--- /dev/null
+++ b/mods/agents-md/hooks/modes/types/mode/mode.ts
@@ -0,0 +1,15 @@
+/**
+ * Which project instructions the plugin loads: the `instructionFiles`
+ * option.
+ *
+ * `claude-md` loads none of its own, the engine's CLAUDE.md walk standing
+ * alone; `claude-md-or-agents-md` loads AGENTS.md where the project has no
+ * CLAUDE.md; `claude-md-and-agents-md` loads AGENTS.md beside CLAUDE.md;
+ * `managed-only` loads neither, taking the project's and the person's
+ * CLAUDE.md files out of the conversation's context.
+ */
+export type Mode =
+ | 'claude-md'
+ | 'claude-md-or-agents-md'
+ | 'claude-md-and-agents-md'
+ | 'managed-only'
diff --git a/mods/agents-md/hooks/names/agents-names.ts b/mods/agents-md/hooks/names/agents-names.ts
new file mode 100644
index 00000000..8a9f2b93
--- /dev/null
+++ b/mods/agents-md/hooks/names/agents-names.ts
@@ -0,0 +1,5 @@
+/**
+ * The instruction files read in each directory, in the order the engine
+ * reads CLAUDE.md and .claude/CLAUDE.md.
+ */
+export const AGENTS_NAMES = ['AGENTS.md', '.claude/AGENTS.md'] as const
diff --git a/mods/agents-md/hooks/names/claude-names.ts b/mods/agents-md/hooks/names/claude-names.ts
new file mode 100644
index 00000000..75eae387
--- /dev/null
+++ b/mods/agents-md/hooks/names/claude-names.ts
@@ -0,0 +1,11 @@
+/**
+ * The engine's own instruction files, as it reads them in each directory of
+ * its walk and under a read file.
+ *
+ * A directory holding one has project instructions the engine loads itself.
+ */
+export const CLAUDE_NAMES = [
+ 'CLAUDE.md',
+ '.claude/CLAUDE.md',
+ 'CLAUDE.local.md',
+] as const
diff --git a/mods/agents-md/hooks/names/index.ts b/mods/agents-md/hooks/names/index.ts
new file mode 100644
index 00000000..12312407
--- /dev/null
+++ b/mods/agents-md/hooks/names/index.ts
@@ -0,0 +1,5 @@
+export * from './agents-names.js'
+export * from './claude-names.js'
+export * from './main-loop.js'
+
+export * as default from '.'
diff --git a/mods/agents-md/hooks/names/main-loop.ts b/mods/agents-md/hooks/names/main-loop.ts
new file mode 100644
index 00000000..5138ec84
--- /dev/null
+++ b/mods/agents-md/hooks/names/main-loop.ts
@@ -0,0 +1,5 @@
+/**
+ * The key the main conversation's delivered files are kept under; a
+ * subagent's are kept under its `agentId`.
+ */
+export const MAIN_LOOP = 'main'
diff --git a/mods/agents-md/hooks/register.ts b/mods/agents-md/hooks/register.ts
new file mode 100644
index 00000000..8ebd38df
--- /dev/null
+++ b/mods/agents-md/hooks/register.ts
@@ -0,0 +1,272 @@
+import type {
+ EngineInterface,
+ FsAncestor,
+ InstructionFile,
+ On,
+ PluginOptions,
+} from 'claude-code'
+
+import Files from './files'
+import Frames from './frames'
+import Modes from './modes'
+import Names from './names'
+import Telemetry from './telemetry'
+
+/**
+ * No files: what a walk not taken, or one that failed, found.
+ */
+const NONE: readonly FsAncestor[] = []
+
+/**
+ * Registers the plugin's hooks for the mode `instructionFiles` names
+ * (`claude-md-or-agents-md` when unset; the manifest lists the four, nothing
+ * else arrives).
+ *
+ * `claude-md`: nothing beyond the usage row, the engine's CLAUDE.md walk
+ * standing alone. `managed-only`: the project's and the person's instruction
+ * files dropped, the organization's kept. `claude-md-or-agents-md` (a project
+ * with none of its own) and `claude-md-and-agents-md`: AGENTS.md files joined
+ * to the engine's instruction files, nested ones on a Read. Every mode sends
+ * its usage rows through `$.telemetry` where that noun is seated and drops
+ * them where it is not.
+ *
+ * @param on the engine's registrar
+ * @param options the plugin's options; `instructionFiles` is `claude-md`,
+ * `claude-md-or-agents-md`, `claude-md-and-agents-md` or `managed-only`
+ */
+export function register(on: On, options: PluginOptions): void {
+ const named = Modes.modeOf(options.instructionFiles)
+ // COMPAT_BREAK(agents-md-project-instructions): drop the projectInstructions
+ // mapping once stored settings have migrated. The host fills in the default,
+ // so an instructionFiles set to it cannot be told from one left unset.
+ const legacy = Modes.legacyModeOf(options.projectInstructions)
+ const isLegacyRead = legacy !== undefined && named === Modes.DEFAULT_MODE
+ const mode = isLegacyRead ? legacy : named
+ let isRenameTold = legacy === undefined
+
+ on('session.start', ($, e, next) => {
+ Telemetry.quietly(() =>
+ $.telemetry.log(Telemetry.modeRowOf(mode, e.isInteractive)),
+ )
+
+ if (!isRenameTold) {
+ isRenameTold = true
+ $.ui.log(
+ isLegacyRead
+ ? 'option projectInstructions in settings is honoured for now, ' +
+ `read as instructionFiles ${mode}; set instructionFiles to ` +
+ `${mode} and remove projectInstructions`
+ : `option projectInstructions in settings is not read: ` +
+ `instructionFiles ${mode} is set; remove projectInstructions`,
+ )
+ }
+
+ return next(e)
+ })
+
+ if (mode === 'claude-md') {
+ return
+ }
+
+ if (mode === 'managed-only') {
+ on(
+ 'prompt.context',
+ { instructionFiles: { kind: Files.DROPPED_KINDS } },
+ ($, e, next) =>
+ next({
+ ...e,
+ instructionFiles: e.instructionFiles?.filter(
+ Files.isKeptWithoutInstructions,
+ ),
+ }),
+ )
+
+ return
+ }
+
+ const isFallback = mode === 'claude-md-or-agents-md'
+ const given = new Map<string, Set<string>>()
+ let inContext: readonly InstructionFile[] = []
+ let home: string | undefined
+ let isClaudeProject: boolean | undefined
+ let rootSeen: string | undefined
+ let rootLogged: string | undefined
+ let isCounted = false
+
+ on('prompt.context', async ($, e, next) => {
+ const handed = e.instructionFiles
+
+ if (handed === undefined) {
+ return next(e).finally(() => {
+ given.clear()
+ })
+ }
+
+ const root = isFallback ? await $.session.root() : undefined
+ rootSeen = root ?? rootSeen
+ let isWalkFailed = false
+ // The walk, not only what was handed: the engine can withhold a project
+ // CLAUDE.md it loaded, and the project still has one.
+ isClaudeProject =
+ root !== undefined &&
+ (handed.some(file => Files.isClaudeFileOnWalk(file, root)) ||
+ (await $.fs.ancestors({ names: Names.CLAUDE_NAMES }).then(
+ files => files.length > 0,
+ () => {
+ isWalkFailed = true
+
+ return true
+ },
+ )))
+ const found = isClaudeProject
+ ? NONE
+ : await $.fs.ancestors({ names: Names.AGENTS_NAMES }).catch(() => {
+ isWalkFailed = true
+
+ return NONE
+ })
+ const added = Files.unseenFiles(Files.filesOf(found), handed)
+
+ if (!isCounted) {
+ isCounted = true
+ const counts = Telemetry.loadCountsOf(
+ added,
+ isClaudeProject && !isWalkFailed,
+ isWalkFailed,
+ )
+ Telemetry.quietly(() =>
+ $.telemetry.log(Telemetry.loadRowOf(mode, counts)),
+ )
+ Telemetry.quietly(() => $.telemetry.mark(Telemetry.loadMarkOf(counts)))
+ }
+
+ const isFirstLoad =
+ root !== undefined && root !== rootLogged && added.length > 0
+
+ if (isFirstLoad) {
+ rootLogged = root
+ $.ui.log(
+ 'no CLAUDE.md found; AGENTS.md loaded: ' +
+ added
+ .filter(file => file.parent === undefined)
+ .map(file => file.path)
+ .join(', '),
+ )
+ }
+
+ const instructionFiles = Files.withProjectFiles(handed, added)
+
+ return next({ ...e, instructionFiles }).finally(() => {
+ given.clear()
+ inContext = instructionFiles
+ })
+ })
+
+ on('agent.spawn', { fork: true }, async ($, e, next) => {
+ const result = await next(e)
+
+ if (result.agentId !== undefined) {
+ const parent = given.get(e.parentAgentId ?? Names.MAIN_LOOP)
+ given.set(result.agentId, new Set(parent))
+ }
+
+ return result
+ })
+
+ on('tool.call', { tool: 'Read' }, async ($, e, next) => {
+ const result = await next(e)
+ const isSettledElsewhere =
+ e.tool !== 'Read' || result.deny !== undefined || result.isError
+
+ if (isSettledElsewhere) {
+ return result
+ }
+
+ const [root, cwd] = await Promise.all([$.session.root(), $.session.cwd()])
+ home ??= await homeOf($, cwd)
+ const read = Frames.absoluteOf(e.file_path, cwd, home)
+
+ if (root !== rootSeen) {
+ rootSeen = root
+ isClaudeProject = undefined
+ given.clear()
+ }
+
+ isClaudeProject ??=
+ isFallback &&
+ (await $.fs.ancestors({ names: Names.CLAUDE_NAMES })).length > 0
+ const isOutOfReach = isClaudeProject || !Frames.isBelow(read, root)
+
+ if (isOutOfReach) {
+ return result
+ }
+
+ const [stack, claude] = await Promise.all([
+ $.fs.ancestors({ names: Names.AGENTS_NAMES, of: read, below: root }),
+ $.fs.ancestors({ names: Names.CLAUDE_NAMES, of: read, below: root }),
+ ]).catch((): [typeof NONE, typeof NONE] => [NONE, NONE])
+ const loop = e.agentId ?? Names.MAIN_LOOP
+ const sent = given.get(loop) ?? new Set<string>()
+ given.set(loop, sent)
+ const nested = (
+ isFallback ? Frames.outsideClaudeDirs(stack, claude) : stack
+ ).filter(file => Frames.isBelow(file.dir, root))
+ const fresh = Files.unseenFiles(Files.filesOf(nested), [
+ ...inContext,
+ ...Files.filesOf(claude),
+ ]).filter(file => !sent.has(file.path))
+ const attached = fresh.filter(file => !Frames.isFileAt(file, read))
+ const isWholeRead = e.offset === undefined && e.limit === undefined
+
+ for (const file of fresh) {
+ const isSent =
+ attached.includes(file) || (Frames.isFileAt(file, read) && isWholeRead)
+
+ if (isSent) {
+ sent.add(file.path)
+ }
+ }
+
+ const hasAttached = attached.length > 0
+
+ if (hasAttached) {
+ Telemetry.quietly(() =>
+ $.telemetry.log(Telemetry.nestedRowOf(mode, attached.length)),
+ )
+ }
+
+ return hasAttached
+ ? {
+ ...result,
+ context: [
+ ...(result.context ?? []),
+ ...attached.map(Frames.nestedFrame),
+ ],
+ }
+ : result
+ })
+}
+
+/**
+ * The home directory a `~` in a Read's path stands for, read the way the
+ * Read tool reads it.
+ *
+ * The profile directory on a Windows spelling of the working directory,
+ * else `HOME`, each falling back to the other.
+ *
+ * @param $ the engine, as the `tool.call` hook holds it
+ * @param cwd the session's working directory, whose spelling names the platform
+ * @returns the home directory, or undefined when the environment names none
+ */
+async function homeOf(
+ $: EngineInterface,
+ cwd: string,
+): Promise<string | undefined> {
+ const [home, profile] = await Promise.all([
+ $.env.get('HOME'),
+ $.env.get('USERPROFILE'),
+ ])
+ const isWindowsSpelling = cwd.includes('\\')
+
+ return isWindowsSpelling ? (profile ?? home) : (home ?? profile)
+}
diff --git a/mods/agents-md/hooks/telemetry/feature-name.ts b/mods/agents-md/hooks/telemetry/feature-name.ts
new file mode 100644
index 00000000..417a1daa
--- /dev/null
+++ b/mods/agents-md/hooks/telemetry/feature-name.ts
@@ -0,0 +1,5 @@
+/**
+ * The plugin's name on the product-wide feature surface: its marks are
+ * `$.telemetry.mark` rows carrying this `feature_name`.
+ */
+export const FEATURE_NAME = 'agents_md'
diff --git a/mods/agents-md/hooks/telemetry/index.ts b/mods/agents-md/hooks/telemetry/index.ts
new file mode 100644
index 00000000..aa1162fe
--- /dev/null
+++ b/mods/agents-md/hooks/telemetry/index.ts
@@ -0,0 +1,15 @@
+export * from './feature-name.js'
+export * from './load-counts-of.js'
+export * from './load-event.js'
+export * from './load-mark-of.js'
+export * from './load-row-of.js'
+export * from './mode-choice-of.js'
+export * from './mode-event.js'
+export * from './mode-row-of.js'
+export * from './nested-event.js'
+export * from './nested-row-of.js'
+export * from './quietly.js'
+export * from './types'
+export * from './walk-failed-reason.js'
+
+export * as default from '.'
diff --git a/mods/agents-md/hooks/telemetry/load-counts-of.ts b/mods/agents-md/hooks/telemetry/load-counts-of.ts
new file mode 100644
index 00000000..ccd08986
--- /dev/null
+++ b/mods/agents-md/hooks/telemetry/load-counts-of.ts
@@ -0,0 +1,35 @@
+import type { InstructionFile } from 'claude-code'
+
+import type { LoadCounts } from './types'
+
+/**
+ * The first context's counts from the files it added: an entry with a parent
+ * is an `@` import, one without is an AGENTS.md file.
+ *
+ * @param added the AGENTS.md instruction files handed to the engine, imports
+ * among them
+ * @param isYielded whether `claude-md-or-agents-md` stood down for a CLAUDE.md
+ * @param isWalkFailed whether the walk threw
+ * @returns the counts the load row and mark are built from
+ */
+export function loadCountsOf(
+ added: readonly InstructionFile[],
+ isYielded: boolean,
+ isWalkFailed: boolean,
+): LoadCounts {
+ const importCount = added.reduce(
+ (sum, file) => sum + (file.parent === undefined ? 0 : 1),
+ 0,
+ )
+
+ return {
+ fileCount: added.length - importCount,
+ importCount,
+ totalContentLength: added.reduce(
+ (sum, file) => sum + file.content.length,
+ 0,
+ ),
+ isYielded,
+ isWalkFailed,
+ }
+}
diff --git a/mods/agents-md/hooks/telemetry/load-event.ts b/mods/agents-md/hooks/telemetry/load-event.ts
new file mode 100644
index 00000000..6f8ec7fa
--- /dev/null
+++ b/mods/agents-md/hooks/telemetry/load-event.ts
@@ -0,0 +1,7 @@
+/**
+ * The row the first context of a load sends under `claude-md-or-agents-md` and
+ * `claude-md-and-agents-md`: what was handed on, in counts.
+ *
+ * The engine's own initial-load row counts its CLAUDE.md files the same way.
+ */
+export const LOAD_EVENT = 'agents_md_load'
diff --git a/mods/agents-md/hooks/telemetry/load-mark-of.ts b/mods/agents-md/hooks/telemetry/load-mark-of.ts
new file mode 100644
index 00000000..5e5a3869
--- /dev/null
+++ b/mods/agents-md/hooks/telemetry/load-mark-of.ts
@@ -0,0 +1,15 @@
+import { FEATURE_NAME } from './feature-name.js'
+import type { LoadCounts, TelemetryMark } from './types'
+import { WALK_FAILED_REASON } from './walk-failed-reason.js'
+
+/**
+ * The first context's feature mark: `ok`, or `sad` when the walk failed and
+ * the context went on without AGENTS.md.
+ *
+ * @param counts what the first context handed on
+ * @returns the mark to send
+ */
+export const loadMarkOf = (counts: LoadCounts): TelemetryMark =>
+ counts.isWalkFailed
+ ? { feature: FEATURE_NAME, kind: 'sad', reason: WALK_FAILED_REASON }
+ : { feature: FEATURE_NAME, kind: 'ok' }
diff --git a/mods/agents-md/hooks/telemetry/load-row-of.ts b/mods/agents-md/hooks/telemetry/load-row-of.ts
new file mode 100644
index 00000000..037a6dff
--- /dev/null
+++ b/mods/agents-md/hooks/telemetry/load-row-of.ts
@@ -0,0 +1,27 @@
+import type Modes from '../modes'
+import { LOAD_EVENT } from './load-event.js'
+import { modeChoiceOf } from './mode-choice-of.js'
+import type { LoadCounts, TelemetryRow } from './types'
+
+/**
+ * The first-context row: the mode and what was handed to the engine, in
+ * counts only; no path and no text.
+ *
+ * @param mode the configured mode
+ * @param counts what the first context handed on
+ * @returns the row to send
+ */
+export const loadRowOf = (
+ mode: Modes.Mode,
+ counts: LoadCounts,
+): TelemetryRow => ({
+ event: LOAD_EVENT,
+ props: {
+ mode: modeChoiceOf(mode),
+ file_count: counts.fileCount,
+ import_count: counts.importCount,
+ total_content_length: counts.totalContentLength,
+ yielded: counts.isYielded,
+ walk_failed: counts.isWalkFailed,
+ },
+})
diff --git a/mods/agents-md/hooks/telemetry/mode-choice-of.ts b/mods/agents-md/hooks/telemetry/mode-choice-of.ts
new file mode 100644
index 00000000..37db0792
--- /dev/null
+++ b/mods/agents-md/hooks/telemetry/mode-choice-of.ts
@@ -0,0 +1,13 @@
+import Modes from '../modes'
+import type { TelemetryProp } from './types'
+
+/**
+ * The mode as a row carries it: the value with the four it is chosen from.
+ *
+ * @param mode the configured mode
+ * @returns the `mode` property
+ */
+export const modeChoiceOf = (mode: Modes.Mode): TelemetryProp => ({
+ value: mode,
+ of: Modes.MODES,
+})
diff --git a/mods/agents-md/hooks/telemetry/mode-event.ts b/mods/agents-md/hooks/telemetry/mode-event.ts
new file mode 100644
index 00000000..054560a6
--- /dev/null
+++ b/mods/agents-md/hooks/telemetry/mode-event.ts
@@ -0,0 +1,5 @@
+/**
+ * The row a fresh load sends at `session.start`, whatever the mode: which
+ * mode is configured.
+ */
+export const MODE_EVENT = 'agents_md_mode'
diff --git a/mods/agents-md/hooks/telemetry/mode-row-of.ts b/mods/agents-md/hooks/telemetry/mode-row-of.ts
new file mode 100644
index 00000000..1c3656ef
--- /dev/null
+++ b/mods/agents-md/hooks/telemetry/mode-row-of.ts
@@ -0,0 +1,20 @@
+import type Modes from '../modes'
+import { modeChoiceOf } from './mode-choice-of.js'
+import { MODE_EVENT } from './mode-event.js'
+import type { TelemetryRow } from './types'
+
+/**
+ * The `session.start` row: the configured mode and whether a person is at
+ * the terminal.
+ *
+ * @param mode the configured mode
+ * @param isInteractive whether a person is at the terminal
+ * @returns the row to send
+ */
+export const modeRowOf = (
+ mode: Modes.Mode,
+ isInteractive: boolean,
+): TelemetryRow => ({
+ event: MODE_EVENT,
+ props: { mode: modeChoiceOf(mode), is_interactive: isInteractive },
+})
diff --git a/mods/agents-md/hooks/telemetry/nested-event.ts b/mods/agents-md/hooks/telemetry/nested-event.ts
new file mode 100644
index 00000000..cade06bc
--- /dev/null
+++ b/mods/agents-md/hooks/telemetry/nested-event.ts
@@ -0,0 +1,5 @@
+/**
+ * The row a Read sends when it attached nested AGENTS.md files; a Read that
+ * attached none sends nothing.
+ */
+export const NESTED_EVENT = 'agents_md_nested'
diff --git a/mods/agents-md/hooks/telemetry/nested-row-of.ts b/mods/agents-md/hooks/telemetry/nested-row-of.ts
new file mode 100644
index 00000000..226fee5d
--- /dev/null
+++ b/mods/agents-md/hooks/telemetry/nested-row-of.ts
@@ -0,0 +1,20 @@
+import type Modes from '../modes'
+import { modeChoiceOf } from './mode-choice-of.js'
+import { NESTED_EVENT } from './nested-event.js'
+import type { TelemetryRow } from './types'
+
+/**
+ * The row of a Read that attached nested AGENTS.md files: the mode and how
+ * many it attached.
+ *
+ * @param mode the configured mode
+ * @param fileCount the files attached to this Read's result
+ * @returns the row to send
+ */
+export const nestedRowOf = (
+ mode: Modes.Mode,
+ fileCount: number,
+): TelemetryRow => ({
+ event: NESTED_EVENT,
+ props: { mode: modeChoiceOf(mode), file_count: fileCount },
+})
diff --git a/mods/agents-md/hooks/telemetry/quietly.ts b/mods/agents-md/hooks/telemetry/quietly.ts
new file mode 100644
index 00000000..86c45c0e
--- /dev/null
+++ b/mods/agents-md/hooks/telemetry/quietly.ts
@@ -0,0 +1,13 @@
+/**
+ * Runs one `$.telemetry` call and drops whatever it throws or rejects with.
+ *
+ * A build with no telemetry noun, a refused row or an ingest that will not
+ * take it never disturbs the instructions.
+ *
+ * @param send the call
+ */
+export const quietly = (send: () => Promise<void>): void => {
+ void Promise.resolve()
+ .then(send)
+ .catch(() => undefined)
+}
diff --git a/mods/agents-md/hooks/telemetry/types/index.ts b/mods/agents-md/hooks/telemetry/types/index.ts
new file mode 100644
index 00000000..385620f7
--- /dev/null
+++ b/mods/agents-md/hooks/telemetry/types/index.ts
@@ -0,0 +1,6 @@
+export * from './load-counts'
+export * from './telemetry-mark'
+export * from './telemetry-prop'
+export * from './telemetry-row'
+
+export * as default from '.'
diff --git a/mods/agents-md/hooks/telemetry/types/load-counts/index.ts b/mods/agents-md/hooks/telemetry/types/load-counts/index.ts
new file mode 100644
index 00000000..0aeedd80
--- /dev/null
+++ b/mods/agents-md/hooks/telemetry/types/load-counts/index.ts
@@ -0,0 +1,3 @@
+export type * from './load-counts.js'
+
+export * as default from '.'
diff --git a/mods/agents-md/hooks/telemetry/types/load-counts/load-counts.ts b/mods/agents-md/hooks/telemetry/types/load-counts/load-counts.ts
new file mode 100644
index 00000000..d6d9f4ac
--- /dev/null
+++ b/mods/agents-md/hooks/telemetry/types/load-counts/load-counts.ts
@@ -0,0 +1,14 @@
+/**
+ * What the first context of a load handed the engine, as counts.
+ *
+ * The AGENTS.md files added, the files they `@`-imported, their characters
+ * in all, whether `claude-md-or-agents-md` stood down for a CLAUDE.md of the
+ * project's own, and whether the walk threw so that nothing was found.
+ */
+export type LoadCounts = {
+ fileCount: number
+ importCount: number
+ totalContentLength: number
+ isYielded: boolean
+ isWalkFailed: boolean
+}
diff --git a/mods/agents-md/hooks/telemetry/types/telemetry-mark/index.ts b/mods/agents-md/hooks/telemetry/types/telemetry-mark/index.ts
new file mode 100644
index 00000000..b096495d
--- /dev/null
+++ b/mods/agents-md/hooks/telemetry/types/telemetry-mark/index.ts
@@ -0,0 +1,3 @@
+export type * from './telemetry-mark.js'
+
+export * as default from '.'
diff --git a/mods/agents-md/hooks/telemetry/types/telemetry-mark/telemetry-mark.ts b/mods/agents-md/hooks/telemetry/types/telemetry-mark/telemetry-mark.ts
new file mode 100644
index 00000000..5d5617da
--- /dev/null
+++ b/mods/agents-md/hooks/telemetry/types/telemetry-mark/telemetry-mark.ts
@@ -0,0 +1,7 @@
+import type { EngineInterface } from 'claude-code'
+
+/**
+ * What `$.telemetry.mark` takes, as the telemetry mod's contract declares
+ * it: the feature, how it went, and why when not ok.
+ */
+export type TelemetryMark = Parameters<EngineInterface['telemetry']['mark']>[0]
diff --git a/mods/agents-md/hooks/telemetry/types/telemetry-prop/index.ts b/mods/agents-md/hooks/telemetry/types/telemetry-prop/index.ts
new file mode 100644
index 00000000..d0434353
--- /dev/null
+++ b/mods/agents-md/hooks/telemetry/types/telemetry-prop/index.ts
@@ -0,0 +1,3 @@
+export type * from './telemetry-prop.js'
+
+export * as default from '.'
diff --git a/mods/agents-md/hooks/telemetry/types/telemetry-prop/telemetry-prop.ts b/mods/agents-md/hooks/telemetry/types/telemetry-prop/telemetry-prop.ts
new file mode 100644
index 00000000..46e49e13
--- /dev/null
+++ b/mods/agents-md/hooks/telemetry/types/telemetry-prop/telemetry-prop.ts
@@ -0,0 +1,9 @@
+import type { TelemetryRow } from '../telemetry-row'
+
+/**
+ * One property value a `$.telemetry` row may carry.
+ *
+ * As the telemetry mod's contract declares it: a finite number, a boolean,
+ * or a string chosen from the list declared beside it.
+ */
+export type TelemetryProp = NonNullable<TelemetryRow['props']>[string]
diff --git a/mods/agents-md/hooks/telemetry/types/telemetry-row/index.ts b/mods/agents-md/hooks/telemetry/types/telemetry-row/index.ts
new file mode 100644
index 00000000..af9dfeca
--- /dev/null
+++ b/mods/agents-md/hooks/telemetry/types/telemetry-row/index.ts
@@ -0,0 +1,3 @@
+export type * from './telemetry-row.js'
+
+export * as default from '.'
diff --git a/mods/agents-md/hooks/telemetry/types/telemetry-row/telemetry-row.ts b/mods/agents-md/hooks/telemetry/types/telemetry-row/telemetry-row.ts
new file mode 100644
index 00000000..4acb5bcf
--- /dev/null
+++ b/mods/agents-md/hooks/telemetry/types/telemetry-row/telemetry-row.ts
@@ -0,0 +1,7 @@
+import type { EngineInterface } from 'claude-code'
+
+/**
+ * What `$.telemetry.log` takes, as the telemetry mod's contract declares
+ * it: the event's name and its properties by snake_case key.
+ */
+export type TelemetryRow = Parameters<EngineInterface['telemetry']['log']>[0]
diff --git a/mods/agents-md/hooks/telemetry/walk-failed-reason.ts b/mods/agents-md/hooks/telemetry/walk-failed-reason.ts
new file mode 100644
index 00000000..3feb1371
--- /dev/null
+++ b/mods/agents-md/hooks/telemetry/walk-failed-reason.ts
@@ -0,0 +1,5 @@
+/**
+ * The `sad` mark's reason when the AGENTS.md walk threw and the load went on
+ * with nothing found.
+ */
+export const WALK_FAILED_REASON = 'walk_failed'
diff --git a/mods/agents-md/tests/fixtures/ancestor-of.ts b/mods/agents-md/tests/fixtures/ancestor-of.ts
new file mode 100644
index 00000000..3d689fc0
--- /dev/null
+++ b/mods/agents-md/tests/fixtures/ancestor-of.ts
@@ -0,0 +1,20 @@
+import type { FsAncestor } from 'claude-code'
+
+/**
+ * One instruction file a walk found.
+ *
+ * @param dir the directory the file stands in
+ * @param name the file's name as the walk asked for it
+ * @param content the file's text
+ * @returns the found file
+ */
+export const ancestorOf = (
+ dir: string,
+ name: string,
+ content: string,
+): FsAncestor => ({
+ dir,
+ name,
+ content,
+ parts: [{ path: `${dir}/${name}`, content }],
+})
diff --git a/mods/agents-md/tests/fixtures/index.ts b/mods/agents-md/tests/fixtures/index.ts
new file mode 100644
index 00000000..9f7f1c39
--- /dev/null
+++ b/mods/agents-md/tests/fixtures/index.ts
@@ -0,0 +1,10 @@
+export * from './ancestor-of.js'
+export * from './project-of.js'
+export * from './recording.js'
+export * from './rows-of.js'
+export * from './session.js'
+export * from './started-of.js'
+export * from './types'
+export * from './unreadable-project-of.js'
+
+export * as default from '.'
diff --git a/mods/agents-md/tests/fixtures/project-of.ts b/mods/agents-md/tests/fixtures/project-of.ts
new file mode 100644
index 00000000..cf7790ed
--- /dev/null
+++ b/mods/agents-md/tests/fixtures/project-of.ts
@@ -0,0 +1,31 @@
+import type { FsAncestor, On } from 'claude-code'
+
+import { startedOf } from './started-of.js'
+import type { Started } from './types'
+
+/**
+ * A project whose walks up from the working directory find the given files,
+ * one list per set of names, its session starting untouched (startedOf);
+ * each walk's first name is kept in `walks`.
+ *
+ * @param on the test's `on`
+ * @param agents what a walk for AGENTS.md and .claude/AGENTS.md finds
+ * @param claude what a walk for CLAUDE.md, .claude/CLAUDE.md and
+ * CLAUDE.local.md finds
+ * @returns the toasts, lines and walks the plugins raised, in order
+ */
+export function projectOf(
+ on: On,
+ agents: readonly FsAncestor[],
+ claude: readonly FsAncestor[],
+): Started {
+ const started = startedOf(on)
+
+ on('fs.ancestors', ($, e) => {
+ started.walks.push(e.names[0] ?? '')
+
+ return { value: e.names.includes('AGENTS.md') ? agents : claude }
+ })
+
+ return started
+}
diff --git a/mods/agents-md/tests/fixtures/recording.ts b/mods/agents-md/tests/fixtures/recording.ts
new file mode 100644
index 00000000..b0a8cdbc
--- /dev/null
+++ b/mods/agents-md/tests/fixtures/recording.ts
@@ -0,0 +1,29 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin standing in for the telemetry built-in: it adds the `telemetry`
+ * noun at `engine.create` over the nouns beneath.
+ *
+ * Its `log` and `mark` write the entry they are handed as one `$.ui.log`
+ * line, `<op> <json>`, which startedOf keeps and rowsOf reads back.
+ */
+export const RECORDING: Plugin = {
+ name: 'recording',
+ tier: 'builtin',
+ register(on) {
+ on('engine.create', async ($, e, next) => {
+ const beneath = await next(e)
+ const built = { ...beneath }
+ built.telemetry = {
+ log: async entry => {
+ await beneath.ui.log(`log ${JSON.stringify(entry)}`)
+ },
+ mark: async entry => {
+ await beneath.ui.log(`mark ${JSON.stringify(entry)}`)
+ },
+ }
+
+ return built
+ })
+ },
+}
diff --git a/mods/agents-md/tests/fixtures/rows-of.ts b/mods/agents-md/tests/fixtures/rows-of.ts
new file mode 100644
index 00000000..9b747fec
--- /dev/null
+++ b/mods/agents-md/tests/fixtures/rows-of.ts
@@ -0,0 +1,17 @@
+import type { Row, Started } from './types'
+
+/**
+ * What the plugin handed the telemetry noun so far, read off the transcript
+ * lines RECORDING wrote, in the order handed; other lines are passed over.
+ *
+ * @param started the session's start, whose lines hold the rows
+ * @returns the `[op, entry]` pairs
+ */
+export const rowsOf = (started: Started): Row[] =>
+ started.lines
+ .filter(line => line.startsWith('log ') || line.startsWith('mark '))
+ .map((line): Row => {
+ const at = line.indexOf(' ')
+
+ return [line.slice(0, at), JSON.parse(line.slice(at + 1))]
+ })
diff --git a/mods/agents-md/tests/fixtures/session.ts b/mods/agents-md/tests/fixtures/session.ts
new file mode 100644
index 00000000..818f0c82
--- /dev/null
+++ b/mods/agents-md/tests/fixtures/session.ts
@@ -0,0 +1,10 @@
+import type { SessionStartInput } from 'claude-code'
+
+/**
+ * An interactive terminal session two directories under /repo.
+ */
+export const SESSION: SessionStartInput = {
+ surface: 'terminal',
+ isInteractive: true,
+ cwd: '/repo/a/b',
+}
diff --git a/mods/agents-md/tests/fixtures/started-of.ts b/mods/agents-md/tests/fixtures/started-of.ts
new file mode 100644
index 00000000..92f85a56
--- /dev/null
+++ b/mods/agents-md/tests/fixtures/started-of.ts
@@ -0,0 +1,36 @@
+import type { On } from 'claude-code'
+import { mock } from 'claude-code/testing'
+
+import { SESSION } from './session.js'
+import type { Started, ToastAsked } from './types'
+
+/**
+ * A session that starts untouched beneath the plugins, rooted at SESSION's
+ * working directory, every toast and transcript line they raise kept for the
+ * test to read, on a mock clock the test settles before it reads them.
+ *
+ * @param on the test's `on`
+ * @returns the toasts, lines and walks raised, in order, and the clock
+ */
+export function startedOf(on: On): Started {
+ const toasts: ToastAsked[] = []
+ const lines: string[] = []
+
+ on('session.start', ($, e) => ({ cwd: e.cwd }))
+
+ on('session.root', () => ({ value: SESSION.cwd }))
+
+ on('ui.toast', ($, e) => {
+ toasts.push(e)
+
+ return { value: undefined }
+ })
+
+ on('ui.log', ($, e) => {
+ lines.push(e.text)
+
+ return { value: undefined }
+ })
+
+ return { toasts, lines, walks: [], clock: mock.clock(on) }
+}
diff --git a/mods/agents-md/tests/fixtures/types/index.ts b/mods/agents-md/tests/fixtures/types/index.ts
new file mode 100644
index 00000000..854988e4
--- /dev/null
+++ b/mods/agents-md/tests/fixtures/types/index.ts
@@ -0,0 +1,5 @@
+export * from './row'
+export * from './started'
+export * from './toast-asked'
+
+export * as default from '.'
diff --git a/mods/agents-md/tests/fixtures/types/row/index.ts b/mods/agents-md/tests/fixtures/types/row/index.ts
new file mode 100644
index 00000000..41a5adfa
--- /dev/null
+++ b/mods/agents-md/tests/fixtures/types/row/index.ts
@@ -0,0 +1,3 @@
+export type * from './row.js'
+
+export * as default from '.'
diff --git a/mods/agents-md/tests/fixtures/types/row/row.ts b/mods/agents-md/tests/fixtures/types/row/row.ts
new file mode 100644
index 00000000..8878fa26
--- /dev/null
+++ b/mods/agents-md/tests/fixtures/types/row/row.ts
@@ -0,0 +1,5 @@
+/**
+ * One entry the plugin handed the telemetry noun, as RECORDING wrote it:
+ * which call (`log` or `mark`) and the entry.
+ */
+export type Row = [op: string, entry: unknown]
diff --git a/mods/agents-md/tests/fixtures/types/started/index.ts b/mods/agents-md/tests/fixtures/types/started/index.ts
new file mode 100644
index 00000000..363ff6d1
--- /dev/null
+++ b/mods/agents-md/tests/fixtures/types/started/index.ts
@@ -0,0 +1,3 @@
+export type * from './started.js'
+
+export * as default from '.'
diff --git a/mods/agents-md/tests/fixtures/types/started/started.ts b/mods/agents-md/tests/fixtures/types/started/started.ts
new file mode 100644
index 00000000..bfbc4bf2
--- /dev/null
+++ b/mods/agents-md/tests/fixtures/types/started/started.ts
@@ -0,0 +1,15 @@
+import type { MockClock } from 'claude-code/testing'
+
+import type { ToastAsked } from '../toast-asked'
+
+/**
+ * What the plugins raised while a session ran: each toast as asked for, each
+ * transcript line, the first name of each walk they asked for; `clock`
+ * settles what they floated.
+ */
+export type Started = {
+ toasts: ToastAsked[]
+ lines: string[]
+ walks: string[]
+ clock: MockClock
+}
diff --git a/mods/agents-md/tests/fixtures/types/toast-asked/index.ts b/mods/agents-md/tests/fixtures/types/toast-asked/index.ts
new file mode 100644
index 00000000..864845b4
--- /dev/null
+++ b/mods/agents-md/tests/fixtures/types/toast-asked/index.ts
@@ -0,0 +1,3 @@
+export type * from './toast-asked.js'
+
+export * as default from '.'
diff --git a/mods/agents-md/tests/fixtures/types/toast-asked/toast-asked.ts b/mods/agents-md/tests/fixtures/types/toast-asked/toast-asked.ts
new file mode 100644
index 00000000..3fff1448
--- /dev/null
+++ b/mods/agents-md/tests/fixtures/types/toast-asked/toast-asked.ts
@@ -0,0 +1,8 @@
+/**
+ * One `$.ui.toast` call as the plugin made it: the text and, when it named
+ * one, how long the bar keeps it.
+ */
+export type ToastAsked = {
+ text: string
+ timeoutMs?: number
+}
diff --git a/mods/agents-md/tests/fixtures/unreadable-project-of.ts b/mods/agents-md/tests/fixtures/unreadable-project-of.ts
new file mode 100644
index 00000000..f555d1b7
--- /dev/null
+++ b/mods/agents-md/tests/fixtures/unreadable-project-of.ts
@@ -0,0 +1,20 @@
+import type { On } from 'claude-code'
+
+import { startedOf } from './started-of.js'
+import type { Started } from './types'
+
+/**
+ * A project whose walk fails, its session starting untouched (startedOf).
+ *
+ * @param on the test's `on`
+ * @returns the toasts and lines the plugins raised, in order
+ */
+export function unreadableProjectOf(on: On): Started {
+ const started = startedOf(on)
+
+ on('fs.ancestors', () => {
+ throw new Error('no walk today')
+ })
+
+ return started
+}
diff --git a/mods/agents-md/tests/register.test.ts b/mods/agents-md/tests/register.test.ts
new file mode 100644
index 00000000..970c98f4
--- /dev/null
+++ b/mods/agents-md/tests/register.test.ts
@@ -0,0 +1,137 @@
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import Hooks from '../hooks'
+import Fixtures from './fixtures'
+
+tier('builtin')
+
+/**
+ * The blocks the engine hands `prompt.context`.
+ */
+const BLOCKS = [
+ { name: 'claudeMd', text: 'x' },
+ { name: 'currentDate', text: 'today' },
+]
+
+describe('register', () => {
+ test('by default a project with AGENTS.md alone gets it', async ($, on) => {
+ const started = Fixtures.projectOf(
+ on,
+ [Fixtures.ancestorOf('/repo', 'AGENTS.md', '# top\n')],
+ [],
+ )
+
+ on('prompt.context', ($, e) => ({
+ blocks: e.blocks,
+ instructionFiles: e.instructionFiles,
+ }))
+
+ const context = await $.prompt.context({
+ blocks: BLOCKS,
+ instructionFiles: [],
+ })
+
+ expect(context.instructionFiles).toEqual([
+ { path: '/repo/AGENTS.md', kind: 'project', content: '# top\n' },
+ ])
+ expect(context.blocks?.[0]?.text).toContain(
+ 'Contents of /repo/AGENTS.md (project instructions, checked into the ' +
+ 'codebase):\n\n# top',
+ )
+
+ await started.clock.settle()
+
+ expect(started.lines).toEqual([
+ 'no CLAUDE.md found; AGENTS.md loaded: /repo/AGENTS.md',
+ ])
+ })
+
+ test('by default a project with a CLAUDE.md is left to the engine', async ($, on) => {
+ const started = Fixtures.projectOf(
+ on,
+ [Fixtures.ancestorOf('/repo', 'AGENTS.md', '# top\n')],
+ [Fixtures.ancestorOf('/repo/a/b', 'CLAUDE.md', '# mine\n')],
+ )
+ const handed = [
+ { path: '/repo/a/b/CLAUDE.md', kind: 'project' as const, content: '#' },
+ ]
+
+ on('prompt.context', ($, e) => ({
+ blocks: e.blocks,
+ instructionFiles: e.instructionFiles,
+ }))
+
+ expect(
+ await $.prompt.context({ blocks: BLOCKS, instructionFiles: handed }),
+ ).toEqual({ blocks: BLOCKS, instructionFiles: handed })
+
+ await started.clock.settle()
+
+ expect(started.walks).toEqual([])
+ expect(started.lines).toEqual([])
+ })
+
+ test('a failed walk leaves the context as handed', async ($, on) => {
+ Fixtures.unreadableProjectOf(on)
+
+ on('prompt.context', ($, e) => ({
+ blocks: e.blocks,
+ instructionFiles: e.instructionFiles,
+ }))
+
+ expect(
+ await $.prompt.context({ blocks: BLOCKS, instructionFiles: [] }),
+ ).toEqual({ blocks: BLOCKS, instructionFiles: [] })
+ })
+
+ test(
+ 'the start sends the mode row alone: no walk, no toast',
+ { plugins: [Fixtures.RECORDING] },
+ async ($, on) => {
+ const started = Fixtures.projectOf(
+ on,
+ [Fixtures.ancestorOf('/repo', 'AGENTS.md', '# top\n')],
+ [],
+ )
+
+ expect(await $.session.start(Fixtures.SESSION)).toEqual({
+ cwd: '/repo/a/b',
+ })
+
+ await started.clock.settle()
+
+ expect(Fixtures.rowsOf(started)).toEqual([
+ [
+ 'log',
+ {
+ event: Hooks.MODE_EVENT,
+ props: {
+ mode: { value: 'claude-md-or-agents-md', of: [...Hooks.MODES] },
+ is_interactive: true,
+ },
+ },
+ ],
+ ])
+ expect(Hooks.MODE_EVENT).toBe('agents_md_mode')
+ expect(started.walks).toEqual([])
+ expect(started.toasts).toEqual([])
+ },
+ )
+
+ test('with no telemetry noun the start goes on untouched', async ($, on) => {
+ const started = Fixtures.projectOf(
+ on,
+ [Fixtures.ancestorOf('/repo', 'AGENTS.md', '# top\n')],
+ [],
+ )
+
+ expect(
+ await $.session.start({ ...Fixtures.SESSION, isInteractive: false }),
+ ).toEqual({ cwd: '/repo/a/b' })
+
+ await started.clock.settle()
+
+ expect(Fixtures.rowsOf(started)).toEqual([])
+ expect(started.toasts).toEqual([])
+ })
+})
diff --git a/mods/diff/tests/fixtures/old-files.ts b/mods/diff/tests/fixtures/old-files.ts
index 4d71a937..a82ef439 100644
--- a/mods/diff/tests/fixtures/old-files.ts
+++ b/mods/diff/tests/fixtures/old-files.ts
@@ -9,10 +9,12 @@ import type { On } from 'claude-code'
export function oldFiles(on: On) {
on('fs.list', () => ({
value: [
- { name: 'old.ts', kind: 'file', size: 2 },
- { name: 'moved.ts', kind: 'file', size: 2 },
+ { name: 'old.ts', kind: 'file', size: 2, isLink: false },
+ { name: 'moved.ts', kind: 'file', size: 2, isLink: false },
],
}))
- on('fs.stat', () => ({ value: { kind: 'file', size: 2, mtimeMs: 0 } }))
+ on('fs.stat', () => ({
+ value: { kind: 'file', size: 2, mtimeMs: 0, isLink: false },
+ }))
}
diff --git a/mods/types/claude-code.d.ts b/mods/types/claude-code.d.ts
index d7d40736..974450a2 100644
--- a/mods/types/claude-code.d.ts
+++ b/mods/types/claude-code.d.ts
@@ -1,10 +1,13 @@
-// Written by Claude Code 2.1.273.
+// Written by Claude Code 2.1.277.
// Claude Code function hooks: the plugin API's TypeScript declarations.
//
// EARLY ACCESS: this surface may change between releases without notice.
// Written by `/plugin-types`; regenerate with that command after an update
// rather than editing. The first line names the Claude Code version that
-// wrote it. TypeScript 5.4 or newer reads it.
+// wrote it. TypeScript 5.4 or newer reads it. `claude plugin validate <dir>`
+// is the other half: it reads a plugin's manifest and its hooks module's
+// source the way the engine will and reports what the module hooks and
+// calls and everything the engine would refuse, before any session loads it.
//
// What is here: the module a hooks module may import types from,
// import type { Register, On, EngineInterface } from 'claude-code'
@@ -12,7 +15,10 @@
// `h` and `Fragment` (what JSX compiles against), the JSX namespace, and
// the environment's web APIs (URL, TextEncoder, AbortController,
// crypto.subtle, ...). A hooks module runs in an environment of its own:
-// no DOM, no Node. The elements a render hook draws with (`Box`, `Text`,
+// no DOM, no Node. The module, and every file it imports from the plugin,
+// is named .ts, .tsx, .jsx, .js, .mjs, .cjs, .mts or .cts (a file named
+// otherwise is not loaded) and is an ES module whatever its suffix: there
+// is no `require`. The elements a render hook draws with (`Box`, `Text`,
// `Button`, ...) are not globals: they come from the surface's table,
// const { Box, Text } = $.ui.resolve(e)
//
@@ -23,7 +29,30 @@
// `test(name, async ($, on) => { ... })`, where `$` is the engine's own
// and the hooks `on` registers sit beneath every plugin; with describe,
// expect, tier, and `mock`, whose clock, store and env answer those nouns
-// beneath the plugins from memory.
+// beneath the plugins from memory. `$.ui.mount` draws a component through
+// the plugin on the surface the test names (terminal, desktop, vscode or
+// mobile: never assumed) and hands back the drawing to read and act on by
+// key: find an element, press a Button, type into an Input, drive a
+// `Client`'s module (keys, pointer, posts, its frame clock), each act typed
+// by that surface's element table, so one test body run over several
+// surfaces covers the mod's hooks and description on each. It exercises
+// the mod (its hooks, the tree they return under each surface's rules, its
+// `Client` modules), never a surface's paint (Ink's, the desktop page's):
+//
+// test('notes add up on every surface that takes input', async $ => {
+// for (const surface of ['terminal', 'desktop'] as const) {
+// const ui = await $.ui.mount({ plugin: 'notes', surface, ...BAND })
+// await ui.input({ key: 'new', text: 'milk' })
+// expect((await ui.find({ key: 'count' }))?.text).toBe('1 note')
+// await ui.key({ key: 'down', in: 'list' })
+// await ui.unmount()
+// }
+// for (const surface of ['terminal', 'desktop', 'vscode', 'mobile'] as const) {
+// const ui = await $.ui.mount({ plugin: 'notes', surface, ...HINT })
+// expect(await ui.find({ type: 'Text', text: /notes/ })).toBeDefined()
+// await ui.press({ key: 'dismiss' })
+// }
+// })
//
// Typing a plugin against it:
// export const register: Register = (on, options) => { ... }
@@ -149,7 +178,8 @@ declare module 'claude-code' {
* offers it to the model.
*
* Listed for the model (the agent listing) or named by it at dispatch
- * (`subagent_type`): the same event at each.
+ * (`subagent_type`): the same event at each. Model-facing only: a plugin's
+ * own `$.agent.spawn` of a type is no offer, and `agent.spawn` governs it.
*/
export type AgentOfferInput = {
/**
@@ -314,6 +344,98 @@ declare module 'claude-code' {
agentId?: undefined;
};
+ /**
+ * What `$.agent.register` takes: an agent type this plugin defines, spelled
+ * as an agent definition in settings JSON is, plus its `name`.
+ *
+ * Every field an agent file or `--agents` entry may carry is here and takes
+ * effect as it does there; the engine validates it with the same schema.
+ */
+ type AgentSpec = {
+ /**
+ * The type's short name (letters, digits, `_`, `-`; up to 64); the type is
+ * `<plugin>:<name>`, as a plugin's agent file `agents/<name>.md` names one.
+ */
+ name: string;
+ /**
+ * When to delegate to this agent: the line the model reads in its listing
+ * of agent types, and `agent.offer`'s `description`.
+ */
+ description: string;
+ /**
+ * The agent's system prompt, whole: it replaces the session's.
+ */
+ prompt: string;
+ /**
+ * What the agent may call, by tool name (`Read`, `Bash`, `mcp__x__y`); a
+ * call to any other is refused. Left out: every tool the parent has.
+ */
+ tools?: readonly string[];
+ /**
+ * Tools withheld from the agent, by name, out of whatever `tools` allows.
+ */
+ disallowedTools?: readonly string[];
+ /**
+ * The agent's model: an alias (`haiku`, `sonnet`, `opus`), a full id, or
+ * `inherit` for the parent's. Left out: the session's subagent default.
+ */
+ model?: string;
+ /**
+ * The agent's effort: a level (`low`, `medium`, `high`, `xhigh`, `max`)
+ * or an integer budget.
+ */
+ effort?: string | number;
+ /**
+ * How the agent's permission asks are decided, a mode: `default`,
+ * `acceptEdits`, `plan`, `auto`, `dontAsk` or `bypassPermissions`.
+ *
+ * Left out: the parent's.
+ */
+ permissionMode?: string;
+ /**
+ * Servers connected over MCP for the agent's run: a configured server's
+ * name, or `{ "<name>": { command, args } }`, one server's config inline.
+ */
+ mcpServers?: readonly (string | Record<string, unknown>)[];
+ /**
+ * Settings hooks in force while the agent runs, in settings.json's `hooks`
+ * shape (`{ PreToolUse: [{ matcher, hooks: [...] }] }`).
+ */
+ hooks?: Record<string, unknown>;
+ /**
+ * The most turns the agent takes before it stops.
+ */
+ maxTurns?: number;
+ /**
+ * Preloaded into the agent's context before its first turn: skill names.
+ */
+ skills?: readonly string[];
+ /**
+ * The agent's first user turn; `{{intent}}` in it takes the spawn's prompt.
+ * Left out: the spawn's prompt is the first turn.
+ */
+ initialPrompt?: string;
+ /**
+ * A persistent memory the agent keeps between runs, and where: `user`,
+ * `project` or `local`.
+ */
+ memory?: 'user' | 'project' | 'local';
+ /**
+ * Set so that every spawn of the agent runs in the background.
+ */
+ background?: true;
+ /**
+ * Set so that the agent's context carries no CLAUDE.md block (the person's,
+ * the project's, the rules): it takes what it needs from its prompt.
+ */
+ omitClaudeMd?: true;
+ /**
+ * Where the agent runs apart from the session: `worktree`, a git worktree
+ * of its own; `remote`, a cloud session where the build allows one.
+ */
+ isolation?: 'worktree' | 'remote';
+ };
+
/**
* The hook `on("*", hook)` takes: it runs on every event, plugin nouns no
* declaration names included, so `e` is `unknown` and `next` is StarNext.
@@ -487,17 +609,22 @@ declare module 'claude-code' {
};
/**
- * The `Box` props a `hover` may override, none of which moves layout, and
- * `scope`, which names the hover group the Box joins instead of a style.
+ * The `Box` props a `hover` may override, none of which moves the Box's
+ * siblings, and `scope`, which names the hover group the Box joins.
*
- * `display` is `"flex"` alone, on a Box drawn `display: "none"` inside a
- * visible keyed Box, and never beside a `scope` (a group lit from another
- * site would move what the pointer is over); `borderStyle` only restyles.
+ * `display` is `"flex"` alone, on a Box drawn `display: "none"`: with a
+ * `scope`, every member of the lit group is revealed, in whichever site it
+ * sits, so a pointer on a glyph in the transcript can swap an entry into a
+ * fixed row of the band, or reveal an absolutely positioned card.
+ * `borderStyle` only restyles a border the Box has; the offsets move a Box
+ * drawn `position: "absolute"`, none in the flow. The surface applies a
+ * hover as the pointer moves, so a reveal that moves what the pointer rests
+ * on is drawn once, not in a loop.
*/
export type BoxHoverProps = {
/**
* Names a hover group of this plugin's: every element it draws with the
- * same `scope`, in any site on the surface, lights while any is hovered.
+ * same `scope`, in any site, lights while any is hovered, reveals included.
*
* A Pane row and a mark on a transcript message can share one. Another
* plugin's elements under the same string are a different group. One to
@@ -509,31 +636,71 @@ declare module 'claude-code' {
borderDimColor?: boolean;
backgroundColor?: string;
display?: 'flex';
+ top?: number;
+ left?: number;
+ right?: number;
+ bottom?: number;
};
/**
- * The props of `Box`: the layout, margin, padding and border props of Ink's
- * Box a tree may set, and the two of hover.
+ * The props of `Box`: the layout, position, margin, padding and border props
+ * of Ink's Box a tree may set, and the two of hover.
*/
export type BoxProps = {
/**
* Makes the Box a hover scope: while the pointer is anywhere over it, its
* own `hover` and that of every element beneath it apply.
*
- * A nested Box with a `key` of its own scopes what is beneath it. A key a
- * sibling Box already took, or one that is no plain string, names no
- * scope: the Box draws, and hovers beneath it stay inert.
+ * A nested Box with a `key` of its own scopes what is beneath it, a placed
+ * card outside its rows included. A key a sibling Box already took, or one
+ * that is no plain string, names no scope: hovers beneath it stay inert.
*/
key?: string;
/**
* Style overrides applied by the surface while the pointer is over the
* nearest keyed `Box`, this one included, or, given a `scope`, its group.
*
- * Never a layout change; no hook runs and nothing crosses to the plugin.
- * To reveal on hover, draw a Box `display: "none"` with `hover: { display:
- * "flex" }` inside a visible keyed Box; a scoped hover never reveals.
+ * No hook runs and nothing crosses to the plugin. To reveal on hover, draw
+ * the Box `display: "none"` with `hover: { display: "flex" }` in a visible
+ * keyed Box or under a `scope`; on a `position: "absolute"` Box, no reflow.
*/
hover?: BoxHoverProps;
+ /**
+ * `"absolute"` leaves the flow, as in CSS: placed against its parent by
+ * the offsets, no room among its siblings, painted over those before it.
+ *
+ * So showing or moving it (a hover may) moves nothing; the pointer on it is
+ * on its parent. Clipped, pointer and paint, by the region its site is in
+ * (viewport, pane, band), by the site itself on the main screen or export.
+ *
+ * @example <Box key="k"><Text>glyph</Text><Box position="absolute" top={-2}
+ * left={2} display="none" hover={{ display: 'flex' }}>the card</Box></Box>
+ */
+ position?: 'relative' | 'absolute';
+ /**
+ * Rows from the parent's top edge, in character cells: an integer,
+ * negative above the edge.
+ *
+ * With `bottom` and no `height` the Box spans the two.
+ */
+ top?: number;
+ /**
+ * Columns from the parent's left edge, in character cells: an integer,
+ * negative left of the edge.
+ *
+ * With `right` and no `width` the Box spans the two.
+ */
+ left?: number;
+ /**
+ * Columns from the parent's right edge, in character cells: an integer,
+ * negative right of the edge.
+ */
+ right?: number;
+ /**
+ * Rows from the parent's bottom edge, in character cells: an integer,
+ * negative below the edge.
+ */
+ bottom?: number;
flexDirection?: 'row' | 'column' | 'row-reverse' | 'column-reverse';
flexGrow?: number;
flexShrink?: number;
@@ -649,12 +816,12 @@ declare module 'claude-code' {
*/
label?: string;
/**
- * One digit (`"1"`) or one lowercase letter (`"w"`) that presses it where
- * the site honours one (the `AbovePrompt` band); anything else is refused.
+ * One digit (`"1"`) or one lowercase letter (`"w"`) that presses it while
+ * the plugin's site holds the focus; anything else is refused.
*
- * A digit presses from an empty composer; a digit or letter presses on
- * keydown while one of the band's Buttons has the focus (Shift+w matches
- * `"w"`; held keys repeat). Of two Buttons on one hotkey the later wins.
+ * The band after ctrl+x tab or a click, a focused `Pane`; never from the
+ * composer, save a bare digit in an empty one pressing a band Button, as a
+ * survey is answered. Shift+w matches `"w"`; two on one key, the later wins.
*/
hotkey?: string;
/**
@@ -933,13 +1100,13 @@ declare module 'claude-code' {
/**
* The element table a surface module draws with, `surface.elements`: the
- * terminal's (Elements) less `Client` (none nests) and `Raster` (needs `$`).
+ * terminal's (Elements) less `Client` (none nests), `Raster` and `Image`.
*
- * What `$.ui.resolve(e)` is to a hooks module, with no `$` and no hook
- * between: `const { Box, Text } = surface.elements`, then `<Box>`. A Button,
- * Input or Select keeps its handler here and still raises `ui.press` etc.
+ * What `$.ui.resolve(e)` is to a hooks module; a Button, Input or Select
+ * keeps its handler here. A tree of them keeps every tree's bounds (20,000
+ * nodes, 32 deep, 100,000 characters serialized) or the instance unmounts.
*/
- export type ClientElements = Omit<Elements['terminal'], 'Client' | 'Raster'>;
+ export type ClientElements = Omit<Elements['terminal'], 'Client' | 'Raster' | 'Image'>;
/**
* One key the person pressed while a `Client` had the focus, as
@@ -963,15 +1130,18 @@ declare module 'claude-code' {
* The component a surface module exports (default, or its one PascalCase
* export): from props and surface to the tree drawn (no nested `Client`).
*
- * Runs in the plugin's surface environment on the drawing thread, under a
- * time budget per call; a throw or an overrun unmounts the instance and
- * draws one line naming the plugin and the module in its place.
+ * Runs on the drawing thread, a second per call at most; `h` and `Fragment`
+ * are the environment's, so nothing of the module's takes those names. A
+ * throw, an overrun or a tree past the bounds (ClientElements) unmounts it.
+ *
+ * @example
+ * const Tag: ClientModule<string> = (t, s) => s.elements.Text({ children: t })
*/
export type ClientModule<P extends JsonValue = JsonValue, S = unknown> = (props: P, surface: ClientSurface<S>) => RenderElement;
/**
* One pointer event over a `Client`'s region, as `surface.onPointer` hands
- * it: cell coordinates relative to the region's top-left corner.
+ * it: region-relative cells, and the sub-cell position where known.
*
* After a `down` in the region the instance holds the pointer until the
* `up`: every `move` reaches it, past the edges too (negative, or beyond
@@ -988,6 +1158,21 @@ declare module 'claude-code' {
* The row under the pointer, 0 at the region's top edge.
*/
y: number;
+ /**
+ * The same position with the fraction of a cell kept (`x: 12`, `fine.x:
+ * 12.375`), where the surface knows it: a terminal that reports pixels.
+ *
+ * kitty, Ghostty, iTerm2, WezTerm and foot do; tmux passes none through.
+ * Absent elsewhere and on `enter`/`leave`; present, a `move` comes within
+ * a cell too. What a module showing another program's pixels forwards.
+ *
+ * @example
+ * surface.onPointer(e => click((e.fine?.x ?? e.x + 0.5) * pixelsPerCell))
+ */
+ fine?: {
+ x: number;
+ y: number;
+ };
/**
* Which button is down (`down`, `move` while held) or came up (`up`);
* absent on a hover `move`, `enter` and `leave`.
@@ -1076,6 +1261,9 @@ declare module 'claude-code' {
/**
* Replaces the local state and schedules one more call of the function on
* the next frame; several calls before it coalesce into one redraw.
+ *
+ * A `setState` on each of three renders in a row with no key, pointer,
+ * tick, press or props between is a render loop: the instance unmounts.
*/
setState: (next: S) => void;
/**
@@ -1110,7 +1298,8 @@ declare module 'claude-code' {
* `ui.message` only that plugin's hooks see, one per frame at most.
*
* A later post in the same frame replaces an undelivered one; a hook
- * answering `{ props }` hands this instance its next props.
+ * answering `{ props }` hands this instance its next props. At most
+ * 20,000 values, 32 deep, 100,000 characters, or the post is not sent.
*/
post: (data: JsonValue) => void;
};
@@ -1264,6 +1453,9 @@ declare module 'claude-code' {
/**
* True under the fullscreen (alternate-screen) layout; false on the main
* screen (`CLAUDE_CODE_NO_FLICKER=0`, tmux by default) and headless.
+ *
+ * The fact `RenderViewport`'s `isFullscreen` carries on every terminal
+ * drawing, from the same source: the two agree.
*/
isFullscreen: boolean;
/**
@@ -1319,14 +1511,19 @@ declare module 'claude-code' {
/**
* What a `command.run` hook returns and what `next(e)` and `$.command.run`
- * resolve to: the command's output text, when it has one.
+ * resolve to: the command's output text and the notes it leaves the model.
*
* From core, `text` is what the command printed (a `local` command's
- * returned text; a panel command may print nothing) and `ref` names the
- * run. A hook's own answer without `next` runs no command: its `text` is
- * shown as the command's output, under the names of the plugins hooking
- * the command unless each is bundled with Claude Code, whose answer reads
- * as the built-in command's own.
+ * returned text; a panel command may print nothing), `context` what it
+ * recorded for the model beside that, and `ref` names the run.
+ *
+ * A hook's own answer without `next` runs no command: its `text` is shown
+ * as the command's output, under the names of the plugins hooking the
+ * command unless each is bundled with Claude Code, whose answer reads as
+ * the built-in command's own, and its `context` is recorded after it.
+ *
+ * Both are the plugin's to size, as a core command's output is; what bounds
+ * them is what bounds any transcript row where a surface draws it.
*/
export type CommandRunResult = {
/**
@@ -1334,6 +1531,15 @@ declare module 'claude-code' {
* command showed nothing as text (a panel, a prompt for the model).
*/
text?: string;
+ /**
+ * What the model reads after the command's output and the person never
+ * sees, each entry one hidden user message recorded after the output row.
+ *
+ * From core, the notes the command left the model, absent when none. Kept
+ * whole from `next`: left out after `next`, the last answer's notes ride
+ * along; written, it keeps every entry that answer had (none empty).
+ */
+ context?: readonly string[];
/**
* Set by core on what `next(e)` resolves to: names the engine's run of
* the command (its result stays on the host side).
@@ -1823,7 +2029,7 @@ declare module 'claude-code' {
};
/**
* Display: a line under an open dialog, a redraw or a repaint, a
- * transcript line, a pane the surface places, a window or a ring moved.
+ * transcript or debug line, panes the surface places, a window or ring.
*/
ui: {
/**
@@ -1845,27 +2051,31 @@ declare module 'claude-code' {
*
* A render hook whose state changed (a countdown) calls it for a redraw, at
* most ten a second, thirty for the shown pane and the band (calls sooner
- * fold); a `prompt.section` or `prompt.context` hook: dropped next turn.
+ * fold); a prompt section, context or attachment hook: dropped next turn.
*
- * @param event `ui.render`, `prompt.section`, `prompt.context`,
- * `tool.describe`, `command.describe` or `config.describe`
+ * @param event `ui.render`, or a cached-answer event: `prompt.section`,
+ * `prompt.context`, `prompt.attachment`, `tool/command/config.describe`
*/
invalidate: (event: InvalidatableEventName) => void;
/**
- * Repaints a `Raster` this plugin's own render hook drew, still mounted,
- * with new cells, without the redraw `invalidate` asks for.
+ * Repaints a mounted `Raster` this plugin's own render hook drew with new
+ * cells, or swaps a keyed `Image` it drew to a new source; no redraw.
*
- * The surface keeps the cells for that Raster (by site and `key`) and
- * paints them at its next frame, so blits between frames fold into one:
- * an animation runs at the frame rate. A resize is a redraw instead.
+ * The surface paints the cells or source at its next frame, so blits
+ * between frames fold into one: up to 120 a second taken, some sixty
+ * shown. An Image swap sends one small command; a resize is a redraw.
*
- * @param args `requestId` (the site), `key` (the Raster's), `cells`
- * (RasterProps), `columns` and `rows` (the mounted size)
- * @returns `{}` once the cells are its next frame, or `{ deny }` (not
- * mounted, not this plugin's, another size, cells that do not
- * decode)
+ * @param args `requestId` (the site), `key`, and `cells` (RasterProps) or
+ * `source` (ImageSource); `columns`, `rows` (the mounted size)
+ * @returns `{}` once the cells or source are its next frame, or `{ deny }`
+ * (not mounted, not this plugin's, another size, cells that do
+ * not decode, a bad source, or an Image drawing its alt there:
+ * no placeholder images, or a file this terminal cannot read)
* @example
* $.clock.every(33, () => $.ui.blit({ requestId, key, cells: frame() }))
+ * @example
+ * await $.ui.blit({ requestId: 'browser', key: 'view',
+ * source: { shm: name, format: 'rgb', width, height } })
*/
blit: (args: UiBlitArgs) => Promise<UiBlitResult>;
/**
@@ -1886,17 +2096,20 @@ declare module 'claude-code' {
resolve: <E extends ResolveInput>(e: E) => Elements[E['surface']];
/**
* Appends one line to the transcript, drawn like a system notice (dim;
- * not sent to the model), and records it in the debug log.
+ * not sent to the model), or with `{ to: "debug" }` to the debug log alone.
*
- * The line is a row of its own at the surface's next frame, wherever the
- * transcript is then; lines keep the order they were logged in. A `-p` or
- * SDK run has no transcript: its host receives the line as `ui_log`.
+ * A row of its own at the next frame, in logging order; a `-p` or SDK
+ * host receives it as `ui_log`; the debug log has every line under this
+ * plugin's name. Raised as `ui.log`: a hook above may rewrite `e.to`.
*
* @param text the line's text
+ * @param options `to`: `transcript` (the default) or `debug`
* @example
* $.ui.log(`prompt from ${e.origin.kind}: ${e.text.length} chars`)
+ * @example
+ * $.ui.log(`cache miss for ${e.tool_use_id}`, { to: "debug" })
*/
- log: (text: string) => void;
+ log: (text: string, options?: UiLogOptions) => void;
/**
* Asks the user `question` in the engine's own AskUserQuestion dialog and
* resolves to the label they chose, or the text typed under "Other".
@@ -1919,7 +2132,8 @@ declare module 'claude-code' {
*
* It leaves the transcript and the model untouched.
*
- * @param text the line to show
+ * @param text the line to show; an unpaired surrogate half in it is drawn
+ * as U+FFFD
* @param options `timeoutMs`: how long it stays (default 4000)
* @example
* $.ui.toast(`turn took ${Math.round(e.durationMs / 1000)} s`)
@@ -1931,7 +2145,8 @@ declare module 'claude-code' {
*
* One per plugin; `undefined` removes it.
*
- * @param text the line to keep on screen; undefined clears it
+ * @param text the line to keep on screen (an unpaired surrogate half is
+ * drawn as U+FFFD); undefined clears it
* @example
* $.ui.status("thinking..."); return next(e)
*/
@@ -1945,7 +2160,7 @@ declare module 'claude-code' {
* waits undrawn below 144 columns (110 once asked), judged at each open.
*
* @param pane `id` (1-64 of letters, digits, `_`, `-`), `title`, `focus`,
- * `closeOnEscape` and `holdToasts` (a dialog), `rows` it wants inline
+ * `closeOnEscape` and `holdToasts` (a dialog), `rows` / `columns` wanted
* @returns settles once the pane is open (or retitled)
* @example
* await $.ui.open({ id: "clock", title: "Clock" })
@@ -1967,6 +2182,19 @@ declare module 'claude-code' {
* onPress: () => $.ui.close({ id: "clock" })
*/
close: (pane: PaneCloseArgs) => Promise<void>;
+ /**
+ * Lists this plugin's own open panes (UiPane): each one's id and title,
+ * and whether it is shown, holds the keyboard, and is placed.
+ *
+ * The engine's record, not the module's: a module reloaded while its
+ * pane stayed up finds it here. Another plugin's panes are not listed.
+ *
+ * @returns the panes in open order, placed ones first; empty with none
+ * @example
+ * const isUp = (await $.ui.panes()).some(pane => pane.id === "clock")
+ * if (!isUp) await $.ui.open({ id: "clock", title: "Clock" })
+ */
+ panes: () => Promise<readonly UiPane[]>;
/**
* Scrolls something into view as the DOM's `scrollIntoView` would: a
* render instance by `requestId`, an element by `key`, a site's edge.
@@ -2093,9 +2321,9 @@ declare module 'claude-code' {
* Calls `tool` on one of the engine's connected MCP servers with the
* engine's own connection and credentials.
*
- * A `cached` server is dialed on first use. Resolves to the tool's result
- * as MCP returns it: `content` blocks and `isError`. No permission prompt:
- * the plugin's call, seen by the hooks above it, is the grant.
+ * A `cached` server is dialed on first use. No permission prompt: the
+ * plugin's call, seen by the hooks above it, is the grant. Positional, not
+ * the `{ tool: "mcp__server__tool", ... }` shape a `tool.call` hook sees.
*
* @param server the server's name as /mcp lists it (`claude.ai Gmail`;
* the tool-name spelling `claude_ai_Gmail` is accepted too)
@@ -2104,7 +2332,10 @@ declare module 'claude-code' {
* @returns the tool's result as MCP returns it: `content` blocks and
* `isError`
* @example
- * const { content } = await $.mcp.call("claude.ai Gmail", "create_draft")
+ * const { content } = await $.mcp.call("claude.ai Gmail", "create_draft", {
+ * subject: "Release notes",
+ * })
*/
call: (server: string, tool: string, args?: Record<string, unknown>) => Promise<McpToolResult>;
};
@@ -2128,6 +2359,14 @@ declare module 'claude-code' {
* Returns the directory the session runs in, absolute.
*/
cwd: () => Promise<string>;
+ /**
+ * Returns the session's project root, absolute: where it started, or
+ * where `/cd`, a host's directory change or a worktree move took it.
+ *
+ * A shell `cd` during the session does not move it; nested instruction
+ * files are read only beneath it.
+ */
+ root: () => Promise<string>;
/**
* Returns the main loop's model, as `/model` shows it.
*/
@@ -2232,8 +2471,8 @@ declare module 'claude-code' {
abort: (input: OpEventOf['turn.abort']) => Promise<void>;
};
/**
- * Submitting a prompt the model reads as a user turn, and putting a text
- * in the person's prompt box, written or proposed.
+ * Submitting a prompt the model reads as a user turn, and the person's
+ * prompt box: read as it stands, written, or proposed into.
*/
prompt: {
/**
@@ -2249,17 +2488,30 @@ declare module 'claude-code' {
*/
submit: EventCalls['prompt']['submit'];
/**
- * Writes `input.text` into the prompt box as the person's draft, cursor
- * at its end, replacing what it held: the event `prompt.fill`.
+ * Returns the prompt box as it stands, the draft typed so far and the
+ * cursor's offset into it, so a `fill` can keep what the person typed.
*
- * It goes through every other plugin's hook with `e.origin` `{ kind:
- * 'plugin', name }`. Resolves `{ isFilled: false }` when a dialog holds
- * the keys or the session has no box (headless); nothing is submitted.
+ * Never rejects: `{ text: '', cursor: 0 }` where the session draws no box
+ * (a -p run, an SDK host) or none is mounted yet.
*
* @example
- * const { isFilled } = await $.prompt.fill({ text: "/review latest" })
+ * const { text, cursor } = await $.prompt.read()
*/
- fill: EventCalls['prompt']['fill'];
+ read: () => Promise<PromptBox>;
+ /**
+ * Puts `input.text` in the prompt box as the draft, by `mode`: `replace`
+ * (the default) over it, `append` after it, `insert` at the cursor.
+ *
+ * The event `prompt.fill` through the other plugins' hooks; `isFilled:
+ * false` under a dialog or headless. To hand the model text WITH the next
+ * prompt instead, a `prompt.submit` hook adds `context` (second example).
+ *
+ * @example
+ * await $.prompt.fill({ text: `> ${quote}\n`, mode: "insert" })
+ * @example
+ * ($, e, next) => next({ ...e, context: [...(e.context ?? []), hunk] })
+ */
+ fill: (input: PromptFillArgs) => Promise<PromptFilled>;
/**
* Proposes `input.text` as the prompt box's dim suggestion, Tab to take:
* the event `prompt.suggest`, as the engine's own guess after a turn.
@@ -2418,25 +2670,61 @@ declare module 'claude-code' {
* the ones plugins did alike.
*/
list: () => Promise<AgentInfo[]>;
+ /**
+ * Defines an agent type the Agent tool dispatches from the next turn on,
+ * named `<plugin>:<name>`: the event `agent.register`.
+ *
+ * Every field takes effect as in an agent file; re-registered, a name is
+ * replaced; unloaded, a plugin's types go. `agent.offer` hides it from
+ * the model alone; any plugin's `$.agent.spawn` answers to `agent.spawn`.
+ *
+ * @param spec `name`, `description` (when to delegate), `prompt` (its
+ * system prompt), and any other field of an agent definition
+ * @returns `{ agent }`, the full name; rejects until the session binds,
+ * on a spec the schema refuses (its reason), on a hook's deny
+ * @example
+ * await $.agent.register({ name: "runner", description: "Runs a spec",
+ * prompt: RUNNER_PROMPT, tools: ["Read", "Bash"], omitClaudeMd: true })
+ * @example
+ * // runner-only: hidden from the model, spawned by this plugin's tool,
+ * // answered by the subagent's turn.complete (matched by agentId)
+ * on("agent.offer", { agent: "lab:runner" }, () => ({ isOffered: false }))
+ * on("tool.call", { tool: "mcp__lab__run" }, async ($, e) => {
+ * const { agentId, deny } = await $.agent.spawn({
+ * subagentType: "lab:runner", prompt: e.spec, description: "run" })
+ * return { result: deny ?? (await answerOf(agentId)) }
+ * })
+ */
+ register: (spec: AgentSpec) => Promise<OpValueOf['agent.register']>;
};
/**
- * The file system as the engine's own process reaches it, text only
- * (UTF-8); a relative path is under the session's working directory.
+ * The file system as the engine's own process reaches it; a relative path
+ * is under the session's working directory, and text is UTF-8.
*
- * An absolute path is used as given. A read or a write over 4 MiB
- * rejects; what the operating system refuses rejects with its errno
- * (`ENOENT`, `EACCES`). Where a path may go is an `fs.*` hook's to say.
+ * An absolute path is used as given; where one may go is an `fs.*` hook's
+ * to say. A read or write over 4 MiB rejects, a foreign network location
+ * as spelled rejects untouched, and an OS refusal rejects with its errno.
*/
fs: {
/**
- * Reads a file and returns its text. Rejects when missing.
+ * Reads a file and returns its text, or with `{ as: "bytes" }` its bytes
+ * as `{ base64 }`.
+ *
+ * Rejects when missing, or over 4 MiB, which bounds what one read copies
+ * into the plugin's environment. A file the plugin ships is under
+ * `$.plugin.root`.
*
* @param path relative to the working directory, or absolute
- * @returns the file's text
+ * @param options `as`: `"text"` (the default) or `"bytes"`
+ * @returns the file's text, or `{ base64 }`
* @example
* const readme = await $.fs.read("README.md")
+ * @example
+ * const { base64 } = await $.fs.read(
+ * `${$.plugin.root}/hooks/weights.bin`, { as: "bytes" })
+ * const weights = Uint8Array.fromBase64(base64)
*/
- read: (path: string) => Promise<string>;
+ read: FsReadCall;
/**
* Writes `text` to a file, creating it and its directories as needed.
*
@@ -2445,34 +2733,90 @@ declare module 'claude-code' {
*/
write: (path: string, text: string) => Promise<void>;
/**
- * Lists a directory: `{ name, kind, size }` per entry, by name.
+ * Lists a directory: `{ name, kind, size, isLink }` per entry, by name,
+ * each entry as it stands (a symbolic link is `other` with `isLink`).
*
* @param path the directory's path; absent, the working directory
- * @returns the entries, `{ name, kind, size }` each
+ * @returns the entries, `{ name, kind, size, isLink }` each
*/
list: (path?: string) => Promise<FsEntry[]>;
/**
- * Returns whether the path exists; never rejects.
+ * Returns whether the path exists; rejects only a network location as
+ * spelled, which no `fs` call reaches.
*/
exists: (path: string) => Promise<boolean>;
/**
- * Returns `{ kind, size, mtimeMs }` of the path. Rejects when missing.
- */
- stat: (path: string) => Promise<FsStat>;
+ * Returns `{ kind, size, mtimeMs, isLink }` of the path: what it leads to,
+ * and whether it is itself a symbolic link. Rejects when missing.
+ *
+ * With `{ resolve: true }` also `realPath`, where the path lands, absent
+ * when it leads nowhere; a guard matches it and denies without it, since a
+ * spelling it cannot resolve (`~`, a file not there yet) the tool may open.
+ *
+ * @param path relative to the working directory, or absolute
+ * @param options `resolve`: also answer `realPath` (one more file system
+ * call)
+ * @returns the stat, `realPath` with it when asked and resolvable; rejects
+ * `ENOENT` for a missing path
+ * @example
+ * // ROOT was resolved the same way and SEP is its separator; an
+ * // allow-list under it is the robust guard, a deny-list on spellings
+ * // only best effort (a hard link or a case alias keeps its own)
+ * on("tool.call", { tool: "Read" }, async ($, e, next) => {
+ * const stat = await $.fs.stat(e.file_path, { resolve: true })
+ * .catch(() => undefined)
+ * const real = stat?.realPath
+ * const isInside = real !== undefined && real.startsWith(ROOT + SEP)
+ * return isInside ? next(e) : { deny: "outside the project" }
+ * })
+ * @example
+ * // a Write may name a file not there yet: `placed` answers where the
+ * // path lands or undefined, and the guard denies on undefined or
+ * // outside ROOT. Unplaceable by spelling first, with no file system
+ * // call (drive-relative `D:x`, a `\\` or `//` network or device path,
+ * // a name that is empty, ".", ".." or itself `C:...`); then the file
+ * // if it stats; else its folder, cut after the last separator and
+ * // keeping it so a drive or share root stays that root, plus the name
+ * const placed = async (path) => {
+ * const cut = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"))
+ * const name = path.slice(cut + 1)
+ * const isPlaceable = !/^[A-Za-z]:(?![\\/])/.test(path) &&
+ * !/^[\\/][\\/]/.test(path) && !/^[A-Za-z]:/.test(name) &&
+ * name !== "" && name !== "." && name !== ".."
+ * if (!isPlaceable) return undefined
+ * const own = await $.fs.stat(path, { resolve: true })
+ * .catch(() => undefined)
+ * if (own) return own.realPath
+ * const folder = cut < 0 ? "." : path.slice(0, cut + 1)
+ * const dir = await $.fs.stat(folder, { resolve: true })
+ * .catch(() => undefined)
+ * return dir?.realPath === undefined ? undefined
+ * : `${dir.realPath.replace(/[\\/]$/, "")}${SEP}${name}`
+ * }
+ * const real = await placed(e.file_path)
+ * const isInside = real !== undefined && real.startsWith(ROOT + SEP)
+ * return isInside ? next(e) : { deny: "cannot place it, or outside" }
+ */
+ stat: (path: string, options?: FsStatOptions) => Promise<FsStat>;
/**
* Reads the named instruction files in every directory above the
* session's original working directory, the way the engine reads CLAUDE.md.
*
* Root first, each `{ dir, name, content }` that exists, the content
- * with its `@include`s after it; with `of`, on down to that file's
- * directory, as the engine reads a nested CLAUDE.md when a file is read.
+ * with its `@include`s after it; `of` and `below` together are the
+ * engine's own walk for a nested CLAUDE.md between root and read file.
*
- * @param request `names`, relative `.md` file names (no `..`) looked for
- * in each directory; `of`, the file whose directory the walk goes down to
+ * @param request `names`, relative `.md` file names (no `..`); `of`, the
+ * file walked down to; `below`, the directory the walk stays inside
* @returns the files found, root first
* @example
* const found = await $.fs.ancestors({ names: ["AGENTS.md"] })
* const stack = await $.fs.ancestors({ names: ["AGENTS.md"], of: path })
+ * const nested = await $.fs.ancestors({
+ * names: ["AGENTS.md"],
+ * of: e.file_path,
+ * below: await $.session.root(),
+ * })
*/
ancestors: (request: FsAncestorsRequest) => Promise<readonly FsAncestor[]>;
};
@@ -2565,10 +2909,16 @@ declare module 'claude-code' {
* `$.session.authorize()` rides https only, to a first-party host.
*
* @param url the URL (http or https)
- * @param init `{ method, headers, body, auth }` (body a string)
+ * @param init `{ method, headers, body, auth, socketPath }` (body a
+ * string; socketPath a Unix socket to go over instead of TCP)
* @returns `{ status, ok, headers, text }` once the body is read
* @example
* const { ok, text } = await $.http.fetch("https://example.com/status")
+ * @example
+ * await $.http.fetch("http://bridge/reload", {
+ * method: "POST",
+ * socketPath: `${runDirectory}/bridge.sock`,
+ * })
*/
fetch: (url: string, init?: HttpInit) => Promise<HttpResponse>;
};
@@ -2718,9 +3068,9 @@ declare module 'claude-code' {
* The element constructors each surface draws, by `e.surface`: what
* `$.ui.resolve(e)` returns and a `ui.resolve` hook passes on; no globals.
*
- * All carry `Box`, `Text`, `Button`, `Link`, `Code`; every remote surface
- * `Svg`; all but mobile `Input` and `Select`; terminal and desktop `Client`;
- * terminal `Raster`. Narrowed on `e.surface`, that table; else the union.
+ * All carry `Box`, `Text`, `Button`, `Link`, `Code`, `Markdown`; every remote
+ * surface `Svg`; all but mobile `Input` and `Select`; terminal and desktop
+ * `Client`; terminal `Raster` and `Image`. Narrowed on `e.surface`, that table.
*/
export type Elements = {
terminal: {
@@ -2731,8 +3081,18 @@ declare module 'claude-code' {
Select: ElementConstructor<SelectProps>;
Link: ElementConstructor<LinkProps>;
Code: ElementConstructor<CodeProps>;
+ Markdown: ElementConstructor<MarkdownProps>;
+ /**
+ * A region one of the plugin's surface modules draws (ClientModule), named
+ * by `module`: a string literal, the module's path relative to this file.
+ *
+ * The engine reads the surface module off the hooks module's source
+ * before anything runs, so a variable, a template with a substitution or
+ * a computed path as `module` is refused at load, naming the line.
+ */
Client: ElementConstructor<ClientProps>;
Raster: ElementConstructor<RasterProps>;
+ Image: ElementConstructor<ImageProps>;
};
desktop: {
Box: ElementConstructor<BoxProps>;
@@ -2743,6 +3103,7 @@ declare module 'claude-code' {
Svg: ElementConstructor<SvgProps>;
Link: ElementConstructor<LinkProps>;
Code: ElementConstructor<CodeProps>;
+ Markdown: ElementConstructor<MarkdownProps>;
Client: ElementConstructor<ClientProps>;
};
/**
@@ -2758,6 +3119,7 @@ declare module 'claude-code' {
Svg: ElementConstructor<SvgProps>;
Link: ElementConstructor<LinkProps>;
Code: ElementConstructor<CodeProps>;
+ Markdown: ElementConstructor<MarkdownProps>;
};
/**
* The desktop's table without `Client`: a remote `Client`'s module, presses
@@ -2775,6 +3137,7 @@ declare module 'claude-code' {
Svg: ElementConstructor<SvgProps>;
Link: ElementConstructor<LinkProps>;
Code: ElementConstructor<CodeProps>;
+ Markdown: ElementConstructor<MarkdownProps>;
};
};
@@ -2818,8 +3181,12 @@ declare module 'claude-code' {
*/
export type EngineCreateInput = {
/**
- * In list order, first is outermost (managed plugins first, so an org
- * plugin's withholding wins).
+ * The modules this fold builds, in list order, first outermost (managed
+ * plugins first, so an org plugin's withholding wins).
+ *
+ * The whole set at a load, this plugin alone at its reload, the ones added
+ * or changed at a refresh that keeps the rest: a module added later that
+ * does not hook this event is built against the table as it stands.
*/
plugins: readonly string[];
};
@@ -2839,9 +3206,9 @@ declare module 'claude-code' {
* The events the engine raises at its call sites, and `engine.create`; the
* classic settings hooks' events are ClassicEventOf.
*
- * At every one, a hook that fails (throws, overruns its budget, answers a
- * wrong shape) is skipped: the hooks beneath and core run in its place, or
- * its last `next` result stands; the failure is reported, naming it.
+ * At every one, a hook that fails (throws, overruns its budget: HookBudget,
+ * answers a wrong shape) is skipped: the hooks beneath and core run in its
+ * place, or its last `next` result stands; the failure is reported by name.
*/
export type EngineEventOf = {
/**
@@ -2973,12 +3340,12 @@ declare module 'claude-code' {
*/
'prompt.submit': PromptSubmitInput;
/**
- * Fires when a text is about to be written into the prompt box as the
- * person's draft (a plugin's `$.prompt.fill`); `next(e)` writes it.
+ * Fires when a text is about to be put in the prompt box as the person's
+ * draft (a plugin's `$.prompt.fill`); `next(e)` writes it by `e.mode`.
*
- * Rewrite with `next({ ...e, text })`, or answer `{ isFilled: false }`
- * without `next` to keep it out; `origin` passes on as received. Core
- * answers `{ isFilled: false }` where no box can take it (a dialog is up).
+ * `replace` over the draft, `append` after it, `insert` at the cursor;
+ * rewrite `text` or `mode` going down, or answer `{ isFilled: false }`
+ * without `next` to keep it out, as core does under a dialog or headless.
*
* @example
* on("prompt.fill", ($, e, next) => next({ ...e, text: e.text.trim() }))
@@ -2996,6 +3363,18 @@ declare module 'claude-code' {
* on("prompt.suggest", { origin: { kind: "suggestion" } }, hide)
*/
'prompt.suggest': PromptSuggestInput;
+ /**
+ * Fires when the person edits the main prompt box: a key the editor took as
+ * an edit, or a paste; `next(e)` resolves the box the editor shows.
+ *
+ * `e` is the draft before and the splice (`start`, `end`, `inputText`); a
+ * burst of keys is one edit. Rewrite `inputText` going down or the box
+ * coming up; `{ text: e.text, cursor: e.cursor }` without `next` consumes.
+ *
+ * @example
+ * on("prompt.edit", ($, e, next) => next({ ...e, inputText: up(e) }))
+ */
+ 'prompt.edit': PromptEditInput;
/**
* Fires once per named section of the system prompt, when the engine
* assembles it; `next(e)` resolves to `{ text }` as core computed it.
@@ -3021,15 +3400,29 @@ declare module 'claude-code' {
*/
'prompt.context': PromptContextInput;
/**
- * Fires once per tool, when the engine first renders the tool's schema for
- * the model in a session; `next(e)` resolves to `{ description }`.
+ * Fires once per message the engine injects for the model on its own (a
+ * reminder, a mode transition, a mentioned file), as a request carries it.
+ *
+ * `next(e)` resolves to `{ text }`; `{ text: null }` leaves it out. The
+ * answer holds per attachment for the process (asked again on resume or
+ * `$.ui.invalidate`); the transcript keeps the engine's record.
+ *
+ * @example
+ * on("prompt.attachment", { type: "todo_reminder" }, () => ({ text: null }))
+ */
+ 'prompt.attachment': PromptAttachmentInput;
+ /**
+ * Fires once per tool, when the engine first renders the tool's schema in
+ * a session; `next(e)` resolves to `{ description, isDeferred? }`.
*
- * Rendered schemas are cached for the session until
- * `$.ui.invalidate("tool.describe")`: an unstable answer spends the model's
- * prompt cache on every call. A hook that fails passes it through.
+ * Cached for the session until `$.ui.invalidate("tool.describe")`: an
+ * unstable answer spends the model's prompt cache. An explicit `isDeferred`
+ * moves the tool behind ToolSearch (true) or into the prompt's list (false).
*
* @example
- * on("tool.describe", { tool: "Bash" }, () => ({ description: "Shell." }))
+ * on("tool.describe", { tool: "Bash" }, ($, e) => ({ ...e, description }))
+ * @example
+ * on("tool.describe", { tool: "Monitor" }, pin) // {...e, isDeferred: false}
*/
'tool.describe': ToolDescribeInput;
/**
@@ -3104,11 +3497,11 @@ declare module 'claude-code' {
'attribution.text': AttributionTextInput;
/**
* Fires once per process for each loaded plugin, before the first prompt,
- * and again for one that loads or reloads later; `next(e)` is `{ cwd }`.
+ * then once per fresh load of one (never `/clear`); `next(e)` is `{ cwd }`.
*
- * Observe. The first is awaited, so a `$.tool.register` here is listed by
- * turn one. A later one (an edit, new options, `/reload-plugins`, an enable)
- * runs that plugin's hooks alone, so its timers start again. Not `/clear`.
+ * Observe. The first is awaited: a `$.tool.register` is listed by turn one.
+ * A later one runs its hooks alone: an enable, a worker respawn, or a reload
+ * (changed modules only; all if one hooks `engine.create`/`plugin.register`).
*
* @example
* on("session.start", ($, e, next) => $.tool.register(t).then(() => next(e)))
@@ -3155,6 +3548,30 @@ declare module 'claude-code' {
* with it attached (`e.reason`). Observe; `next(e)` echoes `{ clientId }`.
*/
'session.detach': SessionDetachInput;
+ /**
+ * Fires when the engine measures the session and a unit moved: after each
+ * main-thread turn, and when a rate-limit window moves a whole point.
+ *
+ * Observe; `next(e)` echoes `{ changed }`. `$.session.usage()`'s figures,
+ * pushed, not polled: compare them with your own threshold here, call the
+ * op for the breakdown. One at a time, a burst folding into one more.
+ *
+ * @example
+ * on("session.measure", ($, e, next) => (toastPast90(e.rateLimits), next(e)))
+ */
+ 'session.measure': SessionMeasureInput;
+ /**
+ * Fires once when the session ends (exit, /clear, resume, logout, signal, a
+ * `-p` run done), after its SessionEnd settings hooks; `e.reason` says which.
+ *
+ * `e.resume.id` is `--resume`'s id; `next(e)` runs the engine's end step for
+ * the plugins (at an exit the attached clients leave): `{ sessionId }`. The
+ * SessionEnd bound afresh, 1.5 s by default; a `kill -9` raises nothing.
+ *
+ * @example
+ * on("session.end", async ($, e, next) => (await keep(e.resume), next(e)))
+ */
+ 'session.end': SessionEndInput;
/**
* Fires once per hooks module about to join the chain, at load (the set
* folded and built, nothing swapped in) and at reload; core allows.
@@ -3178,7 +3595,7 @@ declare module 'claude-code' {
*
* `next({ ...e, model })` or `effort` sends another; the turn, the index and
* the message count are pinned. An answer without `next` sends no request.
- * Every request of the turn passes here; `turn.complete` follows the last.
+ * It streams (StreamNext): the hook's budget counts its own code alone.
*/
'turn.step': TurnStepInput;
/**
@@ -3294,6 +3711,10 @@ declare module 'claude-code' {
* `{ isShown }`.
*/
'prompt.suggest': PromptSuggestResult;
+ /**
+ * `{ text, cursor }`, the box the editor shows next.
+ */
+ 'prompt.edit': PromptEditResult;
/**
* `{ text }` (null leaves the section out).
*/
@@ -3303,7 +3724,11 @@ declare module 'claude-code' {
*/
'prompt.context': PromptContextResult;
/**
- * `{ description }`.
+ * `{ text }` (null leaves the attachment out).
+ */
+ 'prompt.attachment': PromptAttachmentResult;
+ /**
+ * `{ description, isDeferred? }`.
*/
'tool.describe': ToolDescribeResult;
/**
@@ -3350,6 +3775,14 @@ declare module 'claude-code' {
* `{ clientId }`.
*/
'session.detach': SessionDetachResult;
+ /**
+ * `{ changed }`.
+ */
+ 'session.measure': SessionMeasureResult;
+ /**
+ * `{ sessionId }`.
+ */
+ 'session.end': SessionEndResult;
/**
* `{ allow: true }`, or `{ refuse }`.
*/
@@ -3401,6 +3834,7 @@ declare module 'claude-code' {
suggest: (input: PromptSuggestArgs) => Promise<PromptSuggestResult>;
section: (input: PromptSectionInput) => Promise<PromptSectionResult>;
context: (input: PromptContextInput) => Promise<PromptContextResult>;
+ attachment: (input: PromptAttachmentInput) => Promise<PromptAttachmentResult>;
};
skill: {
prompt: (input: SkillPromptInput) => Promise<SkillPromptResult>;
@@ -3418,6 +3852,8 @@ declare module 'claude-code' {
compact: (input?: SessionCompactArgs) => Promise<SessionCompactResult>;
attach: (input: SessionAttachInput) => Promise<SessionAttachResult>;
detach: (input: SessionDetachInput) => Promise<SessionDetachResult>;
+ measure: (input: SessionMeasureInput) => Promise<SessionMeasureResult>;
+ end: (input: SessionEndInput) => Promise<SessionEndResult>;
};
turn: {
start: (input: TurnStartInput) => Promise<TurnStartResult>;
@@ -3510,11 +3946,30 @@ declare module 'claude-code' {
* The file's text, with what its `@include`s bring after it.
*/
content: string;
+ /**
+ * The file and then each file its `@` imports brought, in load order,
+ * path and text apiece; `content` is these texts joined.
+ */
+ parts: readonly FsAncestorPart[];
+ };
+
+ /**
+ * One file of an ancestor entry: the file itself or one it imported.
+ */
+ export type FsAncestorPart = {
+ /**
+ * The file's path, absolute.
+ */
+ path: string;
+ /**
+ * Its text as the engine's memory loader reads it.
+ */
+ content: string;
};
/**
* The argument of `$.fs.ancestors`: the file names to look for in each
- * directory, and the file to walk down to.
+ * directory, the file to walk down to, and the directory to walk beneath.
*/
export type FsAncestorsRequest = {
/**
@@ -3526,10 +3981,31 @@ declare module 'claude-code' {
* working directory or absolute; absent, it ends at the working directory.
*/
of?: string;
+ /**
+ * The directory the walk starts beneath, relative to the working directory
+ * or absolute; absent, the walk starts at the filesystem root.
+ *
+ * Only directories strictly inside it are read, so with `of` a file under
+ * the project root the walk reads the directories between the two, as the
+ * engine reads a nested CLAUDE.md; a file not inside it finds nothing.
+ */
+ below?: string;
+ };
+
+ /**
+ * What `$.fs.read(path, { as: "bytes" })` resolves with: the file's bytes,
+ * base64, since only plain data crosses into a plugin's environment.
+ */
+ export type FsBytes = {
+ /**
+ * The file's content, standard padded base64;
+ * `Uint8Array.fromBase64(base64)` gives the bytes back.
+ */
+ base64: string;
};
/**
- * One entry of `$.fs.list`.
+ * One entry of `$.fs.list`: the entry itself, a link not followed.
*/
export type FsEntry = {
/**
@@ -3537,21 +4013,65 @@ declare module 'claude-code' {
*/
name: string;
/**
- * `file`, `dir`, or `other`.
+ * `file`, `dir`, or `other`, of the entry itself: a symbolic link is
+ * `other` (`$.fs.stat` says what it leads to, and with `resolve` where).
*/
kind: 'file' | 'dir' | 'other';
/**
* Bytes, for a file.
*/
size: number;
+ /**
+ * True when the entry is a symbolic link.
+ */
+ isLink: boolean;
+ };
+
+ /**
+ * How `$.fs.read` answers: `text` (UTF-8, the default) or `bytes` (base64).
+ */
+ export type FsReadAs = 'text' | 'bytes';
+
+ /**
+ * The options of `$.fs.read` that ask for the bytes: the call answers
+ * `{ base64 }`.
+ */
+ export type FsReadBytesOptions = {
+ /**
+ * `bytes`.
+ */
+ as: 'bytes';
+ };
+
+ /**
+ * `$.fs.read`: the file's text, or with `{ as: "bytes" }` its bytes as
+ * `{ base64 }`.
+ */
+ export type FsReadCall = {
+ (path: string): Promise<string>;
+ (path: string, options: FsReadBytesOptions): Promise<FsBytes>;
+ (path: string, options: FsReadOptions): Promise<string | FsBytes>;
+ };
+
+ /**
+ * The options of `$.fs.read`.
+ */
+ export type FsReadOptions = {
+ /**
+ * `bytes` answers `{ base64 }` for a binary file; `text` (the default) the
+ * file's text.
+ */
+ as: FsReadAs;
};
/**
- * What `$.fs.stat` resolves with.
+ * What `$.fs.stat` resolves with: what the path leads to, whether the path
+ * itself is a symbolic link, and where it lands when asked.
*/
export type FsStat = {
/**
- * `file`, `dir`, or `other`.
+ * `file`, `dir`, or `other`, of what the path leads to: a link is
+ * followed, and one that leads nowhere is `other`.
*/
kind: 'file' | 'dir' | 'other';
/**
@@ -3562,6 +4082,37 @@ declare module 'claude-code' {
* Last modification, milliseconds since the epoch.
*/
mtimeMs: number;
+ /**
+ * True when the path itself is a symbolic link; `kind`, `size` and
+ * `mtimeMs` then describe what it points at, or the link when that is gone.
+ */
+ isLink: boolean;
+ /**
+ * Where the path landed when asked with `{ resolve: true }`: absolute,
+ * every symbolic link followed, `.` and `..` folded; else absent.
+ *
+ * Absent too when the path leads nowhere or a hook above withheld it, so
+ * a guard denies without it; and a hard link, a volume or file-id spelling
+ * (macOS `/.vol/`) or a case alias keeps its own spelling, `isLink` false.
+ *
+ * @remarks a deny-list on spellings is thus best effort; an allow-list on
+ * `realPath` under a root resolved the same way is the robust guard.
+ */
+ realPath?: string;
+ };
+
+ /**
+ * The options of `$.fs.stat`.
+ */
+ export type FsStatOptions = {
+ /**
+ * True to resolve where the path lands as well.
+ *
+ * The answer then carries `realPath` when the path leads somewhere, at
+ * the cost of one more file system call: where it landed then, not a hold
+ * on what a tool opens afterwards.
+ */
+ resolve: boolean;
};
/**
@@ -3599,6 +4150,7 @@ declare module 'claude-code' {
readonly event: N;
readonly origin: Origin;
readonly trace: readonly TraceEntry<N, Args<N>, GlobNextResult<N>>[];
+ readonly budget: NextBudget;
};
/**
@@ -3614,6 +4166,45 @@ declare module 'claude-code' {
*/
export type Hook<E extends EventName = EventName> = Events[E];
+ /**
+ * The time bounds every hook runs under, in milliseconds: the engine's own
+ * constants are typed by these members, and `next.budget` reads the live one.
+ *
+ * Each bounds the hook's OWN time: the clock stops while a `next(e)` call or
+ * any `$` call of the hook's is in flight (a `$.clock` wait excepted), so a
+ * slow chain beneath or a minute-long `$.model.complete` costs it nothing.
+ *
+ * @example
+ * await $.model.complete(ask) // a minute; next.budget.remainingMs unmoved
+ */
+ export type HookBudget = {
+ /**
+ * A hook's budget per dispatch, from its call to its return; past it the
+ * hook is absent (its `.catch` asked, else `next(e)` run on its behalf).
+ *
+ * A streaming hook's (`turn.step`, an async generator) spans its whole
+ * run and counts only while its own code runs: never at a `yield`, never
+ * while it reads the stream beneath. Not per chunk: the sum of its work.
+ */
+ readonly ms: 10_000;
+ /**
+ * A `.catch` handler's grace: a fresh budget from the moment it is called,
+ * on the same clock (its `next` replay and its `$` calls are free).
+ *
+ * Past it the hook is absent as if it had no handler; `next.error.budget`
+ * and `next.budget.ms` both read it there. `engine.create` has no budget.
+ */
+ readonly catchMs: 1_000;
+ /**
+ * How long a hook may keep running after `next.signal` aborted (the person
+ * interrupted, a hook above settled first, its own budget ran out).
+ *
+ * Past it the hook is reported as lingering; the dispatch had already gone
+ * on without it when the signal aborted.
+ */
+ readonly lingerMs: 5_000;
+ };
+
/**
* Why a hook failed, as its `.catch` handler reads it on `next.error`: plain
* frozen data.
@@ -3699,6 +4290,18 @@ declare module 'claude-code' {
* session's credential header itself, only for a first-party host.
*/
auth?: string;
+ /**
+ * The absolute path of a Unix domain socket the request goes over instead
+ * of TCP (near 100 B at most): one per session, in a private directory.
+ *
+ * The URL still gives path, query and Host; redirects stay on it; no proxy;
+ * `https:` is TLS verified against the URL's host (always, once `auth`
+ * rides), so a credential reaches only its host. No relative path, no NUL.
+ *
+ * @example
+ * await $.http.fetch(url, { socketPath: `${runDirectory}/bridge.sock` })
+ */
+ socketPath?: string;
};
/**
@@ -3724,53 +4327,230 @@ declare module 'claude-code' {
};
/**
- * The keys of object pattern `P` that object member `E` cannot satisfy, `D`
- * levels down; `never` when there is none, which is what keeps the member.
+ * A `$.ui.blit` argument swapping one of the caller's mounted keyed Images
+ * to its next picture; every call sends it, so a stream needs no generation.
*
- * A key `E` does not have (an open record has every string key), or one
- * whose value `P` narrows to nothing.
- */
- type ImpossibleKeys<E, P, D extends readonly unknown[]> = {
- [K in keyof P]-?: K extends keyof E ? [NarrowedValue<Exclude<E[K], undefined>, P[K], D>] extends [never] ? K : never : K;
- }[keyof P];
-
- /**
- * The props of `Input`, every surface's one-line text field: an address,
- * optional texts, and the closures a change and a submit run. A leaf.
+ * The surface writes them with its frames, some sixty a second: byte and
+ * `file` sources fold to the last per frame; every `shm` source reaches the
+ * terminal (it unlinks each), and is denied while frames are not written.
*
- * Focused through the same ring as `Button` (`abovePrompt:focus`); while it
- * has focus every printable key reaches it alone and Esc returns them; a
- * change and Enter raise `ui.input`, whose bottom is `onInput` / `onSubmit`.
+ * @example await $.ui.blit({ requestId: 'browser', key: 'view',
+ * source: { shm: '/tb-4', format: 'rgb', width: 1280, height: 720 } })
*/
- export type InputProps = {
+ export type ImageBlitArgs = {
/**
- * The element's address: `e.element` at `ui.input`, what a matcher names.
+ * The site the Image is drawn in, by the `requestId` this plugin draws it
+ * under.
*/
- key: string;
+ requestId: string;
/**
- * Text drawn before the field.
+ * The Image's `key` in that drawing.
*/
- label?: string;
+ key: string;
/**
- * Text drawn dim in an empty field.
+ * The next picture (ImageSource): bytes, or a name the terminal reads.
*/
- placeholder?: string;
+ source: ImageSource;
/**
- * The text the field holds when drawn; the person's typing replaces it
- * until the hook draws another.
+ * Refused unless it is the mounted Image's width in cells. Absent, that.
*/
- value?: string;
+ columns?: number;
/**
- * What Enter does, in a word or two, drawn beside the field while it has
- * focus (`send`). Defaults to `submit`.
+ * Refused unless it is the mounted Image's height in cells. Absent, that.
*/
- submitLabel?: string;
- /**
- * The site's focus ring starts here when the site takes the keyboard,
- * instead of on nothing, as the DOM's `autofocus`: Enter acts on it at once.
- *
- * A pane opened with `focus`, or the person's focus chord or click, is the
- * take. Of several in one site the first drawn wins; it raises `ui.focus`,
+ rows?: number;
+ };
+
+ /**
+ * The props of `Image`, the terminal surface's picture leaf: pixels over a
+ * box of cells where the terminal can (kitty, Ghostty), the `alt` elsewhere.
+ *
+ * A leaf: no children, `hover` or `onPress`; the cells are text, so the
+ * picture scrolls and clips as a word does. Drawn again with another `source`
+ * it is replaced in place; keyed, `$.ui.blit` swaps it at the frame rate.
+ *
+ * @example const { bytes } = await $.fs.read('chart.png', { as: 'bytes' })
+ * <Image source={{ png: bytes.toBase64() }} columns={40} rows={12} alt="p95" />
+ * @example <Image key="view" source={{ shm: '/tb-7', format: 'rgb', width: 960,
+ * height: 600 }} columns={80} rows={25} alt="the page" />
+ */
+ export type ImageProps = {
+ /**
+ * The element's address within the drawing: what `$.ui.blit` names to swap.
+ *
+ * Unique among the Images of one tree; absent, only a redraw changes it.
+ */
+ key?: string;
+ /**
+ * The picture (ImageSource): `{ png }` or `{ rgba, width, height }` bytes,
+ * or `{ file, format }` / `{ shm, format, width, height }` read here.
+ */
+ source: ImageSource;
+ /** How many terminal columns wide, 1 to 255; the picture is scaled to fill
+ * the box and the site clips what its body cannot show. */
+ columns: number;
+ /**
+ * How many terminal rows tall, 1 to 255.
+ */
+ rows: number;
+ /**
+ * What the picture says, drawn dim in its place where the picture cannot
+ * be (and read by a screen reader); required, may be a single space.
+ */
+ alt: string;
+ };
+
+ /**
+ * The picture an `Image` shows: base64 bytes the plugin holds (at most 2 MiB
+ * decoded), or the name of a file or POSIX shared-memory object it does not.
+ *
+ * A name is one another process on this machine wrote; the terminal, running
+ * as the person, opens, reads and decodes it itself, so no pixel crosses `$`
+ * and the engine never touches it. One it will not read (not a regular file,
+ * under `/proc`, `/sys` or `/dev`, gone, across ssh) draws a blank box, its
+ * words in the debug log; it unlinks a shared-memory object once read, so
+ * each frame is a fresh one. A source equal to the last drawn sends nothing;
+ * `generation` makes new content under an unchanged name a new source.
+ *
+ * @example { rgba: pixels.toBase64(), width: 64, height: 32 }
+ * @example { file: '/dev/shm/frame-3.rgba', format: 'rgba', width: 640,
+ * height: 400 }
+ * @example { shm: '/tb-view-2', format: 'rgb', width: 1280, height: 720 }
+ */
+ export type ImageSource = {
+ /**
+ * A whole PNG file, base64.
+ */
+ png: string;
+ } | {
+ /**
+ * `width * height` RGBA pixels, 4 bytes each, base64.
+ */
+ rgba: string;
+ /**
+ * Pixels per row, 1 to 2048.
+ */
+ width: number;
+ /**
+ * Rows of pixels, 1 to 2048.
+ */
+ height: number;
+ } | {
+ /**
+ * The absolute path of a regular file holding a whole PNG, at most
+ * 3072 bytes of path; read by the terminal, left in place.
+ */
+ file: string;
+ /**
+ * The file is a whole PNG; the terminal decodes it and sizes it itself.
+ */
+ format: 'png';
+ /**
+ * A whole number that changes when the file's content does under the
+ * same path, so a redraw reads it again; absent, the path alone tells.
+ */
+ generation?: number;
+ } | {
+ /**
+ * The absolute path of a regular file of `width * height` raw pixels, at
+ * most 3072 bytes of path; read by the terminal, left in place.
+ *
+ * On Linux a file under `/dev/shm` is memory.
+ */
+ file: string;
+ /**
+ * `rgba`, 4 bytes a pixel, or `rgb`, 3.
+ */
+ format: 'rgba' | 'rgb';
+ /**
+ * Pixels per row, 1 to 4096.
+ */
+ width: number;
+ /**
+ * Rows of pixels, 1 to 4096.
+ */
+ height: number;
+ /**
+ * A whole number that changes when the file's content does under the
+ * same path, so a redraw reads it again; absent, the path alone tells.
+ */
+ generation?: number;
+ } | {
+ /**
+ * The name of a POSIX shared-memory object of `width * height` raw
+ * pixels: `/` then up to 254 of `A-Z a-z 0-9 . _ -` (macOS takes 30).
+ *
+ * The terminal unlinks it after reading, so a name feeds one Image
+ * drawn once and is never sent again on a redraw; POSIX terminals only.
+ */
+ shm: string;
+ /**
+ * `rgba`, 4 bytes a pixel, or `rgb`, 3.
+ */
+ format: 'rgba' | 'rgb';
+ /**
+ * Pixels per row, 1 to 4096.
+ */
+ width: number;
+ /**
+ * Rows of pixels, 1 to 4096.
+ */
+ height: number;
+ /**
+ * A whole number that changes when a fresh object reuses a name, so a
+ * redraw reads it again; absent, the name alone tells.
+ */
+ generation?: number;
+ };
+
+ /**
+ * The keys of object pattern `P` that object member `E` cannot satisfy, `D`
+ * levels down; `never` when there is none, which is what keeps the member.
+ *
+ * A key `E` does not have (an open record has every string key), or one
+ * whose value `P` narrows to nothing.
+ */
+ type ImpossibleKeys<E, P, D extends readonly unknown[]> = {
+ [K in keyof P]-?: K extends keyof E ? [NarrowedValue<Exclude<E[K], undefined>, P[K], D>] extends [never] ? K : never : K;
+ }[keyof P];
+
+ /**
+ * The props of `Input`, every surface's one-line text field: an address,
+ * optional texts, and the closures a change and a submit run. A leaf.
+ *
+ * Focused through the same ring as `Button` (`abovePrompt:focus`); while it
+ * has focus every printable key reaches it alone and Esc returns them; a
+ * change and Enter raise `ui.input`, whose bottom is `onInput` / `onSubmit`.
+ */
+ export type InputProps = {
+ /**
+ * The element's address: `e.element` at `ui.input`, what a matcher names.
+ */
+ key: string;
+ /**
+ * Text drawn before the field.
+ */
+ label?: string;
+ /**
+ * Text drawn dim in an empty field.
+ */
+ placeholder?: string;
+ /**
+ * The text the field holds when drawn; the person's typing replaces it
+ * until the hook draws another.
+ */
+ value?: string;
+ /**
+ * What Enter does, in a word or two, drawn beside the field while it has
+ * focus (`send`). Defaults to `submit`.
+ */
+ submitLabel?: string;
+ /**
+ * The site's focus ring starts here when the site takes the keyboard,
+ * instead of on nothing, as the DOM's `autofocus`: Enter acts on it at once.
+ *
+ * A pane opened with `focus`, or the person's focus chord or click, is the
+ * take. Of several in one site the first drawn wins; it raises `ui.focus`,
* origin this plugin. A ring the person has moved stays where it was put.
*/
autoFocus?: true;
@@ -3786,6 +4566,41 @@ declare module 'claude-code' {
onSubmit: (value: string, e: UiInputArgument) => void;
};
+ /**
+ * Every tier an instruction file can belong to, for checking a hook's
+ * answer; the kind type is derived from this list.
+ */
+ const INSTRUCTION_FILE_KINDS: readonly ["managed", "user", "project", "local", "memory"];
+
+ /**
+ * One instruction file behind the `claudeMd` block: where it was read, its
+ * tier, its text as loaded, and the file that `@`-imported it if one did.
+ */
+ export type InstructionFile = {
+ /**
+ * The file's path, absolute.
+ */
+ path: string;
+ /**
+ * Its tier.
+ */
+ kind: InstructionFileKind;
+ /**
+ * The text as loaded (comments and frontmatter already stripped).
+ */
+ content: string;
+ /**
+ * The path of the file whose `@` import brought this one, when one did.
+ */
+ parent?: string;
+ };
+
+ /**
+ * What tier an instruction file belongs to: the organization's managed
+ * policy, the person's own, the project's checked-in or private ones, memory.
+ */
+ export type InstructionFileKind = (typeof INSTRUCTION_FILE_KINDS)[number];
+
type InstructionsLoadedHookInput = BaseHookInput & {
hook_event_name: 'InstructionsLoaded';
file_path: string;
@@ -3797,10 +4612,10 @@ declare module 'claude-code' {
};
/**
- * What `$.ui.invalidate` takes: a render event, or one of the five events
+ * What `$.ui.invalidate` takes: a render event, or one of the six events
* whose answers the engine caches for the session.
*/
- export type InvalidatableEventName = RenderEventName | 'prompt.section' | 'prompt.context' | 'tool.describe' | 'command.describe' | 'config.describe';
+ export type InvalidatableEventName = RenderEventName | 'prompt.section' | 'prompt.context' | 'prompt.attachment' | 'tool.describe' | 'command.describe' | 'config.describe';
/**
* Whether tag key `K` selects members of `I`: it does when each member gives
@@ -3898,6 +4713,77 @@ declare module 'claude-code' {
*/
type Literal<X> = X extends RegExp ? unknown : X;
+ /**
+ * What a `Markdown` carries across the boundary: its address, text, dimness
+ * and which links it answers; `onLinkPress` stays behind, a `press` instead.
+ */
+ export type MarkdownLeafProps = {
+ /**
+ * The element's address: what `e.element` carries and what a matcher
+ * names; present whenever the element carries a `press`.
+ */
+ key?: string;
+ /**
+ * The markdown drawn, bounded as a Text's string is.
+ */
+ text: string;
+ /**
+ * The whole block dim, as `Text`'s `dimColor`; absent draws as false.
+ */
+ dimColor?: boolean;
+ /**
+ * Which links a press belongs to, by `href` as written; absent, with a
+ * `press`, every link drawn. Compared with the pressed target only.
+ */
+ pressableLinks?: readonly string[];
+ };
+
+ /**
+ * The props of `Markdown`, a block of markdown every surface draws as it
+ * draws an assistant reply's text: its own renderer, links, tables, fences.
+ *
+ * A leaf: no children. `text` is the element's data as a `Text`'s string is,
+ * bounded the same way. With `onLinkPress` the links it draws are the
+ * plugin's to answer: a press on one raises `ui.press` addressed to `key`.
+ */
+ export type MarkdownProps = {
+ /**
+ * The element's address: `e.element` at `ui.press`, what a matcher names.
+ * Required with `onLinkPress`, since a press needs one; else optional.
+ */
+ key?: string;
+ /**
+ * The markdown drawn, as an assistant reply would write it.
+ *
+ * At most 10000 characters, tab and newline its only control characters;
+ * a link whose scheme is not `https:`, `http:` or `file:` draws as text,
+ * never clickable. Not drawn around the approval dialog.
+ */
+ text: string;
+ /**
+ * The whole block dim, as `Text`'s `dimColor`: a thought, an aside.
+ */
+ dimColor?: boolean;
+ /**
+ * What a press on a link in `text` runs, in the plugin's own environment:
+ * the bottom of a `ui.press` chain whose `e.link` names the link.
+ *
+ * A press is a plain single click where the surface reports clicks (the
+ * fullscreen terminal): it opens nothing and lands once no double-click
+ * followed; a ctrl, alt or terminal-kept cmd click opens it as before.
+ */
+ onLinkPress?: (link: PressedLink, e: UiPressArgument) => void;
+ /**
+ * Which links in `text` a press belongs to, by `href` as the markdown
+ * writes it; absent, every link drawn. Only with `onLinkPress`.
+ *
+ * A link left out keeps the surface's own behaviour. At most 256 entries
+ * of at most 2048 characters; compared with the pressed link's target,
+ * never opened.
+ */
+ pressableLinks?: readonly string[];
+ };
+
/**
* The argument a matched hook receives: `e` narrowed by `M` (Narrowed), per
* event the registration covers.
@@ -4028,16 +4914,37 @@ declare module 'claude-code' {
};
/**
- * The MCP branch: one variant per declared tool when McpToolInputs has
- * entries, else one loose variant over every `mcp__*` name.
+ * The MCP server serving this tool, for `mcp__*` tools: `name` is the server's config key (for `source: "sdk"`, exactly the name the SDK host registered in `sdkMcpServers` / `mcp_set_servers`; for any other source, the key as authored in that configuration - untrusted text, the same value `mcp_status` and system/init report, to be escaped before display), `source` is where its definition came from - `sdk` (an in-process server the SDK host runs; only the host can register one, so a configured server of the same name never reads `sdk`), `plugin` (a server a plugin ships or registers at runtime), or a config scope (`user`, `project`, `local`, `dynamic` for --mcp-config / `mcp_set_servers` process servers, `managed`, `enterprise`, `claudeai`, `agent`). Key trust on `source`, not on the name or the tool-name prefix. Absent for non-MCP tools.
+ */
+ type McpServerProvenance = {
+ name: string;
+ /**
+ * sdk | plugin | user | project | local | dynamic | managed | enterprise | claudeai | agent - an open set; treat unknown values as an unrecognized configured source, never as sdk.
+ */
+ source: string;
+ };
+
+ /**
+ * The MCP branch of a `tool.call` hook's `e` (and of `$.tool.call`'s input):
+ * one variant per declared tool, else the loose McpToolCallInputFallback.
+ *
+ * `$.mcp.call(server, tool, args)` takes none of these: its parameters are
+ * positional, the server and tool by name, then the arguments object.
*/
export type McpToolCallInput = [keyof McpToolInputs] extends [never] ? McpToolCallInputFallback : {
[N in keyof McpToolInputs & string]: ToolInputOf<N, McpToolInputs[N] & Record<string, unknown>>;
}[keyof McpToolInputs & string];
/**
- * The MCP branch's answer when no MCP tool is declared: every `mcp__*`
- * name, its args unconstrained.
+ * The `e` a `tool.call` (or `classic.PreToolUse`) hook receives for an MCP
+ * tool while no MCP tool is declared: every `mcp__*` name, loose arguments.
+ *
+ * McpToolInputs has no entries until `/plugin-types` writes the connected
+ * tools' declarations; also the `input` of `$.tool.call({ tool:
+ * "mcp__<server>__<tool>", ... })`. Not `$.mcp.call`'s, which is positional:
+ *
+ * @example
+ * on("tool.call", { tool: "mcp__gh__issue" }, ($, e, next) => audit(e.title))
*/
type McpToolCallInputFallback = {
/**
@@ -4138,7 +5045,12 @@ declare module 'claude-code' {
*/
system?: string;
/**
- * The reply's token cap. Default 256.
+ * The reply's token cap: any positive integer up to what one reply can
+ * hold, the model's own output limit or 64000, whichever is lower.
+ *
+ * Default 1024. The reply comes back whole, not streamed, and a provider
+ * ends such a request at ten minutes, hence the 64000. One past the limit
+ * is refused, naming it.
*/
maxTokens?: number;
};
@@ -4328,6 +5240,40 @@ declare module 'claude-code' {
* of the engine at a link that answered its last call itself. Data, frozen.
*/
readonly trace: readonly TraceEntry<N, E, O>[];
+ /**
+ * How much time this hook runs under and how much is left (NextBudget),
+ * read fresh on each access; HookBudget says what the clock counts.
+ *
+ * It stands still while a `next` or `$` call of the hook's is in flight;
+ * in a `.catch` handler it is the grace, `ms` being `next.error.budget`.
+ *
+ * @example
+ * if (next.budget.remainingMs < 2_000) return next(e) // skip the polish
+ */
+ readonly budget: NextBudget;
+ };
+
+ /**
+ * The budget the code reading `next.budget` runs under: the whole allowance
+ * and what is left of it now, plain data read fresh on each access.
+ *
+ * In a hook `ms` is HookBudget's `ms`; in a `.catch` handler its `catchMs`
+ * (equal to `next.error.budget`); on a `next` nothing meters (the engine's
+ * own, a test's root one) `ms` is 0 and `remainingMs` Infinity.
+ *
+ * @example
+ * if (next.budget.remainingMs < 2_000) return next(e) // skip the slow path
+ */
+ export type NextBudget = {
+ /**
+ * The whole budget in milliseconds; 0 where nothing meters this `next`.
+ */
+ readonly ms: number;
+ /**
+ * What is left of it now, in milliseconds, never below 0; Infinity where
+ * nothing meters. It stands still while a `next` or `$` call is in flight.
+ */
+ readonly remainingMs: number;
};
/**
@@ -4445,12 +5391,48 @@ declare module 'claude-code' {
* One function stands on every selected event (`next.event` says which),
* under a matcher for the inputs it matches; a plugin's registrations nest
* in order, first outermost; a repeat throws. Returns the Registration.
+ *
+ * @see HookBudget the time each hook has per dispatch (its own time: waits
+ * on `next` and `$` are free), read live from `next.budget`
*/
export type On = {
<P extends Pattern>(pattern: P, hook: NoInfer<HookFor<P>>): Registration<HookFor<P>>;
<P extends Pattern, const M extends Matcher<Args<MatchedNames<P>>>>(pattern: P, matcher: M, hook: NoInfer<MatchedHook<P, M>>): Registration<MatchedHook<P, M>>;
};
+ /**
+ * The part of a transcript message the surface that drew it has on screen:
+ * units `first` to `last` of the message's `of`, counted from its start.
+ *
+ * The terminal counts the rows the site laid out, from its first (the blank
+ * row the engine draws above a message is its row 0; a hook's tree starts at
+ * its own); other surfaces count in their unit, so compare `first / of` there.
+ *
+ * @remarks While `null` the terminal holds the site at the rows it last laid
+ * out (a scroller's geometry needs real rows); on screen, draw anything.
+ * @example if (e.props.onScreen) shown.set(e.requestId, e.props.onScreen)
+ * else shown.delete(e.requestId) // the band's legend lists `shown`
+ */
+ type OnScreen = {
+ /**
+ * The unit inside the viewport, from 0: on the terminal, `7` when the
+ * message's top seven rows are scrolled away.
+ */
+ first: number;
+ /**
+ * The unit inside the viewport, inclusive; at least `first`.
+ */
+ last: number;
+ /**
+ * The message's whole extent in the same unit, as laid out (a hook's tree
+ * taller than the engine's counts its own rows); more than `last`.
+ *
+ * One surface's numbers say nothing of another's: what the phone shows the
+ * terminal may not, and each `ui.render` carries its own surface's.
+ */
+ of: number;
+ };
+
/**
* The keys a variant with a string index signature (an MCP tool's input)
* takes beyond its own: another variant's key as typed there; others free.
@@ -4517,6 +5499,10 @@ declare module 'claude-code' {
* The argument of `$.session.cwd()`.
*/
'session.cwd': NoArgs;
+ /**
+ * The argument of `$.session.root()`.
+ */
+ 'session.root': NoArgs;
/**
* The argument of `$.session.model()`.
*/
@@ -4561,6 +5547,10 @@ declare module 'claude-code' {
'turn.abort': {
turnId: string;
};
+ /**
+ * The argument of `$.prompt.read()`.
+ */
+ 'prompt.read': NoArgs;
/**
* The argument of `$.tool.list()`.
*/
@@ -4585,6 +5575,11 @@ declare module 'claude-code' {
* The argument of `$.agent.list()`.
*/
'agent.list': NoArgs;
+ /**
+ * The argument of `$.agent.register(spec)`: the agent type as the plugin
+ * defined it. A hook above rewrites any of it; the type stays the caller's.
+ */
+ 'agent.register': AgentSpec;
/**
* The argument of `$.ui.toast(text, { timeoutMs })`.
*/
@@ -4599,10 +5594,12 @@ declare module 'claude-code' {
text: string | undefined;
};
/**
- * The argument of `$.ui.log(text)`.
+ * The argument of `$.ui.log(text, { to })`; `to` is always present
+ * (UiLogSink), and `next({ ...e, to: "debug" })` keeps a line off screen.
*/
'ui.log': {
text: string;
+ to: UiLogSink;
};
/**
* The argument of `$.ui.notice(tool_use_id, text)`.
@@ -4628,15 +5625,21 @@ declare module 'claude-code' {
*/
'ui.close': PaneCloseInput;
/**
- * The argument of `$.ui.blit({ requestId, key, cells })`; a hook above
- * the painter may repaint the cells with `next`, or refuse with `{ deny }`.
+ * The argument of `$.ui.panes()`.
+ */
+ 'ui.panes': NoArgs;
+ /**
+ * The argument of `$.ui.blit(...)`: a Raster's `cells` or a keyed Image's
+ * `source`; a hook above may rewrite either with `next`, or `{ deny }`.
*/
'ui.blit': UiBlitArgs;
/**
- * The argument of `$.fs.read(path)`.
+ * The argument of `$.fs.read(path, { as })`: `as` is `text` unless the
+ * caller asked for `bytes`.
*/
'fs.read': {
path: string;
+ as: FsReadAs;
};
/**
* The argument of `$.fs.write(path, text)`.
@@ -4658,13 +5661,15 @@ declare module 'claude-code' {
path: string;
};
/**
- * The argument of `$.fs.stat(path)`.
+ * The argument of `$.fs.stat(path, { resolve })`: `resolve` is false
+ * unless the caller asked where the path lands.
*/
'fs.stat': {
path: string;
+ resolve: boolean;
};
/**
- * The argument of `$.fs.ancestors({ names, of })`.
+ * The argument of `$.fs.ancestors({ names, of, below })`.
*/
'fs.ancestors': FsAncestorsRequest;
/**
@@ -4761,6 +5766,7 @@ declare module 'claude-code' {
'audio.speak': SpeakResult;
'mcp.call': McpToolResult;
'session.cwd': string;
+ 'session.root': string;
'session.model': string;
'session.turns': number;
'session.id': string;
@@ -4775,6 +5781,10 @@ declare module 'claude-code' {
'session.authorize': SessionAuthorization;
'session.usage': SessionUsage;
'turn.abort': void;
+ /**
+ * The box as it stands; the empty box where the session draws none.
+ */
+ 'prompt.read': PromptBox;
'tool.list': ToolInfo[];
'tool.register': {
tool: string;
@@ -4785,6 +5795,9 @@ declare module 'claude-code' {
};
'config.list': ConfigRow[];
'agent.list': AgentInfo[];
+ 'agent.register': {
+ agent: string;
+ };
'ui.toast': void;
'ui.status': void;
'ui.log': void;
@@ -4792,8 +5805,15 @@ declare module 'claude-code' {
'ui.invalidate': void;
'ui.open': void;
'ui.close': void;
+ /**
+ * The calling plugin's open panes, placed then unplaced, in open order.
+ */
+ 'ui.panes': readonly UiPane[];
'ui.blit': UiBlitResult;
- 'fs.read': string;
+ /**
+ * The text; `{ base64 }` when asked for bytes.
+ */
+ 'fs.read': string | FsBytes;
'fs.write': void;
'fs.list': FsEntry[];
'fs.exists': boolean;
@@ -4892,7 +5912,7 @@ declare module 'claude-code' {
/**
* The argument of `$.ui.open`: which pane, its title, whether it asks the
- * person's keyboard, its dialog manners, and the rows it wants inline.
+ * person's keyboard, its dialog manners, its size: rows inline, columns docked.
*
* An open answering the person's input (a command or prompt they entered, a
* press) is placed at any width; one the plugin makes on its own waits
@@ -4909,6 +5929,9 @@ declare module 'claude-code' {
/**
* The pane's tab while more than one pane is open (with one, no title is
* drawn), and the `title` its hook sees; the id when omitted.
+ *
+ * An unpaired surrogate half (a `.slice()` through an emoji) is drawn as
+ * U+FFFD; a control character is refused.
*/
title?: string;
/**
@@ -4924,6 +5947,11 @@ declare module 'claude-code' {
* While the pane holds the keyboard, the key that hands it back (Escape)
* also closes it as the person's close does: `ui.close`, origin `person`.
*
+ * So does Escape at an idle, empty prompt once the prompt has the keys
+ * again (the person typed, or `focus` was refused); over text, a running
+ * turn, a dialog, a footer selection, a viewed agent's transcript or a
+ * prompt mode of its own the key stays theirs.
+ *
* A hook may refuse that close and keep it open. Left out, Escape returns
* the keys to the prompt and the pane stays. Each open sets it anew, as it
* sets the title.
@@ -4946,6 +5974,18 @@ declare module 'claude-code' {
* positive whole number; left out, a third. Each open sets it anew.
*/
rows?: number;
+ /**
+ * The body columns the pane's content wants while docked beside a
+ * fullscreen transcript: the dock opens that wide, floor to ceiling.
+ *
+ * A request, not a grant: a width the person dragged or keyed the dock
+ * to wins, this session's or a kept one, and the inline block ignores
+ * it. A positive whole number; left out, the share. Each open sets it anew.
+ *
+ * @example
+ * await $.ui.open({ id: "browser", focus: true, rows: 24, columns: 100 })
+ */
+ columns?: number;
};
/**
@@ -4971,6 +6011,7 @@ declare module 'claude-code' {
tool_input: unknown;
tool_use_id: string;
reason: string;
+ mcp_server?: McpServerProvenance;
};
/**
@@ -4997,6 +6038,7 @@ declare module 'claude-code' {
tool_name: string;
tool_input: unknown;
permission_suggestions?: PermissionUpdate[];
+ mcp_server?: McpServerProvenance;
};
type PermissionRuleValue = {
@@ -5268,6 +6310,7 @@ declare module 'claude-code' {
* Tool execution time in milliseconds. Excludes permission-prompt and hook time.
*/
duration_ms?: number;
+ mcp_server?: McpServerProvenance;
};
type PostToolUseHookInput = BaseHookInput & {
@@ -5280,6 +6323,7 @@ declare module 'claude-code' {
* Tool execution time in milliseconds. Excludes permission-prompt and hook time.
*/
duration_ms?: number;
+ mcp_server?: McpServerProvenance;
};
type PreCompactHookInput = BaseHookInput & {
@@ -5326,6 +6370,21 @@ declare module 'claude-code' {
pricing: 'configured' | 'catalog' | 'default';
};
+ /**
+ * The link a press landed on: one a `Markdown` drew, pressed where the
+ * surface reports presses (a plain click in the fullscreen terminal).
+ *
+ * What the surface knows of the cell pressed, not which occurrence: two
+ * links written with one target read the same here.
+ */
+ export type PressedLink = {
+ /**
+ * The link's target as the surface drew it: for an `https:` link, the
+ * href as the markdown wrote it.
+ */
+ href: string;
+ };
+
/**
* The decision of a `classic.PreToolUse` result: `allow`, `ask`, `deny`, or
* none.
@@ -5363,6 +6422,7 @@ declare module 'claude-code' {
tool_name: string;
tool_input: unknown;
tool_use_id: string;
+ mcp_server?: McpServerProvenance;
};
/**
@@ -5426,21 +6486,114 @@ declare module 'claude-code' {
};
/**
- * A pasted or attached non-text item of a prompt; its kind, never its bytes.
+ * The input of `prompt.attachment`: one message the engine injects into the
+ * conversation for the model on its own, as a request is about to carry it.
+ *
+ * A reminder, a mode transition, a listing, a mentioned file, a hook's
+ * context: the person never typed it and mostly never sees it. Only an
+ * attachment that carries text for the model is raised.
*/
- export type PromptAttachment = {
+ export type PromptAttachmentInput = {
/**
- * The item's kind.
+ * As the engine names the attachment's kind; the key a matcher narrows on.
+ * Pinned. Builds add and retire kinds: match by name.
+ *
+ * Among them `todo_reminder`, `plan_mode`, `plan_mode_exit`, `auto_mode`,
+ * `auto_mode_exit`, `instructions`, `nested_memory`, `skill_listing`,
+ * `deferred_tools_delta`, `edited_text_file`, `file`, `queued_command`.
*/
- type: 'image' | 'audio' | 'document';
+ type: string;
/**
- * The item's MIME type (`image/png`), when known.
+ * What the model reads for this attachment, inside the engine's framing;
+ * rewritable with `next({ ...e, text })`.
+ *
+ * The `<system-reminder>` wrapper (or the system channel that replaces it)
+ * goes around what the chain answers, never inside it. An attachment
+ * rendered as several text blocks hands them joined by newlines.
*/
- mediaType?: string;
+ text: string;
/**
- * The pasted file's name, when it had one.
+ * Who authored the text (PromptAttachmentOrigin): the engine, a settings
+ * hook, or a plugin's chain context.
+ *
+ * Pinned: a different value is refused, one left out is kept.
*/
- filename?: string;
+ origin: PromptAttachmentOrigin;
+ /**
+ * The loop whose request carries the attachment: a subagent's id, the `id`
+ * `$.agent.list()` gives it and its `tool.call`s carry; absent on main.
+ *
+ * Pinned: a different value is refused, one left out is kept. A subagent
+ * a hook spawned through `$.agent.spawn` is resolved past that hook.
+ */
+ agentId?: string;
+ };
+
+ /**
+ * Who authored the text an injected attachment carries, as the engine knows
+ * it from the attachment itself; a closed set, pinned on the event.
+ *
+ * A hooks module reads `e.origin.kind` to tell the engine's own prose from a
+ * settings hook's output or another plugin's context. `next(e)` passes it on
+ * as received; one left out is put back; no hook sets one.
+ */
+ export type PromptAttachmentOrigin = {
+ /**
+ * The engine's own prose or framing: a reminder, a mode transition, a
+ * listing, a notice, an announced context block.
+ *
+ * A file the person mentioned, as the engine presents it, and a prompt
+ * or notification delivered into a running turn are the engine's too.
+ */
+ kind: 'engine';
+ } | {
+ /**
+ * A settings hook's output the engine injects for the model: its
+ * additional context, a blocking error's note, a stopped continuation.
+ */
+ kind: 'hook';
+ /**
+ * The settings hook event that produced it (`SessionStart`,
+ * `UserPromptSubmit`, `PostToolUse`, ...).
+ */
+ event: string;
+ } | {
+ /**
+ * Text a plugin's hook attached through a chain's `context`
+ * (`prompt.submit`, `tool.call`), as the model reads it.
+ */
+ kind: 'plugin';
+ /**
+ * The chain's event that attached it.
+ */
+ event: string;
+ };
+
+ /**
+ * What a `prompt.attachment` hook returns: the text the model reads for that
+ * attachment, or null to leave the attachment out of the request.
+ */
+ export type PromptAttachmentResult = {
+ text: string | null;
+ };
+
+ /**
+ * The person's prompt box as it stands: the draft and where the cursor is in
+ * it; what `$.prompt.read()` resolves and `$.prompt.fill` hands back.
+ *
+ * No selection: the terminal's box has none of its own, and a surface that
+ * binds one adds it here.
+ */
+ export type PromptBox = {
+ /**
+ * The draft as typed so far; `''` where the session draws no box.
+ */
+ text: string;
+ /**
+ * Where the next typed character lands: an offset into `text` in UTF-16
+ * code units, 0 at the start, `text.length` at the end.
+ */
+ cursor: number;
};
/**
@@ -5475,33 +6628,168 @@ declare module 'claude-code' {
};
/**
- * The input of `prompt.context`: the context blocks the engine prepends to
- * a conversation's first user message, at the moment it computes them.
+ * The input of `prompt.context`: the context blocks the engine prepends to a
+ * conversation's first user message, and the files behind `claudeMd`.
*/
- export type PromptContextInput = PromptContextBlocks;
+ export type PromptContextInput = {
+ /**
+ * From core: `claudeMd` (when instruction files are loaded), `userEmail`,
+ * `attachedProject`, `currentDate`, each only when present.
+ */
+ blocks: readonly PromptContextBlock[];
+ /**
+ * The files behind `claudeMd`, in the order it renders them, `@` imports
+ * included; empty when it renders none.
+ *
+ * Undefined when a hook above rewrote the `claudeMd` text: the files
+ * behind that text are then unknown, and a hook adds none of its own.
+ */
+ instructionFiles?: readonly InstructionFile[];
+ };
/**
* What a `prompt.context` hook returns: the blocks the conversation
* carries, in order; one left out is not sent.
*/
- export type PromptContextResult = PromptContextBlocks;
+ export type PromptContextResult = {
+ /**
+ * What the conversation carries, in order.
+ */
+ blocks: readonly PromptContextBlock[];
+ /**
+ * The files now behind `claudeMd`; left out, the ones from below stand.
+ *
+ * Kept in step with the `claudeMd` text at every link: a changed list
+ * renders the text the next reader gets, a rewritten text makes the files
+ * unknown from there on. Every kind is the hook's to add, drop or rewrite.
+ */
+ instructionFiles?: readonly InstructionFile[];
+ };
/**
- * `prompt.fill`'s input as a plugin's `$.prompt.fill(args)` takes it:
- * `origin` is the engine's to set (the calling plugin's name).
+ * The input of `prompt.edit` (prompt-edit/): one edit the person makes in the
+ * prompt box, as the draft before it and the splice the editor made of it.
*/
- export type PromptFillArgs = Omit<PromptFillInput, 'origin'>;
+ export type PromptEditInput = {
+ /**
+ * Who edits (PromptEditOrigin): the person at the composer. Pinned:
+ * `next(e)` passes it on as received.
+ */
+ origin: PromptEditOrigin;
+ /**
+ * The one key that made the edit, in `Client` `onKey`'s shape, when one
+ * did; absent for a paste and for a burst of keys folded into one edit.
+ *
+ * Pinned: which key the person pressed is a fact, not the hook's to change.
+ */
+ key?: ClientKeyEvent;
+ /**
+ * The draft before the edit. `next({ ...e, text })` applies the edit to
+ * another draft instead.
+ */
+ text: string;
+ /**
+ * Where the person's caret stood in `text` before the edit, 0 to
+ * `text.length`.
+ */
+ cursor: number;
+ /**
+ * Where in `text` the edit begins: the start of the span it replaces, or
+ * where what was typed goes in; a bare cursor move begins where it lands.
+ */
+ start: number;
+ /**
+ * Where the replaced span of `text` ends: `start` for an insertion or a
+ * move, past it for a deletion (Backspace, a kill).
+ */
+ end: number;
+ /**
+ * What goes in between `start` and `end`: the typed or pasted text, `''` for
+ * a deletion or a move.
+ *
+ * `next({ ...e, inputText })` puts in another; the cursor lands after it.
+ */
+ inputText: string;
+ };
/**
- * The input of `prompt.fill` (prompt-fill/): a text about to be written into
- * the prompt box as the person's draft, replacing what the box holds.
+ * Who edits the prompt box at `prompt.edit`, as the engine stamps it where
+ * the edit starts; a closed set a matcher narrows on.
+ *
+ * `next(e)` passes it on as received; no hook sets one.
+ */
+ export type PromptEditOrigin = {
+ /**
+ * The person, typing or pasting into the main prompt box.
+ */
+ kind: 'composer';
+ };
+
+ /**
+ * What a `prompt.edit` hook returns and what `next(e)` resolves to: the box
+ * after the edit (PromptBox), which the editor then shows.
+ *
+ * From core, `e.text` with the splice applied and the cursor after what went
+ * in. Rewrite it (`{ ...r, text, cursor }`) to change what lands; answer
+ * `{ text: e.text, cursor: e.cursor }` without `next` to consume the key.
+ */
+ export type PromptEditResult = PromptBox;
+
+ /**
+ * `prompt.fill`'s input as a plugin's `$.prompt.fill(args)` takes it: no
+ * `origin` (the engine sets the calling plugin's), `mode` optional.
+ */
+ export type PromptFillArgs = {
+ /**
+ * What the box is to take (PromptFillInput `text`).
+ */
+ text: string;
+ /**
+ * Where it goes (PromptFillMode); `replace` when left out.
+ */
+ mode?: PromptFillMode;
+ };
+
+ /**
+ * What `$.prompt.fill` resolves to: whether the box took the text, and the
+ * box afterwards (PromptBox) as the caller's own `$.prompt.read()` reads it.
+ *
+ * The box goes to a plugin whose module calls `$.prompt.read`, through the
+ * hooks on it; one that never does, or is refused there, gets the empty box.
+ */
+ export type PromptFilled = {
+ /**
+ * True once the box holds the text; false where no box could take it or a
+ * hook kept it out (PromptFillResult).
+ */
+ isFilled: boolean;
+ /**
+ * The draft after the fill; unchanged when `isFilled` is false; `''` where
+ * no box is drawn or the caller may not read it (see above).
+ */
+ text: string;
+ /**
+ * Where the person types next: an offset into `text`, past the fill's text
+ * for `insert`, at the end for `replace` and `append`.
+ */
+ cursor: number;
+ };
+
+ /**
+ * The input of `prompt.fill` (prompt-fill/): a text about to be put in the
+ * prompt box as the person's draft, over it, after it, or at the cursor.
*/
export type PromptFillInput = {
/**
- * What the box is to hold, cursor at its end; the person edits it or
- * presses Enter. `next({ ...e, text })` writes another.
+ * What the box takes; the person edits it or presses Enter.
+ * `next({ ...e, text })` writes another.
*/
text: string;
+ /**
+ * Where the text goes (PromptFillMode): over the draft, after it, or in at
+ * the cursor. `next({ ...e, mode })` moves it; left out of a rewrite, kept.
+ */
+ mode: PromptFillMode;
/**
* Who writes (PromptFillOrigin), set by the engine where the write
* starts. Pinned: `next(e)` passes it on as received.
@@ -5509,6 +6797,17 @@ declare module 'claude-code' {
origin: PromptFillOrigin;
};
+ /**
+ * Where a `prompt.fill` puts its text: over the whole draft, after it, or
+ * into it at the cursor.
+ *
+ * `replace` empties the box first and leaves the cursor at the text's end;
+ * `append` keeps the draft and adds the text after it, cursor at the end;
+ * `insert` splices the text in at the cursor and moves the cursor past it,
+ * so what the person had typed stays on either side.
+ */
+ export type PromptFillMode = 'replace' | 'append' | 'insert';
+
/**
* Who writes the prompt box at `prompt.fill`, as the engine stamps it where
* the write starts; a closed set a matcher narrows on.
@@ -5695,6 +6994,25 @@ declare module 'claude-code' {
*/
export type PromptSubmitArgs = Omit<PromptSubmitInput, 'origin' | 'turnId' | 'wait' | 'context'>;
+ /**
+ * A pasted or attached non-text item of a submitted prompt; its kind, never
+ * its bytes.
+ */
+ export type PromptSubmitAttachment = {
+ /**
+ * The item's kind.
+ */
+ type: 'image' | 'audio' | 'document';
+ /**
+ * The item's MIME type (`image/png`), when known.
+ */
+ mediaType?: string;
+ /**
+ * The pasted file's name, when it had one.
+ */
+ filename?: string;
+ };
+
/**
* The input of `prompt.submit`: the prompt as typed, after the input became
* a user message and before it enters the session.
@@ -5707,14 +7025,14 @@ declare module 'claude-code' {
/**
* Present only when the submission carried images or other non-text items.
*/
- attachments?: readonly PromptAttachment[];
+ attachments?: readonly PromptSubmitAttachment[];
/**
* What the model reads beside the prompt and the user never sees, each
* entry one block after the prompt as typed; absent as the engine raises it.
*
* A hook attaches on the way down: `next({ ...e, context: [...(e.context
- * ?? []), mine] })`. It may not leave out an entry it received; the whole
- * is capped at 32000 characters, no entry empty.
+ * ?? []), mine] })`, keeping which it likes; none empty, any length: past
+ * 100,000 characters (200,000 together) the model reads a head and path.
*/
context?: readonly string[];
/**
@@ -5850,6 +7168,39 @@ declare module 'claude-code' {
isShown: boolean;
};
+ /**
+ * A `$.ui.blit` argument repainting one of the caller's mounted Rasters.
+ *
+ * `columns` and `rows`, when given, must be the mounted size (a resize is a
+ * redraw, `$.ui.invalidate("ui.render")`, not a blit).
+ */
+ export type RasterBlitArgs = {
+ /**
+ * The site the Raster is drawn in, by the `requestId` this plugin draws
+ * it under: one of its panes' ids, a tool row's `tool_use_id`, the band's.
+ */
+ requestId: string;
+ /**
+ * The Raster's `key` in that drawing.
+ */
+ key: string;
+ /**
+ * The new cells, encoded as the element's `cells` are (RasterProps), for
+ * the mounted `columns * rows`.
+ */
+ cells: string;
+ /**
+ * The width the cells are laid out for; refused unless it is the mounted
+ * Raster's. Absent, the mounted width.
+ */
+ columns?: number;
+ /**
+ * The height the cells are laid out for; refused unless it is the mounted
+ * Raster's. Absent, the mounted height.
+ */
+ rows?: number;
+ };
+
/**
* The props of `Raster`, the terminal surface's cell-grid leaf: a fixed box
* of cells, each a glyph, a foreground and a background, packed in `cells`.
@@ -5912,6 +7263,9 @@ declare module 'claude-code' {
/**
* Sets the handler run when the hook throws or overruns its budget; its
* answer within the grace stands as the hook's result for the dispatch.
+ *
+ * The budget is HookBudget's `ms` and the grace its `catchMs`, both on
+ * the clock that stops while the code waits on `next` or `$`.
*/
readonly catch: (handler: CatchHandler<F>) => void;
};
@@ -5934,7 +7288,7 @@ declare module 'claude-code' {
* authorises an action; a plugin adds context with `$.ui.notice`. `Pane` is
* the one component whose instances a plugin opens (`$.ui.open`).
*/
- export type RenderComponent = 'AskUserQuestion' | 'UserMessage' | 'AssistantMessage' | 'ToolUse' | 'ToolResult' | 'ToolGroup' | 'CommandOutput' | 'Spinner' | 'TurnDuration' | 'InfoNotice' | 'SessionMode' | 'PromptHint' | 'AbovePrompt' | 'Pane';
+ export type RenderComponent = 'AskUserQuestion' | 'UserMessage' | 'AssistantMessage' | 'ToolUse' | 'ToolResult' | 'ToolGroup' | 'ToolProgress' | 'CommandOutput' | 'Spinner' | 'TurnDuration' | 'InfoNotice' | 'SessionMode' | 'PromptHint' | 'AbovePrompt' | 'Pane';
/**
* What a render hook returns, and what `next(e)` resolves to: a plain-data
@@ -5966,11 +7320,11 @@ declare module 'claude-code' {
label: string;
/**
* One digit (`"1"`) or one lowercase letter (`"w"`) that presses it
- * where the site honours one; anything else is refused.
+ * while the plugin's site holds the focus; anything else is refused.
*
- * A bare digit in an empty composer presses, as a survey is answered;
- * while one of the band's Buttons has the focus a digit or a letter
- * presses on keydown, lowercased. Two on one hotkey: the later wins.
+ * The band after ctrl+x tab or a click, a focused `Pane`: on keydown,
+ * lowercased; never from the composer, save a bare digit in an empty
+ * one pressing a band Button. Two on one hotkey: the later wins.
*/
hotkey?: string;
/**
@@ -6136,6 +7490,36 @@ declare module 'claude-code' {
type: 'Code';
props: CodeProps;
children?: undefined;
+ } | {
+ /**
+ * A block of markdown every surface draws as it draws an assistant
+ * reply's text: its own renderer, theme, hyperlinks and highlighting.
+ *
+ * Built by `<Markdown>` or the table's `t.Markdown`. A leaf: `text` is
+ * bounded as a Text's string is, or the tree is refused. Without a
+ * `press` its links are the surface's own, opened as it opens links.
+ */
+ type: 'Markdown';
+ props: MarkdownLeafProps;
+ children?: undefined;
+ } | {
+ /**
+ * A `Markdown` whose plugin answers the links it drew (`onLinkPress`):
+ * a press on one raises `ui.press` with `e.link`, the surface opens none.
+ */
+ type: 'Markdown';
+ props: MarkdownLeafProps;
+ /**
+ * Where the `onLinkPress` handler lives: the plugin whose hook drew
+ * the element, and the handle its environment keeps the closure under.
+ *
+ * The runtime stamps the plugin as the tree leaves that hook.
+ */
+ press: {
+ plugin: string;
+ handle: number;
+ };
+ children?: undefined;
} | {
/**
* A region one of the plugin's SURFACE MODULES, named by path, draws and
@@ -6186,6 +7570,25 @@ declare module 'claude-code' {
plugin: string;
};
children?: undefined;
+ } | {
+ /**
+ * A picture, the terminal surface's alone: `props.source` drawn over a
+ * box of cells where the terminal can, `props.alt` where it cannot.
+ *
+ * A leaf: hooks above wrap or replace it whole; a press other plugins
+ * should see goes on an enclosing Button; keyed, its plugin's
+ * `$.ui.blit` swaps it. On a surface without it the tree is refused.
+ */
+ type: 'Image';
+ props: ImageProps;
+ /**
+ * Whose Image: the plugin whose hook drew the element, stamped by the
+ * runtime as the tree leaves it; the one plugin whose blit reaches it.
+ */
+ image: {
+ plugin: string;
+ };
+ children?: undefined;
} | {
/**
* The component core draws itself, with the props held under `ref`.
@@ -6234,12 +7637,12 @@ declare module 'claude-code' {
*/
requestId: string;
/**
- * The size of what the surface draws into, in character cells; absent where
- * no surface has measured. Part of the envelope: a rewrite keeps it.
+ * The size of what the surface draws into, in character cells, and whether
+ * its layout docks a pane; absent where no surface has measured.
*
- * On the terminal, the interactive screen's size, where a change of width
- * re-draws every hooked site once the resize settles (a hook that sized its
- * tree to `columns` runs again); on a remote surface, what it reported.
+ * Part of the envelope: a rewrite keeps it. On the terminal, the interactive
+ * screen's, where a change of width re-draws every hooked site once the
+ * resize settles; on a remote surface, what it reported.
*/
viewport?: RenderViewport;
/**
@@ -6258,12 +7661,14 @@ declare module 'claude-code' {
* them under `e.props`; a hook rewrites them with `next({ ...e, props })`.
*
* A rewrite is validated by the component and an invalid one draws the
- * original. This table is the plugin-facing render contract: the terminal
- * and the Code session renderer draw these components from these props.
+ * original. This table is the plugin-facing render contract; the author's
+ * file notes which surfaces raise each member (RENDER_SURFACES_OF).
*/
export type RenderPropsOf = {
/**
* The dialog the AskUserQuestion tool opens.
+ *
+ * Raised on every surface.
*/
AskUserQuestion: {
/**
@@ -6282,26 +7687,66 @@ declare module 'claude-code' {
metadataSource?: string;
};
/**
- * The user's own prompt in the transcript (the `> ...` row); a rewrite is
- * drawn there and nowhere else (the stored message is untouched).
+ * A user-role transcript row: the person's prompt (`> ...`), a background
+ * task's notification, or a message another agent, teammate or session sent.
+ *
+ * `origin`, `task` and `from` tell them apart and are read-only; a rewrite
+ * of `text` draws in the row alone: the stored message, and the model's
+ * framing of another party's words as that party's, stay as they were.
+ *
+ * Raised on every surface.
*/
UserMessage: {
/**
- * The prompt's text, as the row draws it.
+ * What the row shows: the prompt as typed, a notification's summary, or
+ * a message's body less the engine's framing (summary line included).
+ *
+ * A rewrite is printable, bounded text and draws where the engine draws
+ * the body; a teammate block of several frames or with a summary line
+ * keeps the engine's drawing, one string not being those parts.
*/
text: string;
/**
- * Where the stored message came from, as `prompt.submit` named it
- * (PromptOrigin): the composer's, a peer's, a notification's, a plugin's.
+ * Where the stored message came from, as `prompt.submit` named it: the
+ * composer's, a task notification's, a peer's, a channel's, a plugin's.
*
- * Read-only: a rewrite carries it on as received; one that changes or
- * drops it is refused and the engine draws its own row.
+ * `unclassified` for a teammate's (its drain stamps none) and for a
+ * message stored before stamps. Read-only.
*/
origin: PromptOrigin;
+ /**
+ * Whether the view draws the row in full: the ctrl+o transcript,
+ * `--verbose`, a surface with no ctrl+o (an export). Read-only.
+ *
+ * False, a message row is one dim line naming its sender; a hook that
+ * draws a compact row of its own passes when true, so ctrl+o shows all.
+ */
+ isExpanded: boolean;
+ /**
+ * What a notification row (`origin.kind` `task-notification`) reports
+ * on: its background task; absent on every other row. Read-only.
+ */
+ task?: UserMessageTask;
+ /**
+ * Who sent the message the row carries: another agent of this session, a
+ * teammate, another session, a channel; absent otherwise. Read-only.
+ */
+ from?: UserMessageFrom;
+ /**
+ * Which of its rows the transcript's viewport shows now: `null` while
+ * drawn outside it, absent where the surface does not say. Read-only.
+ *
+ * Reported once drawn and again when it changes: on a scroll, for the
+ * messages at the viewport's edges only. A rewrite carries it on as
+ * received; one that changes or drops it is refused.
+ */
+ onScreen?: OnScreen | null;
};
/**
* One text block of an assistant reply in the transcript; a rewrite
* changes the drawing and leaves the stored message alone (ctrl+o).
+ *
+ * Raised on every surface.
*/
AssistantMessage: {
/**
@@ -6312,10 +7757,21 @@ declare module 'claude-code' {
* True on the block that draws the bullet opening a reply.
*/
isFirstOfReply: boolean;
+ /**
+ * Which of its rows the transcript's viewport shows now: `null` while
+ * drawn outside it, absent where the surface does not say. Read-only.
+ *
+ * Reported once drawn and again when it changes: on a scroll, for the
+ * messages at the viewport's edges only. A rewrite carries it on as
+ * received; one that changes or drops it is refused.
+ */
+ onScreen?: OnScreen | null;
};
/**
* A tool call's row in the transcript (`Bash(ls -la)` and its result); the
* call was decided by `tool.call`, so a rewrite here changes the row alone.
+ *
+ * Raised on every surface.
*/
ToolUse: {
/**
@@ -6356,6 +7812,15 @@ declare module 'claude-code' {
* group's rows draw it inline; a standalone row's is its own `ToolResult`.
*/
output?: unknown;
+ /**
+ * Which of its rows the transcript's viewport shows now: `null` while
+ * drawn outside it, absent where the surface does not say. Read-only.
+ *
+ * Reported once drawn and again when it changes: on a scroll, for the
+ * messages at the viewport's edges only. A rewrite carries it on as
+ * received; one that changes or drops it is refused.
+ */
+ onScreen?: OnScreen | null;
};
/**
* The result block drawn under a standalone tool row in the transcript,
@@ -6364,6 +7829,8 @@ declare module 'claude-code' {
* A rewrite of `output` is checked against the tool's output schema (one
* that does not fit draws nothing; one the renderer cannot read hits the
* row's error boundary). The stored result is untouched.
+ *
+ * Raised on every surface.
*/
ToolResult: {
/**
@@ -6389,6 +7856,15 @@ declare module 'claude-code' {
* `output`. Read-only.
*/
isErrored: boolean;
+ /**
+ * Which of its rows the transcript's viewport shows now: `null` while
+ * drawn outside it, absent where the surface does not say. Read-only.
+ *
+ * Reported once drawn and again when it changes: on a scroll, for the
+ * messages at the viewport's edges only. A rewrite carries it on as
+ * received; one that changes or drops it is refused.
+ */
+ onScreen?: OnScreen | null;
};
/**
* A run of tool calls the transcript folds into one count line (`Read 3
@@ -6396,6 +7872,8 @@ declare module 'claude-code' {
*
* A hook that sets `isExpanded` unfolds the group where it is, and each row
* it unfolds into is a `ToolUse` drawing a `ToolUse` hook then sees.
+ *
+ * Raised on every surface.
*/
ToolGroup: {
/**
@@ -6414,6 +7892,15 @@ declare module 'claude-code' {
* The one prop of the three a rewrite changes on the screen.
*/
isExpanded: boolean;
+ /**
+ * Which of its rows the transcript's viewport shows now: `null` while
+ * drawn outside it, absent where the surface does not say. Read-only.
+ *
+ * Reported once drawn and again when it changes: on a scroll, for the
+ * messages at the viewport's edges only. A rewrite carries it on as
+ * received; one that changes or drops it is refused.
+ */
+ onScreen?: OnScreen | null;
};
/**
* The output row a slash command printed in the transcript, under its echo
@@ -6422,6 +7909,8 @@ declare module 'claude-code' {
* What the run resolved as text, a `local` command's or a plugin's alike. A
* rewrite of `text` draws there and the stored row keeps what the model
* reads; a hook's own tree draws in the row's place, the transcript's width.
+ *
+ * Raised on every surface.
*/
CommandOutput: {
/**
@@ -6447,10 +7936,56 @@ declare module 'claude-code' {
* which draws in the error colour and not dim. Read-only.
*/
isErrored: boolean;
+ /**
+ * Which of its rows the transcript's viewport shows now: `null` while
+ * drawn outside it, absent where the surface does not say. Read-only.
+ *
+ * Reported once drawn and again when it changes: on a scroll, for the
+ * messages at the viewport's edges only. A rewrite carries it on as
+ * received; one that changes or drops it is refused.
+ */
+ onScreen?: OnScreen | null;
+ };
+ /**
+ * One row of the live tool-progress region under a running tool call; today
+ * the run-in-background pill. One instance per row.
+ *
+ * A union on `kind`: other progress kinds join as their props become plain
+ * data, each with its own fields, so a hook matches `{ props: { kind:
+ * "background_hint" } }` or branches on `e.props.kind` and stays right.
+ *
+ * Raised on the terminal surface only.
+ */
+ ToolProgress: {
+ /**
+ * The tool call the row belongs to, as `tool.call` and the `ToolUse` row
+ * carry it. Read-only: a rewrite carries it on as received.
+ *
+ * While several foreground calls share one pill, the first of them.
+ */
+ tool_use_id: string;
+ /**
+ * Which progress row: the run-in-background pill. Read-only.
+ */
+ kind: 'background_hint';
+ /**
+ * The pill's text as the engine draws it, dim, under the tool call:
+ * `(ctrl+b to run in background)`, or with the person's own binding.
+ *
+ * A rewrite is drawn in its place, dim; `""` draws nothing. A hook that
+ * returns a tree draws that instead.
+ */
+ hint: string;
};
/**
* The line that animates while a turn runs (`Sauteing... (12s, 300
- * tokens)`). Terminal only: the Code session renderer draws its own.
+ * tokens)`); a remote surface draws its own.
+ *
+ * The row reads `word` (or `message` while one overrides it), then
+ * `suffix`, then the dim parenthetical the engine keeps (elapsed time,
+ * tokens, effort); a hook rewrites the first three or draws its own tree.
+ *
+ * Raised on the terminal surface only.
*/
Spinner: {
/**
@@ -6461,14 +7996,25 @@ declare module 'claude-code' {
* The text drawn instead of the word while a state overrides it, else null.
*/
message: string | null;
+ /**
+ * What the engine draws right after the word or message to say the turn is
+ * still going: one ellipsis character.
+ *
+ * Left off a text that already ends in an ellipsis, so a rewritten
+ * `message` ending in one shows one. A rewrite is drawn as given (`""`
+ * draws the text bare, `" ~"` draws `Sauteing ~`); left out, the engine's.
+ */
+ suffix: string;
/**
* What the turn is doing.
*/
mode: 'requesting' | 'responding' | 'thinking' | 'tool-input' | 'tool-use';
};
/**
- * The line that closes a turn in the transcript (`Baked for 3s`).
- * Terminal only: the Code session renderer draws its own footer.
+ * The line that closes a turn in the transcript (`Baked for 3s`); a
+ * remote surface draws its own footer.
+ *
+ * Raised on the terminal surface only.
*/
TurnDuration: {
/**
@@ -6480,10 +8026,21 @@ declare module 'claude-code' {
* `1m 4s`).
*/
durationMs: number;
+ /**
+ * Which of its rows the transcript's viewport shows now: `null` while
+ * drawn outside it, absent where the surface does not say. Read-only.
+ *
+ * Reported once drawn and again when it changes: on a scroll, for the
+ * messages at the viewport's edges only. A rewrite carries it on as
+ * received; one that changes or drops it is refused.
+ */
+ onScreen?: OnScreen | null;
};
/**
* One dim status line under the logo (the model source, an experiment
- * enrollment, a settings hint), with a trailing `/command`. Terminal only.
+ * enrollment, a settings hint), with a trailing `/command`.
+ *
+ * Raised on the terminal surface only.
*/
InfoNotice: {
/**
@@ -6495,13 +8052,24 @@ declare module 'claude-code' {
* none.
*/
command: string | null;
+ /**
+ * Which of its rows the transcript's viewport shows now: `null` while
+ * drawn outside it, absent where the surface does not say. Read-only.
+ *
+ * Reported once drawn and again when it changes: on a scroll, for the
+ * messages at the viewport's edges only. A rewrite carries it on as
+ * received; one that changes or drops it is refused.
+ */
+ onScreen?: OnScreen | null;
};
/**
* The dim mode labels at the right of the prompt footer (`focus`, `memory
- * paused`), joined by ` & `. One instance; terminal only.
+ * paused`), joined by ` & `. One instance.
*
* A hook adds a mode by rewriting `modes`, removes one by filtering, or
* draws its own tree.
+ *
+ * Raised on the terminal and desktop surfaces only.
*/
SessionMode: {
/**
@@ -6511,10 +8079,12 @@ declare module 'claude-code' {
};
/**
* The dim hint line under the prompt (`? for shortcuts`, `esc to
- * interrupt`, the pills beside them). One instance; terminal only.
+ * interrupt`, the pills beside them). One instance.
*
* A hook rewrites `hint` and the rewrite is drawn in the line's place, or
* draws its own tree; `isDraft` and `isWorking` say what the line is for.
+ *
+ * Raised on the terminal surface only.
*/
PromptHint: {
/**
@@ -6538,9 +8108,11 @@ declare module 'claude-code' {
* The band directly above the prompt input, where the surveys draw; the
* engine draws nothing of its own here.
*
- * A hook draws a tree, or passes; one instance, terminal only. The person
- * collapses it (ctrl+x ctrl+a, `[-]`) or focuses it (a click, ctrl+x tab):
- * an Input types, a Button arms the hotkeys, a tree taller than it scrolls.
+ * A hook draws a tree, or passes; one instance. The person collapses it
+ * (ctrl+x ctrl+a, `[-]`) or focuses it (a click, ctrl+x tab): an Input
+ * types, a Button arms the hotkeys, a tree taller than it scrolls.
+ *
+ * Raised on the terminal surface only.
*/
AbovePrompt: {
/**
@@ -6555,9 +8127,9 @@ declare module 'claude-code' {
* Rows the band may take: in fullscreen, what the bottom slot has left
* above the prompt; otherwise the terminal's height. Read-only.
*
+ * That slot is capped at half the terminal's rows, the prompt's included.
* A tree of at most `maxRows` rows shows whole; a taller one scrolls in a
- * window of `scroll.bodyRows` (one fewer, over a dim `n more` row), and a
- * bare digit arms none of its Buttons' hotkeys.
+ * window of `scroll.bodyRows`, and a bare digit arms no Button's hotkey.
*/
maxRows: number;
/**
@@ -6592,6 +8164,8 @@ declare module 'claude-code' {
* Placed by the surface (docked in fullscreen, else above the prompt) and
* keyed by the person (ctrl+x tab, Esc), who closes it from the engine's mark
* or ctrl+x x: `ui.close` with origin `person`, which a hook may refuse.
+ *
+ * Raised on every surface.
*/
Pane: {
/**
@@ -6603,7 +8177,8 @@ declare module 'claude-code' {
*/
title: string;
/**
- * True while the person has given the pane the keyboard. Read-only.
+ * True while the person has given the pane the keyboard: Tab walks its
+ * elements, a Button's `hotkey` presses it, the arrows scroll. Read-only.
*/
isFocused: boolean;
/**
@@ -6819,7 +8394,8 @@ declare module 'claude-code' {
*/
clientId: string;
/**
- * The size the client draws into, in character cells, when it said.
+ * The size the client draws into, in character cells, and whether its
+ * layout docks a pane, when it said.
*/
viewport?: RenderViewport;
};
@@ -7129,6 +8705,91 @@ declare module 'claude-code' {
reason: ExitReason;
};
+ /**
+ * The input of `session.end`: the session is ending, why, and how to come back
+ * to it.
+ *
+ * Every field is the engine's: a hook observes, and `next(e)` passes them on.
+ */
+ export type SessionEndInput = {
+ /**
+ * Why it ends (SessionEndReason), the word the classic SessionEnd hook
+ * receives as its `reason`.
+ */
+ reason: SessionEndReason;
+ /**
+ * The ending session's id (`$.session.id()` until now); after a `/clear`
+ * or a resume the process goes on under another.
+ */
+ sessionId: string;
+ /**
+ * What `claude --resume` takes to return to it.
+ */
+ resume: SessionResume;
+ };
+
+ /**
+ * Why the session ended: the classic SessionEnd hook's own `reason`, word for
+ * word.
+ *
+ * `prompt_input_exit`, the person left (/exit, ctrl+c, ctrl+d); `clear`, a
+ * /clear started a fresh one; `resume`, another took its place; `logout`;
+ * `other`, a `-p` run finished or the process got SIGINT, SIGTERM or SIGHUP.
+ */
+ export type SessionEndReason = ClassicHookInputs['SessionEnd']['reason'];
+
+ /**
+ * What a `session.end` hook returns and what `next(e)` resolves to:
+ * `{ sessionId }`, echoed by core; a hook's own value changes nothing.
+ */
+ export type SessionEndResult = {
+ sessionId: string;
+ };
+
+ /**
+ * The input of `session.measure`: what `$.session.usage()` answers at this
+ * moment, and which of its units moved since the last measurement a hook saw.
+ *
+ * The same figures the op reads, without `context.breakdown`: call
+ * `$.session.usage({ breakdown })` from the hook when the categories matter.
+ * Every field is the engine's: a hook observes, and `next(e)` passes them on.
+ */
+ export type SessionMeasureInput = {
+ /**
+ * The live context window (`$.session.usage()`'s `context`): the window,
+ * and its fill once a response of the live window reported one.
+ *
+ * Never carries `breakdown` here.
+ */
+ context: SessionContextUsage;
+ /**
+ * The rate-limit windows the last response reported, each with its
+ * `percentUsed`; empty off a subscription or before the first reading.
+ */
+ rateLimits: SessionRateLimit[];
+ /**
+ * What the session has cost so far; absent where the host keeps no ledger.
+ */
+ cost?: SessionCost;
+ /**
+ * Which units differ from the last measurement raised (UsageUnit), never
+ * empty; the first measurement names every unit it has a figure for.
+ *
+ * `context`: the fill moved; `rateLimits`: a window moved a whole point,
+ * appeared or left, or the account's limit status changed; `cost`: the
+ * total grew.
+ */
+ changed: UsageUnit[];
+ };
+
+ /**
+ * What a `session.measure` hook returns and what `next(e)` resolves to:
+ * `{ changed }`, echoed by core; a hook's own value changes nothing.
+ */
+ export type SessionMeasureResult = {
+ changed: UsageUnit[];
+ };
+
/**
* One message of the transcript as `$.session.messages()` returns it.
*/
@@ -7170,8 +8831,8 @@ declare module 'claude-code' {
*/
kind: string;
/**
- * How much of the window is used, 0 to 100 (above 100 once a spend limit
- * is exceeded).
+ * How much of the window is used, 0 to 100 with at most one decimal:
+ * 23.5, or 7, never 7.000000000000001; past 100 on an exceeded spend limit.
*/
percentUsed: number;
/**
@@ -7308,6 +8969,19 @@ declare module 'claude-code' {
name: string | null;
};
+ /**
+ * How to come back to the session that ended: what `claude --resume` takes.
+ */
+ export type SessionResume = {
+ /**
+ * What `claude --resume <id>` takes, the ending session's own.
+ *
+ * It resumes a session that wrote a transcript: one that never ran a
+ * prompt, or ran with persistence off, left nothing under this id.
+ */
+ id: string;
+ };
+
type SessionStartHookInput = BaseHookInput & {
hook_event_name: 'SessionStart';
source: 'startup' | 'resume' | 'clear' | 'compact' | 'fork';
@@ -7565,6 +9239,7 @@ declare module 'claude-code' {
readonly event: EventName;
readonly origin: Origin;
readonly trace: readonly TraceEntry<EventName, unknown, unknown>[];
+ readonly budget: NextBudget;
};
type StopFailureHookInput = BaseHookInput & {
@@ -7637,12 +9312,14 @@ declare module 'claude-code' {
* own chunks and returns its own result, and nothing beneath runs.
*
* @template S what `next.is(pattern, e)` narrows `e` to, as Next's
+ * @see HookBudget `ms`: the hook's budget counts its own code, never a wait
+ * at a `yield` or on this stream, however long the response beneath takes
*/
export type StreamNext<N extends StreamingEventName = StreamingEventName, E = Args<N>, O = NextResult<N>, S extends {
[K in N]?: unknown;
} = {
[K in N]: Args<K>;
- }> = Pick<Next<N, E, O, S>, 'signal' | 'is' | 'event' | 'origin'> & {
+ }> = Pick<Next<N, E, O, S>, 'signal' | 'is' | 'event' | 'origin' | 'budget'> & {
(e: E): HookStream<Chunk<N>, O>;
/**
* Continues this dispatch at a tier, as Next's `to`: the stream beneath
@@ -7667,7 +9344,7 @@ declare module 'claude-code' {
type StyledElement<Tag extends 'Box' | 'Text', Hover> = {
type: Tag;
/**
- * A Box's layout, margin, padding and border props and the `key` that
+ * A Box's layout, position, spacing and border props and the `key` that
* makes it a hover scope; a Text's colors and styles. Others are refused.
*/
props?: Record<string, string | number | boolean>;
@@ -7675,9 +9352,9 @@ declare module 'claude-code' {
* Style overrides the surface applies while the pointer is over the
* nearest keyed Box, or over any member of the group `scope` names.
*
- * Plain data, no hook. Never a layout change: `borderStyle` restyles a
- * border the Box has, `display` only reveals a Box drawn `"none"` inside
- * a keyed Box, and never in a scope.
+ * Plain data, no hook. Nothing that moves a sibling: `borderStyle`
+ * restyles a border the Box has, `display` only reveals a Box drawn
+ * `"none"` (under a keyed Box or in a scope), an offset moves a placed Box.
*/
hover?: Hover;
/**
@@ -7981,9 +9658,9 @@ declare module 'claude-code' {
* What the model reads after the tool's result and the user never
* sees. From core, none.
*
- * One newline-joined reminder, as a PostToolUse hook's additional
- * context is, after the managed tier's review of it; none on a plugin's
- * own `$.tool.call`. Kept whole from `next`; capped at 32000 characters.
+ * One reminder, as a PostToolUse hook's is, after the managed tier's
+ * review; none on a plugin's own `$.tool.call`. Kept whole from `next`,
+ * none empty, any length: past 100,000 (200,000 together) head + path.
*/
context?: readonly string[];
/**
@@ -8095,6 +9772,14 @@ declare module 'claude-code' {
rule?: string;
};
+ /**
+ * Where a `tool.describe` answer places the tool: `true` behind ToolSearch
+ * (its schema loads when the model asks for it), `false` in the prompt's list.
+ *
+ * Left out of an answer, the placement beneath stands.
+ */
+ export type ToolDeferral = boolean;
+
/**
* The input of `tool.describe`: one tool's description, at the moment the
* engine first renders the tool's schema for the model.
@@ -8109,6 +9794,14 @@ declare module 'claude-code' {
* The tool's description as it computed it.
*/
description: string;
+ /**
+ * Present, and true, when the engine lists the tool behind ToolSearch (its
+ * schema loads when the model asks for it by name); absent for one listed.
+ *
+ * By the engine's rule an MCP server's tool, or one that asks to be,
+ * unless a rule keeps it in front.
+ */
+ isDeferred?: true;
/**
* Who provides this tool: the plugin and its tier; `{ plugin: "engine",
* tier: "core" }` for a built-in. Pinned: a rewrite is refused.
@@ -8121,10 +9814,15 @@ declare module 'claude-code' {
/**
* What a `tool.describe` hook returns: the description the model sees for that
- * tool.
+ * tool and, when the hook moves it, where the tool waits (ToolDeferral).
+ *
+ * `{ description }` alone, or `{ ...(await next(e)), description }`, changes
+ * the text and keeps the engine's placement; `isDeferred: true` puts the tool
+ * behind ToolSearch, `isDeferred: false` puts its schema in the prompt's list.
*/
export type ToolDescribeResult = {
description: string;
+ isDeferred?: ToolDeferral;
};
/**
@@ -8268,7 +9966,8 @@ declare module 'claude-code' {
*/
name: string;
/**
- * What the tool does, for the model.
+ * What the tool does, for the model (and the person where tools are
+ * listed); an unpaired surrogate half in it is drawn as U+FFFD.
*/
description: string;
/**
@@ -8707,58 +10406,33 @@ declare module 'claude-code' {
* A turn's counts are its responses' summed; its model is the last response's.
*/
export type TurnUsage = ModelForkUsage & {
- /**
- * Which model answered, by the id the API reports.
- */
- model: string;
- };
-
- /**
- * What a plugin's `$.ui.blit(args)` takes: which of its mounted Rasters to
- * repaint, in which of its sites, and the cells to paint it with.
- *
- * The Raster is one this plugin's own `ui.render` hook drew, still mounted;
- * `columns` and `rows`, when given, must be the mounted size (a resize is a
- * redraw, `$.ui.invalidate("ui.render")`, not a blit).
- */
- export type UiBlitArgs = {
- /**
- * The site the Raster is drawn in, by the `requestId` this plugin draws
- * it under: one of its panes' ids, a tool row's `tool_use_id`, the band's.
- */
- requestId: string;
- /**
- * The Raster's `key` in that drawing.
- */
- key: string;
- /**
- * The new cells, encoded as the element's `cells` are (RasterProps), for
- * the mounted `columns * rows`.
- */
- cells: string;
- /**
- * The width the cells are laid out for; refused unless it is the mounted
- * Raster's. Absent, the mounted width.
- */
- columns?: number;
- /**
- * The height the cells are laid out for; refused unless it is the mounted
- * Raster's. Absent, the mounted height.
+ /**
+ * Which model answered, by the id the API reports.
*/
- rows?: number;
+ model: string;
};
+ /**
+ * What a plugin's `$.ui.blit(args)` takes: a Raster's next `cells`
+ * (RasterBlitArgs) or a keyed Image's next `source` (ImageBlitArgs).
+ *
+ * Either names an element this plugin's own `ui.render` hook drew, still
+ * mounted; a hook above may rewrite the cells or the source, never the
+ * address or which kind it is.
+ */
+ export type UiBlitArgs = RasterBlitArgs | ImageBlitArgs;
+
/**
* What `$.ui.blit` resolves to and what a `ui.blit` hook's `{ value }`
- * holds: `{}` once the cells are the Raster's next frame, or why not.
+ * holds: `{}` once the cells or source are the next frame's, or why not.
*/
export type UiBlitResult = {
/**
- * Absent when the cells were taken; else why not: nothing of this plugin's
- * is mounted there, the size is not the mounted one, the cells are bad.
+ * Absent when the cells or source were taken; else why not.
*
- * Another plugin's Raster under the same site and key reads as not this
- * plugin's; a cell that does not decode is named by its index.
+ * Nothing of this plugin's is mounted there (another plugin's reads so),
+ * the size is not the mounted one, the cells or source are bad, or the
+ * Image draws its `alt` there, the reason spelled out for a fallback.
*/
deny?: string;
};
@@ -8929,6 +10603,26 @@ declare module 'claude-code' {
value: string;
};
+ /**
+ * Options of `$.ui.log`.
+ */
+ export type UiLogOptions = {
+ /**
+ * Where the line goes (UiLogSink); `transcript` when left out. A hook on
+ * `ui.log` reads it as `e.to` and may send the line elsewhere.
+ */
+ to?: UiLogSink;
+ };
+
+ /**
+ * Where a `$.ui.log` line goes: `transcript`, a dim row of its own (and the
+ * debug log, as every line); `debug`, the debug log alone, nothing on screen.
+ *
+ * The debug log is `claude --debug` or the `--debug-file`; either way the
+ * line is led by the plugin's name.
+ */
+ export type UiLogSink = 'transcript' | 'debug';
+
/**
* The argument of `ui.message`: what a `Client` instance's surface module
* posted (`surface.post(data)`), addressed by where the instance is drawn.
@@ -8985,8 +10679,40 @@ declare module 'claude-code' {
};
/**
- * The argument of `ui.press`: a press on a `Button` a render hook drew.
- * Flat and frozen like every event's.
+ * One of this plugin's open panes as `$.ui.panes()` lists it: the pane's
+ * id and title, and where it stands with the person right now.
+ *
+ * Where a surface seated it (`dock` or `inline`) is that surface's to say, on
+ * the `Pane` render props (`placement`); a session may draw on several.
+ */
+ export type UiPane = {
+ /**
+ * What `$.ui.open({ id })` named it, which `$.ui.close` and its
+ * `ui.render` `requestId` name too.
+ */
+ id: string;
+ /**
+ * Its tab's label: the `title` of its latest open, or the id.
+ */
+ title: string;
+ /**
+ * True for the one pane the surface shows; the rest are tabs behind it.
+ */
+ isShown: boolean;
+ /**
+ * True while the person has given it the keyboard.
+ */
+ isFocused: boolean;
+ /**
+ * False while it waits undrawn: opened unasked on a terminal too narrow
+ * for an unrequested pane, until an open the width or the person admits.
+ */
+ isPlaced: boolean;
+ };
+
+ /**
+ * The argument of `ui.press`: a press on a `Button` a render hook drew, or
+ * on an answered `Markdown` link. Flat and frozen like every event's.
*
* Another plugin addresses one button by matcher:
* `on("ui.press", { plugin: "explainer", element: "explain" }, ...)`.
@@ -8997,7 +10723,8 @@ declare module 'claude-code' {
*/
plugin: string;
/**
- * The `key` the hook gave its `Button`: its address, what a matcher names.
+ * The `key` the hook gave its `Button` or `Markdown`: its address, what a
+ * matcher names.
*/
element: string;
/**
@@ -9015,6 +10742,14 @@ declare module 'claude-code' {
* `if (e.surface === "terminal")` narrows `e`.
*/
surface: RenderSurface;
+ /**
+ * Where the press landed, when the element is a `Markdown` whose links
+ * its plugin answers (`onLinkPress`); absent for a `Button`.
+ *
+ * A hook may rewrite its `href` for the hooks and the closure beneath; one
+ * that adds or drops it fails, and the press goes on beneath it.
+ */
+ link?: PressedLink;
};
/**
@@ -9279,6 +11014,68 @@ declare module 'claude-code' {
*/
type UnionToIntersection<U> = (U extends unknown ? (member: U) => void : never) extends (member: infer I) => void ? I : never;
+ /**
+ * One unit of what `$.session.usage()` answers, by its key there: the
+ * context window's fill, the rate-limit windows, the session's cost.
+ */
+ export type UsageUnit = 'context' | 'rateLimits' | 'cost';
+
+ /**
+ * Who sent the message a `UserMessage` row carries, when someone other than
+ * the person did: another agent, a teammate, another session, a channel.
+ *
+ * Read-only. The sender's words are not the person's: the model reads them
+ * framed as that sender's whatever a hook draws for the row.
+ */
+ type UserMessageFrom = {
+ /**
+ * The sender's name as the row shows it: a subagent's name, else its type;
+ * a teammate's; another session's title; a channel's sender, else server.
+ *
+ * One printable line: control and format characters stripped, whitespace
+ * collapsed, length bounded. Absent (no `from`) for a teammate block whose
+ * frames name different senders or none.
+ */
+ name: string;
+ };
+
+ /**
+ * The background task a `UserMessage` notification row reports on: a
+ * subagent, a background shell, a workflow, a remote agent, a monitor.
+ *
+ * Every field is the notification's own, so the row names the same task on
+ * every draw, a resumed session's included; the session's record of it
+ * (name, type, description) is `$.agent.list()`'s, by `id`. Each string is
+ * one printable line, bounded (a forged envelope's bytes capped). Read-only.
+ */
+ type UserMessageTask = {
+ /**
+ * The task's id as the notification names it; for a subagent, the
+ * `agentId` its `turn.complete` carried and `$.agent.list()` keys.
+ */
+ id?: string;
+ /**
+ * How the task ended: `completed`, `failed` or `killed` (stopped, by the
+ * person or by Claude), or another word its producer wrote.
+ */
+ status?: string;
+ /**
+ * What kind of task, when the notification says (`remote_agent`, an
+ * artifact watch's kind); a subagent's and a shell's leave it out.
+ */
+ type?: string;
+ /**
+ * Which call started the task: its `tool_use_id`, when the notification
+ * carries it.
+ */
+ toolUseId?: string;
+ /**
+ * How long the task ran, in milliseconds, when the notification says; the
+ * row draws it after the summary (`2m 2s`).
+ */
+ durationMs?: number;
+ };
+
type UserPromptExpansionHookInput = BaseHookInput & {
hook_event_name: 'UserPromptExpansion';
expansion_type: 'slash_command' | 'mcp_prompt';
@@ -9322,12 +11119,24 @@ declare module 'claude-code' {
/**
* The globals of a hooks module's environment: these and no others (no DOM,
- * no Node).
+ * no Node). No code generation either: `eval` and `new Function` over a
+ * string throw, and there is no `WebAssembly` (deliberately; a module that
+ * needs compiled code runs it in a process of its own through `$.process.run`).
+ * A surface module's environment (Client) has the same globals and a
+ * `console`; neither has timers (a hooks module waits on `$.clock`, a
+ * surface module on `surface.every`).
*/
global {
/**
* The JSX factory (classic runtime, `@jsx h`; the engine prepends the
* pragma): a plain-data element from a string tag or a component.
+ *
+ * JSX compiles to bare `h(...)` calls resolved by name, so a module (hooks or
+ * surface) never declares, imports or takes as a parameter anything named
+ * `h` or `Fragment` where it writes JSX, and carries no `@jsx` pragma of its
+ * own: either silently points its JSX away from this factory, and a
+ * `<Client>` tag written under another factory is not found when the
+ * module's surface modules are read off its source.
*/
const h: (
tag: string | ((props: never) => RenderNode | null | undefined),
@@ -9448,15 +11257,28 @@ declare module 'claude-code' {
declare module 'claude-code/testing' {
import type { Args } from 'claude-code';
import type { Chunk } from 'claude-code';
+ import type { ClientKeyEvent } from 'claude-code';
+ import type { ClientPointerEvent } from 'claude-code';
+ import type { Elements } from 'claude-code';
import type { EventCalls } from 'claude-code';
import type { EventName } from 'claude-code';
import type { HookStream } from 'claude-code';
+ import type { JsonValue } from 'claude-code';
import type { On } from 'claude-code';
+ import type { PressedLink } from 'claude-code';
import type { Register } from 'claude-code';
+ import type { RenderComponent } from 'claude-code';
+ import type { RenderElement } from 'claude-code';
+ import type { RenderPropsOf } from 'claude-code';
+ import type { RenderSurface } from 'claude-code';
+ import type { RenderViewport } from 'claude-code';
import type { ResultOf } from 'claude-code';
import type { StreamingEventName } from 'claude-code';
import type { Tier } from 'claude-code';
+ import type { UiInputArgument } from 'claude-code';
+ import type { UiInputResult } from 'claude-code';
import type { UiPressResult } from 'claude-code';
+ import type { UiSelectResult } from 'claude-code';
/**
* A value that matches by a rule inside `toEqual` and its kin
@@ -9474,6 +11296,14 @@ declare module 'claude-code/testing' {
[K in keyof Matchers]: (...args: Parameters<Matchers[K]>) => Promise<void>;
};
+ /**
+ * Which `Client` of a mounted drawing an act or a read means, by the `key`
+ * its element carries; optional while the drawing holds exactly one.
+ */
+ export type ClientScope = {
+ in?: string;
+ };
+
/**
* A class, as `toThrow`, `toBeInstanceOf` and `expect.any` take it.
*/
@@ -9488,16 +11318,56 @@ declare module 'claude-code/testing' {
*/
export const describe: (name: string, body: () => void) => void;
+ /**
+ * The element each surface-dependent act of a mounted drawing reaches: a
+ * handle carries the act only where the surface's table has the element.
+ *
+ * `input` needs `Input` and `select` needs `Select` (every surface but
+ * mobile today); `key`, `pointer`, `post`, `advance` and `resize` reach a
+ * `Client` (terminal and desktop today). The rest need nothing but a tree.
+ */
+ export type ElementOfAct = {
+ input: 'Input';
+ select: 'Select';
+ key: 'Client';
+ pointer: 'Client';
+ post: 'Client';
+ advance: 'Client';
+ resize: 'Client';
+ };
+
+ /**
+ * What a mounted drawing's `find` and `findAll` match an element on, every
+ * field given at once: its tag, its `key`, and the text it shows.
+ *
+ * `text` matches the element's whole shown text (string children, a Button
+ * or Link's label, a Markdown's text, a Code's source, an Input's value):
+ * a string by inclusion, a RegExp by test.
+ *
+ * @example
+ * await ui.findAll({ type: 'Text', text: /overdue/, in: 'board' })
+ */
+ export type ElementQuery = {
+ type?: string;
+ key?: string;
+ text?: string | RegExp;
+ /**
+ * Searches what this `Client`'s surface module drew (by the `Client`'s
+ * key) instead of the plugin's own tree.
+ */
+ in?: string;
+ };
+
/**
* What a test holds as `$`, the engine's own: every call on it is made as
* the REPL, the query loop and the render sites make theirs, over every plugin.
*
* `next.origin` is the engine, and the whole chain runs over the plugins
- * loaded. A tool call's `tool_use_id` is minted when left out, as the engine
- * mints it; `$.ui.press` is the terminal pressing a Button a test rendered.
+ * loaded. A tool call's `tool_use_id` is minted when left out; `$.ui.mount`
+ * is a surface the test names drawing an instance, `$.ui.press` a press on it.
*/
export type Engine = {
- [N in keyof EventCalls]: N extends 'ui' ? EngineNoun<N> & EnginePress : EngineNoun<N>;
+ [N in keyof EventCalls]: N extends 'ui' ? EngineNoun<N> & EnginePress & EngineMount : EngineNoun<N>;
};
/**
@@ -9506,6 +11376,34 @@ declare module 'claude-code/testing' {
*/
export type EngineCall<E extends EventName> = E extends StreamingEventName ? (e: Args<E>) => HookStream<Chunk<E>, ResultOf[E]> : (e: Args<E>) => Promise<ResultOf[E]>;
+ /**
+ * A surface drawing a component instance through the plugins, then driven
+ * by key through a handle typed by that surface (Mounted).
+ *
+ * `ui.render` raised there for those props, the tree validated by that
+ * table, its `Client`s running; the reads and `press` on every surface,
+ * `input` where the table has `Input`, the `Client` acts where `Client`.
+ *
+ * @example
+ * for (const surface of SURFACES) run(await $.ui.mount({ ...HINT, surface }))
+ */
+ export type EngineMount = {
+ /**
+ * Raises the plugins' drawing of the component on the surface and holds
+ * it, as that surface showing the instance does.
+ *
+ * Resolves once the tree validated and every `Client` in it drew once.
+ *
+ * @param target whose elements, the surface, the component, its props,
+ * the instance's requestId, and what the surface measured
+ * @returns the mounted drawing; rejects when no `surface` (or an unknown
+ * one) is named, when the surface cannot draw the tree the chain
+ * returned (with the reason: an element its table lacks, a prop not
+ * allowed), or when a `Client`'s module failed or drew nothing
+ */
+ mount: <P extends RenderSurface, C extends RenderComponent>(target: MountTarget<P, C>) => Promise<Mounted<P, C>>;
+ };
+
/**
* One noun of the engine's `$`: each of its events as the engine calls it,
* `tool.call` and `ui.render` typed per tool and component, `ui.resolve` out.
@@ -9521,16 +11419,20 @@ declare module 'claude-code/testing' {
export type EngineNounEvent<N extends keyof EventCalls> = Exclude<keyof EventCalls[N] & string, `${N}.resolve` extends 'ui.resolve' ? 'resolve' : never>;
/**
- * The terminal pressing a Button a test rendered: the `ui.press` chain over
- * every plugin hooked on it, the Button's own `onPress` at the bottom.
+ * A surface pressing a Button a test rendered, or a Markdown's link: the
+ * `ui.press` chain over every plugin hooked on it, its own closure last.
*/
export type EnginePress = {
/**
- * Presses the Button, as a click or its hotkey does.
+ * Presses the Button, as a click or its hotkey does; with `link`, the
+ * Markdown's link, as a click on it does.
*
- * @param target whose Button, its key, and the instance when several
- * @returns what the chain settled on; rejects when no such Button is
- * drawn on the terminal, or several are and no instance is named
+ * `e.surface` is the surface of the drawing that holds it.
+ *
+ * @param target whose element, its key, the instance and surface when
+ * several hold it, and for a Markdown the link
+ * @returns what the chain settled on; rejects when no such element is
+ * drawn, or several are and neither instance nor surface tells them apart
*/
press: (target: PressTarget) => Promise<UiPressResult | undefined>;
};
@@ -9573,6 +11475,38 @@ declare module 'claude-code/testing' {
*/
export type Expecting = (received: unknown, message?: string) => Expectation;
+ /**
+ * One element of a mounted drawing as `find` returns it: the description
+ * the plugin's hook (or a `Client`'s module) built, read as plain data.
+ *
+ * What every surface is handed to draw, not what any surface painted: the
+ * same on the terminal, the desktop, VS Code and mobile.
+ */
+ export type FoundElement = {
+ /**
+ * The element's tag: `Box`, `Text`, `Button`, `Input`, `Client`, ...
+ */
+ type: string;
+ /**
+ * What its props carry as `key`, when they do.
+ */
+ key: string | undefined;
+ /**
+ * Its props, plain data: a Button's `label`, a Text's `color`, ...;
+ * handlers never cross (a Button's `onPress` is not here).
+ */
+ props: Record<string, unknown>;
+ /**
+ * What it shows: its string children in document order and, for the
+ * leaves that draw a prop as text, that prop (ElementQuery `text`).
+ */
+ text: string;
+ /**
+ * Its children as drawn: strings and element descriptions.
+ */
+ children: unknown[];
+ };
+
/**
* The checks `expect(received)` offers; each throws an AssertionError when
* it fails, naming what was expected and what was received.
@@ -9862,6 +11796,278 @@ declare module 'claude-code/testing' {
now?: number;
};
+ /**
+ * A drawing of component `C` the test mounted on surface `P`: reads over its
+ * description, acts on its elements by key, `Client` acts where `P` has one.
+ *
+ * Narrowed by the `surface` the test passed, as `e.surface` narrows
+ * `$.ui.resolve(e)`: no `input` on `mobile`, no `key` on `vscode`, whose
+ * tables (Elements) lack `Input` and `Client`; over a union, their meet.
+ */
+ export type Mounted<P extends RenderSurface = RenderSurface, C extends RenderComponent = RenderComponent> = {
+ [K in keyof MountedMembers<P, C> as K extends keyof ElementOfAct ? ElementOfAct[K] extends keyof Elements[P] ? K : never : K]: MountedMembers<P, C>[K];
+ };
+
+ /**
+ * Every member a mounted drawing of component `C` can have; `Mounted<P, C>`
+ * keeps the ones surface `P` has the element for (ElementOfAct).
+ *
+ * Each act resolves once the loop settled and what a plugin invalidated
+ * was drawn again. The kit exercises the mod (its hooks, its description
+ * under the surface's rules, its `Client` modules), never a surface's paint.
+ */
+ export type MountedMembers<P extends RenderSurface, C extends RenderComponent = RenderComponent> = {
+ /**
+ * Where this drawing is, as the test named it.
+ */
+ readonly surface: P;
+ /**
+ * The tree as last drawn: what the plugins' `ui.render` chain returned
+ * for this instance, validated by the surface's table, as plain data.
+ *
+ * With `in`, what that `Client`'s surface module last drew instead.
+ *
+ * @param scope `{ in }`: a `Client`'s key, to read its module's tree
+ * @returns the tree; rejects with the refusal when the surface could not
+ * draw what the chain returned, or with a `Client`'s fault line
+ * @example
+ * expect(await ui.drawn()).toMatchObject({ type: 'Box' })
+ */
+ drawn: (scope?: ClientScope) => Promise<RenderElement>;
+ /**
+ * The first element matching the query, outermost first in document
+ * order, or undefined.
+ *
+ * @param query tag, key and shown text to match; `in` to search a Client
+ * @returns the element's description, or undefined when none matches
+ * @example
+ * expect((await ui.find({ key: 'count' }))?.text).toBe('3 notes')
+ */
+ find: (query: ElementQuery) => Promise<FoundElement | undefined>;
+ /**
+ * Every element matching the query, in document order.
+ *
+ * @param query tag, key and shown text to match; `in` to search a Client
+ * @returns the matching elements' descriptions
+ * @example
+ * expect(await ui.findAll({ type: 'Button' })).toHaveLength(2)
+ */
+ findAll: (query: ElementQuery) => Promise<FoundElement[]>;
+ /**
+ * Presses the Button keyed `key`, as the person activating it on this
+ * surface does: the `ui.press` chain, the Button's own `onPress` last.
+ *
+ * `e.surface` is this drawing's. With `link`, presses that link of the
+ * Markdown keyed `key` instead. A Button a `Client`'s module drew is
+ * pressed the same way, by its key.
+ *
+ * @param target the key; another plugin's name to press its Button; a link
+ * @returns what the chain settled on
+ * @example
+ * await ui.press({ key: 'save' })
+ */
+ press: (target: MountPressTarget) => Promise<UiPressResult | undefined>;
+ /**
+ * Types into the Input keyed `key`: the `ui.input` chain with the text as
+ * `e.value`, the Input's own handler last.
+ *
+ * `kind` `submit` (the default) is Enter with that text, `change` an edit
+ * that leaves it in the field.
+ *
+ * @param target the key and the text; `kind`; another plugin's name
+ * @returns what the chain settled on
+ * @example
+ * await ui.input({ key: 'title', text: 'groceries' })
+ */
+ input: (target: MountInputTarget) => Promise<UiInputResult | undefined>;
+ /**
+ * Picks `value` in the Select keyed `key`: the `ui.select` chain, the
+ * Select's own `onSelect` last.
+ *
+ * @param target the key and the option's value; another plugin's name
+ * @returns what the chain settled on
+ * @example
+ * await ui.select({ key: 'sort', value: 'date' })
+ */
+ select: (target: MountSelectTarget) => Promise<UiSelectResult | undefined>;
+ /**
+ * Hands a `Client`'s `onKey` listener one key, as a key pressed while
+ * its region has the focus does.
+ *
+ * `in` names the `Client` by key; optional when the drawing holds one.
+ *
+ * @param event the key (`{ key: 'right' }`, `{ key: 'a', ctrl: true }`)
+ * @example
+ * await ui.key({ key: 'return', in: 'board' })
+ */
+ key: (event: MountKeyEvent) => Promise<void>;
+ /**
+ * Hands a `Client`'s `onPointer` listener one event, in the cells of its
+ * region as every surface that draws a `Client` reports them.
+ *
+ * @param event the event (`{ type: 'down', x: 3, y: 0, button: 'left' }`)
+ * @example
+ * await ui.pointer({ type: 'down', x: 2, y: 0, button: 'left' })
+ */
+ pointer: (event: MountPointerEvent) => Promise<void>;
+ /**
+ * Posts as a `Client`'s own `surface.post(data)` does: the plugin's
+ * `ui.message` hooks run with `e.data`, `e.surface` this drawing's.
+ *
+ * A `{ props }` they answer reaches the instance, which redraws with
+ * its state kept.
+ *
+ * @param data plain data (JsonValue)
+ * @param scope `{ in }`: which `Client`, when the drawing holds several
+ * @example
+ * await ui.post({ pick: 2 })
+ */
+ post: (data: JsonValue, scope?: ClientScope) => Promise<void>;
+ /**
+ * Moves the drawing's frame clock on: each `surface.every(ms, fn)` timer
+ * of its `Client`s fires at every interval of its own the move crosses.
+ *
+ * @param ms how far, in milliseconds
+ * @example
+ * await ui.advance(250)
+ */
+ advance: (ms: number) => Promise<void>;
+ /**
+ * Lays a `Client`'s region out at a size, as the surface measuring it
+ * does: what its module reads as `surface.columns` and `surface.rows`.
+ *
+ * @param size cells across and down; `in`: which `Client`
+ * @example
+ * await ui.resize({ columns: 40, rows: 3 })
+ */
+ resize: (size: MountResizeTarget) => Promise<void>;
+ /**
+ * Draws the instance again, as the engine does when its props change (a
+ * tool row's output arrived): the `ui.render` chain with the next props.
+ *
+ * A plugin's own `$.ui.invalidate` needs no call: the drawing follows it
+ * before the next read.
+ *
+ * @param props the component's next props; the current ones when absent
+ * @example
+ * await ui.redraw({ ...TOOL_ROW, isRunning: false, output: 'done' })
+ */
+ redraw: (props?: RenderPropsOf[C]) => Promise<void>;
+ /**
+ * Lets the drawing go, as the surface dropping the instance does: its
+ * `Client`s and their timers end. Later acts on the handle reject.
+ *
+ * @example
+ * await ui.unmount()
+ */
+ unmount: () => Promise<void>;
+ };
+
+ /**
+ * What a mounted drawing's `input` takes: the Input's key, the text, which
+ * of the two inputs it is (`submit` when unsaid), another plugin's name.
+ */
+ export type MountInputTarget = {
+ key: string;
+ text: string;
+ kind?: UiInputArgument['kind'];
+ plugin?: string;
+ };
+
+ /**
+ * What a mounted drawing's `key` takes: the key as a `Client`'s `onKey`
+ * listener receives it (ClientKeyEvent), and which `Client` when several.
+ */
+ export type MountKeyEvent = ClientKeyEvent & ClientScope;
+
+ /**
+ * What a mounted drawing's `pointer` takes: the event as a `Client`'s
+ * `onPointer` listener receives it, in its region's cells, and which one.
+ */
+ export type MountPointerEvent = ClientPointerEvent & ClientScope;
+
+ /**
+ * What a mounted drawing's `press` takes: the Button's key, another
+ * plugin's name when the Button is not the mounted plugin's, a link.
+ */
+ export type MountPressTarget = {
+ key: string;
+ plugin?: string;
+ /**
+ * Presses this link of the Markdown keyed `key` instead of a Button.
+ */
+ link?: PressedLink;
+ };
+
+ /**
+ * What a mounted drawing's `resize` takes: a `Client` region's size in
+ * cells, as the surface measuring it hands it, and which `Client`.
+ */
+ export type MountResizeTarget = {
+ columns: number;
+ rows: number;
+ in?: string;
+ };
+
+ /**
+ * What a mounted drawing's `select` takes: the Select's key, the picked
+ * option's value, another plugin's name when the Select is not its own.
+ */
+ export type MountSelectTarget = {
+ key: string;
+ value: string;
+ plugin?: string;
+ };
+
+ /**
+ * What `$.ui.mount` takes: whose elements the test will act on, the surface
+ * that draws, and the component instance the engine asks the plugins for.
+ *
+ * The envelope a `ui.render` hook sees as `e` (`surface`, `component`,
+ * `requestId`, `viewport`, `props`) plus `plugin`. `surface` is never
+ * defaulted: one body run over several surfaces is what shows independence.
+ *
+ * @example
+ * $.ui.mount({ plugin: 'notes', surface, component: 'Pane', props: PANE })
+ */
+ export type MountTarget<P extends RenderSurface = RenderSurface, C extends RenderComponent = RenderComponent> = {
+ /**
+ * Whose elements the handle's acts address by bare `key`: the plugin
+ * under test, usually. An act names another plugin to reach its element.
+ */
+ plugin: string;
+ /**
+ * What draws: its element table validates every tree the plugins
+ * return, and every dispatch the handle raises carries it as `e.surface`.
+ *
+ * One of `terminal`, `desktop`, `vscode`, `mobile`.
+ */
+ surface: P;
+ /**
+ * Which component the engine asks the plugins to draw (`Pane`,
+ * `AbovePrompt`, `ToolUse`, ...): what a `ui.render` matcher narrows on.
+ */
+ component: C;
+ /**
+ * The component's props, what the hook reads as `e.props`.
+ */
+ props: RenderPropsOf[C];
+ /**
+ * The instance drawn (a pane's id, a tool row's tool_use_id); one is
+ * minted when absent. Two mounts of one component are two instances.
+ */
+ requestId?: string;
+ /**
+ * What the surface measured, as the hook reads it under `e.viewport`;
+ * absent when the surface has not measured, as on `e`.
+ *
+ * Cells across and down in the surface's monospace metric and whether it
+ * docks a pane. A `Client` in the drawing starts laid out at this size
+ * (0 by 0 when absent) until the handle's `resize` lays its region out.
+ */
+ viewport?: RenderViewport;
+ };
+
/**
* A set of checks and, under `not`, the same set passing where they fail.
*/
@@ -9891,13 +12097,25 @@ declare module 'claude-code/testing' {
export type PluginTier = Exclude<Tier, 'core'>;
/**
- * What `$.ui.press` takes: the plugin whose `ui.render` hook drew the Button,
- * the `key` it gave it, and the instance when it drew one in several.
+ * What `$.ui.press` takes: the plugin whose `ui.render` hook drew the element,
+ * the `key` it gave it, the instance and surface when several, a `link`.
*/
export type PressTarget = {
plugin: string;
key: string;
+ /**
+ * Which instance holds it, when the plugin drew the key in several.
+ */
requestId?: string;
+ /**
+ * Which surface's drawing, when the key is drawn on more than one; the
+ * press carries the surface of the drawing it lands in either way.
+ */
+ surface?: RenderSurface;
+ /**
+ * For a Markdown answering its links: which of them the press lands on.
+ */
+ link?: PressedLink;
};
/**