Plugin API
Implement plugins against the published @subshell-ai/plugin-api contract.
Choose a plugin type
| Manifest type | Returned interface | Runs or configures |
|---|---|---|
agent-harness | SubshellPlugin | An agent CLI in a session on the selected execution machine. |
terminal | SubshellPlugin | A shell or other non-agent program in a session. |
network | NetworkPlugin | A network connection or publication on the server host. |
Types group plugins for people and select the required interface. Capabilities opt into supported features. Installing a harness doesn't install its executable on every node.
Start with Build a harness plugin for a runnable shell example or Build a network plugin for a fixture-tested network adapter.
Manifest contract
The package's package.json contains a subshell object:
| Field | Meaning |
|---|---|
apiVersion | Contract version required by the plugin. The implemented manifest API version is 2. |
id | Stable plugin ID, unique within an instance. Don't claim another package's or built-in plugin's ID. |
type | One of the three types above. |
name, description | Human-facing identity and explanation. |
entry | Path to the bundled ESM factory, relative to the package. |
detect | Binary name, environment override, and known paths used for manifest-driven detection. |
install | Optional unprivileged installation command and documentation link. This isn't a plugin package dependency installer. |
update | Optional unprivileged update command and documentation link, for a vendor that ships a dedicated verb. When absent, the node page's Update action runs install.command, so declare this where the vendor's install line isn't an updater. |
hostEnv | Optional names of execution-host environment values needed for path computation. |
network | Required for network plugins: supported platforms, exposure, login behavior, and optional privileged instructions. |
Known paths can be absolute or HOME-relative. Keep detection data in the manifest so a remote machine can locate a binary without loading plugin code. Prefer canonical HTTP(S) documentation URLs; unsupported schemes are refused in manifest links.
Network privilege instructions live under network.privileged, keyed by platform. Each step has label, command, and optional docsUrl and group. Steps with the same group form an ordered sequence; different groups are alternative installation routes. Omit group for one plain sequence. These commands are displayed for the operator to run; install.command is the separate unprivileged command the host can execute.
Only HTTP(S) URLs are accepted in docsUrl. An invalid manifest URL prevents loading. An invalid URL in a runtime hint is removed while its message remains visible. Use the exported isDocsUrl helper to validate links obtained from vendor output before returning them.
The npm package version is independent of apiVersion. Package 3.0.0, used by the tutorials, still exposes manifest API 2. A host implementing a lower API version refuses the manifest. A higher host version doesn't guarantee an older interface works: required members and capabilities are checked at load. Rebuild and test across contract changes.
Factory and loading
The ESM entry default-exports a factory. Use the type matching your interface:
import type {
HarnessPluginFactory,
NetworkPluginFactory,
} from "@subshell-ai/plugin-api";HarnessPluginFactory receives PluginHost and returns SubshellPlugin. NetworkPluginFactory returns NetworkPlugin. PluginFactory is their union, useful for a loader; using the narrower factory in your implementation keeps tests correctly typed.
Runtime-installed plugin code runs in the server process with its OS privileges. It isn't sandboxed. The host service restrictions guide supported behavior; a malicious plugin can bypass them using process privileges. See Security model.
Required harness members
| Member | Signature or return | Responsibility |
|---|---|---|
buildCommand | (input: BuildCommandInput) => string[] | Return separate argv elements beginning with the supplied resolved binary. |
validatePreset | (preset: PresetDefinition) => PresetValidationResult | Return { valid, issues }; each issue has field and message. |
capabilities | () => PluginCapability[] | Declare implemented optional features. |
PresetDefinition has name, env, flags, settings, and configIsolation, plus optional description and restartOnExit. validateGenericPreset checks common fields; add your own setting validation.
BuildCommandInput provides:
| Field | Use |
|---|---|
binary, cwd | Resolved executable and target-machine working directory. The host applies the directory. |
preset, extraFlags | Saved configuration and additional launch arguments. |
subshellName | Display name, or an empty string when no name is supplied. |
mcp | Optional rendered registration. Consume args; the host applies its env. |
harnessSession | Optional conversation id and mode, either start or resume. |
reporter | Optional host-resolved reporting command and arguments for execution on the pane's machine. |
Return argv without pre-quoting. The host handles quoting at the tmux shell boundary. Don't substitute the server's filesystem or executable paths for target-machine information.
MCP, resumption, and reporting
mcpRegistration(launch, configPath) returns fileContent and optional args and env in the agent's configuration dialect. McpLaunchSpec contains a resolved command and args for the stdio MCP server. Alternatively, mcpSetup(launch) returns automatic guidance or manual setup steps.
Resume support supplies allocateHarnessSessionId() and resumePath(id, cwd, hostEnv). The latter is a pure path computation; the host checks existence on the execution machine. Use the supplied conversation ID in both new and resumed launches rather than generating a second unrelated identity.
Attention hooks require supportsAttentionHooks: true and actual reporting hooks in the launch. Build those from reporter.command and reporter.args; omit hooks when it is absent. Don't assume the execution machine has Bun or the server's binary path.
Preview reporting declares the previews capability and a previews descriptor: { reporting: "extension" | "hooks", setup? }. The reporter POSTs the ports a harness's tooling serves to /api/subshells/:id/views/report with the pane's inherited bearer token. Only that subshell's own token may report. Send { ports: [{ port, title? }] }, at most 32 entries; titles are bounded and normalized, and a report carries no host, so it can only describe loopback. Reports are transient and are merged into the pane's view list.
Other optional members include parseVersion, parsePaneTitle, exitStatus, presetSettings, suggestedEnv, and suggestedFlags. See the exported types for complete field definitions.
When a harness titles its terminal with something other than the name the host supplied, implement parsePaneTitle(raw). The host removes escape sequences and control bytes and trims the result before calling it; strip the harness's own brand, run-state separator, or status glyph and return the session name, or "" when the title names nothing. Omit it when the title is the name itself.
Required network members
| Member | Signature or return | Responsibility |
|---|---|---|
status | (ctx: NetworkContext) => Promise<NetworkStatus> | Report verified state, addresses, and actionable hints. Routine vendor failures should not throw. |
join | (input: JoinInput, ctx) => Promise<JoinOutcome> | Confirm membership or return an interactive login URL and optional code. |
leave | (ctx) => Promise<void> | Leave membership, treating an already-left network as an ordinary condition. |
capabilities | () => PluginCapability[] | Declare the implemented optional network features. |
NetworkContext supplies the current server port, non-secret settings, and secrets.has(name). Re-read context on every call. A factory must not remember a publication port or settings value across calls.
NetworkStatus contains state, addresses, and hints, with optional login and identity information. States are not-installed, daemon-down, needs-privilege, needs-login, joined, and published. Unsupported operating systems come from manifest platform data rather than another status value.
A NetworkAddress has canonical origin url, scheme, human-facing label, and secureContext. The last field reports browser secure-context eligibility, not the mesh's transport encryption. PublishOutcome returns addresses and an optional supervised process; PublishRefusal returns { refused: NetworkHint }.
Capability requirements
| Capability | Harness requirement | Network requirement |
|---|---|---|
settings | presetSettings() | settingsFields() |
mcp | mcpRegistration or mcpSetup | Not applicable. |
resume | Both members of resume | Not applicable. |
attention | supportsAttentionHooks: true, with hooks implemented | Not applicable. |
previews | previews: { reporting: "extension" | "hooks" } | Not applicable. |
publish | Not applicable. | Both publish() and unpublish(). |
supervise | Not applicable. | supervisedProcess(ctx). |
guard | Not applicable. | requestGuard(ctx). |
A mismatched capability or missing required method makes the plugin fail loading. Don't declare a feature to obtain a UI control before implementing it.
Host services
| Service | Contract and constraints |
|---|---|
findBinary(name, envOverride, knownPaths) | Resolve an executable or return null. |
detectBinary(...) | Resolve an executable with a reason when unavailable. |
probeVersion(binary, args?) | Run a bounded probe and return trimmed output or null. |
shellQuote(value) | Quote one token when you must build an agent hook's shell command. Don't apply it to ordinary argv. |
log.debug, log.warn | Namespaced diagnostics; never log secrets. |
run(argv, opts?) | Execute an absolute-path command with bounds and an allowlisted environment. Inspect code, stdout, stderr, timedOut, and aborted. |
secrets.set, has, delete | Per-plugin persistent secret storage; no value-reading API. |
platform, homeDir, apiVersion | Server-host context and implemented contract version. |
run accepts options such as timeoutMs, onLine, signal, extra env, and stdin. Nonzero process exits are returned, not automatically thrown. Invalid executable paths or privilege-elevation commands are plugin errors and are refused. Long-running processes belong in supervisedProcess, not run.
Persistent secrets live in permission-protected files under the server's data directory, not encrypted storage. A supervised process can name secrets using secretFileArgs or secretEnv; the host supplies the values. These files are separate from replaceable plugin code. See Files and paths.
Testing and bundling
Import createTestHost or createScriptedHost from @subshell-ai/plugin-api/testing. Override the services you rely on; assert emitted arguments, parse failures, and refused operations as well as success.
Bundle all third-party runtime dependencies, including contract helpers. A compiled server has no adjacent workspace node_modules for bare imports to resolve. Node built-ins are permitted; external package imports need to be inlined. The tutorials use bun build --target bun --format esm and verify the packed output against the compiled loader.
See Publish a plugin for archive inspection, registry requirements, installation, and troubleshooting.
Subagent integration
Declare the subagents capability and a subagents descriptor with discovery (hooks or extension) and navigation (native or unavailable). Optional setup text is shown in the preset editor's harness schema, so a one-time human act (trusting hooks, installing an extension) reaches the person who has to take it. Discovery and navigation are independent: don't promise view selection when only lifecycle events are available.
An mcpSetup implementation can accept a second, optional argument: the host-resolved reporter command. Omit runnable hook instructions if it is absent; don't derive a reporter from an MCP override.
Hook integrations invoke the host-provided reporter with subagents as its argument. Never hard-code Bun or a server binary path. The reporter accepts Claude Code and Codex lifecycle payloads, Hermes shell-hook payloads, and Claude Code's PreToolUse input for an Agent or Task spawn, which becomes a describe report pairing the tool's description with the next child of that type to start. It retains only bounded identity, status, and one-line task-label metadata; prompts and transcripts never ship.
An extension uses its inherited subshell bearer token to POST to /api/subshells/:id/subagents/report. Only that subshell's own token can report. Send event: "snapshot" and an agents array of { id, parentId?, name, status, activity? }. selectedId (null for the parent) and canSelect are optional: include them when the extension observes selection itself, and omit them when the host's select driver owns it. Omit completed children. IDs are limited to 256 characters, names and activity labels to 160, and snapshots to 256 children.
A navigable integration refreshes its snapshot while attached. The response may contain command: { id, agentId }; null selects the parent. Verify the requested child belongs to the current parent, use the harness's native navigation API, and acknowledge the command ID in the next report. Read back the actual native selection for selectedId; don't announce a successful selection merely because a command was queued. Navigation must preserve unsent input and must never submit prompts, approve requests, stop agents, or create a terminal.
An integration can declare navigation: "native" and implement select(input) when its harness only exposes a picker or inspector inside its own TUI. The host hands the plugin a pane with read() (the screen, ANSI stripped) and type(text) (raw bytes, no Enter appended). Drive the picker by the id it prints and return that row's id; when the picker stays open, re-read it and confirm the highlighted row is the one you chose. Refuse when it did not move there. Refuse rather than overwrite unsent input: a draft prompt is not yours to clear. The sidebar offers the switch only to callers with edit access, because this path types into the pane; a pane driver has no bridge heartbeat to refresh.
McpRegistration.files can carry up to eight companion files, each at most 65,536 characters, checked against those bounds when the launch is built. A launch carries them to the execution machine, where they are written beside the registration at <configPath>.d/<name>; on a node, the node agent writes them under its own data-dir policy. Names accept letters, numbers, underscores, and hyphens with .mjs, .py, or .json extensions. Return the harness's own activation arguments or environment settings along with those files. The node executes the prepared launch; it doesn't load the control-plane plugin.
Last updated on
