Skip to content

Writing plugins in TypeScript

The developing-plugins stock plugin provides model-callable tools for inspecting, scaffolding, and building TypeScript plugin projects. The stock source lives in js/stock-plugins/developing-plugins/; build it with //js/stock-plugins/developing-plugins:developing_plugins, then verify and install bazel-bin/js/stock-plugins/developing-plugins/developing-plugins.pt-plugin explicitly. The stock plugin’s tools use read_files, write_files, and shell; approving shell grants host shell privileges and does not sandbox commands or filesystem access.

After you install developing-plugins and approve its capabilities, the model can call these tools. The JSON objects below are the complete accepted arguments; each tool rejects additional properties.

ToolJSON arguments
plugin__developing-plugins__inspect{"type":"object","properties":{"project":{"type":"string"}},"additionalProperties":false}. project is optional and defaults to . (the project root).
plugin__developing-plugins__scaffold{"type":"object","properties":{"project":{"type":"string"},"name":{"type":"string"}},"required":["project","name"],"additionalProperties":false}. Both values are required.
plugin__developing-plugins__doctor{"type":"object","properties":{},"additionalProperties":false}. Pass {}.
plugin__developing-plugins__build{"type":"object","properties":{"project":{"type":"string"}},"required":["project"],"additionalProperties":false}. project is required.
plugin__developing-plugins__pack{"type":"object","properties":{"project":{"type":"string"}},"required":["project"],"additionalProperties":false}. project is required.
plugin__developing-plugins__verify{"type":"object","properties":{"project":{"type":"string"}},"required":["project"],"additionalProperties":false}. project is required.

For example, check the local build tools, create example-plugin, then run each build stage separately and inspect each result before continuing:

plugin__developing-plugins__doctor({})
plugin__developing-plugins__scaffold({"project":"example-plugin","name":"example-plugin"})
plugin__developing-plugins__build({"project":"example-plugin"})
plugin__developing-plugins__pack({"project":"example-plugin"})
plugin__developing-plugins__verify({"project":"example-plugin"})

The scaffold tool refuses to overwrite existing files. The build, pack, and verify tools each require the project directory and run one stage per call.

This walkthrough builds a separate plugin named example. The plugin exposes a run tool, emits a durable conversation card through the emit_message capability, handles the session_start and pre_user_prompt hooks, and packs one skill resource.

The authoring commands use tools already installed on your machine. plugin-dev never installs or downloads tools. The sign command contacts public Sigstore services by design when the author’s keyless cosign installation requests Fulcio/OIDC signing and Rekor transparency logging. Run polytoken plugin-dev doctor before building.

Create the project and its source directories:

Terminal window
mkdir -p example-plugin/src example-plugin/resources/skills/example-helper
cd example-plugin

Create package.json with the Extism PDK and Polytoken framework package:

{
"name": "example-plugin",
"private": true,
"type": "commonjs",
"dependencies": {
"@extism/js-pdk": "1.1.1",
"@polytoken/plugin-framework": "workspace:*"
}
}

The Polytoken repository provides @polytoken/plugin-framework in its private js/ workspace. The package will be published to npm as @polytoken/plugin-framework; until publication, a plugin project outside that workspace can use the package from the Polytoken repository or a local package link. The framework supplies envelope helpers, typed host capability wrappers, and hook output helpers.

Create src/index.d.ts for the interface passed to extism-js:

declare module "main" {
export function run(): I32;
export function polytoken_hook_session_start(): I32;
export function polytoken_hook_pre_user_prompt(): I32;
}
declare module "extism:host" {
interface user {
polytoken_plugin_emit_message(ptr: I64): I64;
}
}

The main declaration must list every tool and hook export. The extism:host declaration must list every host import used by the bundle. I32, I64, Host, and Memory come from the Extism JavaScript interface.

Create src/index.ts:

import {
acceptHook,
allowHook,
emitCard,
err,
inputJson,
ok,
outputJson,
type PluginHookOutcome,
type PreUserPromptHookOutcome,
type PreUserPromptInput,
} from "@polytoken/plugin-framework";
const MARKER = "example-plugin-marker";
export function run(): number {
const input = inputJson<Record<string, unknown>>();
const markdown = `**${MARKER}**\n\n\`\`\`json\n${JSON.stringify(input, null, 2)}\n\`\`\``;
const emitted = emitCard({ markdown, durable: true });
outputJson(emitted.ok ? ok(MARKER) : err(emitted.error));
return 0;
}
export function polytoken_hook_session_start(): number {
outputJson(allowHook() satisfies PluginHookOutcome);
return 0;
}
export function polytoken_hook_pre_user_prompt(): number {
const input = inputJson<PreUserPromptInput>();
// The card is a side effect: a failed emit must never block the prompt.
void emitCard({ markdown: input.prompt, durable: false });
outputJson(acceptHook() satisfies PreUserPromptHookOutcome);
return 0;
}

A plugin tool reads its input with inputJson, writes one JSON envelope with outputJson, and returns the Extism status code. ok(MARKER) produces {"ok":true,"data":"example-plugin-marker"}. err produces the matching failure envelope when the host call fails.

emitCard calls polytoken_plugin_emit_card, and the existing emit_message capability authorizes both card and message emission. The capability must appear in the manifest and in the approval granted to the plugin. Polytoken does not expose a host function merely because the plugin declares it. An unapproved import fails closed at plugin instantiation.

The session-start hook returns the typed allow outcome. Hooks use the polytoken_hook_<event> naming convention. A blocking hook can return the event-specific blocking outcome instead.

The pre-user-prompt hook demonstrates both halves of that convention. Polytoken runs it before recording your prompt, passes the raw prompt text as {"prompt_id": "...", "prompt": "..."}, and expects the event’s own outcome shape: accept to let the prompt through, reject to block it. The example sends the exact prompt text in a client-only card, so connected clients see the prompt card without adding the text to durable session history.

Create polytoken.plugin.json:

{
"name": "example",
"version": "1.0.0",
"description": "A small TypeScript plugin that demonstrates a tool and lifecycle hooks.",
"capabilities": ["emit_message"],
"tools": [
{
"name": "run",
"description": "Return the example plugin marker and emit a message.",
"input_schema": {
"type": "object",
"additionalProperties": true
}
}
],
"config_schema": {
"type": "object",
"properties": {},
"additionalProperties": false
},
"lifecycle": {
"persist_across_clear": true
}
}

The declaration file has five independent sections:

  • capabilities grants access to named host functions after approval.
  • tools publishes model-callable tool metadata and input schemas.
  • config_schema validates values under plugins.example.
  • lifecycle controls whether the plugin instance survives /clear.
  • resources/ supplies read-only files to the plugin resource namespace.

The packer copies only name, version, and description into the package manifest. The other declaration fields become WebAssembly custom sections. This projection lets Polytoken inspect declarations before instantiating the guest module.

Create resources/skills/example-helper/SKILL.md:

---
name: example-helper
description: Explains the example plugin marker.
---
# Example helper
The example plugin returns the marker `example-plugin-marker` from its `run` tool.

Resource paths use one of these top-level directories: skills, facets, subagents, or templates. Polytoken preserves the path below resources/ and exposes the file through the plugin-qualified URI. This skill is available as:

plugin+example://skills/example-helper/SKILL.md

Run the authoring-tool check:

Terminal window
polytoken plugin-dev doctor

The command checks esbuild, extism-js, wasm-opt, and wasm-merge as build tools and reports cosign in a separate signing-workflow section. An exact tested version reports ok. Another version reports a warning, while a missing or unusable build tool reports an error and makes doctor exit non-zero. Missing cosign produces an advisory only and does not fail the build-tool check. Each report includes an official installation URL. The tested compatibility matrix is esbuild 0.25.11, extism-js 1.7.0, binaryen 132, and cosign 2.6.5.

Build from the project directory:

Terminal window
polytoken plugin-dev build --project .

The command bundles src/index.ts as CommonJS targeting ES2020, converts the bundle to WebAssembly, merges the module imports, and optimizes the result. The final module appears at dist/bundle.wasm.

Pack the module and resources:

Terminal window
polytoken plugin-dev pack --project . --out ./example.pt-plugin

pack reads polytoken.plugin.json, dist/bundle.wasm, and resources/. The output is deterministic, so identical inputs produce identical package bytes. The package contains the manifest, WebAssembly module, declarations, and resource sections. Use plugin-dev sign after packing when the package should carry a keyless Sigstore bundle.

plugin-dev sign uses the author’s cosign executable in keyless mode. The command signs the framed manifest-and-WASM payload with public Fulcio/OIDC and Rekor services, then embeds the resulting sigstore.bundle.json without changing the package digest. The command does not accept private-key flags or custom Sigstore service URLs.

Sign the package created above:

Terminal window
polytoken plugin-dev sign ./example.pt-plugin --out ./example.signed.pt-plugin

Without --out, Polytoken writes example.signed.pt-plugin beside the input. Pass --force to replace an existing output. The command refuses to replace the input package unless you explicitly select the input as --out and pass --force.

Run the offline preflight before installing:

Terminal window
polytoken plugin-dev verify ./example.signed.pt-plugin

verify checks the manifest, declaration sections, tools, lifecycle data, and resource VFS. A signed package then goes through the production Sigstore verification path, including the plugin_trust publisher settings. An unsigned package passes the structural preflight with an explicit unsigned notice. Add --require-signature when the preflight must reject unsigned packages. Verification does not contact the network.

Enable unsigned-local trust in the global configuration. The global config directory is $XDG_CONFIG_HOME (default ~/.config), and the setting belongs in $XDG_CONFIG_HOME/polytoken/config.toml:

[plugin_trust]
allow_unsigned_local = true

Install the package for a project:

Terminal window
polytoken plugin-dev install ./example.pt-plugin --project ../my-project

The command derives the trusted per-project directory from the canonical project path and validates that the filename matches the manifest name. An identical package is idempotent. A different package with the same name is rejected unless you pass --force. A signed package does not need plugin_trust.allow_unsigned_local; Polytoken verifies the signature when the daemon loads the package. An unsigned package needs the unsigned-local setting shown above.

The trusted package home follows the global configuration root, not the --config-dir option used for a particular Polytoken invocation. --config-dir can isolate config loading, but it does not relocate installed plugin packages. Install into the global trusted home, then use --config-dir for the session that should load a separate configuration.

Start a session in my-project. Polytoken asks you to approve the plugin’s emit_message capability before publishing the tool and hooks. After approval, every prompt you send is echoed back as a plugin notification carrying the exact prompt text, visible as a status-line message while the pending-notification count ticks up. Ask the model to run plugin__example__run. The tool result contains example-plugin-marker.

Inspect the installed package without a daemon:

Terminal window
polytoken plugin list --project ../my-project

Inspect live publication from a running session:

Terminal window
polytoken plugin status

plugin-dev add creates a correctly shaped resource and refuses to overwrite an existing file:

Terminal window
polytoken plugin-dev add skill example-helper --project .
polytoken plugin-dev add subagent reviewer --project .
polytoken plugin-dev add facet review --project .
polytoken plugin-dev add template release-notes --project .

Edit the generated frontmatter and body before packaging. Use the resource kind that matches how Polytoken should load the file.

Plugin installation is per project. To remove the stock plugin or another installed plugin, delete its package from the project’s trusted plugin directory. The default global config directory is ~/.config/polytoken; substitute the actual path when $XDG_CONFIG_HOME is set. Find the project-specific package directory with polytoken plugin list --project <project-dir>, then remove the matching <name>.pt-plugin file:

Terminal window
rm ~/.config/polytoken/projects/<project-key>/plugins/developing-plugins.pt-plugin

Start a new session or run /reload in an existing session. The removed package no longer publishes its tools or resources for that project.

Re-run build and pack, then install the new package. Start a new session or run /reload in an existing session. Polytoken compares the package digest and declarations with the previous approval. A changed package or capability set requires approval again.