---
lastModified: 2026-11-25
---

# Plugins

Plugins are TypeScript or JavaScript modules that add tools, commands, and event-driven behavior to
Amp. A plugin can be a single file or a directory with supporting files. Plugins run code in your
environment, so only load plugins you trust.

Plugins can:

- **Handle events** — `amp.on(...)` for tool calls, tool results, and agent lifecycle events
- **Add tools** — `amp.registerTool(...)` for custom tools the agent can call
- **Call tools** — `ctx.tools.call(name, input)` for direct built-in, plugin, and MCP tool calls
- **Bundle skills** — `await amp.registerSkill(...)` to register skill directories
- **Add commands** — `amp.registerCommand(...)` for command palette actions
- **Show UI** — `ctx.ui.notify(...)`, `ctx.ui.confirm(...)`, `ctx.ui.input(...)`, `ctx.ui.select(...)`,
  and `ctx.ui.insertPromptText(...)` to prefill the composer
- **Classify with AI** — `amp.ai.ask(...)` for thread-scoped yes/no decisions, `amp.ai.decide(...)`
  for fast typed decisions with calibrated probabilities
- **Label threads** — `ctx.thread.addLabels(...)` and `ctx.thread.setLabels(...)` to tag the
  current thread

<h2 id="plugin-locations">Plugin Locations and Precedence</h2>

Amp loads plugins from these sources:

- **Personal plugins.** Manage them in [Personal Settings](/settings/plugins). They apply everywhere
  you use Amp.
- **Workspace plugins.** Workspace admins manage them in [Workspace Settings](/workspace/plugins).
  They apply to everyone in the workspace.
- **Project plugins.** Put files or directories in `.amp/plugins/` at the project root. They apply
  when you run Amp in that project.
- **System plugins.** If `XDG_CONFIG_HOME` is set, put files or directories in
  `$XDG_CONFIG_HOME/amp/plugins/`. Otherwise, use `~/.config/amp/plugins/` on macOS and Linux or
  `%USERPROFILE%\.config\amp\plugins\` on Windows. They apply to your projects on that machine.

When plugins have the same name, the precedence order is project, system, personal, then workspace.

<h2 id="adding-plugins">Adding Plugins</h2>

For most plugins, import a shared plugin into your personal plugins. Personal plugins are available
everywhere you use Amp. Paste the plugin's share URL into a thread and ask Amp to import it:

```prompt
Import this shared plugin into my personal plugins: <shared-plugin-url>
```

Workspace admins can import a shared plugin into workspace plugins to make it available to everyone
in the workspace. See [Global Plugin Repositories](#personal-workspace-plugins) below.

For a plugin tied to one project, put its file or directory in `.amp/plugins/`.

To install a single-file plugin from a URL for all projects on your machine, run:

```bash
amp plugins add <url>
```

Add `--target workspace` to install it in the current project's `.amp/plugins/` directory instead.

<h2 id="personal-workspace-plugins">Global Plugin Repositories</h2>

Personal and workspace plugins live in global plugin repositories. Your personal plugin repository
applies only to you. Workspace admins manage the workspace repository, whose plugins apply to
everyone in the workspace. The simplest way to manage either is to ask Amp in a thread.

Amp finds the right repository, makes the requested change, commits it, and asks before pushing. A
push publishes the change. Amp can then reload the plugin in the current thread without restarting.

To share a personal plugin, open <span class="ui">Plugins</span> in [Personal Settings](/settings/plugins),
select the plugin, choose <span class="ui">Share</span>, make it available to the workspace, and copy
its URL. Send the URL directly or paste it into Slack, where it unfurls with details about the
plugin. Teammates can paste the URL into a thread or ask Amp, “Has anyone got a tmux plugin?”

For direct shell access, `amp plugins repositories` lists the repositories and clone commands.
`amp clone user-plugins` and `amp clone workspace-plugins` clone them. The `amp plugins import` and
`amp plugins update` commands manage shared imports. Repository owners can require signed commits
in the repository's Advanced settings.

### Hosted repository limits

Amp loads a plugin from a personal or workspace plugin repository only when it fits these limits:

| Resource                                            | Limit  |
| --------------------------------------------------- | ------ |
| Plugins per repository                              | 50     |
| Files in one directory plugin, including `index.ts` | 500    |
| Size of one file                                    | 10 MiB |
| Total size of one plugin                            | 25 MiB |
| Total repository size                               | 25 MiB |

A plugin that exceeds a limit is not loaded. It does not appear in Settings or in new threads, even
though the push succeeds. Remove files the plugin does not need at runtime, or split it into
smaller plugins. These limits do not apply to project or system plugins.

<h2 id="writing-plugins">Writing Plugins</h2>

A single-file plugin is a `.ts` or `.js` file directly inside a plugin location. A directory plugin
uses `<plugin-name>/index.ts` or `<plugin-name>/index.js`. If both entry files exist, Amp uses
`index.ts`. The entry file can import supporting files with relative paths.

```text
deploy-status/
├── index.ts
├── client.ts
└── prompts/
```

Every plugin entry file exports a default function. Amp passes a `PluginAPI` object to that
function.

```ts
import type { PluginAPI } from '@ampcode/plugin'

export default function (amp: PluginAPI) {
	amp.logger.log('Plugin initialized')
}
```

Code in the exported function runs when the plugin loads. Use `session.start` only for work that should run when Amp starts a specific thread session.

Amp also has a built-in skill for writing plugins, so you can just ask it to write a plugin for you.

<h3 id="plugin-bundled-skills">Bundle a Skill</h3>

A directory plugin can include a standard skill and its resources. Amp does not scan the
`skills/` directory automatically, so the plugin must register each skill when it loads.

```text
deploy-status/
├── index.ts
└── skills/
    └── deploy-guide/
        ├── SKILL.md
        └── reference/
            └── checklist.md
```

```ts
import type { PluginAPI } from '@ampcode/plugin'

export default async function (amp: PluginAPI) {
	await amp.registerSkill({ path: 'skills/deploy-guide' })
}
```

The path is relative to the plugin directory and must name a directory that contains `SKILL.md`.
The skill's frontmatter `name` must match its directory name. In this example, Amp lists the skill
as `deploy-status:deploy-guide`.

A plugin can also register skills it downloads or generates while it runs. Write the skill under
`amp.system.cacheDirectory`, a directory each plugin may write to, and pass its absolute path to
`registerSkill`. Single-file plugins can register skills only this way. Amp rejects absolute paths
outside the plugin's cache directory.

A bundled skill can list the plugin's own tools in its `builtin-tools` frontmatter field. Amp
offers those tools through `tool_search` like the plugin's other tools, and tells the model to load
the skill before calling them. See the
[Plugin API reference](/docs/plugin-api#example-plugin-bundled-skill) for details.

<h3 id="reloading-plugins">Reloading Plugins</h3>

After changing a plugin, ask Amp to reload it. You can also ask Amp to list the plugins available in
the thread. For direct control, open the command palette with <kbd>Ctrl+O</kbd> and run
`plugins: reload` or `plugins: list`. Run `amp plugins list` in a shell to see loaded plugins, their
sources, registered events, commands, and tools.

Spaces and Puck have no executor, so plugins do not load in them and they do not offer these
commands. Plugins load in the threads a Space starts. A new thread loads the latest version of your
personal and workspace plugins; to update a thread that is already running, run `plugins: reload`
in that thread.

**Web app:**
		<video controls loop muted playsinline preload="metadata" data-autoplay-in-view width="1100" height="720" aria-label="Listing and reloading plugins from the command palette in the Amp web app" src="https://static.ampcode.com/docs/plugin-web-reload-list.mp4"></video>

**CLI:**
		<video controls loop muted playsinline preload="metadata" data-autoplay-in-view width="768" height="521" aria-label="Listing and reloading plugins from the command palette in the Amp CLI" src="https://static.ampcode.com/docs/plugin-reload-list.mp4"></video>

Plugin UI is mirrored across TUI and Web surfaces:

<!-- prettier-ignore -->
<video width="1280" style="aspect-ratio: 1280/688" playsinline autoplay loop muted src="https://static.ampcode.com/docs/plugin-ui-on-web-optimized.mp4" type="video/mp4"></video>

Plugin activation settings apply to both interactive `amp` sessions and `amp --execute` runs.

<h2 id="event-examples">Event Examples</h2>

Plugin events follow a thread session's agent lifecycle. `session.start` is emitted for the thread session; each user turn then starts, may run tools, and eventually ends.

```
╭───────────────╮    ╭─────────────╮    ╭───────────╮    ╭─────────────╮    ╭───────────╮
│ session.start │───▶│ agent.start │───▶│ tool.call │───▶│ tool.result │───▶│ agent.end │
╰───────────────╯    ╰─────────────╯    ╰───────────╯    ╰─────────────╯    ╰───────────╯
                                              ▲                 │
                                              ╰──── per tool ───╯
```

### `session.start`: Run Setup When a Thread Starts

`session.start` fires when Amp starts a thread session, such as when the user sends the first message in a new thread or opens/switches to an existing thread. Put plugin-load initialization directly in the exported function body. Multiple threads can be started and continue to run at the same time in the same Amp CLI. There is no `session.end` event.

```ts
import type { PluginAPI } from '@ampcode/plugin'

export default function (amp: PluginAPI) {
	amp.on('session.start', async (event, ctx) => {
		await ctx.ui.notify(`Example session.start for ${event.thread.id}.`)
	})
}
```

### `tool.call`: Approve or Reject a Tool Call

`tool.call` fires before a tool runs. Return `allow` to run the tool, `reject-and-continue` to block it and let the agent continue, `modify` to change the input, or `synthesize` to provide a result without running the tool.

`tool.call` and `tool.result` fire for tools that run in the Amp CLI, an orb, or a runner. These include built-in tools such as `shell_command`, `Read`, `edit_file`, and `create_file`, MCP tools configured on that machine, and plugin tools. They also fire when a `Task` subagent calls these tools.

Neither event fires for tools that run on Amp's servers. Examples include `Task` itself, `code_exec`, `tool_search`, `skill`, `read_thread`, `create_thread`, `painter`, `view_media`, and tools from MCP servers connected in Amp settings. A plugin cannot use these events to observe, reject, or modify a `Task` call itself.

```ts
import type { PluginAPI } from '@ampcode/plugin'

export default function (amp: PluginAPI) {
	amp.on('tool.call', async (event, ctx) => {
		const confirmed = await ctx.ui.confirm({
			title: `Allow ${event.tool}?`,
			message: `Amp wants to call ${event.tool}.`,
			confirmButtonText: 'Allow',
		})

		if (confirmed) {
			return { action: 'allow' }
		}

		return {
			action: 'reject-and-continue',
			message: `The user rejected ${event.tool}.`,
		}
	})
}
```

**Web app:**
		<img src="https://static.ampcode.com/docs/plugin-web-tool-call-confirm.png" alt="A plugin confirmation dialog in the Amp web app asking whether to allow a tool call" width="1100" height="720" />

**CLI:**
		<img src="https://static.ampcode.com/docs/plugin-tool-call-modal.png" alt="A plugin confirmation dialog in the Amp CLI asking whether to allow a tool call" width="768" />

### `tool.result`: Observe or Modify a Tool Result

`tool.result` fires after a tool finishes and before the result is sent back to the model. It covers the same tools as `tool.call`, not tools that run on Amp's servers. Return nothing to keep the original result, or return a replacement status/output.

```ts
import type { PluginAPI } from '@ampcode/plugin'

export default function (amp: PluginAPI) {
	amp.on('tool.result', async (event, ctx) => {
		if (event.status === 'error') {
			await ctx.ui.notify(`Tool failed: ${event.tool}`)
		}
	})
}
```

### `agent.start`: Notify When a Turn Starts

`agent.start` fires when the user submits a prompt. It is useful for reacting to new turns before
the agent starts working.

```ts
import type { PluginAPI } from '@ampcode/plugin'

export default function (amp: PluginAPI) {
	amp.on('agent.start', async (_event, ctx) => {
		await ctx.ui.notify('Amp is starting a new turn.')
	})
}
```

Return `message` to append instructions to the user message for that turn. The appended text is hidden unless `display` is `true`. `event.changesWorkflow` is `'ship'` or `'push_branch'` when the Ship or Push to Branch button started the turn, so a plugin can react to shipping without matching on the prompt text. To add instructions the user can see and edit before shipping, use `changes.prompt` instead.

### `changes.prompt`: Add to the Ship Prompt

`changes.prompt` fires when Amp prepares the prompt behind the Ship or Push to Branch button, before the user sees it. Return `append` to add instructions after the prompt. The Ship dialog shows the assembled prompt, so the user can edit or remove what your plugin added before sending, and a press-and-hold Ship sends it as shown. `event.workflow` is `'ship'` or `'push_branch'`.

```ts
import type { PluginAPI } from '@ampcode/plugin'

export default function (amp: PluginAPI) {
	amp.on('changes.prompt', (event) => {
		if (event.workflow !== 'ship') {
			return {}
		}
		return {
			append:
				'If this thread fixes a Linear issue, put its ID in the commit message and, after pushing, add a comment to the issue linking the commit.',
		}
	})
}
```

### `agent.end`: Continue After a Turn Ends

`agent.end` fires when the agent finishes a turn. Return `continue` to append a follow-up user message and start another turn. Always include a marker or other guard when returning `continue` so your plugin does not loop forever. As a backstop, Amp stops chaining plugin `continue` messages after five in a row; the next message from the user starts a fresh chain. A plugin that drives long-running work can raise this limit by setting `maxContinuations` on the `continue` result, as the [/goal example](#example-plugin-goal) does.

```ts
import type { PluginAPI } from '@ampcode/plugin'

const marker = '[plugin:tests-requested]'

export default function (amp: PluginAPI) {
	amp.on('agent.end', (event) => {
		if (!event.message.toLowerCase().includes('verify')) {
			return
		}
		if (event.message.includes(marker)) {
			return
		}

		return {
			action: 'continue',
			userMessage: `${marker} Before finishing, run the most relevant tests for your changes.`,
		}
	})
}
```

<h2 id="command-tool-and-ui-examples">Command, Tool, and UI Examples</h2>

### Add a Command

Commands appear in Amp's command palette.

```ts
import type { PluginAPI } from '@ampcode/plugin'

export default function (amp: PluginAPI) {
	amp.registerCommand(
		'open-plugin-docs',
		{
			title: 'Open plugin docs',
			category: 'docs',
			description: 'Open the Amp Plugin API reference page.',
		},
		async (ctx) => {
			await ctx.system.open('https://ampcode.com/docs/plugin-api')
		},
	)
}
```

**Web app:**
		<img src="https://static.ampcode.com/docs/plugin-web-command-palette.png" alt="The Amp web app command palette showing custom plugin commands" width="1100" height="720" />

**CLI:**
		<img src="https://static.ampcode.com/docs/plugin-command-palette.png" alt="The Amp CLI command palette showing a custom plugin command" width="768" />

### Changing Command Availability

`amp.registerCommand(...)` accepts an optional `availability` and returns a subscription whose `setAvailability(...)` method updates how the command appears in the palette:

- `{ type: 'enabled' }` — shown and selectable (the default).
- `{ type: 'disabled', reason: '...' }` — shown but not selectable; `reason` is displayed alongside the command.
- `{ type: 'hidden' }` — not shown at all.

This plugin adds two commands that toggle Amp's built-in `notifications.enabled` setting and keeps the palette showing only the relevant one.

```ts
import type { CommandSubscription, PluginAPI } from '@ampcode/plugin'

export default async function (amp: PluginAPI) {
	const isEnabled = (config: Record<string, unknown>) => config['notifications.enabled'] !== false

	let mute: CommandSubscription | undefined
	let unmute: CommandSubscription | undefined

	const refresh = (enabled: boolean) => {
		mute?.setAvailability(enabled ? { type: 'enabled' } : { type: 'hidden' })
		unmute?.setAvailability(enabled ? { type: 'hidden' } : { type: 'enabled' })
	}

	const enabled = isEnabled(await amp.configuration.get())

	mute = amp.registerCommand(
		'mute-notifications',
		{
			title: 'Mute notifications',
			category: 'notifications',
			availability: enabled ? { type: 'enabled' } : { type: 'hidden' },
		},
		async (ctx) => {
			await amp.configuration.update({ 'notifications.enabled': false }, 'global')
			await ctx.ui.notify('Notifications muted.')
		},
	)

	unmute = amp.registerCommand(
		'unmute-notifications',
		{
			title: 'Unmute notifications',
			category: 'notifications',
			availability: enabled ? { type: 'hidden' } : { type: 'enabled' },
		},
		async (ctx) => {
			await amp.configuration.update({ 'notifications.enabled': true }, 'global')
			await ctx.ui.notify('Notifications unmuted.')
		},
	)

	amp.configuration.subscribe((config) => {
		refresh(isEnabled(config))
	})
}
```

### Register a Tool

Tools registered by plugins are available to the model alongside Amp's built-in tools.

```ts
import type { PluginAPI } from '@ampcode/plugin'

export default function (amp: PluginAPI) {
	amp.registerTool({
		name: 'project_status',
		description: 'Show the current git status for this repository.',
		inputSchema: {
			type: 'object',
			properties: {},
			required: [],
		},
		async execute() {
			const result = await amp.$`git status --short`
			return result.stdout || 'No changes.'
		},
	})
}
```

Tools can also return images by returning an array of content blocks that mixes text and image
blocks. For large images such as screenshots, upload the bytes with `amp.attachments.upload(...)`
and return a URL-backed image block so thread state stores a URL instead of the base64 payload.
Image uploads are validated against Amp's inference image limits (at most 4.9 MB decoded and
8000px per dimension). Fall back to an inline base64 block if the upload fails.

```ts
async execute() {
	const png: Uint8Array = await captureScreenshot()
	try {
		const { url } = await amp.attachments.upload({ data: png, mimeType: 'image/png' })
		return [{ type: 'image', mimeType: 'image/png', url }]
	} catch {
		return [{ type: 'image', mimeType: 'image/png', data: Buffer.from(png).toString('base64') }]
	}
}
```

### Link Text in the Transcript

`registerLinkPattern` turns matching text in the thread transcript into links: issue IDs in user messages, ticket numbers in assistant prose, and identifiers in inline code. Amp records the patterns on each thread the plugin's executor connects to, so someone who opens the thread later without an executor still sees the links. Because a thread keeps patterns it has already recorded, existing links stay linked even after a later executor without the plugin connects.

```ts
import type { PluginAPI } from '@ampcode/plugin'

export default function (amp: PluginAPI) {
	amp.registerLinkPattern({
		id: 'issue',
		pattern: 'ENG-\\d{1,6}',
		href: 'https://linear.app/acme/issue/{{match}}',
	})
}
```

`pattern` is a regular expression source without anchors, flags, or delimiters. Amp compiles it with the `u` flag, requires a token boundary on both sides of the match, and rejects patterns longer than 200 characters, patterns that use backreferences or lookbehind, and patterns that can match the empty string. `href` must expand to an `http:` or `https:` URL or to an absolute path on Amp such as `/admin/bug-reports/{{match}}`; `{{match}}` is the whole match and `{{name}}` is the named capture group `name`, both URL-encoded. When two patterns match the same text, the pattern registered first wins.

### Ask the User for Input

Plugins can show notifications, confirmation dialogs, text inputs, and selection dialogs.

```ts
import type { PluginAPI } from '@ampcode/plugin'

export default function (amp: PluginAPI) {
	amp.registerCommand(
		'add-note-to-thread',
		{
			title: 'Add note to thread',
			category: 'notes',
			description: 'Prompt for a note and append it to the current thread.',
		},
		async (ctx) => {
			const note = await ctx.ui.input({
				title: 'Thread note',
				helpText: 'What should Amp remember in this thread?',
				submitButtonText: 'Add note',
			})

			if (!note) {
				return
			}

			if (!ctx.thread) {
				await ctx.ui.notify(
					'No active thread. Send any message to create one, then re-run this command.',
				)
				return
			}

			await ctx.thread.append([{ type: 'user-message', content: note }])
		},
	)
}
```

**Web app:**
		<video controls loop muted playsinline preload="metadata" data-autoplay-in-view width="1100" height="720" aria-label="A plugin asking for text input, a selection, and a confirmation in the Amp web app" src="https://static.ampcode.com/docs/plugin-web-ui-input.mp4"></video>

**CLI:**
		<video controls loop muted playsinline preload="metadata" data-autoplay-in-view width="768" height="521" aria-label="A plugin asking for text input, a selection, and a confirmation in the Amp CLI" src="https://static.ampcode.com/docs/plugin-ui-input.mp4"></video>

Selection dialogs can optionally append a final inline text field with **Other** as its placeholder.
Set `allowOther: true` and enter a custom value directly in the list. Surrounding whitespace is
trimmed, and empty values are not submitted. The promise resolves to either a listed option or the
entered text, and still resolves to `undefined` if the user cancels.

Confirmation dialogs can include editable text fields, file fields, read-only image previews,
attachment cards, link buttons, and checkboxes. A field is a text field by default. Each text field starts with
the supplied value and must be non-empty to confirm unless it sets `optional: true`. An optional
text field that starts empty can also set `collapsed: true`, such as CC on an email: the web client
shows a small button with its label until the user opens it, and the CLI shows the field. Set
`inlineLabel: true` on a single-line text field to show its label to its left instead of above it,
for a compact form such as an email's To and Subject. Set `readOnly: true` on a text field to show
its value as plain text the user cannot edit, such as the email a reply answers: the web client
shows the first few lines in a box that scrolls, and the CLI shows the whole text. A read-only
field is omitted from the returned record. Set
`type: 'file'` to take a small text file such as a key or certificate: the web client shows a drop
zone that also opens the file picker (`accept: ['.p8']` filters it) with an option to paste the
text instead, the CLI takes a path on that computer or the pasted text, and the returned value is
the file's text. Files over 64 KiB or not valid UTF-8 are refused. Set `type: 'image'` to show an
HTTP or HTTPS image URL in the same field order. Set `type: 'attachment'` to show a file at an HTTP
or HTTPS URL, such as an email attachment, as a card with its `label` as the file name, its
`mimeType` and `sizeBytes` when given, and a preview where the client can render one (in the web
app, an image shows a thumbnail that opens it in the lightbox). Set `type: 'link'` to show a button labelled with the field's `label` that
opens an HTTP or HTTPS URL in the browser, for example an approval page in another app; the dialog
stays open, so the user can still confirm or cancel afterwards. In the CLI, `Ctrl+O` opens the
first link. Image, attachment, and link fields are not editable, do not affect required field
validation, and are omitted from the returned record. Set `removable: true` on an image or
attachment field to let the user remove it before confirming; the returned record then includes
the field, with its `value` when kept or an empty string when removed. Set `type: 'checkbox'` to
show a box the user can tick, with `label` as its text, such as "Always allow replies in this
thread"; set `value: 'true'` to start it ticked. Its returned value is always `'true'` or
`'false'`, and `'false'` when the client cannot show the box (the CLI does not), so treat only
`'true'` as the user's choice. Cancelling returns
`undefined`. Without `fields`, `confirm` keeps returning a boolean. Set `expandButtonText` to start
a long form collapsed: the web client first shows only the title, the message, and a button with
that text, and shows the fields and the confirm button after the user clicks it. Set
`collapsedMessage` to show different text while collapsed, such as a short case for connecting, and
keep the details in `message`. The CLI shows the whole form and `message` immediately. Set
`iconURL` to an HTTP or HTTPS image URL, such as a service logo, to show it before the title in the
web client.

```ts
const values = await ctx.ui.confirm({
	title: 'Review content',
	message: 'Check these values before continuing.',
	confirmButtonText: 'Continue',
	fields: [
		{ name: 'title', label: 'Title', value: 'Weekly update' },
		{ name: 'cc', label: 'CC', value: '', optional: true, collapsed: true },
		{ name: 'content', label: 'Content', value: 'Hello team,', multiline: true },
		{
			name: 'preview',
			label: 'Rendered preview',
			type: 'image',
			value: 'https://example.com/weekly-update.png',
		},
		{
			name: 'approval',
			label: 'Review in Approvals',
			type: 'link',
			value: 'https://approvals.example.com/requests/42',
		},
		{
			name: 'report',
			label: 'weekly-update.pdf',
			type: 'attachment',
			value: 'https://example.com/weekly-update.pdf',
			mimeType: 'application/pdf',
			sizeBytes: 182_000,
			removable: true,
		},
	],
})

if (!values) return
const attachReport = values.report !== ''
```

**Web app:**
		<img src="https://static.ampcode.com/docs/plugin-web-confirm-link.png" alt="A plugin confirmation dialog in the Amp web app with an optional note field and an Open request in Approvals link button" width="1082" height="609" />

**CLI:**
		<img src="https://static.ampcode.com/docs/plugin-tui-confirm-link.png" alt="A plugin confirmation dialog in the Amp CLI with an optional note field, an Open request in Approvals link, and a Ctrl+O open link hint" width="810" height="313" />

```ts
const environment = await ctx.ui.select({
	title: 'Choose an environment',
	message: 'Select a known environment or enter another one.',
	allowOther: true,
	options: ['Development', 'Staging', 'Production'],
})
```

Set `requireHuman: true` on an `input`, `confirm`, or `select` dialog to require a human response
rather than an agent response. The thread owner can answer these dialogs. While multiplayer is
active, human contributors can also answer interactive selections, confirmations, and non-secret
inputs, including dialogs with `requireHuman: true`. Secret inputs remain owner-only and always
require a human. Dialogs targeted to a specific connection are not shared with contributors.

Use `requireHuman` for approval and permission prompts. It does not grant agents access to dialogs
or enable them to answer on the owner's behalf. When a person sends a new message to the thread
while a tool shows a `requireHuman` dialog, the dialog closes without an answer and the tool call
ends as cancelled, so the agent can act on the message.

```ts
const approved = await ctx.ui.confirm({
	title: 'Deploy to production?',
	message: 'This restarts the API servers.',
	confirmButtonText: 'Deploy',
	requireHuman: true,
})
```

To record who answered, such as who approved a change, pass an `onAnswered` callback to an
`input`, `confirm`, or `select` dialog. Amp calls it with details about the answer and resolves
the dialog with the usual answer only after the callback returns (or its promise settles), so the
details are ready once you have the answer. `responder.userID` is the Amp
user ID of the person who answered, who can be a contributor rather than the user in
`ctx.system.user`. `responder` is undefined when no person answered, such as a
`skipIfUnwatched` dialog nobody saw.

```ts
let approver: string | undefined
const approved = await ctx.ui.confirm({
	title: 'Ship this pull request?',
	requireHuman: true,
	onAnswered: ({ responder }) => {
		approver = responder?.userID
	},
})
```

### Call Tools Directly

Use `ctx.tools.call(name, input)` in a command, tool, event handler, or webhook to call a tool
without asking a model. Calls use the handler's current thread and return the tool's result.
A command needs an active, connected thread. Local tools run on that thread's executor.
Server-managed MCP tools use the thread owner's connection, including OAuth token refresh.
Plugins never receive the OAuth credentials.

Use the bare name for built-in and plugin tools, such as `Read`. For MCP, use the
`module.function` name shown by `tool_search`, such as `github.issue_read`. Local MCP tools also
accept `mcp__server__tool` names. To find a name and its input schema:

- Ask Amp to use `tool_search` in the target thread. Plugins can call it too:
  `await ctx.tools.call('tool_search', { query: 'github.issue_read' })`.
- Inspect a server's tools in your [personal MCP settings](/settings/integrations) or
  [workspace MCP settings](/workspace/integrations), or run
  `amp mcp remote tools github --personal --json`. These show the server's original tool names;
  `tool_search` shows the module and export names to use here.
- For local tools, run `amp tools list` and `amp tools show <name> --json`.

Normal tool permissions and confirmation dialogs still apply. Unknown, disabled, denied, or
failed calls reject the promise, including MCP `isError: true` responses. Successful MCP calls
return an MCP `CallToolResult` with `content`, `structuredContent`, and metadata when present.
Subagent tools and durable waits such as `wait_for_threads` are not supported.

Calls do not add messages to the transcript or start an agent turn. They have a five-minute
deadline, including time spent waiting for approval. If the connection is lost, Amp does not
retry the call: it reports that the outcome is unknown. Check whether a write took effect before
retrying it. An event handler that calls tools can trigger more tool events; restrict it to the
tools it needs to avoid recursion.

#### Example: Bring a GitHub Issue Into the Thread

Connect [GitHub's MCP server](https://github.com/github/github-mcp-server) at
`https://api.githubcopilot.com/mcp/` in your [personal MCP settings](/settings/integrations) or
[workspace MCP settings](/workspace/integrations) and sign in. This command asks for an issue
URL, fetches its details through your existing connection, and adds them to the current thread.
It assumes the server's ID is `github`; adjust the module name if yours differs.

```ts
import type { PluginAPI } from '@ampcode/plugin'

export default function (amp: PluginAPI) {
	amp.registerCommand('github-issue', { title: 'Bring in GitHub issue' }, async (ctx) => {
		if (!ctx.thread) throw new Error('Open a thread first')
		const url = await ctx.ui.input({ title: 'GitHub issue URL' })
		if (!url) return
		const match = /^https:\/\/github\.com\/([^/]+)\/([^/]+)\/issues\/(\d+)\/?$/.exec(url.trim())
		if (!match) throw new Error('Enter a GitHub issue URL')

		const result = await ctx.tools.call('github.issue_read', {
			method: 'get',
			owner: match[1],
			repo: match[2],
			issue_number: Number(match[3]),
		})
		await ctx.thread.appendUserMessage({
			type: 'user-message',
			content: `Use this GitHub issue as context: ${url}\n\n${JSON.stringify(result)}`,
		})
	})
}
```

### Use Thread-Scoped AI

Use `amp.ai.ask(...)` when a plugin needs a small yes/no classification decision with reasoning.
This helper runs through the current thread; pass `{ threadID }` when calling it outside a
thread-bound handler. AI helper calls default to no reasoning; pass `{ reasoningEffort }` to opt in
for models that support it.

```ts
import type { PluginAPI } from '@ampcode/plugin'

export default function (amp: PluginAPI) {
	amp.on('agent.start', async (event, ctx) => {
		const answer = await amp.ai.ask(
			`Is this request asking to change production infrastructure? ${event.message}`,
		)

		if (answer.result === 'yes') {
			await ctx.ui.notify(`This looks production-related: ${answer.reason}`)
		}
	})
}
```

Use `amp.ai.decide(...)` when a plugin needs many small decisions and does not need reasoning or
prose. It asks a decision model, which does not generate text: it answers typed questions about a
`state` with calibrated probabilities in well under a second. Each question is a `choice` (pick
one of 2–20 options), a `noul` (probability that a condition holds), or a `score` (a distribution
over 2–10 ordered levels). All questions in one call are answered against the same `state` in one
round trip, and the answer type of each question is inferred from the request, so
`answers.route.choice` is typed as the option names you passed. For a single question,
`amp.ai.choice(...)`, `amp.ai.noul(...)`, and `amp.ai.score(...)` return one `ChoiceAnswer`,
`NoulAnswer`, or `ScoreAnswer`.

TypeSafe's Jev (`typesafe/jev`) answers by default. Pass `model: 'openai/gpt-6-luna'` to ask
OpenAI's Decisions API instead. See
[Decision Models](/docs/customize/decision-models#select-a-decision-model) for how to choose
between them. The two models are calibrated differently, so tune thresholds for
the model you ask; `result.model` reports the exact version that answered. A workspace can disable
a model provider. The call then rejects instead of asking the other model, so name the model the
workspace allows, and handle the error where a decision is optional. A decision answered by OpenAI
is billed like other OpenAI inference in the thread. The typed shape is guaranteed; the answer can
still be wrong, and text inside `state` can steer it, so keep the thresholds and the control flow
in your plugin.

```ts
import type { PluginAPI } from '@ampcode/plugin'

export default function (amp: PluginAPI) {
	amp.on('tool.call', async (event, ctx) => {
		const command = amp.helpers.shellCommandFromToolCall(event)
		if (!command) return { action: 'allow' }

		const { answers } = await amp.ai.decide({
			state: command.command,
			questions: {
				destructive: {
					type: 'noul',
					instructions:
						'Does this shell command delete or overwrite data outside a scratch directory?',
				},
				scope: {
					type: 'choice',
					instructions: 'What does the command mostly touch?',
					criteria: { files: 'Local files', git: 'Git history or remotes', network: null },
				},
			},
		})

		if (answers.destructive.noul > 0.8 || answers.scope.choice === 'git') {
			const ok = await ctx.ui.confirm({
				title: `Run ${answers.scope.choice} command?`,
				message: command.command,
			})
			return ok
				? { action: 'allow' }
				: { action: 'reject-and-continue', message: 'Declined by user' }
		}
		return { action: 'allow' }
	})
}
```

### Label the Thread

Use `ctx.thread.labels()`, `ctx.thread.addLabels(...)`, and `ctx.thread.setLabels(...)` to read
and change the current thread's labels. `addLabels` keeps the labels the user already applied;
`setLabels` replaces them. Labels are lowercased, deduplicated, and limited to alphanumeric
characters and hyphens, at most 32 characters each and 20 per thread. Both methods resolve with
the thread's resulting labels. Combined with `amp.ai.choice(...)`, this labels a thread by what
it worked on once the turn ends:

```ts
import type { PluginAPI } from '@ampcode/plugin'

export default function (amp: PluginAPI) {
	amp.on('agent.end', async (event, ctx) => {
		const { choice, confidence } = await amp.ai.choice({
			state: event.message,
			instructions: 'What kind of work did this turn mostly do?',
			criteria: { bugfix: null, feature: null, refactor: null, docs: null, other: null },
		})
		if (choice !== 'other' && confidence > 0.7) {
			await ctx.thread.addLabels([choice])
		}
	})
}
```

### Show Quick Actions

`ctx.thread.createQuickAction(...)` shows a button above the thread's composer in the Amp web app,
after Amp's own quick actions. A quick action is not tied to a turn: it stays until you call
`unsubscribe()` on the handle it returns or the plugin stops, and `update(...)` changes it in
place. Create, change, and remove quick actions whenever your plugin learns something, such as in
an `agent.end` handler, a webhook, or a command. Amp shows up to 5 per thread across all plugins,
oldest first.

Each quick action has its `text` (1 to 40 characters), an optional `icon`, an `action`, and the
`args` that action takes:

| `action`       | `args`                | What a click does                                                                                     |
| -------------- | --------------------- | ----------------------------------------------------------------------------------------------------- |
| `send-message` | `{ message: string }` | Sends `message` as the user's next message. ⌘/Ctrl-click puts it in the composer to edit first.       |
| `open-url`     | `{ url: string }`     | Opens an `http:` or `https:` URL in a new browser tab.                                                |
| `copy`         | `{ text: string }`    | Copies `text` to the clipboard.                                                                       |
| `run-command`  | `{ command: string }` | Runs a command this plugin registered with `amp.registerCommand(...)`. It needs a connected executor. |
| `open-pane`    | `{ pane: string }`    | Opens a pane, as in [Open Panes](#open-panes).                                                        |
| `open-portal`  | `{ url: string }`     | Opens a URL in the Portal pane, as in [Open Panes](#open-panes).                                      |

`icon` is one of `activity`, `archive`, `bug`, `check`, `copy`, `external-link`, `eye`,
`flask-conical`, `git-pull-request`, `message-square`, `play`, `refresh-cw`, `rocket`, `send`,
`sparkles`, or `terminal`, named as in [Lucide](https://lucide.dev). Without one, the button shows
the action's icon, or for `open-pane`, the pane's icon. A quick action that opens a pane the
thread cannot show, such as `desktop` outside an orb, is hidden. `createQuickAction` and `update`
throw when the definition is invalid.

This plugin asks a decision model whether each turn finished the work, and offers to ship it:

```ts
import type { PluginAPI, QuickAction } from '@ampcode/plugin'

export default function (amp: PluginAPI) {
	const shown = new Map<string, QuickAction>()

	amp.on('agent.end', async (event, ctx) => {
		shown.get(ctx.thread.id)?.unsubscribe()
		shown.delete(ctx.thread.id)
		if (event.status !== 'done') return

		const reply = event.messages.at(-1)
		const text =
			reply?.role === 'assistant'
				? reply.content.flatMap((block) => (block.type === 'text' ? [block.text] : [])).join('\n')
				: ''
		const { choice, confidence } = await amp.ai.choice({
			state: text.slice(-8000),
			instructions: 'Where does this reply leave the work?',
			criteria: { implemented: 'Done and verified, not shipped yet', other: null },
		})
		if (choice === 'implemented' && confidence > 0.7) {
			shown.set(
				ctx.thread.id,
				ctx.thread.createQuickAction({
					text: 'Send It',
					icon: 'rocket',
					action: 'send-message',
					args: { message: 'Send it' },
				}),
			)
		}
	})
}
```

### Open Panes

`ctx.ui.perform(...)` runs a UI action in the thread for the people viewing it in the Amp web app.
There are two:

| `action`      | `args`             | What it does                                                                      |
| ------------- | ------------------ | --------------------------------------------------------------------------------- |
| `open-pane`   | `{ pane: string }` | Opens the thread's `changes`, `files`, `terminal`, `desktop`, or `portal` pane.   |
| `open-portal` | `{ url: string }`  | Opens an `http:` or `https:` URL served from the thread's orb in the Portal pane. |

A pane that is already open is left as it is, even when another tab is in front of it, so a
plugin can run the same action on every event. The action reaches only the thread owner's open browser tabs, opens a pane only as a tab
beside the transcript (not on a phone), and does not take focus. It is not queued for viewers who
open the thread later. The same action objects work as quick actions, where a click opens the pane
on any screen.

This plugin opens the Changes pane whenever the agent edits a file:

```ts
import type { PluginAPI, UIAction } from '@ampcode/plugin'

const EDIT_TOOLS = ['edit_file', 'create_file', 'apply_patch']
const showChanges: UIAction = { action: 'open-pane', args: { pane: 'changes' } }

export default function (amp: PluginAPI) {
	amp.on('tool.result', async (event, ctx) => {
		if (event.status === 'done' && EDIT_TOOLS.includes(event.tool)) {
			await ctx.ui.perform(showChanges)
		}
	})
}
```

### Prefill the Composer

`ctx.ui.insertPromptText(text)` puts text at the cursor of the thread's composer without sending
it, so the user can finish the message. It reaches the thread owner's composer in the Amp CLI and
in the Amp web app tab in front of them. In the web app, typing `/` in an empty composer opens the
command palette, so a command like this one works like a slash command:

```ts
import type { PluginAPI } from '@ampcode/plugin'

export default function (amp: PluginAPI) {
	amp.registerCommand(
		'simple-english',
		{ title: 'simple-english', category: 'Skills' },
		async (ctx) => {
			await ctx.ui.insertPromptText('Use the simple-english skill to rewrite ')
		},
	)
}
```

<h3 id="define-a-custom-agent-mode">Define a Custom Agent Mode</h3>

Use `amp.createAgent(...)` and `amp.registerAgentMode(...)` to add a mode that appears alongside
Amp's models in supported clients. The mode shows up in the model selector under **Other Models**,
in the **Your Agents** group. See [Your Agents](/docs/model-selector#your-agents).
Write the mode description to state both what the mode does and when to use it.
Run `amp plugins show-agent-options` to list the model IDs and built-in tools available to custom
plugin agents.
External plugins must include one matching `// @amp-agent-mode ...` metadata comment with the mode
`key` and `label` for each registered mode. Clients use those comments for static discovery and show
a warning toast when a runtime registration does not match its directive. Multiple mode comments in
one plugin file are supported.

```ts
// @amp-agent-mode {"key":"architect","label":"architect"}

import type { PluginAPI } from '@ampcode/plugin'

export default function (amp: PluginAPI) {
	const architect = amp.createAgent({
		name: 'architect',
		model: 'openai/gpt-5.5',
		instructions: [
			'You are an architecture-focused Amp mode.',
			'Before editing code, map the current design, name the tradeoffs,',
			'and prefer small changes that preserve clear module boundaries.',
		].join(' '),
		tools: 'all',
		reasoningEffort: 'high',
		display: { label: 'architect', color: '#7c3aed' },
	})

	amp.registerAgentMode({
		key: 'architect',
		description:
			'Plans and implements changes with extra architecture scrutiny. Use for architecture-sensitive work.',
		agent: architect.definition,
	})
}
```

The optional `name` is part of the agent's identity. Amp includes
`You are <name>, a custom agent running in Amp.` in the base system prompt. Omit `name` to avoid
adding a named identity. The `label` only controls how the mode appears in the UI.

Set `omitDefaultSystemPrompt: true` to use your `instructions` verbatim as the entire system
prompt. Amp will not add its base prompt, identity, environment, or workspace guidance. Tool
definitions and conversation messages are unaffected. Omit the option or set it to `false` to keep
the default prompt. Declarative agents support the same option in `defineAgent({...})`; their
system prompt contains only `instructions.md`, without automatic MCP server guidance.

`model` is required. When you omit `instructions`, the agent runs
the model with Amp's own system prompt for it, the same prompt a normal thread on that model gets.
By default an agent gets the tools a normal thread on its model gets. Use `tools: { add: [...] }`
to add tools on top of that list, or `tools: { exclude: [...] }` to remove some.

```ts
const carefulReviewer = amp.createAgent({
	model: 'anthropic/claude-opus-5-5',
	instructions: 'Review changes with extra care. Never edit files.',
	tools: { add: ['mcp__linear__*'], exclude: ['edit_file'] },
})
```

Agents used to build on a built-in mode with `extends`. Amp ignores `extends` next to `model`, and
`createAgent` throws when an agent sets `extends` without `model`.

Setting `model` and `reasoningEffort` sets the agent's main model. Every Task subagent in a thread
that runs your agent uses the same model and effort. If you pass the older `oracle` or `subagents`
options, Amp ignores them.

This example runs the main agent and its Task subagents on GPT-6.1 Sol:

```ts
// @amp-agent-mode {"key":"gpt61s-everywhere","label":"GPT-6.1 Sol Everywhere"}

import type { PluginAPI } from '@ampcode/plugin'

export default function (amp: PluginAPI) {
	const sol = amp.createAgent({
		model: 'openai/gpt-6.1-sol',
		reasoningEffort: 'high',
		display: { label: 'GPT-6.1 Sol Everywhere', color: '#d97706' },
	})

	amp.registerAgentMode({
		key: 'gpt61s-everywhere',
		description:
			'Runs the main agent on GPT-6.1 Sol. Task subagents run the same model. ' +
			'Use when you want one model for the whole thread.',
		agent: sol.definition,
	})
}
```

The model you set covers the main agent and its subagents only.
[Supporting system models](/docs/models-and-subagents#system-models), such as image generation and
thread naming, keep their own routing, so setting `model` does not put every model call on that
model.

The optional `display` on `createAgent` travels with the agent definition, so threads created
from it — including by other plugins via a `thread.agent()` handle — show its label and color.
`registerAgentMode` defaults its `label` and `color` from the agent's `display`; pass them
explicitly to override.

Features set on `createAgent` are inherited by every thread created from that agent, as well as
Task and Read Thread calls. Features passed to
`agent.createThread(...)` are added to that list. If a registered mode requires features, include the
same `features` list in its `// @amp-agent-mode ...` metadata so clients can discover the requirements
before the plugin starts.

Custom mode keys and labels must be unique (case-insensitive), non-empty, 24 characters or less, and
must not conflict with built-in modes. Existing external plugins that register an agent mode without
the directive continue to load and their mode remains available, but clients warn until the plugin
adds matching metadata and is reloaded.

Plugin agents can create threads from interactive sessions, `amp --execute`, and `amp --no-tui`
runners. Modes from a live runner can also appear in the model selector on ampcode.com.

<h3 id="define-a-custom-subagent">Define a Custom Subagent</h3>

Create an agent and expose it through a plugin tool when you want the main agent to delegate a
specific kind of work on demand. The `parentThreadID` option keeps the subagent run connected to the
thread that invoked the tool.

```ts
import type { PluginAPI } from '@ampcode/plugin'

export default function (amp: PluginAPI) {
	const researcher = amp.createAgent({
		name: 'dependency-researcher',
		model: 'openai/gpt-5.5',
		instructions: [
			'You are a focused dependency research subagent.',
			'Research only the dependency and question named by the caller.',
			'Return concise findings with links to primary sources.',
		].join(' '),
		tools: 'all',
		reasoningEffort: 'medium',
	})

	amp.registerTool({
		name: 'dependency_research_subagent',
		description: 'Run a focused subagent for a dependency research request.',
		inputSchema: {
			type: 'object',
			properties: {
				request: {
					type: 'string',
					description: 'The dependency and question the subagent should research.',
				},
			},
			required: ['request'],
		},
		async execute(input, ctx) {
			const request = typeof input.request === 'string' ? input.request : ''
			if (!request.trim()) {
				return 'Missing research request.'
			}

			const result = await researcher.run(request, {
				parentThreadID: ctx.thread.id,
				timeoutMs: 10 * 60 * 1000,
			})

			return result.text
		},
	})
}
```

<h3 id="use-a-builtin-agent">Use a Built-in Agent</h3>

Use `amp.getBuiltinAgent(mode)` to get a handle for one of Amp's built-in agent modes
(`'low'`, `'medium'`, `'high'`, or `'ultra'`) instead of defining a custom agent. The deprecated
`'smart'`, `'deep'`, and `'rush'` modes are still accepted but spawn threads in their replacement
mode (`'rush'` → `'low'`; `'smart'`/`'deep'` → `'medium'`).

You can also pass the `provider/model` ID of a model from the model picker, such as
`amp.getBuiltinAgent('anthropic/claude-opus-5-5')`. Threads from that handle run exactly like a
thread you start on that model in the model picker, with the same system prompt, tools, model, and
default reasoning effort. Amp refuses to create the thread if the thread's owner cannot use that
model. Any other key throws.

Both custom and built-in agent handles support `run(message, options?)` for a one-shot run and
`createThread(options?)` for a thread you can keep appending messages to. Pass `parentThreadID` to
connect the new thread to its parent. From a command handler without `ctx.thread`, use
`createThread({ show: true })` to create a thread and make it active in supported clients.
Pass `executor: 'orb'` to `run(...)` or `createThread(...)` to start the thread in an orb when
the current client supports orb-backed thread creation. To target a live Amp runner, pass
`executor: { type: 'runner', id }`. For workspace Orb threads created with `createThread(...)`,
pass `multiplayerTTLSeconds` to enable multiplayer for 5 minutes through 7 days.
By default, Amp picks the project whose Git remote matches the plugin's working directory, which
in an Orb is its repository checkout. When several projects use the same repository, that may not
be the one you want. To choose the project yourself, pass `project` with any ref that
`amp --project` accepts, such as `'acme/research'`. The new thread then gets that project's
repository, secrets, and workspace. Don't take `project` from
untrusted input such as a webhook payload. Whoever controls it could run threads in any project
you can access, with that project's secrets.

```ts
import type { PluginAPI } from '@ampcode/plugin'

export default function (amp: PluginAPI) {
	const high = amp.getBuiltinAgent('high')

	amp.registerCommand(
		'start-deep-dive',
		{ title: 'Start Deep Dive', description: 'Start a background high-mode thread' },
		async (ctx) => {
			const thread = await high.createThread({
				executor: 'orb',
				multiplayerTTLSeconds: 3 * 60 * 60,
			})
			await thread.appendUserMessage({
				type: 'user-message',
				content: 'Investigate flaky tests in the CI pipeline.',
			})
			await ctx.ui.notify(`Started background thread ${thread.id}`)
		},
	)
}
```

<h2 id="example-plugin-permissions">Example Plugin: Permissions</h2>

This plugin asks the user before running potentially destructive git commands. It uses `amp.ai.ask(...)` to classify each git command and only prompts when the command looks risky.

Save this as `.amp/plugins/no-destructive-git-operations.ts`, then run `plugins: reload`.

```ts
import type { PluginAIAskResult, PluginAPI } from '@ampcode/plugin'

/**
 * Plugin that prevents risky git operations by asking the user for confirmation.
 * Uses amp.ai.ask() to classify git commands as risky and prompts the user accordingly.
 */
export default function (amp: PluginAPI) {
	const safePatterns = [
		/^\s*git\s+status\b/,
		/^\s*git\s+log\b/,
		/^\s*git\s+diff\b/,
		/^\s*git\s+show\b/,
		/^\s*git\s+branch\s*$/,
		/^\s*git\s+branch\s+-[av]\b/,
		/^\s*git\s+stash\s+list\b/,
		/^\s*git\s+remote\s+-v\b/,
		/^\s*git\s+fetch\b/,
		/^\s*git\s+pull\b/,
		/^\s*git\s+add\b/,
		/^\s*git\s+commit\b/,
		/^\s*git\s+push\b(?!.*(-f|--force))/,
	]

	amp.on('tool.call', async (event, ctx) => {
		const shellCommand = amp.helpers.shellCommandFromToolCall(event)
		if (!shellCommand?.command) {
			return { action: 'allow' }
		}

		const command = shellCommand.command

		if (!/^\s*git\s+/.test(command)) {
			return { action: 'allow' }
		}

		if (safePatterns.some((pattern) => pattern.test(command))) {
			return { action: 'allow' }
		}

		const aiResponse: PluginAIAskResult = await amp.ai.ask(
			`Does this git command look like a potentially destructive operation that could lose work? Answer yes if it's a destructive operation like force push, branch deletion, reset, or checkout to detached HEAD. Command: ${command}`,
		)

		if (aiResponse.result === 'no') {
			return { action: 'allow' }
		}

		const confirmed = await ctx.ui.confirm({
			title: 'Potentially destructive git operation',
			message: `${command}\n\nReason: ${aiResponse.reason}\n\nDo you want to proceed?`,
			confirmButtonText: 'Allow',
		})

		if (confirmed) {
			return { action: 'allow' }
		}

		return {
			action: 'reject-and-continue',
			message: `User cancelled potentially destructive git operation: ${command}`,
		}
	})
}
```

<h2 id="example-plugin-btw">Example Plugin: BTW</h2>

This plugin adds a `BTW: Ask` command for quick side questions. It asks for the question with
`ctx.ui.input(...)`, creates a separate low-mode thread with `amp.getBuiltinAgent('low')` and
`createThread(...)`, waits for the answer with `waitForResponse(...)`, and shows it in a
`ctx.ui.confirm(...)` dialog with a button that opens the new thread. Your current thread is not
interrupted, and the side thread is linked to it through `parentThreadID`.

Save this as `.amp/plugins/btw.ts`, then run `plugins: reload`. Open the command palette and run
`BTW: Ask`.

**Web app:**
		<video controls loop muted playsinline preload="metadata" data-autoplay-in-view width="1100" height="720" aria-label="Asking a side question with the BTW plugin in the Amp web app" src="https://static.ampcode.com/docs/plugin-btw-web.mp4"></video>

**CLI:**
		<video controls loop muted playsinline preload="metadata" data-autoplay-in-view width="1600" height="1040" aria-label="Asking a side question with the BTW plugin in the Amp CLI" src="https://static.ampcode.com/docs/plugin-btw-tui.mp4"></video>

`ctx.system.open(...)` opens a URL on the machine running the plugin, so it only works when
`ctx.system.executor.kind` is `'local'`. In an orb, the plugin shows the thread URL in a
notification instead.

```ts
import type { PluginAPI } from '@ampcode/plugin'

export default function (amp: PluginAPI) {
	const low = amp.getBuiltinAgent('low')

	amp.registerCommand(
		'btw.ask',
		{
			title: 'Ask',
			category: 'BTW',
			description: 'Ask a quick side question in a separate thread',
		},
		async (ctx) => {
			const question = await ctx.ui.input({
				title: 'BTW',
				helpText: 'Ask a quick side question without interrupting this thread.',
				submitButtonText: 'Send',
			})
			if (!question?.trim()) {
				return
			}

			const btw = await low.createThread(ctx.thread ? { parentThreadID: ctx.thread.id } : {})
			await btw.appendUserMessage({
				type: 'user-message',
				content: `Answer in a few sentences: ${question}`,
			})
			await ctx.ui.notify('BTW sent.')

			const reply = await btw.waitForResponse({ timeoutMs: 2 * 60 * 1000 })
			const answer = reply.content
				.filter((block) => block.type === 'text')
				.map((block) => block.text)
				.join('\n')
				.trim()

			const open = await ctx.ui.confirm({
				title: 'BTW Response',
				message: answer || '(No response.)',
				confirmButtonText: 'Open BTW Thread',
			})
			if (!open) {
				return
			}

			// Orbs cannot open a browser on your machine, so show the URL instead.
			const url = new URL(`/threads/${btw.id}`, ctx.system.ampURL).href
			if (ctx.system.executor.kind === 'local') {
				await ctx.system.open(url)
			} else {
				await ctx.ui.notify(`BTW thread: ${url}`)
			}
		},
	)
}
```

<h2 id="example-plugin-turn-stats">Example Plugin: Turn Stats</h2>

This plugin times each agent turn and counts tool calls. It listens to `agent.start`,
`tool.result`, and `agent.end`, shows a live status item that ticks every second, sends a
notification when the turn ends, and adds a `Turn Stats: Show Turn Details` command that shows the
tool breakdown for the last turn. Clicking the status item runs that command through its
`command:` URL.

Status items appear in the CLI status line. Other clients ignore them, so the notification and the
command work everywhere while the live counter is CLI-only.

Plugins receive events for every thread the client hosts, including side threads such as the ones
the BTW plugin creates. The plugin compares `event.thread.id` with `amp.activeThread.current` so it
only tracks the thread you are looking at.

Save this as `.amp/plugins/turn-stats.ts`, then run `plugins: reload`.

**Web app:**
		<video controls loop muted playsinline preload="metadata" data-autoplay-in-view width="1100" height="720" aria-label="The Turn Stats plugin reporting turn duration and tool calls in the Amp web app" src="https://static.ampcode.com/docs/plugin-turn-stats-web.mp4"></video>

**CLI:**
		<video controls loop muted playsinline preload="metadata" data-autoplay-in-view width="1600" height="1040" aria-label="The Turn Stats plugin ticking in the status line and reporting tool calls in the Amp CLI" src="https://static.ampcode.com/docs/plugin-turn-stats-tui.mp4"></video>

```ts
import type { PluginAPI } from '@ampcode/plugin'

export default function (amp: PluginAPI) {
	let startedAt = 0
	let endedAt: number | null = null
	const toolCounts = new Map<string, number>()
	let ticker: ReturnType<typeof setInterval> | undefined

	const elapsedSeconds = () => Math.round(((endedAt ?? Date.now()) - startedAt) / 1000)
	const toolTotal = () => [...toolCounts.values()].reduce((sum, count) => sum + count, 0)
	const summary = () => {
		const total = toolTotal()
		return `${elapsedSeconds()}s · ${total} tool ${total === 1 ? 'call' : 'calls'}`
	}

	// Plugins receive events for every thread this client hosts, including side threads.
	// Only track the thread the user is looking at.
	const isActiveThread = (event: { thread: { id: string } }) =>
		event.thread.id === amp.activeThread.current?.id

	// Status items are shown in the TUI's status line; other clients ignore them.
	const status = amp.experimental?.createStatusItem()
	const render = () =>
		status?.update({
			text: `${endedAt === null ? '⏱' : '✓'} ${summary()}`,
			url: 'command:turn-stats.details',
		})

	amp.on('agent.start', (event) => {
		if (!isActiveThread(event)) {
			return {}
		}
		startedAt = Date.now()
		endedAt = null
		toolCounts.clear()
		clearInterval(ticker)
		ticker = setInterval(render, 1000)
		render()
		return {}
	})

	amp.on('tool.result', (event) => {
		if (!isActiveThread(event)) {
			return
		}
		toolCounts.set(event.tool, (toolCounts.get(event.tool) ?? 0) + 1)
		render()
	})

	amp.on('agent.end', async (event, ctx) => {
		if (!isActiveThread(event)) {
			return
		}
		endedAt = Date.now()
		clearInterval(ticker)
		render()
		await ctx.ui.notify(`Turn finished in ${summary()}.`)
	})

	amp.onDispose(() => clearInterval(ticker))

	amp.registerCommand(
		'turn-stats.details',
		{
			title: 'Show Turn Details',
			category: 'Turn Stats',
			description: 'Show how long the last turn took and which tools it used',
		},
		async (ctx) => {
			if (startedAt === 0) {
				await ctx.ui.notify('No turn has started yet.')
				return
			}
			const breakdown = [...toolCounts]
				.sort((a, b) => b[1] - a[1])
				.map(([tool, count]) => `${tool}: ${count}`)
				.join('\n')
			await ctx.ui.confirm({
				title: 'Last Turn',
				message: `${summary()}\n\n${breakdown || 'No tools were called.'}`,
				confirmButtonText: 'OK',
			})
		},
	)
}
```

<h2 id="example-plugin-goal">Example Plugin: /goal</h2>

This plugin gives Amp a `/goal` command: it keeps the agent working toward a goal instead of
stopping to report after each slice of work. `Goal: Set` asks for the goal with `ctx.ui.input(...)`
and appends it to the thread. On each `agent.end`, the plugin asks `amp.ai.ask(...)` whether the
last assistant message shows the goal is fully reached. If not, it returns `continue` with a
follow-up message. `Goal: Clear` stops the loop, and so does cancelling a turn.

By default Amp stops chaining plugin `continue` messages after five in a row. This plugin needs
more, so it sets `maxContinuations` on each `continue` result and pauses at its own cap of 50
instead, asking you to send a message. Any message from you starts a fresh chain, and the goal
stays set until it is reached or cleared.

Save this as `.amp/plugins/goal.ts`, then run `plugins: reload`. Open the command palette and run
`Goal: Set`.

```ts
import type { PluginAPI, ThreadID, ThreadMessage } from '@ampcode/plugin'

const marker = '[plugin:goal]'

// Amp allows five chained plugin `continue` messages by default. This plugin raises that limit
// through `maxContinuations` on each `continue` result and pauses at its own cap instead. Any
// message from the user starts a fresh chain.
const maxChainedContinues = 50

interface Goal {
	text: string
	chainedContinues: number
}

const lastAssistantText = (messages: ThreadMessage[]): string => {
	for (let i = messages.length - 1; i >= 0; i--) {
		const message = messages[i]
		if (message?.role !== 'assistant') {
			continue
		}
		const text = message.content
			.filter((block) => block.type === 'text')
			.map((block) => block.text)
			.join('\n')
			.trim()
		if (text) {
			return text
		}
	}
	return ''
}

export default function (amp: PluginAPI) {
	const goals = new Map<ThreadID, Goal>()

	amp.registerCommand(
		'goal.set',
		{
			title: 'Set',
			category: 'Goal',
			description: 'Keep the agent working until a goal is reached',
		},
		async (ctx) => {
			if (!ctx.thread) {
				await ctx.ui.notify('No active thread. Send a message first, then set a goal.')
				return
			}
			const text = await ctx.ui.input({
				title: 'Goal',
				helpText: 'Amp keeps working after each turn until this goal is reached.',
				submitButtonText: 'Set Goal',
			})
			if (!text?.trim()) {
				return
			}
			goals.set(ctx.thread.id, { text: text.trim(), chainedContinues: 0 })
			await ctx.thread.appendUserMessage({
				type: 'user-message',
				content: `${marker} Work toward this goal until it is fully reached. Do not stop to ask whether to continue.\n\nGoal: ${text.trim()}`,
			})
		},
	)

	amp.registerCommand(
		'goal.clear',
		{ title: 'Clear', category: 'Goal', description: 'Stop continuing toward the current goal' },
		async (ctx) => {
			if (ctx.thread && goals.delete(ctx.thread.id)) {
				await ctx.ui.notify('Goal cleared.')
				return
			}
			await ctx.ui.notify('No goal is set for this thread.')
		},
	)

	amp.on('agent.end', async (event, ctx) => {
		const goal = goals.get(event.thread.id)
		if (!goal) {
			return
		}

		// Cancelling a turn is how the user stops the loop.
		if (event.status !== 'done') {
			goals.delete(event.thread.id)
			await ctx.ui.notify(`Goal stopped: turn ${event.status}.`)
			return
		}

		// A turn the user started (not one of our continue messages) resets the chain.
		if (!event.message.includes(marker)) {
			goal.chainedContinues = 0
		}
		if (goal.chainedContinues >= maxChainedContinues) {
			await ctx.ui.notify(
				`Goal paused after ${maxChainedContinues} continues. Send any message to keep going, or run Goal: Clear.`,
			)
			return
		}

		const report = lastAssistantText(event.messages)
		const check = await amp.ai.ask(
			[
				`An agent is working toward this goal:\n${goal.text}`,
				`Its latest report:\n${report || '(no text)'}`,
				'Is the goal fully reached, with nothing left to do? Partial progress or a plan for remaining work means no.',
			].join('\n\n'),
		)

		if (check.result === 'yes') {
			goals.delete(event.thread.id)
			await ctx.ui.notify(`Goal reached: ${check.reason}`)
			return
		}

		goal.chainedContinues += 1
		return {
			action: 'continue',
			userMessage: `${marker} Not done yet (${check.reason}). Continue working toward the goal without stopping to report until it is reached.\n\nGoal: ${goal.text}`,
			maxContinuations: maxChainedContinues,
		}
	})
}
```

<h2 id="example-plugin-kitchen-sink">Example Plugin: Kitchen Sink</h2>

For a single plugin that exercises the core plugin surfaces — events, commands, tools, UI, and AI helpers — see the [Kitchen Sink example](/docs/plugin-api#example-plugin-kitchen-sink) on the Plugin API reference page.

## Acknowledgment

Amp's plugin API is inspired by [pi's extension API](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/docs/extensions.md), created by the awesome genius Mario Zechner.

See the [Plugin API reference](/docs/plugin-api) for the full `@ampcode/plugin` type reference.
