feat(plugins): hooks for agent launches and prompts, plus plugin dev hook (#37295)

* plugins: agent.launch.before and agent.prompt.before hooks; orca plugin dev hook

agent.launch.before runs at the PTY spawn every agent terminal goes through
(window tabs, runtime/CLI agent launch, automations, orchestration), before
dispatch to its host: change the command line, add env (Orca's own ORCA_*
variables and the agent's environment stay hidden), or deny. Restores and
resumes are not hooked. agent.prompt.before runs in sendTerminalAgentPrompt
(launch prompts, orchestration dispatch, terminal send to an agent) with the
agent named: rewrite or deny. The terminal hooks move into one runtime layer.
orca plugin dev hook runs a hook through one dev plugin and prints the decision.

Co-Authored-By: Claude <noreply@anthropic.com>

* plugins: recheck rewritten launch commands, forward hook env to WSL, keep prompt delivery outside the hook order

- A command agent.launch.before rewrote passes the AI Vault resume check again
  on both spawn paths.
- Variables a hook adds are named in WSLENV on Windows so WSL agents get them.
- agent.prompt.before holds the terminal's order only while it decides; a
  delivery waiting on a permission answer no longer blocks later input.

Co-Authored-By: Claude <noreply@anthropic.com>

* plugins: plugin dev hook honours onError: deny

Co-Authored-By: Claude <noreply@anthropic.com>

* plugins: regenerate the testing bundle and skill guides on the rebased hooks

Generated files only (lint-staged's oxlint refuses a commit with no lintable files).

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
Neil
2026-11-01 21:20:29 -08:00
committed by GitHub
co-authored by Claude
parent d9a070aa09
commit 60d262ebee
30 changed files with 753 additions and 72 deletions
+3 -1
View File
@@ -203,9 +203,11 @@ Hooks run in the workers of the Orca that handles the request, before it acts: f
| Hook | Event | Stop result | `next` may change | Summary |
| --- | --- | --- | --- | --- |
| `terminal.send` | `{ terminalId: string; text: string; enter: boolean; inputKind: "driving" \| "orchestration" \| "launch" }` | `{ deny: string }` | `text`, `enter` | Text Orca, the CLI or a plugin is about to send to a terminal. A person typing (on the desktop, a phone or a paired client) is never hooked, and prompts Orca submits to an agent are not included (a separate agent prompt hook covers them). Writes to one terminal stay in order while a hook decides. Rewrite `text` or `enter` with `next`, or return `{ deny }` to refuse the send. |
| `terminal.send` | `{ terminalId: string; text: string; enter: boolean; inputKind: "driving" \| "orchestration" \| "launch" }` | `{ deny: string }` | `text`, `enter` | Text Orca, the CLI or a plugin is about to send to a terminal. A person typing (on the desktop, a phone or a paired client) is never hooked, and prompts Orca submits to an agent take `agent.prompt.before` instead. Writes to one terminal stay in order while a hook decides. Rewrite `text` or `enter` with `next`, or return `{ deny }` to refuse the send. |
| `workspace.create.before` | `{ kind: "worktree" \| "folder"; projectId: string; name: string; branch?: string; base?: string }` | `{ deny: string }` | `name`, `branch`, `base` | A worktree or folder workspace is about to be created. Change `name`, `branch` or `base` with `next`, or return `{ deny }` to refuse it. |
| `workspace.create.after` | `{ workspaceId: string; kind: "worktree" \| "folder"; path: string; branch: string }` | none | nothing | A worktree or folder workspace was created. Observe only: Orca does not wait for it, and results are ignored. |
| `agent.launch.before` | `{ agent: string; workspaceId: string \| null; workspaceKind: "worktree" \| "folder" \| null; terminalId?: string; command: string; env: Record<string, string> }` | `{ deny: string }` | `command`, `env` | Orca is about to start an agent CLI in a terminal, from any launcher (new tab, workspace create, CLI, automation, orchestration). Change `command` or add `env` with `next`, or return `{ deny }` to refuse the launch. Restores of saved sessions are not hooked. |
| `agent.prompt.before` | `{ agent: string \| null; terminalId: string; prompt: string; inputKind: "driving" \| "orchestration" \| "launch" }` | `{ deny: string }` | `prompt` | Orca is about to submit a prompt to an agent in a terminal: a launch prompt, an orchestration dispatch, an issue or task prompt, or `orca terminal send` to an agent. A prompt a person submits is never hooked, and writes to one terminal stay in order while it decides. Rewrite `prompt` with `next`, or return `{ deny }` to refuse it. |
## Errors
+2 -2
View File
@@ -33,7 +33,7 @@ Add `"$schema": "https://raw.githubusercontent.com/stablyai/orca/main/docs/schem
| `contributes.panels` | [PanelContribution](#panelcontribution)[] | no | 1.4.160 | Sidebar panels. At most 64. |
| `contributes.commands` | [CommandContribution](#commandcontribution)[] | no | 1.4.160 | Command palette entries. At most 256. |
| `contributes.events` | [EventContribution](#eventcontribution)[] | no | 1.4.160 | Events delivered to the plugin worker. At most 4. |
| `contributes.hooks` | [HookContribution](#hookcontribution)[] | no | 1.4.248 | Hooks the worker runs before or after Orca acts; Orca waits only on plugins that list one. At most 3. |
| `contributes.hooks` | [HookContribution](#hookcontribution)[] | no | 1.4.248 | Hooks the worker runs before or after Orca acts; Orca waits only on plugins that list one. At most 5. |
| `contributes.languagePacks` | [LanguagePackContribution](#languagepackcontribution)[] | no | 1.4.160 | Interface translations. At most 16. |
| `contributes.keybindings` | [KeybindingContribution](#keybindingcontribution)[] | no | 1.4.160 | Keyboard shortcuts for contributed commands. At most 256. |
| `contributes.vmRecipes` | [VmRecipeContribution](#vmrecipecontribution)[] | no | 1.4.160 | Virtual machine environment recipes. At most 64. |
@@ -95,7 +95,7 @@ A hook Orca runs through the worker before (or after) it acts. Requires `main` a
| Field | Type | Required | Since | Description |
| --- | --- | --- | --- | --- |
| `event` | `"terminal.send"` \| `"workspace.create.before"` \| `"workspace.create.after"` | yes | 1.4.248 | Hook the worker handles with `orca.hooks.on`. |
| `event` | `"terminal.send"` \| `"workspace.create.before"` \| `"workspace.create.after"` \| `"agent.launch.before"` \| `"agent.prompt.before"` | yes | 1.4.248 | Hook the worker handles with `orca.hooks.on`. |
| `onError` | `"pass"` \| `"deny"` | no | 1.4.248 | What Orca does when this plugin's hook throws, times out, crashes or does not start: `pass` (the default) carries on as if it passed; `deny` refuses the action, naming the plugin, so a guard fails closed. Ignored for hooks that only observe. |
## LanguagePackContribution
@@ -218,9 +218,9 @@
},
"hooks": {
"default": [],
"description": "Hooks the worker runs before or after Orca acts; Orca waits only on plugins that list one. At most 3.",
"description": "Hooks the worker runs before or after Orca acts; Orca waits only on plugins that list one. At most 5.",
"x-orca-since": "1.4.248",
"maxItems": 3,
"maxItems": 5,
"type": "array",
"items": {
"$ref": "#/$defs/HookContribution"
@@ -724,14 +724,18 @@
"enum": [
"terminal.send",
"workspace.create.before",
"workspace.create.after"
"workspace.create.after",
"agent.launch.before",
"agent.prompt.before"
],
"description": "Hook the worker handles with `orca.hooks.on`.",
"x-orca-since": "1.4.248",
"x-orca-enum-since": {
"terminal.send": "1.4.248",
"workspace.create.before": "1.4.248",
"workspace.create.after": "1.4.248"
"workspace.create.after": "1.4.248",
"agent.launch.before": "1.4.248",
"agent.prompt.before": "1.4.248"
}
},
"onError": {
File diff suppressed because one or more lines are too long
+5 -1
View File
@@ -181,12 +181,16 @@ declare module 'orca/host' {
/** Worker `orca.hooks.on(hook, handler)`: the event each hook carries and its stop result. */
export type PluginHooks = {
/** Text Orca, the CLI or a plugin is about to send to a terminal. A person typing (on the desktop, a phone or a paired client) is never hooked, and prompts Orca submits to an agent are not included (a separate agent prompt hook covers them). Writes to one terminal stay in order while a hook decides. Rewrite `text` or `enter` with `next`, or return `{ deny }` to refuse the send. */
/** Text Orca, the CLI or a plugin is about to send to a terminal. A person typing (on the desktop, a phone or a paired client) is never hooked, and prompts Orca submits to an agent take `agent.prompt.before` instead. Writes to one terminal stay in order while a hook decides. Rewrite `text` or `enter` with `next`, or return `{ deny }` to refuse the send. */
"terminal.send": { event: { terminalId: string; text: string; enter: boolean; inputKind: "driving" | "orchestration" | "launch" }; result: { deny: string } }
/** A worktree or folder workspace is about to be created. Change `name`, `branch` or `base` with `next`, or return `{ deny }` to refuse it. */
"workspace.create.before": { event: { kind: "worktree" | "folder"; projectId: string; name: string; branch?: string; base?: string }; result: { deny: string } }
/** A worktree or folder workspace was created. Observe only: Orca does not wait for it, and results are ignored. */
"workspace.create.after": { event: { workspaceId: string; kind: "worktree" | "folder"; path: string; branch: string }; result: never }
/** Orca is about to start an agent CLI in a terminal, from any launcher (new tab, workspace create, CLI, automation, orchestration). Change `command` or add `env` with `next`, or return `{ deny }` to refuse the launch. Restores of saved sessions are not hooked. */
"agent.launch.before": { event: { agent: string; workspaceId: string | null; workspaceKind: "worktree" | "folder" | null; terminalId?: string; command: string; env: Record<string, string> }; result: { deny: string } }
/** Orca is about to submit a prompt to an agent in a terminal: a launch prompt, an orchestration dispatch, an issue or task prompt, or `orca terminal send` to an agent. A prompt a person submits is never hooked, and writes to one terminal stay in order while it decides. Rewrite `prompt` with `next`, or return `{ deny }` to refuse it. */
"agent.prompt.before": { event: { agent: string | null; terminalId: string; prompt: string; inputKind: "driving" | "orchestration" | "launch" }; result: { deny: string } }
}
export type PluginHookName = keyof PluginHooks
}
+18 -18
View File
@@ -27,24 +27,24 @@ Pass `--json` to every `ORCA plugin` command and branch on `error.code`, not on
Use the lowest `execution` profile that covers the request; it decides what the user must approve.
| The user asks for | Build (manifest) | Start from |
| --------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------ |
| An app color theme | `data`; `contributes.themes` | `--template theme` |
| A terminal color palette | `data`; `contributes.terminalThemes` | `--template terminal-theme` |
| File icons | `data`; `contributes.iconThemes` | `--template icon-theme` |
| Highlighting for a language | `data`; `contributes.syntaxes` (TextMate grammar) | `--template syntax`; example `orca-gleam-syntax` |
| Orca's UI in another language | `data`; `contributes.languagePacks` | `--template language-pack` |
| A custom view or editor for a file type | `sandboxed-ui`; `contributes.customEditors`, optionally `newFiles` | `--template editor` |
| A sidebar panel of lists, forms, buttons, status | `sandboxed-ui`; `panels` entry `.tsx` with `"ui": "components"` | `--template components`; example `hello-tsx` |
| A sidebar panel needing its own HTML, canvas or libraries | `sandboxed-ui`; `panels` entry `.html` (or `.ts`/`.tsx`) | `--template panel` |
| A palette command or shortcut for a built-in Orca action | `declarative`; `commands[].action`, `keybindings` | hand-written; fields in `references/manifest.md` |
| A command that runs code, storage, secrets, terminal text | `trusted-worker`; `main`, `commands` (no `action`), `capabilities` | example `hello-orca` |
| A panel backed by its own Node code, storage or settings | `trusted-worker`; `main`, a panel, `capabilities`, `settings` | `--template worker-panel` |
| Settings the user edits in Orca's Settings | `contributes.settings` and `settings:own` | `references/manifest.md` |
| Reacting to workspace or agent status changes | `trusted-worker`; `main`, `contributes.events`, `*:read` capability | example `hello-orca` |
| Rewriting or refusing terminal text or workspace creates | `trusted-worker`; `main`, `contributes.hooks` | `--template hook`; `references/recipes.md` |
| A virtual machine environment recipe | `declarative`; `contributes.vmRecipes` | hand-written; fields in `references/manifest.md` |
| A status bar item (a worker can update it) | `declarative`; `contributes.statusBarItems` | `references/recipes.md` |
| The user asks for | Build (manifest) | Start from |
| ----------------------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------ |
| An app color theme | `data`; `contributes.themes` | `--template theme` |
| A terminal color palette | `data`; `contributes.terminalThemes` | `--template terminal-theme` |
| File icons | `data`; `contributes.iconThemes` | `--template icon-theme` |
| Highlighting for a language | `data`; `contributes.syntaxes` (TextMate grammar) | `--template syntax`; example `orca-gleam-syntax` |
| Orca's UI in another language | `data`; `contributes.languagePacks` | `--template language-pack` |
| A custom view or editor for a file type | `sandboxed-ui`; `contributes.customEditors`, optionally `newFiles` | `--template editor` |
| A sidebar panel of lists, forms, buttons, status | `sandboxed-ui`; `panels` entry `.tsx` with `"ui": "components"` | `--template components`; example `hello-tsx` |
| A sidebar panel needing its own HTML, canvas or libraries | `sandboxed-ui`; `panels` entry `.html` (or `.ts`/`.tsx`) | `--template panel` |
| A palette command or shortcut for a built-in Orca action | `declarative`; `commands[].action`, `keybindings` | hand-written; fields in `references/manifest.md` |
| A command that runs code, storage, secrets, terminal text | `trusted-worker`; `main`, `commands` (no `action`), `capabilities` | example `hello-orca` |
| A panel backed by its own Node code, storage or settings | `trusted-worker`; `main`, a panel, `capabilities`, `settings` | `--template worker-panel` |
| Settings the user edits in Orca's Settings | `contributes.settings` and `settings:own` | `references/manifest.md` |
| Reacting to workspace or agent status changes | `trusted-worker`; `main`, `contributes.events`, `*:read` capability | example `hello-orca` |
| Changing or refusing terminal text, workspace creates or agent launches and prompts | `trusted-worker`; `main`, `contributes.hooks` | `--template hook`; `references/recipes.md` |
| A virtual machine environment recipe | `declarative`; `contributes.vmRecipes` | hand-written; fields in `references/manifest.md` |
| A status bar item (a worker can update it) | `declarative`; `contributes.statusBarItems` | `references/recipes.md` |
Examples are in `examples/plugins/` of github.com/stablyai/orca. Sidebar cards, task sources,
connections, MCP servers and skills are reserved and not buildable yet: say so instead of faking
@@ -23,6 +23,7 @@
- `ORCA plugin dev reload [<dir>] [--approve <fingerprint>] [--json]`: Reload development plugins now, or one folder and re-check its approval
- `ORCA plugin dev inspect <plugin-key> [--json]`: Open DevTools for a plugin's open panels and editors
- `ORCA plugin dev emit <dir|plugin-key> <event> [--data <json>] [--json]`: Fire a test event at a development plugin's worker and open panels
- `ORCA plugin dev hook <dir|plugin-key> <hook> --data <json> [--json]`: Run a hook through a development plugin's worker and print what the chain decided
- `ORCA plugin dev request <dir|plugin-key> <name> [--data <json>] [--panel <id>] [--timeout-ms <ms>] [--json]`: Call a development plugin's worker handler the way a panel's plugin.request does
- `ORCA plugin dev unload <dir|plugin-key> [--json]`: Remove a development folder from Orca
- `ORCA plugin open <plugin-key> [--panel <id> | --editor <file>] [--json]`: Show a plugin's panel in Orca's right sidebar, or open a file in its editor
@@ -87,12 +87,16 @@ Host API 1.2 (`"pluginApi": 1`). Call `host.call(method, params, { signal })`; a
List each in `contributes.hooks` (`{ "event", "onError"? }`; `main` and `trusted-worker`) and handle it with `orca.hooks.on(event, (event, next) => ...)`. Return `next(event)` (or nothing) to go on, or the stop result. Plugins run in turn, 2 s each; a throw, timeout or crash passes unless the entry says `"onError": "deny"`. Decide first: an awaited call before you return (a notification, say) can fail or time out and turn your deny into a pass.
- `terminal.send` (since 1.4.248): Text Orca, the CLI or a plugin is about to send to a terminal. A person typing (on the desktop, a phone or a paired client) is never hooked, and prompts Orca submits to an agent are not included (a separate agent prompt hook covers them). Writes to one terminal stay in order while a hook decides. Rewrite `text` or `enter` with `next`, or return `{ deny }` to refuse the send.
- `terminal.send` (since 1.4.248): Text Orca, the CLI or a plugin is about to send to a terminal. A person typing (on the desktop, a phone or a paired client) is never hooked, and prompts Orca submits to an agent take `agent.prompt.before` instead. Writes to one terminal stay in order while a hook decides. Rewrite `text` or `enter` with `next`, or return `{ deny }` to refuse the send.
event `{ terminalId: string; text: string; enter: boolean; inputKind: "driving" | "orchestration" | "launch" }`; `next` may change `text`, `enter`; stop with `{ deny: string }`
- `workspace.create.before` (since 1.4.248): A worktree or folder workspace is about to be created. Change `name`, `branch` or `base` with `next`, or return `{ deny }` to refuse it.
event `{ kind: "worktree" | "folder"; projectId: string; name: string; branch?: string; base?: string }`; `next` may change `name`, `branch`, `base`; stop with `{ deny: string }`
- `workspace.create.after` (since 1.4.248): A worktree or folder workspace was created. Observe only: Orca does not wait for it, and results are ignored.
event `{ workspaceId: string; kind: "worktree" | "folder"; path: string; branch: string }`; `next` may change nothing; stop with nothing (observe only)
- `agent.launch.before` (since 1.4.248): Orca is about to start an agent CLI in a terminal, from any launcher (new tab, workspace create, CLI, automation, orchestration). Change `command` or add `env` with `next`, or return `{ deny }` to refuse the launch. Restores of saved sessions are not hooked.
event `{ agent: string; workspaceId: string | null; workspaceKind: "worktree" | "folder" | null; terminalId?: string; command: string; env: Record<string, string> }`; `next` may change `command`, `env`; stop with `{ deny: string }`
- `agent.prompt.before` (since 1.4.248): Orca is about to submit a prompt to an agent in a terminal: a launch prompt, an orchestration dispatch, an issue or task prompt, or `orca terminal send` to an agent. A prompt a person submits is never hooked, and writes to one terminal stay in order while it decides. Rewrite `prompt` with `next`, or return `{ deny }` to refuse it.
event `{ agent: string | null; terminalId: string; prompt: string; inputKind: "driving" | "orchestration" | "launch" }`; `next` may change `prompt`; stop with `{ deny: string }`
## Capabilities
@@ -36,7 +36,7 @@
- `panels` (PanelContribution[], since 1.4.160): Sidebar panels. At most 64.
- `commands` (CommandContribution[], since 1.4.160): Command palette entries. At most 256.
- `events` (EventContribution[], since 1.4.160): Events delivered to the plugin worker. At most 4.
- `hooks` (HookContribution[], since 1.4.248): Hooks the worker runs before or after Orca acts; Orca waits only on plugins that list one. At most 3.
- `hooks` (HookContribution[], since 1.4.248): Hooks the worker runs before or after Orca acts; Orca waits only on plugins that list one. At most 5.
- `languagePacks` (LanguagePackContribution[], since 1.4.160): Interface translations. At most 16.
- `keybindings` (KeybindingContribution[], since 1.4.160): Keyboard shortcuts for contributed commands. At most 256.
- `vmRecipes` (VmRecipeContribution[], since 1.4.160): Virtual machine environment recipes. At most 64.
@@ -80,7 +80,7 @@ An event subscription. Requires `main`, the `trusted-worker` execution profile a
A hook Orca runs through the worker before (or after) it acts. Requires `main` and the `trusted-worker` execution profile.
- `event` ("terminal.send" | "workspace.create.before" | "workspace.create.after", required, since 1.4.248): Hook the worker handles with `orca.hooks.on`.
- `event` ("terminal.send" | "workspace.create.before" | "workspace.create.after" | "agent.launch.before" | "agent.prompt.before", required, since 1.4.248): Hook the worker handles with `orca.hooks.on`.
- `onError` ("pass" | "deny", since 1.4.248): What Orca does when this plugin's hook throws, times out, crashes or does not start: `pass` (the default) carries on as if it passed; `deny` refuses the action, naming the plugin, so a guard fails closed. Ignored for hooks that only observe.
## LanguagePackContribution
@@ -85,10 +85,15 @@ export default function activate(orca: OrcaWorkerApi) {
}
```
Other hooks: `workspace.create.before`/`.after`, `agent.launch.before` (change the command line or
add `env`; the agent's own environment is never shown) and `agent.prompt.before` (rewrite a prompt
Orca submits to an agent).
Return `{ deny }` to stop, nothing (or `next(event)`) to pass. Past 2 s or on a throw Orca carries
on as if the hook passed and logs it (`ORCA plugin logs`); a guard that must fail closed lists the
hook as `{ "event": "terminal.send", "onError": "deny" }`. Decide before any other awaited call:
`await orca.host.call('notifications.show', …)` ahead of `return { deny }` can throw or time out and
let the action through, so count blocks after deciding (`void orca.host.call(...)`). Unit-test with
`(await mountWorker(worker)).hooks.fire('terminal.send', event)`, which returns
`{ kind: 'continue', event }` or `{ kind: 'deny', reason }`.
`{ kind: 'continue', event }` or `{ kind: 'deny', reason }`; against the loaded dev plugin,
`ORCA plugin dev hook . terminal.send --data '<json>'` prints the same decision.
+32 -22
View File
@@ -2592,24 +2592,24 @@ const ORCA_PLUGIN_AUTHORING_MARKDOWN = [
"",
"Use the lowest `execution` profile that covers the request; it decides what the user must approve.",
"",
"| The user asks for | Build (manifest) | Start from |",
"| --------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------ |",
"| An app color theme | `data`; `contributes.themes` | `--template theme` |",
"| A terminal color palette | `data`; `contributes.terminalThemes` | `--template terminal-theme` |",
"| File icons | `data`; `contributes.iconThemes` | `--template icon-theme` |",
"| Highlighting for a language | `data`; `contributes.syntaxes` (TextMate grammar) | `--template syntax`; example `orca-gleam-syntax` |",
"| Orca's UI in another language | `data`; `contributes.languagePacks` | `--template language-pack` |",
"| A custom view or editor for a file type | `sandboxed-ui`; `contributes.customEditors`, optionally `newFiles` | `--template editor` |",
"| A sidebar panel of lists, forms, buttons, status | `sandboxed-ui`; `panels` entry `.tsx` with `\"ui\": \"components\"` | `--template components`; example `hello-tsx` |",
"| A sidebar panel needing its own HTML, canvas or libraries | `sandboxed-ui`; `panels` entry `.html` (or `.ts`/`.tsx`) | `--template panel` |",
"| A palette command or shortcut for a built-in Orca action | `declarative`; `commands[].action`, `keybindings` | hand-written; fields in `references/manifest.md` |",
"| A command that runs code, storage, secrets, terminal text | `trusted-worker`; `main`, `commands` (no `action`), `capabilities` | example `hello-orca` |",
"| A panel backed by its own Node code, storage or settings | `trusted-worker`; `main`, a panel, `capabilities`, `settings` | `--template worker-panel` |",
"| Settings the user edits in Orca's Settings | `contributes.settings` and `settings:own` | `references/manifest.md` |",
"| Reacting to workspace or agent status changes | `trusted-worker`; `main`, `contributes.events`, `*:read` capability | example `hello-orca` |",
"| Rewriting or refusing terminal text or workspace creates | `trusted-worker`; `main`, `contributes.hooks` | `--template hook`; `references/recipes.md` |",
"| A virtual machine environment recipe | `declarative`; `contributes.vmRecipes` | hand-written; fields in `references/manifest.md` |",
"| A status bar item (a worker can update it) | `declarative`; `contributes.statusBarItems` | `references/recipes.md` |",
"| The user asks for | Build (manifest) | Start from |",
"| ----------------------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------------------------ |",
"| An app color theme | `data`; `contributes.themes` | `--template theme` |",
"| A terminal color palette | `data`; `contributes.terminalThemes` | `--template terminal-theme` |",
"| File icons | `data`; `contributes.iconThemes` | `--template icon-theme` |",
"| Highlighting for a language | `data`; `contributes.syntaxes` (TextMate grammar) | `--template syntax`; example `orca-gleam-syntax` |",
"| Orca's UI in another language | `data`; `contributes.languagePacks` | `--template language-pack` |",
"| A custom view or editor for a file type | `sandboxed-ui`; `contributes.customEditors`, optionally `newFiles` | `--template editor` |",
"| A sidebar panel of lists, forms, buttons, status | `sandboxed-ui`; `panels` entry `.tsx` with `\"ui\": \"components\"` | `--template components`; example `hello-tsx` |",
"| A sidebar panel needing its own HTML, canvas or libraries | `sandboxed-ui`; `panels` entry `.html` (or `.ts`/`.tsx`) | `--template panel` |",
"| A palette command or shortcut for a built-in Orca action | `declarative`; `commands[].action`, `keybindings` | hand-written; fields in `references/manifest.md` |",
"| A command that runs code, storage, secrets, terminal text | `trusted-worker`; `main`, `commands` (no `action`), `capabilities` | example `hello-orca` |",
"| A panel backed by its own Node code, storage or settings | `trusted-worker`; `main`, a panel, `capabilities`, `settings` | `--template worker-panel` |",
"| Settings the user edits in Orca's Settings | `contributes.settings` and `settings:own` | `references/manifest.md` |",
"| Reacting to workspace or agent status changes | `trusted-worker`; `main`, `contributes.events`, `*:read` capability | example `hello-orca` |",
"| Changing or refusing terminal text, workspace creates or agent launches and prompts | `trusted-worker`; `main`, `contributes.hooks` | `--template hook`; `references/recipes.md` |",
"| A virtual machine environment recipe | `declarative`; `contributes.vmRecipes` | hand-written; fields in `references/manifest.md` |",
"| A status bar item (a worker can update it) | `declarative`; `contributes.statusBarItems` | `references/recipes.md` |",
"",
"Examples are in `examples/plugins/` of github.com/stablyai/orca. Sidebar cards, task sources,",
"connections, MCP servers and skills are reserved and not buildable yet: say so instead of faking",
@@ -2722,6 +2722,7 @@ const ORCA_PLUGIN_AUTHORING_CLI_REFERENCE_MARKDOWN = [
"- `ORCA plugin dev reload [<dir>] [--approve <fingerprint>] [--json]`: Reload development plugins now, or one folder and re-check its approval",
"- `ORCA plugin dev inspect <plugin-key> [--json]`: Open DevTools for a plugin's open panels and editors",
"- `ORCA plugin dev emit <dir|plugin-key> <event> [--data <json>] [--json]`: Fire a test event at a development plugin's worker and open panels",
"- `ORCA plugin dev hook <dir|plugin-key> <hook> --data <json> [--json]`: Run a hook through a development plugin's worker and print what the chain decided",
"- `ORCA plugin dev request <dir|plugin-key> <name> [--data <json>] [--panel <id>] [--timeout-ms <ms>] [--json]`: Call a development plugin's worker handler the way a panel's plugin.request does",
"- `ORCA plugin dev unload <dir|plugin-key> [--json]`: Remove a development folder from Orca",
"- `ORCA plugin open <plugin-key> [--panel <id> | --editor <file>] [--json]`: Show a plugin's panel in Orca's right sidebar, or open a file in its editor",
@@ -2961,12 +2962,16 @@ const ORCA_PLUGIN_AUTHORING_HOST_API_REFERENCE_MARKDOWN = [
"",
"List each in `contributes.hooks` (`{ \"event\", \"onError\"? }`; `main` and `trusted-worker`) and handle it with `orca.hooks.on(event, (event, next) => ...)`. Return `next(event)` (or nothing) to go on, or the stop result. Plugins run in turn, 2 s each; a throw, timeout or crash passes unless the entry says `\"onError\": \"deny\"`. Decide first: an awaited call before you return (a notification, say) can fail or time out and turn your deny into a pass.",
"",
"- `terminal.send` (since 1.4.248): Text Orca, the CLI or a plugin is about to send to a terminal. A person typing (on the desktop, a phone or a paired client) is never hooked, and prompts Orca submits to an agent are not included (a separate agent prompt hook covers them). Writes to one terminal stay in order while a hook decides. Rewrite `text` or `enter` with `next`, or return `{ deny }` to refuse the send.",
"- `terminal.send` (since 1.4.248): Text Orca, the CLI or a plugin is about to send to a terminal. A person typing (on the desktop, a phone or a paired client) is never hooked, and prompts Orca submits to an agent take `agent.prompt.before` instead. Writes to one terminal stay in order while a hook decides. Rewrite `text` or `enter` with `next`, or return `{ deny }` to refuse the send.",
" event `{ terminalId: string; text: string; enter: boolean; inputKind: \"driving\" | \"orchestration\" | \"launch\" }`; `next` may change `text`, `enter`; stop with `{ deny: string }`",
"- `workspace.create.before` (since 1.4.248): A worktree or folder workspace is about to be created. Change `name`, `branch` or `base` with `next`, or return `{ deny }` to refuse it.",
" event `{ kind: \"worktree\" | \"folder\"; projectId: string; name: string; branch?: string; base?: string }`; `next` may change `name`, `branch`, `base`; stop with `{ deny: string }`",
"- `workspace.create.after` (since 1.4.248): A worktree or folder workspace was created. Observe only: Orca does not wait for it, and results are ignored.",
" event `{ workspaceId: string; kind: \"worktree\" | \"folder\"; path: string; branch: string }`; `next` may change nothing; stop with nothing (observe only)",
"- `agent.launch.before` (since 1.4.248): Orca is about to start an agent CLI in a terminal, from any launcher (new tab, workspace create, CLI, automation, orchestration). Change `command` or add `env` with `next`, or return `{ deny }` to refuse the launch. Restores of saved sessions are not hooked.",
" event `{ agent: string; workspaceId: string | null; workspaceKind: \"worktree\" | \"folder\" | null; terminalId?: string; command: string; env: Record<string, string> }`; `next` may change `command`, `env`; stop with `{ deny: string }`",
"- `agent.prompt.before` (since 1.4.248): Orca is about to submit a prompt to an agent in a terminal: a launch prompt, an orchestration dispatch, an issue or task prompt, or `orca terminal send` to an agent. A prompt a person submits is never hooked, and writes to one terminal stay in order while it decides. Rewrite `prompt` with `next`, or return `{ deny }` to refuse it.",
" event `{ agent: string | null; terminalId: string; prompt: string; inputKind: \"driving\" | \"orchestration\" | \"launch\" }`; `next` may change `prompt`; stop with `{ deny: string }`",
"",
"## Capabilities",
"",
@@ -3038,7 +3043,7 @@ const ORCA_PLUGIN_AUTHORING_MANIFEST_REFERENCE_MARKDOWN = [
"- `panels` (PanelContribution[], since 1.4.160): Sidebar panels. At most 64.",
"- `commands` (CommandContribution[], since 1.4.160): Command palette entries. At most 256.",
"- `events` (EventContribution[], since 1.4.160): Events delivered to the plugin worker. At most 4.",
"- `hooks` (HookContribution[], since 1.4.248): Hooks the worker runs before or after Orca acts; Orca waits only on plugins that list one. At most 3.",
"- `hooks` (HookContribution[], since 1.4.248): Hooks the worker runs before or after Orca acts; Orca waits only on plugins that list one. At most 5.",
"- `languagePacks` (LanguagePackContribution[], since 1.4.160): Interface translations. At most 16.",
"- `keybindings` (KeybindingContribution[], since 1.4.160): Keyboard shortcuts for contributed commands. At most 256.",
"- `vmRecipes` (VmRecipeContribution[], since 1.4.160): Virtual machine environment recipes. At most 64.",
@@ -3082,7 +3087,7 @@ const ORCA_PLUGIN_AUTHORING_MANIFEST_REFERENCE_MARKDOWN = [
"",
"A hook Orca runs through the worker before (or after) it acts. Requires `main` and the `trusted-worker` execution profile.",
"",
"- `event` (\"terminal.send\" | \"workspace.create.before\" | \"workspace.create.after\", required, since 1.4.248): Hook the worker handles with `orca.hooks.on`.",
"- `event` (\"terminal.send\" | \"workspace.create.before\" | \"workspace.create.after\" | \"agent.launch.before\" | \"agent.prompt.before\", required, since 1.4.248): Hook the worker handles with `orca.hooks.on`.",
"- `onError` (\"pass\" | \"deny\", since 1.4.248): What Orca does when this plugin's hook throws, times out, crashes or does not start: `pass` (the default) carries on as if it passed; `deny` refuses the action, naming the plugin, so a guard fails closed. Ignored for hooks that only observe.",
"",
"## LanguagePackContribution",
@@ -3285,13 +3290,18 @@ const ORCA_PLUGIN_AUTHORING_RECIPES_REFERENCE_MARKDOWN = [
"}",
"```",
"",
"Other hooks: `workspace.create.before`/`.after`, `agent.launch.before` (change the command line or",
"add `env`; the agent's own environment is never shown) and `agent.prompt.before` (rewrite a prompt",
"Orca submits to an agent).",
"",
"Return `{ deny }` to stop, nothing (or `next(event)`) to pass. Past 2 s or on a throw Orca carries",
"on as if the hook passed and logs it (`ORCA plugin logs`); a guard that must fail closed lists the",
"hook as `{ \"event\": \"terminal.send\", \"onError\": \"deny\" }`. Decide before any other awaited call:",
"`await orca.host.call('notifications.show', …)` ahead of `return { deny }` can throw or time out and",
"let the action through, so count blocks after deciding (`void orca.host.call(...)`). Unit-test with",
"`(await mountWorker(worker)).hooks.fire('terminal.send', event)`, which returns",
"`{ kind: 'continue', event }` or `{ kind: 'deny', reason }`.",
"`{ kind: 'continue', event }` or `{ kind: 'deny', reason }`; against the loaded dev plugin,",
"`ORCA plugin dev hook . terminal.send --data '<json>'` prints the same decision.",
"",
].join('\n')
+23
View File
@@ -9,6 +9,12 @@ export type PluginDevEmitReply = {
delivered: { worker: boolean; panels: number }
}
export type PluginDevHookReply = {
pluginKey: string
event: string
decision: { kind: 'continue'; event: unknown } | { kind: 'deny'; reason: string }
}
/** `--data` as JSON; shared by `dev emit` and `dev request`. */
export function parseDataFlag(ctx: HandlerContext): unknown {
const raw = stringFlag(ctx, 'data')
@@ -26,6 +32,23 @@ export function parseDataFlag(ctx: HandlerContext): unknown {
}
export const PLUGIN_DEV_EMIT_HANDLERS: Record<string, CommandHandler> = {
'plugin dev hook': async (ctx) => {
const target = devTargetParams(ctx, requirePluginPathArg(ctx, 'target'))
const event = requirePluginPathArg(ctx, 'event')
const result = await callPlugins<PluginDevHookReply>(ctx, 'plugins.devHook', {
...target,
event,
payload: parseDataFlag(ctx)
})
const decision = result.decision
printPluginResult(
ctx,
result,
decision.kind === 'deny'
? `${result.event}: denied by ${result.pluginKey}: ${decision.reason}`
: `${result.event}: continue with ${JSON.stringify(decision.event)}`
)
},
'plugin dev emit': async (ctx) => {
const target = devTargetParams(ctx, requirePluginPathArg(ctx, 'target'))
const event = requirePluginPathArg(ctx, 'event')
+1 -1
View File
@@ -39,7 +39,7 @@ export const PLUGIN_HANDLER_GROUPS: readonly HandlerGroup[] = [
},
{
name: 'plugin-dev-emit',
keys: ['plugin dev emit'],
keys: ['plugin dev emit', 'plugin dev hook'],
load: async () => (await import('./handlers/plugin-dev-emit.js')).PLUGIN_DEV_EMIT_HANDLERS
},
{
+1
View File
@@ -67,6 +67,7 @@ export const ROOT_HELP_TEXT_PRIMARY = [
' plugin dev reload Reload development plugins',
" plugin dev inspect Open DevTools for a plugin's open frames",
" plugin dev emit Fire a test event at a dev plugin's worker",
" plugin dev hook Run a hook through a dev plugin's worker",
" plugin dev request Call a dev plugin's worker handler like a panel",
' plugin dev unload Remove a development folder',
'',
+16
View File
@@ -1,6 +1,22 @@
import type { CommandSpec } from '../args'
import { GLOBAL_FLAGS } from '../args'
/** `orca plugin dev hook`; listed in PLUGIN_RUNTIME_COMMAND_SPECS. */
export const PLUGIN_DEV_HOOK_COMMAND_SPEC: CommandSpec = {
path: ['plugin', 'dev', 'hook'],
summary: "Run a hook through a development plugin's worker and print what the chain decided",
usage: 'orca plugin dev hook <dir|plugin-key> <hook> --data <json> [--json]',
allowedFlags: [...GLOBAL_FLAGS, 'target', 'event', 'data'],
positionalArgs: ['target', 'event'],
notes: [
"Runs the worker's `orca.hooks.on` handlers with that plugin as the only one in the chain, under the same deadline and checks as a real hook; nothing in Orca acts on the result. The plugin must be an approved development plugin listing the hook in contributes.hooks.",
"--data is the hook's event as JSON (the host API reference lists them). Prints `{ pluginKey, event, decision }`, where decision is `{ kind: 'continue', event }` or `{ kind: 'deny', reason }`. A timeout or throw counts as passing and shows in `orca plugin logs`."
],
examples: [
'orca plugin dev hook . terminal.send --data \'{"terminalId":"t1","text":"rm -rf /","enter":true,"inputKind":"driving"}\''
]
}
/** `orca plugin dev request`; listed in PLUGIN_RUNTIME_COMMAND_SPECS. */
export const PLUGIN_DEV_REQUEST_COMMAND_SPEC: CommandSpec = {
path: ['plugin', 'dev', 'request'],
+2 -1
View File
@@ -1,7 +1,7 @@
import type { CommandSpec } from '../args'
import { GLOBAL_FLAGS, LOCAL_COMMAND_FLAGS } from '../args'
import { PLUGIN_TEMPLATE_NAMES } from '../plugin-authoring/plugin-template-names'
import { PLUGIN_DEV_REQUEST_COMMAND_SPEC } from './plugin-dev-request'
import { PLUGIN_DEV_HOOK_COMMAND_SPEC, PLUGIN_DEV_REQUEST_COMMAND_SPEC } from './plugin-dev-request'
const TEMPLATES = PLUGIN_TEMPLATE_NAMES.join('|')
@@ -283,6 +283,7 @@ export const PLUGIN_RUNTIME_COMMAND_SPECS: CommandSpec[] = [
'orca plugin dev emit acme.notes agent.status.changed --data \'{"workspaceId":null,"paneKey":"p1","state":"done","receivedAt":1}\' --json'
]
},
PLUGIN_DEV_HOOK_COMMAND_SPEC,
PLUGIN_DEV_REQUEST_COMMAND_SPEC,
{
path: ['plugin', 'dev', 'unload'],
+4
View File
@@ -5,6 +5,7 @@ import { checkPtyIpcLaunchPane, resolveEarlyPaneKey } from './spawn-begin'
import { stopReplacedPaneOwner } from '../pane/pane-owner-replacement'
import { keepAbsentBindingForSwap } from './spawn-absent-binding-swap'
import { planPaneAgentLaunch } from './spawn-agent-launch'
import { applyAgentLaunchPluginHook } from '../spawn-agent-launch-plugin-hook'
import { endPaneAgentLaunch } from './spawn-agent-launch-end'
import { preparePtyIpcSpawnPreflight } from './spawn-preflight'
import { assemblePtyIpcSpawnEnv } from './spawn-env'
@@ -46,6 +47,9 @@ export async function runPtyIpcSpawn(deps: PtySpawnIpcDeps, request: PtySpawnIpc
if (ctx.args.agentLaunch !== undefined) {
await planPaneAgentLaunch(ctx)
}
if (!ctx.earlyStablePaneOwner) {
ctx.args = await applyAgentLaunchPluginHook(ctx.args, deps.runtime)
}
await preparePtyIpcSpawnPreflight(ctx)
await assemblePtyIpcSpawnEnv(ctx)
await preparePtyIpcQoderCommand(ctx)
+2
View File
@@ -2,6 +2,7 @@ import { runPtySpawn, normalizePtySpawnSessionId } from '../spawn-operation'
import { requireAcceptedSpawn } from '../spawn-outcome'
import type { PtyRuntimeControllerDeps } from './controller-deps'
import { prepareRuntimePtySpawn } from './spawn-preflight'
import { applyAgentLaunchPluginHook } from '../spawn-agent-launch-plugin-hook'
import { buildRuntimePtySpawnOptions } from './spawn-options'
import { commitRuntimePtySpawn } from './spawn-commit'
import { createRuntimePtySpawnState, type RuntimePtySpawnArgs } from './spawn-state'
@@ -21,6 +22,7 @@ export async function spawnPtyFromRuntimeController(
const outcome = await runPtySpawn({
state: ctx,
prepare: async () => {
ctx.args = await applyAgentLaunchPluginHook(ctx.args, deps.runtime)
await prepareRuntimePtySpawn(ctx)
await buildRuntimePtySpawnOptions(ctx)
},
@@ -0,0 +1,67 @@
import { PLUGIN_HOOK_SPECS } from '../../../shared/plugins/events/plugin-hook-payloads'
import { isRestoreSpawnIntent } from '../../../shared/host-spawn-admission'
import type { TuiAgent } from '../../../shared/tui-agent'
import { workspaceKindForWorktreeId } from '../../../shared/workspace-launch-kind'
import { pluginHookWanted, runPluginHook } from '../../plugins/hooks/plugin-hook-dispatch'
import { assertLegacyAiVaultResumeCommandAllowed } from '../../ai-vault/structured-session-ownership'
import { addWslEnvKeys } from '../../../shared/wsl-env'
type AgentSpawnArgs = {
launchAgent?: TuiAgent
command?: string
env?: Record<string, string>
worktreeId?: string
preAllocatedHandle?: string
spawnIntent?: unknown
resumeOrigin?: unknown
resumeProviderSession?: unknown
}
/**
* `agent.launch.before` at the one place every agent terminal starts (window, runtime, CLI,
* automation, orchestration), before the spawn goes to its host, so SSH, WSL and daemon terminals
* are decided on this Orca. Restores and resumes are not launches. Throws PluginHookDeniedError.
*/
export async function applyAgentLaunchPluginHook<Args extends AgentSpawnArgs>(
args: Args,
runtime: { ensureStructuredAgentSessionHost(): Promise<void> } | undefined
): Promise<Args> {
const { launchAgent, command } = args
if (
!launchAgent ||
!command ||
isRestoreSpawnIntent(args.spawnIntent) ||
args.resumeOrigin !== undefined ||
args.resumeProviderSession !== undefined ||
!pluginHookWanted('agent.launch.before')
) {
return args
}
const kind = args.worktreeId ? workspaceKindForWorktreeId(args.worktreeId) : null
const decided = await runPluginHook(
'agent.launch.before',
PLUGIN_HOOK_SPECS['agent.launch.before'].payload,
{
agent: launchAgent,
workspaceId: kind && kind !== 'floating' ? (args.worktreeId ?? null) : null,
workspaceKind: kind === 'folder' ? 'folder' : kind === 'git-worktree' ? 'worktree' : null,
...(args.preAllocatedHandle ? { terminalId: args.preAllocatedHandle } : {}),
command,
env: {}
}
)
if (decided.command !== command) {
// The caller checked its own command; a plugin's must not resume a chat-owned session either.
await assertLegacyAiVaultResumeCommandAllowed(
decided.command,
() => runtime?.ensureStructuredAgentSessionHost() ?? Promise.resolve()
)
}
const addedKeys = Object.keys(decided.env)
const env = addedKeys.length > 0 ? { ...args.env, ...decided.env } : undefined
if (env && process.platform === 'win32') {
// wsl.exe imports only the variables WSLENV names.
addWslEnvKeys(env, addedKeys)
}
return { ...args, command: decided.command, ...(env ? { env } : {}) }
}
@@ -0,0 +1,172 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { PluginHookName } from '../../../shared/plugins/contributions/plugin-hook-contribution'
import { runPluginHookChain } from '../../../shared/plugins/workers/plugin-hook-chain'
import type { PluginHookChainOutcome } from '../../../shared/plugins/workers/plugin-hook-chain'
import { applyAgentLaunchPluginHook } from '../../ipc/pty/spawn-agent-launch-plugin-hook'
import {
agentPromptHookApplies,
runAgentPromptPluginHook
} from '../../runtime/terminal/input/terminal-send-plugin-hook'
import { PluginHookDeniedError, setPluginHookRunner } from './plugin-hook-dispatch'
const { resumeCheck } = vi.hoisted(() => ({
resumeCheck: vi.fn<(command: string, ensureHost: () => Promise<void>) => Promise<void>>()
}))
vi.mock('../../ai-vault/structured-session-ownership', () => ({
assertLegacyAiVaultResumeCommandAllowed: resumeCheck
}))
const runtime = { ensureStructuredAgentSessionHost: vi.fn(async () => undefined) }
type Decide = (event: PluginHookName, payload: unknown) => PluginHookChainOutcome
function installRunner(decide: Decide, wanted: readonly PluginHookName[]) {
const run = vi.fn(async (event: PluginHookName, payload: unknown) => decide(event, payload))
setPluginHookRunner({ wants: (event) => wanted.includes(event), run })
return run
}
const rewrite =
(changes: Record<string, unknown>): Decide =>
(_event, payload) => ({ kind: 'continue', payload: { ...Object(payload), ...changes } })
afterEach(() => {
setPluginHookRunner(null)
resumeCheck.mockReset()
vi.unstubAllGlobals()
})
describe('agent.launch.before at the spawn', () => {
const launch = {
launchAgent: 'claude' as const,
command: "claude 'fix the bug'",
env: { ORCA_TERMINAL_HANDLE: 'h', PATH: '/bin' },
worktreeId: 'folder:notes',
preAllocatedHandle: 'term_1',
cols: 80
}
it('shows the agent, workspace and command but never the environment, and applies changes', async () => {
const run = installRunner(rewrite({ command: 'claude --verbose', env: { FOO: '1' } }), [
'agent.launch.before'
])
await expect(applyAgentLaunchPluginHook(launch, runtime)).resolves.toEqual({
...launch,
command: 'claude --verbose',
env: { ...launch.env, FOO: '1' }
})
expect(run).toHaveBeenCalledWith('agent.launch.before', {
agent: 'claude',
workspaceId: 'folder:notes',
workspaceKind: 'folder',
terminalId: 'term_1',
command: "claude 'fix the bug'",
env: {}
})
})
it('leaves restores, resumes, shells and unhooked launches alone', async () => {
const run = installRunner(rewrite({ command: 'x' }), ['agent.launch.before'])
for (const args of [
{ ...launch, spawnIntent: 'automatic-restore' },
{ ...launch, resumeOrigin: 'saved' },
{ ...launch, resumeProviderSession: { id: 's' } },
{ ...launch, launchAgent: undefined }
]) {
await expect(applyAgentLaunchPluginHook(args, runtime)).resolves.toBe(args)
}
expect(run).not.toHaveBeenCalled()
setPluginHookRunner(null)
await expect(applyAgentLaunchPluginHook(launch, runtime)).resolves.toBe(launch)
})
it('rechecks a rewritten command the way the caller checked its own', async () => {
installRunner(rewrite({ command: 'codex resume chat-owned' }), ['agent.launch.before'])
resumeCheck.mockRejectedValueOnce(new Error('owned by a chat'))
await expect(applyAgentLaunchPluginHook(launch, runtime)).rejects.toThrow('owned by a chat')
expect(resumeCheck).toHaveBeenCalledWith('codex resume chat-owned', expect.any(Function))
installRunner(rewrite({}), ['agent.launch.before'])
await applyAgentLaunchPluginHook(launch, runtime)
expect(resumeCheck).toHaveBeenCalledOnce()
})
it('names added variables in WSLENV on Windows so WSL agents receive them', async () => {
vi.stubGlobal('process', { ...process, platform: 'win32', env: { WSLENV: 'USERPROFILE/p' } })
installRunner(rewrite({ env: { FOO: '1' } }), ['agent.launch.before'])
const decided = await applyAgentLaunchPluginHook(launch, runtime)
expect(decided.env).toMatchObject({ FOO: '1', WSLENV: 'USERPROFILE/p:FOO' })
})
it('refuses the spawn on a deny', async () => {
installRunner(
() => ({ kind: 'deny', pluginKey: 'acme.policy', reason: 'no yolo' }),
['agent.launch.before']
)
await expect(applyAgentLaunchPluginHook(launch, runtime)).rejects.toBeInstanceOf(
PluginHookDeniedError
)
})
it('keeps Orca’s own variables out of a plugin’s reach', async () => {
const outcome = await runPluginHookChain({
event: 'agent.launch.before',
payload: {
agent: 'codex',
workspaceId: null,
workspaceKind: null,
command: 'codex',
env: {}
},
participants: ['acme.env'],
invoke: async (_key, payload) => ({
decision: 'continue',
payload: { ...Object(payload), env: { ORCA_AGENT_LAUNCH_TOKEN: 'stolen' } }
}),
log: vi.fn(),
now: () => 0
})
expect(outcome).toMatchObject({ kind: 'continue', payload: { env: {} } })
})
})
describe('agent.prompt.before', () => {
const allowed = vi.fn(async () => undefined)
const input = {
handle: 'term_1',
prompt: 'fix it',
inputKind: 'orchestration' as const,
agent: 'codex'
}
it('rewrites the prompt with the agent named and rechecks the rewrite', async () => {
const run = installRunner(rewrite({ prompt: 'be brief: fix it' }), ['agent.prompt.before'])
await expect(runAgentPromptPluginHook(input, allowed)).resolves.toBe('be brief: fix it')
expect(run).toHaveBeenCalledWith('agent.prompt.before', {
agent: 'codex',
terminalId: 'term_1',
prompt: 'fix it',
inputKind: 'orchestration'
})
expect(allowed).toHaveBeenCalledWith('be brief: fix it')
const refuse = vi.fn(async () => {
throw new Error('legacy writer refused')
})
await expect(runAgentPromptPluginHook(input, refuse)).rejects.toThrow('legacy writer refused')
})
it('denies, and never holds a person’s own prompt', async () => {
installRunner(
() => ({ kind: 'deny', pluginKey: 'acme.p', reason: 'secret' }),
['agent.prompt.before']
)
await expect(runAgentPromptPluginHook(input, allowed)).rejects.toThrow(
'agent.prompt.before denied by plugin acme.p: secret'
)
expect(agentPromptHookApplies({})).toBe(true)
expect(agentPromptHookApplies({ inputSource: 'programmatic' })).toBe(true)
expect(agentPromptHookApplies({ inputSource: 'desktop' })).toBe(false)
expect(agentPromptHookApplies({ inputSource: 'mobile' })).toBe(false)
setPluginHookRunner(null)
expect(agentPromptHookApplies({})).toBe(false)
})
})
@@ -0,0 +1,94 @@
import { PluginCliError } from '../../../shared/plugins/approval/plugin-cli-approval'
import {
isPluginHookName,
PLUGIN_HOOK_NAMES,
type PluginHookName
} from '../../../shared/plugins/contributions/plugin-hook-contribution'
import { PLUGIN_HOOK_SPECS } from '../../../shared/plugins/events/plugin-hook-payloads'
import { PLUGIN_WORKER_READY_TIMEOUT_MS } from '../../../shared/plugins/workers/plugin-host-protocol'
import { runPluginHookChain } from '../../../shared/plugins/workers/plugin-hook-chain'
import { isInvalidDiscoveredPlugin } from '../plugin-discovery'
import { assertPluginSystemEnabled, resolveDevPlugin } from '../plugin-dev-event-emit'
import type { PluginDevFolderLookup, PluginDevFolderTarget } from '../plugin-dev-folders'
import type { PluginEventDeliveryContext } from '../plugin-event-delivery'
import type { PluginWorkerHandle } from '../workers/plugin-host-process'
export type PluginDevHookService = PluginDevFolderLookup & {
options: { isPluginSystemEnabled: () => boolean }
eventDelivery: PluginEventDeliveryContext
}
export type PluginDevHookResult = {
pluginKey: string
event: PluginHookName
decision: { kind: 'continue'; event: unknown } | { kind: 'deny'; reason: string }
}
function refuse(message: string, nextSteps: string[]): PluginCliError {
return new PluginCliError('invalid_argument', message, { nextSteps })
}
/** `orca plugin dev hook`: one hook through the real chain, with one development plugin in it. */
export async function firePluginDevHook(input: {
service: PluginDevHookService
target: PluginDevFolderTarget
event: string
payload: unknown
}): Promise<PluginDevHookResult> {
const { service, event } = input
assertPluginSystemEnabled(service)
if (!isPluginHookName(event)) {
throw refuse(`${event} is not an Orca plugin hook.`, [
`Pass one of: ${PLUGIN_HOOK_NAMES.join(', ')}.`
])
}
const plugin = await resolveDevPlugin(
service,
input.target,
'dev hook only runs hooks through development plugins'
)
if (isInvalidDiscoveredPlugin(plugin) || !service.eventDelivery.isRuntimeApproved(plugin)) {
throw refuse(`${plugin.pluginKey} is not a valid, approved and enabled plugin.`, [
'Run `orca plugin dev load <dir>` and approve it with `--approve`.'
])
}
if (!plugin.manifest.main || !plugin.manifest.contributes.hooks.some((h) => h.event === event)) {
throw refuse(`${plugin.pluginKey} does not list ${event}.`, [
`Add { "event": "${event}" } to contributes.hooks (with \`main\`), then reload.`
])
}
const parsed = PLUGIN_HOOK_SPECS[event].payload.safeParse(input.payload ?? {})
if (!parsed.success) {
const issues = parsed.error.issues.map(
(issue) => `${issue.path.join('.') || '(event)'}: ${issue.message}`
)
throw refuse(`--data is not a valid ${event} event.`, [
...issues,
'The host API reference lists every hook event.'
])
}
let worker: PluginWorkerHandle | null = null
const outcome = await runPluginHookChain({
event,
payload: parsed.data,
participants: [plugin.pluginKey],
start: async () => {
worker = await service.eventDelivery.ensureWorker(plugin)
},
startTimeoutMs: PLUGIN_WORKER_READY_TIMEOUT_MS,
invoke: (_key, current, timeoutMs) =>
worker ? worker.runHook(event, current, timeoutMs) : Promise.reject(new Error('no worker')),
log: (pluginKey, line) => service.eventDelivery.logWarning(pluginKey)(line),
now: () => performance.now(),
failsClosed: () =>
plugin.manifest.contributes.hooks.some((h) => h.event === event && h.onError === 'deny')
})
return {
pluginKey: plugin.pluginKey,
event,
decision:
outcome.kind === 'deny'
? { kind: 'deny', reason: outcome.reason }
: { kind: 'continue', event: outcome.payload }
}
}
@@ -1,5 +1,9 @@
import { defineMethod } from '../core'
import { PluginDevEmitParams } from '../../../../shared/rpc-contract/plugins-params'
import {
PluginDevEmitParams,
PluginDevHookParams
} from '../../../../shared/rpc-contract/plugins-params'
import { firePluginDevHook } from '../../../plugins/hooks/plugin-dev-hook-fire'
import { emitPluginDevEvent } from '../../../plugins/plugin-dev-event-emit'
import { requirePluginService } from './plugins'
@@ -22,5 +26,23 @@ export const PLUGIN_DEV_EMIT_METHODS = [
payload: params.payload
})
}
}),
defineMethod({
name: 'plugins.devHook',
permission: 'host-admin',
params: PluginDevHookParams,
handler: async (params) => {
const service = requirePluginService()
await service.whenReady()
return firePluginDevHook({
service,
target:
params.pluginKey !== undefined
? { pluginKey: params.pluginKey }
: { path: params.path ?? '' },
event: params.event,
payload: params.payload
})
}
})
]
@@ -0,0 +1,120 @@
import { mkdtemp, realpath, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { fingerprintPluginConsent } from '../../../../shared/plugins/approval/plugin-consent-fingerprint'
import { pluginManifestSchema } from '../../../../shared/plugins/manifest/plugin-manifest'
import { devFolderConsentIdentity } from '../../../plugins/plugin-discovery'
import { PluginService } from '../../../plugins/plugin-service'
import type { PluginWorkerHandle } from '../../../plugins/workers/plugin-host-process'
import type { PluginWorkerFactory } from '../../../plugins/workers/plugin-worker-manager'
import { eraseRpcMethods, type RpcContext } from '../core'
import { PLUGIN_DEV_EMIT_METHODS } from './plugin-dev-emit'
import { setPluginServiceForRpc } from './plugins'
const roots: string[] = []
const services: PluginService[] = []
afterEach(async () => {
setPluginServiceForRpc(null)
await Promise.all(services.splice(0).map((service) => service.dispose()))
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: plugin handlers never touch the runtime.
const context: RpcContext = { runtime: {} as RpcContext['runtime'], caller: { kind: 'local-cli' } }
const manifest = pluginManifestSchema.parse({
manifestVersion: 1,
id: 'guard',
publisher: 'samples',
name: 'Guard',
version: '1.0.0',
engines: { orca: '>=1.4.248' },
pluginApi: 1,
main: 'worker.js',
contributes: { hooks: [{ event: 'terminal.send' }] }
})
function devHook() {
const method = eraseRpcMethods(PLUGIN_DEV_EMIT_METHODS).find(
(candidate) => candidate.name === 'plugins.devHook'
)
if (!method || 'stream' in method) {
throw new Error('plugins.devHook is missing')
}
return method
}
async function realService(answer: (payload: unknown) => unknown) {
const root = await realpath(await mkdtemp(join(tmpdir(), 'orca-dev-hook-rpc-')))
roots.push(root)
await writeFile(join(root, 'orca-plugin.json'), JSON.stringify(manifest))
await writeFile(join(root, 'worker.js'), 'export default function activate() {}')
const consent = fingerprintPluginConsent(manifest, await devFolderConsentIdentity(root))
const runHook = vi.fn(async (_event: string, payload: unknown) => answer(payload))
const factory = vi.fn<PluginWorkerFactory>(async (): Promise<PluginWorkerHandle> => ({
commands: [],
invokeCommand: vi.fn(async () => null),
requestFromPanel: vi.fn(),
runHook,
notifyDataChanged: vi.fn(),
deliverEvent: vi.fn(),
lastActivityAt: () => 1_700_000_000_000,
inFlightCount: () => 0,
dispose: vi.fn(async () => undefined),
kill: vi.fn(),
onExit: vi.fn()
}))
const service = new PluginService({
userDataPath: root,
hostVersion: '1.4.248',
isPluginSystemEnabled: () => true,
getDisabledPlugins: () => [],
getPluginConsents: () => ({ 'samples.guard': consent }),
getDevPluginPaths: () => [root],
workerFactory: factory
})
services.push(service)
await service.initialize()
setPluginServiceForRpc(service, { applyConsent: vi.fn(), applyEnablement: vi.fn() })
return { root, runHook }
}
const SEND = { terminalId: 't1', text: 'rm -rf /', enter: true, inputKind: 'driving' }
describe('plugins.devHook', () => {
it('runs the hook through the dev plugin and returns the decision', async () => {
const { root, runHook } = await realService(() => ({
decision: 'result',
result: { deny: 'blocked' }
}))
await expect(
devHook().handler({ path: root, event: 'terminal.send', payload: SEND }, context)
).resolves.toEqual({
pluginKey: 'samples.guard',
event: 'terminal.send',
decision: { kind: 'deny', reason: 'blocked' }
})
expect(runHook).toHaveBeenCalledWith('terminal.send', SEND, 2_000)
})
it('returns the changed event, and refuses unknown, unlisted or invalid input', async () => {
const { root } = await realService((payload) => ({
decision: 'continue',
payload: { ...Object(payload), text: 'ls' }
}))
await expect(
devHook().handler({ path: root, event: 'terminal.send', payload: SEND }, context)
).resolves.toMatchObject({ decision: { kind: 'continue', event: { ...SEND, text: 'ls' } } })
await expect(
devHook().handler({ path: root, event: 'terminal.write', payload: SEND }, context)
).rejects.toThrow(/not an Orca plugin hook/)
await expect(
devHook().handler({ path: root, event: 'agent.prompt.before', payload: {} }, context)
).rejects.toThrow(/does not list agent.prompt.before/)
await expect(
devHook().handler({ path: root, event: 'terminal.send', payload: { text: 1 } }, context)
).rejects.toThrow(/not a valid terminal.send event/)
})
})
@@ -219,7 +219,8 @@ export abstract class OrcaRuntimeWithControllerKnowsPtyIsLive extends OrcaRuntim
)
}
async sendTerminalAgentPrompt(
/** sendTerminalAgentPrompt once plugin hooks decided. */
protected async sendAgentPromptAfterPluginHooks(
handle: string,
prompt: string,
options: RuntimeAgentPromptWriteOptions
@@ -243,7 +244,7 @@ export abstract class OrcaRuntimeWithControllerKnowsPtyIsLive extends OrcaRuntim
: null
if (starting) {
const target = await starting
return { ...(await this.sendTerminalAgentPrompt(target, prompt, options)), handle }
return { ...(await this.sendAgentPromptAfterPluginHooks(target, prompt, options)), handle }
}
const pty = this.getLivePtyForHandle(handle)
if (pty) {
@@ -2,7 +2,10 @@ import type { RuntimeTerminalSend } from '../../../../shared/runtime-types'
import { assertLegacyAiVaultResumeCommandAllowed } from '../../../ai-vault/structured-session-ownership'
import type { RuntimeTerminalWriteOptions } from '../../runtime-terminal-writer'
import { OrcaRuntimeWithControllerKnowsPtyIsLive } from './terminal-input-dispatch'
import type { RuntimeAgentPromptWriteOptions } from '../../runtime-terminal-contracts'
import {
agentPromptHookApplies,
runAgentPromptPluginHook,
runTerminalSendPluginHook,
terminalHookOrderKind,
TerminalPluginHookOrder,
@@ -11,8 +14,9 @@ import {
type TerminalSendAction = { text?: string; enter?: boolean; interrupt?: boolean }
/** Text Orca writes to terminals passes plugin hooks first; with no plugin listing one, a write
* adds no await. */
/** Text and prompts Orca writes to terminals pass plugin hooks first (`terminal.send`,
* `agent.prompt.before`), in order per terminal; with no plugin listing one, a write adds no
* await. */
export abstract class OrcaRuntimeWithPluginHookedTerminalInput extends OrcaRuntimeWithControllerKnowsPtyIsLive {
protected readonly pluginHookOrder = new TerminalPluginHookOrder()
@@ -37,6 +41,33 @@ export abstract class OrcaRuntimeWithPluginHookedTerminalInput extends OrcaRunti
)
}
async sendTerminalAgentPrompt(
handle: string,
prompt: string,
options: RuntimeAgentPromptWriteOptions
): Promise<RuntimeTerminalSend> {
const hooked = agentPromptHookApplies(options)
return this.pluginHookOrder.run(
handle,
terminalHookOrderKind(hooked, {}, options),
prompt,
(value) => {
const pty = this.getLivePtyForHandle(handle)?.pty
return runAgentPromptPluginHook(
{
handle,
prompt: value,
inputKind: options.inputKind,
agent: pty?.foregroundAgent ?? pty?.launchAgent ?? null
},
(text) => this.assertRewrittenTerminalTextAllowed(text)
)
},
// Why outside the order: a delivery may wait on a permission answer (`onPermission: 'wait'`).
(final) => this.sendAgentPromptAfterPluginHooks(handle, final, options)
)
}
/** The checks callers ran on the original text, run again on what a plugin wrote. */
protected async assertRewrittenTerminalTextAllowed(text: string): Promise<void> {
await assertLegacyAiVaultResumeCommandAllowed(text, () =>
@@ -100,3 +100,39 @@ export class TerminalPluginHookOrder {
return decided.then(deliver)
}
}
/** Whether `agent.prompt.before` runs: prompts Orca, the CLI or a plugin submits, as for
* `terminal.send`; a person's own prompt is never held. */
export function agentPromptHookApplies(options: { inputSource?: TerminalInputSource }): boolean {
return (
(options.inputSource === undefined || options.inputSource === 'programmatic') &&
pluginHookWanted('agent.prompt.before')
)
}
/** `agent.prompt.before`, before the prompt is encoded for the agent. Throws PluginHookDeniedError. */
export async function runAgentPromptPluginHook(
input: {
handle: string
prompt: string
inputKind: Exclude<TerminalInputKind, 'query-reply'>
agent: string | null
},
/** The caller's checks on the original prompt, run again on what a plugin wrote. */
assertRewrittenAllowed: (prompt: string) => Promise<void>
): Promise<string> {
const { prompt } = await runPluginHook(
'agent.prompt.before',
PLUGIN_HOOK_SPECS['agent.prompt.before'].payload,
{
agent: input.agent,
terminalId: input.handle,
prompt: input.prompt,
inputKind: input.inputKind
}
)
if (prompt !== input.prompt) {
await assertRewrittenAllowed(prompt)
}
return prompt
}
@@ -7,7 +7,9 @@ import { pluginFieldDoc, PLUGIN_HOOKS_SINCE } from '../manifest/plugin-schema-fi
export const PLUGIN_HOOK_NAMES = [
'terminal.send',
'workspace.create.before',
'workspace.create.after'
'workspace.create.after',
'agent.launch.before',
'agent.prompt.before'
] as const
export const PLUGIN_HOOK_LIMIT = PLUGIN_HOOK_NAMES.length
@@ -17,7 +19,9 @@ export type PluginHookName = (typeof PLUGIN_HOOK_NAMES)[number]
export const PLUGIN_HOOK_SINCE: Record<PluginHookName, string> = {
'terminal.send': PLUGIN_HOOKS_SINCE,
'workspace.create.before': PLUGIN_HOOKS_SINCE,
'workspace.create.after': PLUGIN_HOOKS_SINCE
'workspace.create.after': PLUGIN_HOOKS_SINCE,
'agent.launch.before': PLUGIN_HOOKS_SINCE,
'agent.prompt.before': PLUGIN_HOOKS_SINCE
}
/** RPC error code for an action a plugin hook refused; `data` names the plugin and its reason. */
@@ -54,6 +54,43 @@ export const workspaceCreateAfterHookPayloadSchema = z.object({
branch: z.string().max(1024)
})
/** Variables a hook may add or override; Orca's own (`ORCA_*`) stay Orca's. */
export const pluginHookEnvSchema = z
.record(
z
.string()
.regex(/^[A-Za-z_][A-Za-z0-9_]*$/)
.max(256)
.refine((key) => !key.toUpperCase().startsWith('ORCA_'), 'ORCA_* variables are reserved'),
z.string().max(32 * 1024)
)
.refine((env) => Object.keys(env).length <= 64, 'at most 64 variables')
const workspaceKindSchema = z.enum(['worktree', 'folder'])
export const agentLaunchBeforeHookPayloadSchema = z.object({
/** The agent CLI, e.g. `claude` or `codex`. */
agent: z.string().min(1).max(64),
/** Null for a terminal outside any workspace. */
workspaceId: z.string().min(1).max(2048).nullable(),
workspaceKind: workspaceKindSchema.nullable(),
/** As `terminal.sendText` names it, when Orca has one before the process starts. */
terminalId: z.string().min(1).max(PLUGIN_TERMINAL_ID_MAX_LENGTH).optional(),
/** The command line Orca runs in the terminal's shell; a prompt given at launch is part of it. */
command: z.string().min(1).max(TERMINAL_INPUT_MAX_BYTES),
/** Starts empty: variables to add or override. Orca never shows the agent's environment. */
env: pluginHookEnvSchema
})
export const agentPromptBeforeHookPayloadSchema = z.object({
/** The agent running in the terminal, when Orca knows it. */
agent: z.string().min(1).max(64).nullable(),
terminalId: z.string().min(1).max(PLUGIN_TERMINAL_ID_MAX_LENGTH),
prompt: z.string().max(TERMINAL_INPUT_MAX_BYTES),
/** `launch`: the prompt an agent starts with; `driving`/`orchestration` as for `terminal.send`. */
inputKind: z.enum(['driving', 'orchestration', 'launch'])
})
export const PLUGIN_HOOK_SPECS = {
'terminal.send': {
payload: terminalSendHookPayloadSchema,
@@ -61,7 +98,7 @@ export const PLUGIN_HOOK_SPECS = {
mutable: ['text', 'enter'],
deadlineMs: PLUGIN_HOOK_DEFAULT_DEADLINE_MS,
summary:
'Text Orca, the CLI or a plugin is about to send to a terminal. A person typing (on the desktop, a phone or a paired client) is never hooked, and prompts Orca submits to an agent are not included (a separate agent prompt hook covers them). Writes to one terminal stay in order while a hook decides. Rewrite `text` or `enter` with `next`, or return `{ deny }` to refuse the send.'
'Text Orca, the CLI or a plugin is about to send to a terminal. A person typing (on the desktop, a phone or a paired client) is never hooked, and prompts Orca submits to an agent take `agent.prompt.before` instead. Writes to one terminal stay in order while a hook decides. Rewrite `text` or `enter` with `next`, or return `{ deny }` to refuse the send.'
},
'workspace.create.before': {
payload: workspaceCreateBeforeHookPayloadSchema,
@@ -78,6 +115,22 @@ export const PLUGIN_HOOK_SPECS = {
deadlineMs: PLUGIN_HOOK_DEFAULT_DEADLINE_MS,
summary:
'A worktree or folder workspace was created. Observe only: Orca does not wait for it, and results are ignored.'
},
'agent.launch.before': {
payload: agentLaunchBeforeHookPayloadSchema,
result: denyResultSchema,
mutable: ['command', 'env'],
deadlineMs: PLUGIN_HOOK_DEFAULT_DEADLINE_MS,
summary:
'Orca is about to start an agent CLI in a terminal, from any launcher (new tab, workspace create, CLI, automation, orchestration). Change `command` or add `env` with `next`, or return `{ deny }` to refuse the launch. Restores of saved sessions are not hooked.'
},
'agent.prompt.before': {
payload: agentPromptBeforeHookPayloadSchema,
result: denyResultSchema,
mutable: ['prompt'],
deadlineMs: PLUGIN_HOOK_DEFAULT_DEADLINE_MS,
summary:
'Orca is about to submit a prompt to an agent in a terminal: a launch prompt, an orchestration dispatch, an issue or task prompt, or `orca terminal send` to an agent. A prompt a person submits is never hooked, and writes to one terminal stay in order while it decides. Rewrite `prompt` with `next`, or return `{ deny }` to refuse it.'
}
} satisfies Record<PluginHookName, PluginHookSpec>
@@ -74,6 +74,9 @@ export const PluginDevEmitParams = z
message: 'pass exactly one of path or pluginKey'
})
/** `orca plugin dev hook`: one hook through a development plugin's worker alone. */
export const PluginDevHookParams = PluginDevEmitParams
/** `orca plugin dev request`: one `plugin.request` to a development plugin's worker. */
export const PluginDevRequestParams = z
.object({
+1
View File
@@ -1323,6 +1323,7 @@ export const RPC_PARAMS_BY_METHOD = {
'pairing.registerDeviceKey': RegisterDeviceKeyParamsSchema,
'plugins.consent': PluginRpcConsentParams,
'plugins.devEmit': PluginDevEmitParams,
'plugins.devHook': PluginDevEmitParams,
'plugins.devInspect': PluginDevInspectParams,
'plugins.devLoad': PluginDevLoadParams,
'plugins.devRequest': PluginDevRequestParams,