---
name: help-how-to-codemode-plugin
description: 'Add code-mode support to a Po package: contribute a namespace to exec and discover, replace the direct tool it supersedes, and ship the skill that teaches agents to use it.'
---

# Develop a code-mode plugin

Use this when a Po package should be driven from code mode: a `name` global in every `exec` script, typed by `discover`. A namespace replaces a large multi-action tool with small methods. It costs the model nothing until it calls `discover`, and a script can chain several calls and return only what matters.

## The rule

Every package that contributes a namespace ships a skill that teaches an agent to use it. The namespace carries types and one-line reference. The skill carries judgement: when to use it, ordering, what it refuses and why, and the mistakes to avoid. A namespace without a skill is half shipped.

Package how-to guides have two roles, gated differently. A code-mode guide teaches agents to use a plugin through `exec`. Code mode is always available, so its `codemode-how-to-<plugin>` guide carries `pinned: true`, no `when` gate, and is always active. A namespace offered only in one mode gates its guide on that mode instead: `selfImprove` on `PO_HELP_WHEN`, and the `computer` namespace on the `computer-use` mode condition. Its summary stays in the system prompt, outside the `load_skill` catalog and `search_skills`; the full body still loads by exact name. Read the base `how-to-codemode` guide first. A `help-how-to-<plugin>` guide, such as this one, teaches how to maintain or modify a plugin, and is gated on Help mode (`when: PO_HELP_WHEN`). Help guides and all other skills remain searchable. Never gate a code-mode guide behind Help.

## Contribute the namespace

- Build the namespace in `src/services/<name>Namespace/index.ts` and register it from the package's session `root.server.ts`. Inject the registry softly so the package still mounts without code mode: `context.inject([PO_CODEMODE_SERVICE], (scoped) => { const registration = readPoCodemode(scoped)?.register(source, namespace); return () => registration?.dispose(); })`.
- `name` is a lowercase identifier that is not reserved (`console`, `image`, `sleep`, `globalThis`). `summary` is one line, at most 600 characters, and appears in the `exec` description on every turn, so spend it on what the namespace is for.
- `declarations` is TypeScript for `discover({ namespace })`: `declare const <name>: { ... }`, one JSDoc line per member, and a named `interface` for every result. Keep the whole text under 24,000 characters.
- Return structured, JSON-safe data, not printed text, so scripts use fields instead of parsing. Deep-clone what you return so a script cannot mutate shared state.
- `portable: true` only when every member is JSON in, JSON out and safe on the edge host.

## Bind per run

`bind(run)` builds the members for one `exec` call. Every member must:

- refuse a run from another session: compare `run.sessionId` with the session the package serves;
- honour `run.signal` (`throwIfAborted`), refuse after `run.onDispose` cleanups ran, and re-check the package's own availability before and after the work;
- validate its input at the boundary, reusing the direct tool's validator or schema, and reject with an error that says how to fix the call;
- create the members object with `Object.create(null)` and expose nothing else.

## One code path

Do not copy the tool. Extract its body into a function both call (`runX(store, params, signal)`), so the tool and the namespace cannot drift. Reads that must not lock or write get their own path.

## Withdraw the tool it replaces

When the namespace covers every action of a direct tool, hide the tool while code mode is bound so the model has one surface. In the same `inject` callback that registers the namespace: `const restriction = agent.registerToolRestriction({ excludedTools: ['x'] })`, and dispose it with the registration. Keep the tool for hosts without code mode, and for remote MCP, which has no isolate.

## Show calls with the tool's own card

If the namespace replaces a tool that has a transcript card, record each call so the cockpit draws it with that card inside the `exec` card. In the member, after the work, call `run.record?.({ name: 'tasks.upsert', tool: 'task', args, ok, ms, result })`, where `tool` is the replaced tool's registered name, `args` is what that tool would have been called with, and `result` is what it would have returned (`{ content, details }`). Record failures too, with `ok: false` and `error`. Better still, run the call through the tool's own function, as `worktrees` does with `executeRunWorktreeTool`, so the card gets exactly the text and details it already parses. `exec` keeps text blocks only, at most 50 calls, and drops args or details over 16,000 characters. A namespace with no card, such as `browser`, records nothing and its calls simply do not appear.

## Subagents

Subagents borrow the parent's Po tools, `exec` included, and share the session's namespaces: they run under the parent's session id, so the session check in `bind` passes for them and they act on the same objects. Design members for two callers at once: do not assume one agent owns the browser page or task graph. A tool that needs the person to answer, since nobody answers a subagent, or that acts for the main agent itself, sets `mainAgentOnly: true` on its tool and subagents never receive it.

## Review or gate calls with operation hooks

Every direct headless tool call already runs through `operation_before` and `operation_after` hooks (`operation.kind: 'tool'`). A namespace member opts in by running its work through `run.operation?.(call, perform)`, with `call.name` such as `browser.fill` (`kind: 'codemode'`). Without `run.operation` (no headless host) just perform. Types live in `@agimon-ai/po-core/operationHook` and `@agimon-ai/po-core/codemode`.

- Register hooks from the session root with `agent.registerHook({ event: 'operation_before', handle(event, context) { ... } })` and dispose them in `onDispose`. Match on `event.operation`, and return `undefined` for calls you do not own.
- `event.lint` is the optional `po/lint-review` service (see `help-how-to-lint`). Check `lint.sessionId === context.sessionId` before using it, and pass `context.signal`.
- A before hook returns `block` (refuse; nothing runs), `approval` (ask the person), `args` (patch the arguments), `notes` (lines added to the result) and `meta` (handed to the same hook's `operation_after` as `beforeMeta`). Every block is evaluated before any approval, so an approval never overrides an error.
- `approval: { requirement, pin, describe, heldMessage? }` goes through po-approval. Approve mints one single-use grant keyed by session, hook owner, operation name and `pin`; the agent repeats the exact call, every hook runs again, and the grant is spent. Put the exact target and content in `pin`, and keep screenshots for `describe()`, which runs only for a new approval. A subagent, background script or unattended run gets the call refused rather than a card.
- An after hook sees `outcome` and applies only when it is `executed`: its `block` reports the call failed after it already ran, so say what stayed changed.
- A hook that throws fails open, unless the call was aborted. Fail closed yourself with `block` when a rule requires it.
- Give the call in-process helpers when a hook needs them: `recheck(exact)` rereads the target after a slow review, `capture()` reads the rendered result for an after review, `evidence()` saves files for the approval card. They are never persisted.
- po-browse `src/services/formReview` is the reference: form review as two hooks on `browser.fill` and `browser.type`.

## Ship the skill

- `src/prompts/codemode-how-to-<plugin>/SKILL.md` with `name` equal to the folder and a `description` that says when to use it. Refer to the base `how-to-codemode` guide for shared execution guidance.
- `resource/codemode-how-to-<plugin>.server.ts` with `defineResource({ name, description, kind: 'skill', pinned: true, path: packageResourcePath(...), read: () => readPackageResource(...) })`, and no `when`. When the model needs session facts (which servers or tools exist), build them in `read()` from the root's state and append them after the static text; keep the file useful on its own, list names only, sanitize names from external sources, and leave signatures to `discover`.
- A link in `llms.txt`, and `src/prompts` and `llms.txt` in `package.json` `files`.
- Examples in the skill are `exec` scripts. Say which calls change state, which are read-only, and what `exec` timeout a slow call needs (30 s by default, 120 s at most).

## Check

One test that fails if the logic breaks: the member list, each member named in `declarations`, a foreign session refused, abort and dispose refused, bad input rejected before any work, and one real write. Then measure the token change: the tool's description and schema should leave the prompt, the summary should enter it.
