@punch-bot/cli 1.5.0 → 1.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +168 -1
- package/README.md +6 -8
- package/dist/bundle/chunks/anthropic-messages-WIBS5YKY.js +6 -0
- package/dist/bundle/chunks/azure-openai-responses-GP5GDEGO.js +2 -0
- package/dist/bundle/chunks/bedrock-converse-stream.js +7 -4
- package/dist/bundle/chunks/chunk-35EHANXE.js +2 -0
- package/dist/bundle/chunks/chunk-3IMHRFLG.js +6 -0
- package/dist/bundle/chunks/chunk-77CRE5SV.js +9 -0
- package/dist/bundle/chunks/chunk-CE33JMCE.js +861 -0
- package/dist/bundle/chunks/{chunk-MYNHUMKE.js → chunk-CXY7BILM.js} +2 -44
- package/dist/bundle/chunks/chunk-EISXNXOQ.js +41 -0
- package/dist/bundle/chunks/chunk-ENMVUQHE.js +26 -0
- package/dist/bundle/chunks/chunk-FFMDRXC4.js +10 -0
- package/dist/bundle/chunks/chunk-GFUN2N5K.js +2 -0
- package/dist/bundle/chunks/chunk-HQH636GU.js +361 -0
- package/dist/bundle/chunks/chunk-IEBK4HQA.js +2 -0
- package/dist/bundle/chunks/chunk-JAJLG57O.js +4 -0
- package/dist/bundle/chunks/{chunk-RFVYQ7ZX.js → chunk-LOHGXPCL.js} +2 -2
- package/dist/bundle/chunks/{chunk-NO2FNWW3.js → chunk-OV2VGRRS.js} +1 -1
- package/dist/bundle/chunks/chunk-P7FPUEYA.js +2 -0
- package/dist/bundle/chunks/chunk-PDENR63J.js +16 -0
- package/dist/bundle/chunks/chunk-RHOWRSGK.js +2 -0
- package/dist/bundle/chunks/{chunk-BRECMFDT.js → chunk-UZ3LUZDC.js} +1 -1
- package/dist/bundle/chunks/chunk-WN2D4UD4.js +2 -0
- package/dist/bundle/chunks/chunk-X4T5TGM4.js +82 -0
- package/dist/bundle/chunks/chunk-ZG74NES2.js +2 -0
- package/dist/bundle/chunks/cli-OQNR6ESL.js +53 -0
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-FDCKYGTP.js → cloudflare-workers-ai-system-one-36EDUVVN.js} +1 -1
- package/dist/bundle/chunks/codemode-worker.js +2 -0
- package/dist/bundle/chunks/{execute-HXULRBCI.js → execute-EHT55MW7.js} +5 -3
- package/dist/bundle/chunks/github-copilot.js +1 -1
- package/dist/bundle/chunks/{google-generative-ai-2ESDEFYR.js → google-generative-ai-KA6FZCHM.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-YERBWL2T.js → google-vertex-DXKQ4IYR.js} +1 -1
- package/dist/bundle/chunks/image-resize-worker.js +1 -1
- package/dist/bundle/chunks/kimi-coding.js +1 -1
- package/dist/bundle/chunks/{llama-cpp-classify-M4KMJHPS.js → llama-cpp-classify-676UCBOD.js} +1 -1
- package/dist/bundle/chunks/meta.js +1 -1
- package/dist/bundle/chunks/mistral-conversations-PJ56UMXO.js +5 -0
- package/dist/bundle/chunks/openai-codex-responses-DWVG7MAQ.js +10 -0
- package/dist/bundle/chunks/openai-completions-OKI6KBNP.js +7 -0
- package/dist/bundle/chunks/{openai-decisions-PPJMQ3W4.js → openai-decisions-SO57QA6O.js} +1 -1
- package/dist/bundle/chunks/openai-responses-3HV234HB.js +4 -0
- package/dist/bundle/chunks/{openrouter-images-WWPCCAPX.js → openrouter-images-5X6D7HFS.js} +1 -1
- package/dist/bundle/chunks/pi-messages-BS5Z34RE.js +8 -0
- package/dist/bundle/chunks/radius.js +1 -1
- package/dist/bundle/chunks/{runtime-R5GXO4CV.js → runtime-74PFKASL.js} +1 -1
- package/dist/bundle/chunks/{typesafe-system-one-NLWRPIRL.js → typesafe-system-one-IPNULX2M.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-2Y422I6U.js +2 -0
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/cli/args.d.ts +0 -1
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +8 -12
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/auth-command.d.ts.map +1 -1
- package/dist/cli/auth-command.js +26 -2
- package/dist/cli/auth-command.js.map +1 -1
- package/dist/cli/auth-login.d.ts +15 -0
- package/dist/cli/auth-login.d.ts.map +1 -0
- package/dist/cli/auth-login.js +232 -0
- package/dist/cli/auth-login.js.map +1 -0
- package/dist/cli/auth-logout.d.ts +14 -0
- package/dist/cli/auth-logout.d.ts.map +1 -0
- package/dist/cli/auth-logout.js +63 -0
- package/dist/cli/auth-logout.js.map +1 -0
- package/dist/cli/auth-terminal.d.ts +17 -0
- package/dist/cli/auth-terminal.d.ts.map +1 -0
- package/dist/cli/auth-terminal.js +63 -0
- package/dist/cli/auth-terminal.js.map +1 -0
- package/dist/cli/project-trust.js +1 -1
- package/dist/cli/project-trust.js.map +1 -1
- package/dist/config.d.ts +10 -2
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +24 -11
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts +5 -0
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +20 -5
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session.d.ts +31 -15
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +158 -71
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js +3 -2
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js +3 -1
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/cache-warmer.d.ts +4 -37
- package/dist/core/cache-warmer.d.ts.map +1 -1
- package/dist/core/cache-warmer.js +11 -89
- package/dist/core/cache-warmer.js.map +1 -1
- package/dist/core/compaction/branch-summarization.d.ts +4 -2
- package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
- package/dist/core/compaction/branch-summarization.js +16 -4
- package/dist/core/compaction/branch-summarization.js.map +1 -1
- package/dist/core/compaction/utils.d.ts.map +1 -1
- package/dist/core/compaction/utils.js +2 -1
- package/dist/core/compaction/utils.js.map +1 -1
- package/dist/core/exec.d.ts +9 -1
- package/dist/core/exec.d.ts.map +1 -1
- package/dist/core/exec.js +104 -60
- package/dist/core/exec.js.map +1 -1
- package/dist/core/export-html/template.css +9 -0
- package/dist/core/export-html/template.js +165 -45
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +10 -13
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/pi-ai-extension-view.d.ts +19 -0
- package/dist/core/extensions/pi-ai-extension-view.d.ts.map +1 -0
- package/dist/core/extensions/pi-ai-extension-view.js +22 -0
- package/dist/core/extensions/pi-ai-extension-view.js.map +1 -0
- package/dist/core/extensions/runner.d.ts +1 -4
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +0 -14
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +5 -18
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/extensions/virtual-modules.d.ts.map +1 -1
- package/dist/core/extensions/virtual-modules.js +8 -7
- package/dist/core/extensions/virtual-modules.js.map +1 -1
- package/dist/core/index.d.ts +1 -1
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js.map +1 -1
- package/dist/core/mcp-servers.d.ts +23 -41
- package/dist/core/mcp-servers.d.ts.map +1 -1
- package/dist/core/mcp-servers.js +51 -120
- package/dist/core/mcp-servers.js.map +1 -1
- package/dist/core/model-config.d.ts +1730 -2029
- package/dist/core/model-config.d.ts.map +1 -1
- package/dist/core/model-config.js +2 -3
- package/dist/core/model-config.js.map +1 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +36 -29
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/model-runtime.d.ts +5 -0
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +11 -4
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/package-manager.d.ts +24 -1
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +210 -51
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/pi-ai-schemas.d.ts +167 -0
- package/dist/core/pi-ai-schemas.d.ts.map +1 -0
- package/dist/core/pi-ai-schemas.js +21 -0
- package/dist/core/pi-ai-schemas.js.map +1 -0
- package/dist/core/pi-manifest.d.ts +1 -0
- package/dist/core/pi-manifest.d.ts.map +1 -1
- package/dist/core/pi-manifest.js +4 -0
- package/dist/core/pi-manifest.js.map +1 -1
- package/dist/core/preferred-providers.d.ts +17 -0
- package/dist/core/preferred-providers.d.ts.map +1 -0
- package/dist/core/preferred-providers.js +24 -0
- package/dist/core/preferred-providers.js.map +1 -0
- package/dist/core/project-trust.d.ts +1 -1
- package/dist/core/project-trust.d.ts.map +1 -1
- package/dist/core/project-trust.js +1 -1
- package/dist/core/project-trust.js.map +1 -1
- package/dist/core/prompt-templates.d.ts.map +1 -1
- package/dist/core/prompt-templates.js +18 -2
- package/dist/core/prompt-templates.js.map +1 -1
- package/dist/core/provider-composer.d.ts.map +1 -1
- package/dist/core/provider-composer.js +3 -1
- package/dist/core/provider-composer.js.map +1 -1
- package/dist/core/provider-matching.d.ts +11 -0
- package/dist/core/provider-matching.d.ts.map +1 -0
- package/dist/core/provider-matching.js +14 -0
- package/dist/core/provider-matching.js.map +1 -0
- package/dist/core/radius-mcp.d.ts +13 -0
- package/dist/core/radius-mcp.d.ts.map +1 -0
- package/dist/core/radius-mcp.js +29 -0
- package/dist/core/radius-mcp.js.map +1 -0
- package/dist/core/radius.d.ts +0 -3
- package/dist/core/radius.d.ts.map +1 -1
- package/dist/core/radius.js +0 -5
- package/dist/core/radius.js.map +1 -1
- package/dist/core/remote-catalog-provider.d.ts.map +1 -1
- package/dist/core/remote-catalog-provider.js +2 -0
- package/dist/core/remote-catalog-provider.js.map +1 -1
- package/dist/core/resource-loader.d.ts +4 -1
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +40 -25
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/runtime-credentials.d.ts +8 -0
- package/dist/core/runtime-credentials.d.ts.map +1 -1
- package/dist/core/runtime-credentials.js +15 -1
- package/dist/core/runtime-credentials.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +3 -1
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-cwd.d.ts +0 -1
- package/dist/core/session-cwd.d.ts.map +1 -1
- package/dist/core/session-cwd.js +0 -3
- package/dist/core/session-cwd.js.map +1 -1
- package/dist/core/session-manager.d.ts +7 -0
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +32 -13
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/settings-defaults.d.ts +1 -31
- package/dist/core/settings-defaults.d.ts.map +1 -1
- package/dist/core/settings-defaults.js +1 -31
- package/dist/core/settings-defaults.js.map +1 -1
- package/dist/core/settings-manager.d.ts +4 -56
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +11 -247
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/settings-schema.d.ts +4 -54
- package/dist/core/settings-schema.d.ts.map +1 -1
- package/dist/core/settings-schema.js +7 -101
- package/dist/core/settings-schema.js.map +1 -1
- package/dist/core/skills.d.ts.map +1 -1
- package/dist/core/skills.js +6 -14
- package/dist/core/skills.js.map +1 -1
- package/dist/core/slash-commands.d.ts +0 -6
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +1 -27
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/source-info.d.ts +9 -0
- package/dist/core/source-info.d.ts.map +1 -1
- package/dist/core/source-info.js +13 -0
- package/dist/core/source-info.js.map +1 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +5 -6
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/telemetry.js +1 -1
- package/dist/core/telemetry.js.map +1 -1
- package/dist/core/theme/theme.d.ts.map +1 -1
- package/dist/core/theme/theme.js +5 -1
- package/dist/core/theme/theme.js.map +1 -1
- package/dist/core/tools/bash.d.ts +2 -2
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +35 -5
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/edit-diff.d.ts +23 -14
- package/dist/core/tools/edit-diff.d.ts.map +1 -1
- package/dist/core/tools/edit-diff.js +182 -41
- package/dist/core/tools/edit-diff.js.map +1 -1
- package/dist/core/tools/edit.d.ts +3 -3
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +10 -11
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/find.d.ts +2 -2
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +82 -36
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/grep.d.ts +7 -5
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +87 -75
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/ls.d.ts +2 -2
- package/dist/core/tools/ls.d.ts.map +1 -1
- package/dist/core/tools/ls.js +2 -1
- package/dist/core/tools/ls.js.map +1 -1
- package/dist/core/tools/powershell.d.ts.map +1 -1
- package/dist/core/tools/powershell.js +15 -2
- package/dist/core/tools/powershell.js.map +1 -1
- package/dist/core/tools/read.d.ts +10 -2
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +141 -25
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.d.ts +11 -1
- package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
- package/dist/core/tools/truncate.d.ts +4 -14
- package/dist/core/tools/truncate.d.ts.map +1 -1
- package/dist/core/tools/truncate.js +23 -29
- package/dist/core/tools/truncate.js.map +1 -1
- package/dist/core/tools/write.d.ts +2 -2
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js.map +1 -1
- package/dist/core/trust-manager.d.ts.map +1 -1
- package/dist/core/trust-manager.js +14 -8
- package/dist/core/trust-manager.js.map +1 -1
- package/dist/core/usage-totals.d.ts.map +1 -1
- package/dist/core/usage-totals.js +2 -0
- package/dist/core/usage-totals.js.map +1 -1
- package/dist/extensions/codemode/execute.js +4 -4
- package/dist/extensions/codemode/execute.js.map +1 -1
- package/dist/extensions/codemode/tool.d.ts +2 -1
- package/dist/extensions/codemode/tool.d.ts.map +1 -1
- package/dist/extensions/codemode/tool.js +59 -12
- package/dist/extensions/codemode/tool.js.map +1 -1
- package/dist/extensions/llama/client.d.ts +2 -0
- package/dist/extensions/llama/client.d.ts.map +1 -1
- package/dist/extensions/llama/client.js +23 -2
- package/dist/extensions/llama/client.js.map +1 -1
- package/dist/extensions/llama/index.d.ts.map +1 -1
- package/dist/extensions/llama/index.js +1 -1
- package/dist/extensions/llama/index.js.map +1 -1
- package/dist/extensions/mcp/cli.d.ts +2 -0
- package/dist/extensions/mcp/cli.d.ts.map +1 -1
- package/dist/extensions/mcp/cli.js +83 -22
- package/dist/extensions/mcp/cli.js.map +1 -1
- package/dist/extensions/mcp/config.d.ts.map +1 -1
- package/dist/extensions/mcp/config.js +4 -7
- package/dist/extensions/mcp/config.js.map +1 -1
- package/dist/extensions/mcp/index.d.ts.map +1 -1
- package/dist/extensions/mcp/index.js +5 -4
- package/dist/extensions/mcp/index.js.map +1 -1
- package/dist/extensions/mcp/oauth.d.ts +11 -49
- package/dist/extensions/mcp/oauth.d.ts.map +1 -1
- package/dist/extensions/mcp/oauth.js +56 -296
- package/dist/extensions/mcp/oauth.js.map +1 -1
- package/dist/extensions/mcp/resources.d.ts +1 -1
- package/dist/extensions/mcp/resources.d.ts.map +1 -1
- package/dist/extensions/mcp/resources.js +4 -3
- package/dist/extensions/mcp/resources.js.map +1 -1
- package/dist/extensions/mcp/runtime.d.ts +4 -3
- package/dist/extensions/mcp/runtime.d.ts.map +1 -1
- package/dist/extensions/mcp/runtime.js +7 -5
- package/dist/extensions/mcp/runtime.js.map +1 -1
- package/dist/extensions/mcp/tools.d.ts +2 -23
- package/dist/extensions/mcp/tools.d.ts.map +1 -1
- package/dist/extensions/mcp/tools.js +6 -58
- package/dist/extensions/mcp/tools.js.map +1 -1
- package/dist/extensions/punch/index.d.ts.map +1 -1
- package/dist/extensions/punch/index.js +1 -1
- package/dist/extensions/punch/index.js.map +1 -1
- package/dist/extensions/punch/todos.js +1 -1
- package/dist/extensions/punch/todos.js.map +1 -1
- package/dist/extensions/subagent/index.d.ts.map +1 -1
- package/dist/extensions/subagent/index.js +278 -129
- package/dist/extensions/subagent/index.js.map +1 -1
- package/dist/extensions/tool-search/tool.d.ts +21 -6
- package/dist/extensions/tool-search/tool.d.ts.map +1 -1
- package/dist/extensions/tool-search/tool.js +122 -42
- package/dist/extensions/tool-search/tool.js.map +1 -1
- package/dist/index.d.ts +4 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +106 -14
- package/dist/main.js.map +1 -1
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +19 -10
- package/dist/modes/print-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +53 -23
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/package-manager-cli.d.ts.map +1 -1
- package/dist/package-manager-cli.js +94 -12
- package/dist/package-manager-cli.js.map +1 -1
- package/dist/utils/ansi.d.ts.map +1 -1
- package/dist/utils/ansi.js +5 -2
- package/dist/utils/ansi.js.map +1 -1
- package/dist/utils/changelog.d.ts +2 -2
- package/dist/utils/changelog.d.ts.map +1 -1
- package/dist/utils/changelog.js +12 -9
- package/dist/utils/changelog.js.map +1 -1
- package/dist/utils/clipboard-command.d.ts.map +1 -1
- package/dist/utils/clipboard-command.js +4 -0
- package/dist/utils/clipboard-command.js.map +1 -1
- package/dist/utils/fuzzy.d.ts.map +1 -1
- package/dist/utils/fuzzy.js +59 -44
- package/dist/utils/fuzzy.js.map +1 -1
- package/dist/utils/git.d.ts +11 -1
- package/dist/utils/git.d.ts.map +1 -1
- package/dist/utils/git.js +44 -0
- package/dist/utils/git.js.map +1 -1
- package/dist/utils/image-resize-core.d.ts.map +1 -1
- package/dist/utils/image-resize-core.js +5 -3
- package/dist/utils/image-resize-core.js.map +1 -1
- package/dist/utils/image-resize.d.ts.map +1 -1
- package/dist/utils/image-resize.js +3 -1
- package/dist/utils/image-resize.js.map +1 -1
- package/dist/utils/open-browser.d.ts.map +1 -1
- package/dist/utils/open-browser.js +4 -1
- package/dist/utils/open-browser.js.map +1 -1
- package/dist/utils/paths.d.ts +17 -0
- package/dist/utils/paths.d.ts.map +1 -1
- package/dist/utils/paths.js +42 -1
- package/dist/utils/paths.js.map +1 -1
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +14 -0
- package/dist/utils/shell.js.map +1 -1
- package/dist/utils/terminal-question.d.ts +8 -0
- package/dist/utils/terminal-question.d.ts.map +1 -0
- package/dist/utils/terminal-question.js +24 -0
- package/dist/utils/terminal-question.js.map +1 -0
- package/dist/utils/text.d.ts +2 -0
- package/dist/utils/text.d.ts.map +1 -1
- package/dist/utils/text.js +5 -0
- package/dist/utils/text.js.map +1 -1
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +30 -35
- package/dist/utils/tools-manager.js.map +1 -1
- package/dist/utils/web-url.d.ts +12 -0
- package/dist/utils/web-url.d.ts.map +1 -0
- package/dist/utils/web-url.js +20 -0
- package/dist/utils/web-url.js.map +1 -0
- package/docs/cli-integration.md +3 -5
- package/docs/cli.md +45 -26
- package/docs/compaction.md +9 -9
- package/docs/configuration.md +1 -2
- package/docs/containerization.md +16 -14
- package/docs/custom-provider.md +5 -3
- package/docs/docs.json +9 -9
- package/docs/environment-variables.md +5 -12
- package/docs/extensions.md +683 -757
- package/docs/how-pi-works.md +5 -5
- package/docs/index.md +5 -5
- package/docs/llama-cpp.md +41 -39
- package/docs/mcp.md +12 -10
- package/docs/message-types.md +1 -1
- package/docs/models-configuration.md +6 -1
- package/docs/models.md +18 -19
- package/docs/nvidia-rtx-llama-cpp.md +1 -1
- package/docs/packages.md +21 -1
- package/docs/prompt-templates.md +11 -9
- package/docs/providers.md +8 -8
- package/docs/quickstart.md +28 -52
- package/docs/rpc-commands.md +2 -2
- package/docs/rpc-extension-ui.md +5 -7
- package/docs/rpc.md +4 -2
- package/docs/sdk.md +1 -1
- package/docs/security.md +9 -5
- package/docs/session-format.md +7 -9
- package/docs/sessions.md +26 -26
- package/docs/settings.md +36 -67
- package/docs/shell-aliases.md +7 -7
- package/docs/skills.md +4 -4
- package/docs/slash-commands.md +50 -58
- package/docs/termux.md +8 -9
- package/docs/themes.md +21 -41
- package/docs/usage.md +59 -177
- package/docs/virtual-models.md +4 -4
- package/docs/windows.md +8 -10
- package/examples/extensions/README.md +3 -2
- package/examples/extensions/custom-provider-anthropic/index.ts +27 -31
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +19 -29
- package/examples/extensions/gondolin/package.json +2 -2
- package/examples/extensions/reload-runtime.ts +17 -5
- package/examples/extensions/rpc-demo.ts +2 -2
- package/examples/extensions/subagent/README.md +14 -11
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/examples/tsconfig.json +208 -0
- package/npm-shrinkwrap.json +58 -53
- package/package.json +15 -17
- package/schemas/models.schema.json +65 -36
- package/schemas/settings.schema.json +17 -243
- package/dist/bundle/chunks/anthropic-messages-WCANLUXE.js +0 -6
- package/dist/bundle/chunks/azure-openai-responses-46GRAI5B.js +0 -2
- package/dist/bundle/chunks/chunk-37OLNCAX.js +0 -16
- package/dist/bundle/chunks/chunk-3V45WARH.js +0 -7
- package/dist/bundle/chunks/chunk-4LBJE4YM.js +0 -14
- package/dist/bundle/chunks/chunk-4NE64BTO.js +0 -82
- package/dist/bundle/chunks/chunk-5NXXRYVM.js +0 -2
- package/dist/bundle/chunks/chunk-7BOHO7TR.js +0 -1190
- package/dist/bundle/chunks/chunk-7XECPCHN.js +0 -2
- package/dist/bundle/chunks/chunk-NJK3U3WK.js +0 -8
- package/dist/bundle/chunks/chunk-PLK2QSUR.js +0 -2
- package/dist/bundle/chunks/chunk-TEPMHNKQ.js +0 -2
- package/dist/bundle/chunks/chunk-UE7JCDFW.js +0 -2
- package/dist/bundle/chunks/chunk-UKVNB6C4.js +0 -2
- package/dist/bundle/chunks/chunk-USJZMAIR.js +0 -2
- package/dist/bundle/chunks/chunk-WZONBDPY.js +0 -11
- package/dist/bundle/chunks/cli-W5KJM7YB.js +0 -51
- package/dist/bundle/chunks/mistral-conversations-D6VQXE7C.js +0 -5
- package/dist/bundle/chunks/openai-codex-responses-QSNSWBYG.js +0 -10
- package/dist/bundle/chunks/openai-completions-72VXSFHQ.js +0 -7
- package/dist/bundle/chunks/openai-responses-PMTL72CY.js +0 -4
- package/dist/bundle/chunks/pi-messages-WVCFUCBL.js +0 -8
- package/dist/bundle/chunks/virtual-modules-7Y5QW4VK.js +0 -2
- package/dist/core/bug-report-upload.d.ts +0 -12
- package/dist/core/bug-report-upload.d.ts.map +0 -1
- package/dist/core/bug-report-upload.js +0 -22
- package/dist/core/bug-report-upload.js.map +0 -1
- package/dist/core/bug-report.d.ts +0 -184
- package/dist/core/bug-report.d.ts.map +0 -1
- package/dist/core/bug-report.js +0 -292
- package/dist/core/bug-report.js.map +0 -1
- package/dist/core/crash-log.d.ts +0 -27
- package/dist/core/crash-log.d.ts.map +0 -1
- package/dist/core/crash-log.js +0 -140
- package/dist/core/crash-log.js.map +0 -1
- package/dist/core/footer-data-provider.d.ts +0 -64
- package/dist/core/footer-data-provider.d.ts.map +0 -1
- package/dist/core/footer-data-provider.js +0 -338
- package/dist/core/footer-data-provider.js.map +0 -1
- package/dist/utils/zip.d.ts +0 -7
- package/dist/utils/zip.d.ts.map +0 -1
- package/dist/utils/zip.js +0 -60
- package/dist/utils/zip.js.map +0 -1
- package/docs/images/interactive-mode.png +0 -0
- package/docs/images/tree-view.png +0 -0
- package/docs/keybindings.md +0 -194
- package/docs/terminal-setup.md +0 -17
- package/docs/tmux.md +0 -55
- package/docs/tui.md +0 -125
- package/examples/extensions/sandbox/index.ts +0 -321
- package/examples/extensions/sandbox/package-lock.json +0 -92
- package/examples/extensions/sandbox/package.json +0 -19
package/docs/extensions.md
CHANGED
|
@@ -4,27 +4,26 @@
|
|
|
4
4
|
|
|
5
5
|
Extensions are TypeScript modules that extend pi's behavior. They can subscribe to lifecycle events, register custom tools callable by the LLM, add commands, and more.
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
An extension runs inside the pi process with the same operating-system permissions. It can inspect prompts, tool calls, files, credentials, and session history, so load extensions only from sources you trust.
|
|
8
|
+
|
|
9
|
+
> **Placement for reload:** Put extensions in `~/.pi/agent/extensions/` (global) or `.pi/extensions/` (project-local) for auto-discovery. Use `pi -e ./path.ts` only for quick tests. Extensions in auto-discovered locations are reloaded by [`ctx.reload()`](#ctxreload) and in the next Pi process.
|
|
8
10
|
|
|
9
11
|
**Key capabilities:**
|
|
10
12
|
- **Custom tools** - Register tools the LLM can call via `pi.registerTool()`
|
|
11
13
|
- **Event interception** - Block or modify tool calls, inject context, customize compaction
|
|
12
14
|
- **User interaction** - Prompt users via `ctx.ui` (select, confirm, input, notify)
|
|
13
|
-
- **Custom UI components** - Full TUI components with keyboard input via `ctx.ui.custom()` for complex interactions
|
|
14
15
|
- **Custom commands** - Register commands like `/mycommand` via `pi.registerCommand()`
|
|
15
16
|
- **Session persistence** - Store state that survives restarts via `pi.appendEntry()`
|
|
16
|
-
- **
|
|
17
|
+
- **Providers and MCP servers** - Register model providers, virtual models, and MCP servers
|
|
17
18
|
|
|
18
19
|
**Example use cases:**
|
|
19
20
|
- Permission gates (confirm before `rm -rf`, `sudo`, etc.)
|
|
20
21
|
- Git checkpointing (stash at each turn, restore on branch)
|
|
21
22
|
- Path protection (block writes to `.env`, `node_modules/`)
|
|
22
23
|
- Custom compaction (summarize conversation your way)
|
|
23
|
-
-
|
|
24
|
-
- Interactive tools (questions, wizards, custom dialogs)
|
|
24
|
+
- Interactive tools (questions, confirmations, text input)
|
|
25
25
|
- Stateful tools (todo lists, connection pools)
|
|
26
26
|
- External integrations (file watchers, webhooks, CI triggers)
|
|
27
|
-
- Games while you wait (see `snake.ts` example)
|
|
28
27
|
|
|
29
28
|
See [examples/extensions/](../examples/extensions/) for working implementations.
|
|
30
29
|
|
|
@@ -37,28 +36,37 @@ See [examples/extensions/](../examples/extensions/) for working implementations.
|
|
|
37
36
|
- [Extension Styles](#extension-styles)
|
|
38
37
|
- [Events](#events)
|
|
39
38
|
- [Lifecycle Overview](#lifecycle-overview)
|
|
39
|
+
- [Handler Composition](#handler-composition)
|
|
40
|
+
- [Startup Events](#startup-events)
|
|
40
41
|
- [Resource Events](#resource-events)
|
|
41
42
|
- [Session Events](#session-events)
|
|
42
43
|
- [Agent Events](#agent-events)
|
|
43
44
|
- [Model Events](#model-events)
|
|
44
45
|
- [Tool Events](#tool-events)
|
|
46
|
+
- [User Bash Events](#user-bash-events)
|
|
47
|
+
- [Input Events](#input-events)
|
|
45
48
|
- [ExtensionContext](#extensioncontext)
|
|
46
49
|
- [ExtensionCommandContext](#extensioncommandcontext)
|
|
47
50
|
- [ExtensionAPI Methods](#extensionapi-methods)
|
|
48
51
|
- [State Management](#state-management)
|
|
49
52
|
- [Custom Tools](#custom-tools)
|
|
53
|
+
- [Tool Exposure](#tool-exposure)
|
|
54
|
+
- [Calling Other Tools](#calling-other-tools)
|
|
50
55
|
- [Dynamic Tool Loading](#dynamic-tool-loading)
|
|
56
|
+
- [MCP Servers](#mcp-servers)
|
|
51
57
|
- [Custom UI](#custom-ui)
|
|
52
58
|
- [Error Handling](#error-handling)
|
|
53
59
|
- [Mode Behavior](#mode-behavior)
|
|
54
60
|
- [Examples Reference](#examples-reference)
|
|
55
61
|
|
|
62
|
+
<a id="create-an-extension"></a>
|
|
63
|
+
|
|
56
64
|
## Quick Start
|
|
57
65
|
|
|
58
66
|
Create `~/.pi/agent/extensions/my-extension.ts`:
|
|
59
67
|
|
|
60
68
|
```typescript
|
|
61
|
-
import type
|
|
69
|
+
import { type ExtensionAPI, isToolCallEventType } from "@punch-bot/cli";
|
|
62
70
|
import { Type } from "typebox";
|
|
63
71
|
|
|
64
72
|
export default function (pi: ExtensionAPI) {
|
|
@@ -68,7 +76,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
68
76
|
});
|
|
69
77
|
|
|
70
78
|
pi.on("tool_call", async (event, ctx) => {
|
|
71
|
-
if (
|
|
79
|
+
if (isToolCallEventType("bash", event) && event.input.command.includes("rm -rf")) {
|
|
72
80
|
const ok = await ctx.ui.confirm("Dangerous!", "Allow rm -rf?");
|
|
73
81
|
if (!ok) return { block: true, reason: "Blocked by user" };
|
|
74
82
|
}
|
|
@@ -106,6 +114,8 @@ Test with `--extension` (or `-e`) flag:
|
|
|
106
114
|
pi -e ./my-extension.ts
|
|
107
115
|
```
|
|
108
116
|
|
|
117
|
+
<a id="choose-where-it-loads"></a>
|
|
118
|
+
|
|
109
119
|
## Extension Locations
|
|
110
120
|
|
|
111
121
|
> **Security:** Extensions run with your full system permissions and can execute arbitrary code. Only install from sources you trust.
|
|
@@ -114,10 +124,12 @@ Extensions are auto-discovered from trusted locations. Project-local `.pi/extens
|
|
|
114
124
|
|
|
115
125
|
| Location | Scope |
|
|
116
126
|
|----------|-------|
|
|
117
|
-
| `~/.pi/agent/extensions/*.ts` | Global (all projects) |
|
|
118
|
-
| `~/.pi/agent/extensions/*/index.ts` | Global (subdirectory) |
|
|
119
|
-
|
|
|
120
|
-
| `.pi/extensions
|
|
127
|
+
| `~/.pi/agent/extensions/*.ts` or `*.js` | Global (all projects) |
|
|
128
|
+
| `~/.pi/agent/extensions/*/index.ts` or `index.js` | Global (subdirectory) |
|
|
129
|
+
| `~/.pi/agent/extensions/*/package.json` with a `pi.extensions` field | Global (subdirectory with manifest) |
|
|
130
|
+
| `.pi/extensions/...` | Project-local, same layouts |
|
|
131
|
+
|
|
132
|
+
Discovery goes one level deep. Larger packages declare their entry points in a `package.json` manifest.
|
|
121
133
|
|
|
122
134
|
Additional paths via `settings.json`:
|
|
123
135
|
|
|
@@ -134,20 +146,35 @@ Additional paths via `settings.json`:
|
|
|
134
146
|
}
|
|
135
147
|
```
|
|
136
148
|
|
|
137
|
-
To share extensions via npm or git as pi packages, see [packages.md](packages.md).
|
|
149
|
+
Settings also accept built-in extensions as `builtin:<name>` entries; see [Settings](settings.md#resources). To share extensions via npm or git as pi packages, see [packages.md](packages.md).
|
|
138
150
|
|
|
139
151
|
## Available Imports
|
|
140
152
|
|
|
141
153
|
| Package | Purpose |
|
|
142
154
|
|---------|---------|
|
|
143
|
-
| `@punch-bot/cli` | Extension types (`ExtensionAPI`, `ExtensionContext`, events) |
|
|
144
|
-
| `
|
|
145
|
-
|
|
|
146
|
-
| `@punch-bot/
|
|
155
|
+
| `@punch-bot/cli` | Extension types (`ExtensionAPI`, `ExtensionContext`, events) and helpers, including `StringEnum` for string enums |
|
|
156
|
+
| `@punch-bot/agent` | Agent message and tool types |
|
|
157
|
+
| `typebox`, `typebox/compile`, `typebox/value` | Schema definitions for tool parameters |
|
|
158
|
+
| `@punch-bot/ai` | AI utilities (transcript helpers, model types). Inside pi it also exports TypeBox's `Type`, `Static` and `TSchema`, which the published package no longer re-exports; import them from `typebox` in new code |
|
|
159
|
+
| `@punch-bot/ai/compat`, `/models`, `/oauth`, `/providers/all` | Provider construction, built-in APIs, and OAuth helpers |
|
|
160
|
+
|
|
161
|
+
pi maps these imports to its own copies, so extensions share pi's classes and registries. The legacy `@mariozechner/*` and `@sinclair/typebox` names map to the same modules.
|
|
147
162
|
|
|
148
163
|
npm dependencies work too. Add a `package.json` next to your extension (or in a parent directory), run `npm install`, and imports from `node_modules/` are resolved automatically.
|
|
149
164
|
|
|
150
|
-
For distributed pi packages installed with `pi install` (npm or git), runtime deps must be in `dependencies
|
|
165
|
+
For distributed pi packages installed with `pi install` (npm or git), runtime deps must be in `dependencies`; `devDependencies` are not installed. Do not list the host-provided packages above in `dependencies`. See [Declare dependencies](packages.md#declare-dependencies).
|
|
166
|
+
|
|
167
|
+
### Tool parameter schemas and TypeBox
|
|
168
|
+
|
|
169
|
+
pi validates tool arguments as JSON Schema with `@punch-bot/schema`, whatever built the schema; TypeBox schemas are JSON Schema and work unchanged. Before validation, loosely typed arguments are coerced: numeric strings to numbers, `"true"` to `true`, a single value to a one-item array, `null` in an optional property dropped. TypeBox features outside JSON Schema do not apply to tool arguments:
|
|
170
|
+
|
|
171
|
+
- `Type.Refine()` refinements are not run. Check such constraints in `execute()`.
|
|
172
|
+
- `Type.BigInt()`, `Type.Undefined()` and `Type.Void()` reject every argument, since JSON has no such values. Codecs (`Type.Codec()`) do not decode: `execute()` receives the JSON value.
|
|
173
|
+
- Formats registered with TypeBox's `Format.Set()` are not checked. The standard formats are, plus `url` and `json-pointer-uri-fragment`.
|
|
174
|
+
- Property names are matched as names, not as regular expressions, and `additionalProperties` applies only to properties the object does not declare.
|
|
175
|
+
- A `$ref` that names nothing rejects only arguments at its place.
|
|
176
|
+
|
|
177
|
+
Validation errors the model sees use `@punch-bot/schema`'s messages, such as `- path: missing` or `- limit: expected number, got string`.
|
|
151
178
|
|
|
152
179
|
Node.js built-ins (`node:fs`, `node:path`, etc.) are also available.
|
|
153
180
|
|
|
@@ -168,10 +195,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
168
195
|
ctx.ui.setWidget("my-ext", ["Line 1", "Line 2"]); // Widget above editor (default)
|
|
169
196
|
});
|
|
170
197
|
|
|
171
|
-
// Register tools, commands,
|
|
198
|
+
// Register tools, commands, flags
|
|
172
199
|
pi.registerTool({ ... });
|
|
173
200
|
pi.registerCommand("name", { ... });
|
|
174
|
-
pi.registerShortcut("ctrl+x", { ... });
|
|
175
201
|
pi.registerFlag("my-flag", { ... });
|
|
176
202
|
}
|
|
177
203
|
```
|
|
@@ -215,7 +241,7 @@ export default async function (pi: ExtensionAPI) {
|
|
|
215
241
|
}
|
|
216
242
|
```
|
|
217
243
|
|
|
218
|
-
This pattern makes the fetched models available during normal startup and to `pi --list-models`.
|
|
244
|
+
This pattern makes the fetched models available during normal startup and to `pi --list-models`. For model lists that change while pi runs, implement `refreshModels` instead; see [pi.registerProvider()](#piregisterprovidername-config).
|
|
219
245
|
|
|
220
246
|
### Long-lived resources and shutdown
|
|
221
247
|
|
|
@@ -270,94 +296,133 @@ Defer background resource startup until `session_start` or the command/tool/even
|
|
|
270
296
|
|
|
271
297
|
Run `npm install` in the extension directory, then imports from `node_modules/` work automatically.
|
|
272
298
|
|
|
299
|
+
<a id="extension-events"></a>
|
|
300
|
+
|
|
273
301
|
## Events
|
|
274
302
|
|
|
303
|
+
<a id="understand-the-lifecycle"></a>
|
|
304
|
+
|
|
275
305
|
### Lifecycle Overview
|
|
276
306
|
|
|
307
|
+
A prompt starts a run. Input handling comes first:
|
|
308
|
+
|
|
309
|
+
1. Extension commands (`/name`) run their handler. The `input` event does not fire. Typed and RPC prompts always check for commands; `pi.sendUserMessage()` checks only with `expandPromptTemplates: true`.
|
|
310
|
+
2. `input` handlers can intercept, transform, or handle the text.
|
|
311
|
+
3. Skill commands (`/skill:name`) and prompt templates (`/template`) expand.
|
|
312
|
+
4. `before_agent_start` runs, then the agent loop starts.
|
|
313
|
+
|
|
314
|
+
The run repeats turns, then checks whether more work starts another low-level agent run:
|
|
315
|
+
|
|
316
|
+
```mermaid
|
|
317
|
+
flowchart TD
|
|
318
|
+
Input["input"] --> Before["before_agent_start"]
|
|
319
|
+
Before --> AgentStart["agent_start"]
|
|
320
|
+
AgentStart --> Turns[["turns"]]
|
|
321
|
+
Turns --> AgentEnd["agent_end"]
|
|
322
|
+
AgentEnd --> MoreRuns{"More work?"}
|
|
323
|
+
MoreRuns -->|yes| AgentStart
|
|
324
|
+
MoreRuns -->|no| BeforeSettle["agent_before_settle"]
|
|
325
|
+
BeforeSettle --> Continue{"Continuation requested?"}
|
|
326
|
+
Continue -->|yes| AgentStart
|
|
327
|
+
Continue -->|no| Settled["agent_settled"]
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
More work means a retry, final-attempt recovery, a compaction retry, or queued messages. `agent_end` is therefore not a final-idle signal; use `agent_settled` for that. An aborted run skips `agent_before_settle` and goes from `agent_end` to `agent_settled`. pi counts as busy while a run starts, including the compaction check and `before_agent_start`, so messages sent meanwhile go into the starting run.
|
|
331
|
+
|
|
332
|
+
Each turn sends one model request and executes the tool calls in the assistant response:
|
|
333
|
+
|
|
334
|
+
```mermaid
|
|
335
|
+
flowchart TD
|
|
336
|
+
TurnStart["turn_start"] --> Request[["model request"]]
|
|
337
|
+
Request --> ToolDecision{"Tool calls?"}
|
|
338
|
+
ToolDecision -->|yes| Tools[["tool execution"]]
|
|
339
|
+
Tools --> TurnEnd["turn_end"]
|
|
340
|
+
ToolDecision -->|no| TurnEnd
|
|
341
|
+
TurnEnd --> MoreTurns{"Another turn?"}
|
|
342
|
+
MoreTurns -->|yes| TurnStart
|
|
343
|
+
MoreTurns -->|no| AgentEnd(["agent_end"])
|
|
277
344
|
```
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
│
|
|
319
|
-
user sends another prompt ◄────────────────────────────────┘
|
|
320
|
-
|
|
321
|
-
/new (new session) or /resume (switch session)
|
|
322
|
-
├─► session_before_switch (can cancel)
|
|
323
|
-
├─► session_shutdown
|
|
324
|
-
├─► session_start { reason: "new" | "resume", previousSessionFile? }
|
|
325
|
-
└─► resources_discover { reason: "startup" }
|
|
326
|
-
|
|
327
|
-
/fork or /clone
|
|
328
|
-
├─► session_before_fork (can cancel)
|
|
329
|
-
├─► session_shutdown
|
|
330
|
-
├─► session_start { reason: "fork", previousSessionFile }
|
|
331
|
-
└─► resources_discover { reason: "startup" }
|
|
332
|
-
|
|
333
|
-
/name or pi.setSessionName()
|
|
334
|
-
└─► session_info_changed
|
|
335
|
-
|
|
336
|
-
/compact or auto-compaction
|
|
337
|
-
├─► session_before_compact (can cancel or customize)
|
|
338
|
-
├─► session_compact (success)
|
|
339
|
-
└─► session_compact_failed (failure or abort)
|
|
340
|
-
|
|
341
|
-
/tree navigation
|
|
342
|
-
├─► session_before_tree (can cancel or customize)
|
|
343
|
-
└─► session_tree
|
|
344
|
-
|
|
345
|
-
/model or Ctrl+P (model selection/cycling)
|
|
346
|
-
├─► thinking_level_select (if model change changes/clamps thinking level)
|
|
347
|
-
└─► model_select
|
|
348
|
-
|
|
349
|
-
thinking level changes (settings, keybinding, pi.setThinkingLevel())
|
|
350
|
-
└─► thinking_level_select
|
|
351
|
-
|
|
352
|
-
exit (Ctrl+C, Ctrl+D, SIGHUP, SIGTERM)
|
|
353
|
-
└─► session_shutdown
|
|
345
|
+
|
|
346
|
+
The model request runs these hooks in order:
|
|
347
|
+
|
|
348
|
+
1. `context` (can modify conversation messages)
|
|
349
|
+
2. `context_with_system` (can modify the full transcript)
|
|
350
|
+
3. `before_provider_headers` (can mutate headers)
|
|
351
|
+
4. `before_provider_request` (can inspect or replace the payload)
|
|
352
|
+
5. `after_provider_response` (status and headers, before the stream is consumed)
|
|
353
|
+
6. `provider_stream_event` (raw parsed stream events) and `message_start` / `message_update` / `message_end` for the assistant message
|
|
354
|
+
|
|
355
|
+
A tool call that executes runs these hooks in order:
|
|
356
|
+
|
|
357
|
+
1. `tool_execution_start`
|
|
358
|
+
2. `tool_call` (can block or mutate input)
|
|
359
|
+
3. `tool_execution_update` while the tool executes
|
|
360
|
+
4. `tool_result` (can modify the result)
|
|
361
|
+
5. `tool_execution_end`
|
|
362
|
+
|
|
363
|
+
Calls that do not execute end early. An unknown tool or invalid arguments skip `tool_call`; a blocked or aborted call skips execution and `tool_result`. Each of these still gets `tool_execution_end` with an error result, so use `tool_execution_end` to observe every finalized call.
|
|
364
|
+
|
|
365
|
+
`turn_end` can append entries and request a continuation. Threshold compaction runs before a naturally required next turn. Message events also fire for other messages, such as user, tool-result, and custom messages. Provider hooks run only when the transport exposes the corresponding stage.
|
|
366
|
+
|
|
367
|
+
Session startup and replacement follow a separate lifecycle:
|
|
368
|
+
|
|
369
|
+
```mermaid
|
|
370
|
+
flowchart TD
|
|
371
|
+
Startup["Process startup"] --> Trust["project_trust when needed"]
|
|
372
|
+
Trust --> SessionStart["session_start"]
|
|
373
|
+
Switch["new_session or switch_session"] --> BeforeSwitch["session_before_switch"]
|
|
374
|
+
Fork["fork or clone"] --> BeforeFork["session_before_fork"]
|
|
375
|
+
BeforeSwitch --> Shutdown["session_shutdown"]
|
|
376
|
+
BeforeFork --> Shutdown
|
|
377
|
+
Reload["ctx.reload()"] --> Shutdown
|
|
378
|
+
Exit["exit"] --> Shutdown
|
|
379
|
+
Shutdown --> Replacing{"Replacing the runtime?"}
|
|
380
|
+
Replacing -->|yes| ReplacementTrust["project_trust when the working directory is new"]
|
|
381
|
+
ReplacementTrust --> Replacement["load replacement extension runtime"]
|
|
382
|
+
Replacement --> SessionStart
|
|
383
|
+
Replacing -->|no| Stop["process exits"]
|
|
384
|
+
SessionStart --> Discover["resources_discover"]
|
|
354
385
|
```
|
|
355
386
|
|
|
387
|
+
`session_start` carries `reason: "startup" | "reload" | "new" | "resume" | "fork"`, and `session_shutdown` carries `reason: "quit" | "reload" | "new" | "resume" | "fork"`. `resources_discover` uses `reason: "reload"` after a reload and `"startup"` otherwise. Exit covers the end of a print-mode run, the RPC input closing, `ctx.shutdown()`, SIGHUP, and SIGTERM. `project_trust` runs before trusted project resources load and can run again when session replacement enters a new working directory.
|
|
388
|
+
|
|
389
|
+
Other operations change the current session without replacing the runtime:
|
|
390
|
+
|
|
391
|
+
| Operation | Events |
|
|
392
|
+
|---|---|
|
|
393
|
+
| RPC `compact`, `ctx.compact()`, or automatic compaction | `session_before_compact` (can cancel or customize), then `session_compact` or `session_compact_failed` |
|
|
394
|
+
| `ctx.navigateTree()` | `session_before_tree` (can cancel or customize), then `session_tree` |
|
|
395
|
+
| `--name`, RPC `set_session_name`, or `pi.setSessionName()` | `session_info_changed` |
|
|
396
|
+
| RPC `set_model`, model cycling (RPC `cycle_model`), or `pi.setModel()` | `thinking_level_select` if the level changes or is clamped, then `model_select` |
|
|
397
|
+
| Thinking-level change (settings, RPC `set_thinking_level` or `cycle_thinking_level`, `pi.setThinkingLevel()`) | `thinking_level_select` |
|
|
398
|
+
| RPC `bash` command | `user_bash` (can intercept) |
|
|
399
|
+
| Extension dialog waits for the user | `ui_prompt_start`, `ui_prompt_end` |
|
|
400
|
+
| Idle prompt-cache refresh | `cache_warming_decision` |
|
|
401
|
+
| Extension registers or removes an MCP server after startup | `mcp_servers_change` |
|
|
402
|
+
|
|
403
|
+
<a id="events-and-concurrency"></a>
|
|
404
|
+
<a id="work-with-events"></a>
|
|
405
|
+
|
|
406
|
+
### Handler Composition
|
|
407
|
+
|
|
408
|
+
Handlers run in extension load order, then registration order. Some events notify; others transform data, replace results, or cancel an operation:
|
|
409
|
+
|
|
410
|
+
| Pattern | Behavior |
|
|
411
|
+
|---|---|
|
|
412
|
+
| Notification | Return values are ignored. Use the event for observation only. |
|
|
413
|
+
| In-place mutation | Later handlers see changes to values such as `before_provider_headers.headers`, `before_agent_start.systemPromptOptions`, and `tool_call.input`. |
|
|
414
|
+
| Chained transformation | Later handlers receive the value returned by earlier `input`, `context`, `context_with_system`, `message_end`, `tool_result`, and `before_provider_request` handlers. |
|
|
415
|
+
| Gate | A handled input, blocked tool call, cancelled session operation, or handled `user_bash` command stops that operation's normal fallback path. |
|
|
416
|
+
| Actionable boundary | Each `turn_end` or `agent_before_settle` handler sees the entries and continuation decision proposed so far. |
|
|
417
|
+
| Last override | The last `cache_warming_decision` handler that returns an action wins. |
|
|
418
|
+
|
|
419
|
+
Notification handlers should not perform slow work on a streaming event. Transform handlers should preserve fields they do not intentionally own, and gate handlers should fail closed when their safety decision cannot be made.
|
|
420
|
+
|
|
356
421
|
### Startup Events
|
|
357
422
|
|
|
358
423
|
#### project_trust
|
|
359
424
|
|
|
360
|
-
Fired before pi decides whether to trust a project with dynamic configs (`.pi` or `.agents/skills`). It runs during startup and when session replacement (for example
|
|
425
|
+
Fired before pi decides whether to trust a project with dynamic configs (`.pi` or `.agents/skills`). It runs during startup and when session replacement (for example RPC `switch_session`) enters a cwd whose trust has not been resolved in the current process. Only user/global extensions and CLI `-e` extensions participate; project-local extensions are not loaded until after trust is resolved.
|
|
361
426
|
|
|
362
427
|
```typescript
|
|
363
428
|
pi.on("project_trust", async (event, ctx) => {
|
|
@@ -391,6 +456,10 @@ pi.on("resources_discover", async (event, _ctx) => {
|
|
|
391
456
|
});
|
|
392
457
|
```
|
|
393
458
|
|
|
459
|
+
#### mcp_servers_change
|
|
460
|
+
|
|
461
|
+
Fired when an extension registers or unregisters an MCP server after extensions are bound. `event.servers` lists every registered server after the change. Handling this event marks the extension as the one that connects registered servers; see [MCP Servers](#mcp-servers).
|
|
462
|
+
|
|
394
463
|
### Session Events
|
|
395
464
|
|
|
396
465
|
See [Session Format](session-format.md) for session storage internals and the SessionManager API.
|
|
@@ -409,7 +478,7 @@ pi.on("session_start", async (event, ctx) => {
|
|
|
409
478
|
|
|
410
479
|
#### session_info_changed
|
|
411
480
|
|
|
412
|
-
Fired when the current session display name is set via
|
|
481
|
+
Fired when the current session display name is set via `--name`, RPC `set_session_name`, or `pi.setSessionName()`.
|
|
413
482
|
|
|
414
483
|
```typescript
|
|
415
484
|
pi.on("session_info_changed", async (event, ctx) => {
|
|
@@ -420,7 +489,7 @@ pi.on("session_info_changed", async (event, ctx) => {
|
|
|
420
489
|
|
|
421
490
|
#### session_before_switch
|
|
422
491
|
|
|
423
|
-
Fired before starting a new session (
|
|
492
|
+
Fired before starting a new session (RPC `new_session`, `ctx.newSession()`) or switching sessions (RPC `switch_session`, `ctx.switchSession()`).
|
|
424
493
|
|
|
425
494
|
```typescript
|
|
426
495
|
pi.on("session_before_switch", async (event, ctx) => {
|
|
@@ -439,12 +508,12 @@ Do cleanup work in `session_shutdown`, then reestablish any in-memory state in `
|
|
|
439
508
|
|
|
440
509
|
#### session_before_fork
|
|
441
510
|
|
|
442
|
-
Fired when forking via
|
|
511
|
+
Fired when forking via RPC `fork` or cloning via RPC `clone`, or through `ctx.fork()`.
|
|
443
512
|
|
|
444
513
|
```typescript
|
|
445
514
|
pi.on("session_before_fork", async (event, ctx) => {
|
|
446
515
|
// event.entryId - ID of the selected entry
|
|
447
|
-
// event.position - "before" for
|
|
516
|
+
// event.position - "before" for fork, "at" for clone
|
|
448
517
|
return { cancel: true }; // Cancel fork/clone
|
|
449
518
|
// OR
|
|
450
519
|
return { skipConversationRestore: true }; // Reserved for future conversation restore control
|
|
@@ -454,6 +523,8 @@ pi.on("session_before_fork", async (event, ctx) => {
|
|
|
454
523
|
After a successful fork or clone, pi emits `session_shutdown` for the old extension instance, reloads and rebinds extensions for the new session, then emits `session_start` with `reason: "fork"` and `previousSessionFile`.
|
|
455
524
|
Do cleanup work in `session_shutdown`, then reestablish any in-memory state in `session_start`.
|
|
456
525
|
|
|
526
|
+
<a id="session_before_compact--session_compact"></a>
|
|
527
|
+
|
|
457
528
|
#### session_before_compact / session_compact / session_compact_failed
|
|
458
529
|
|
|
459
530
|
Fired on compaction. See [compaction.md](compaction.md) for details.
|
|
@@ -462,7 +533,7 @@ Fired on compaction. See [compaction.md](compaction.md) for details.
|
|
|
462
533
|
pi.on("session_before_compact", async (event, ctx) => {
|
|
463
534
|
const { preparation, branchEntries, customInstructions, reason, willRetry, signal } = event;
|
|
464
535
|
|
|
465
|
-
// reason - "manual" (
|
|
536
|
+
// reason - "manual" (RPC `compact` or `ctx.compact()`), "threshold", or "overflow"
|
|
466
537
|
// willRetry - whether the aborted turn is retried after compaction (overflow recovery)
|
|
467
538
|
|
|
468
539
|
// Cancel:
|
|
@@ -482,12 +553,12 @@ pi.on("session_before_compact", async (event, ctx) => {
|
|
|
482
553
|
pi.on("session_compact", async (event, ctx) => {
|
|
483
554
|
// event.compactionEntry - the saved compaction
|
|
484
555
|
// event.fromExtension - whether extension provided it
|
|
485
|
-
// event.reason - "manual" (
|
|
556
|
+
// event.reason - "manual" (RPC `compact` or `ctx.compact()`), "threshold", or "overflow"
|
|
486
557
|
// event.willRetry - whether the aborted turn is retried after compaction (overflow recovery)
|
|
487
558
|
});
|
|
488
559
|
|
|
489
560
|
pi.on("session_compact_failed", async (event, ctx) => {
|
|
490
|
-
// event.reason - "manual" (
|
|
561
|
+
// event.reason - "manual" (RPC `compact` or `ctx.compact()`), "threshold", or "overflow"
|
|
491
562
|
// event.errorMessage - present for non-abort failures
|
|
492
563
|
// event.aborted - true for cancelled/aborted compactions
|
|
493
564
|
// event.willRetry - whether the aborted turn would have retried after compaction
|
|
@@ -497,13 +568,15 @@ pi.on("session_compact_failed", async (event, ctx) => {
|
|
|
497
568
|
|
|
498
569
|
#### session_before_tree / session_tree
|
|
499
570
|
|
|
500
|
-
Fired on
|
|
571
|
+
Fired on `ctx.navigateTree()`. See [Sessions](sessions.md) for tree navigation concepts.
|
|
501
572
|
|
|
502
573
|
```typescript
|
|
503
574
|
pi.on("session_before_tree", async (event, ctx) => {
|
|
504
575
|
const { preparation, signal } = event;
|
|
576
|
+
// preparation.targetId, oldLeafId, commonAncestorId, entriesToSummarize,
|
|
577
|
+
// userWantsSummary, customInstructions, replaceInstructions, label
|
|
505
578
|
return { cancel: true };
|
|
506
|
-
// OR provide custom summary:
|
|
579
|
+
// OR provide custom summary (used only when preparation.userWantsSummary is true):
|
|
507
580
|
return {
|
|
508
581
|
summary: {
|
|
509
582
|
summary: "...",
|
|
@@ -511,6 +584,7 @@ pi.on("session_before_tree", async (event, ctx) => {
|
|
|
511
584
|
details: {},
|
|
512
585
|
},
|
|
513
586
|
};
|
|
587
|
+
// OR override summarization options: customInstructions, replaceInstructions, label
|
|
514
588
|
});
|
|
515
589
|
|
|
516
590
|
pi.on("session_tree", async (event, ctx) => {
|
|
@@ -534,21 +608,25 @@ pi.on("session_shutdown", async (event, ctx) => {
|
|
|
534
608
|
|
|
535
609
|
#### before_agent_start
|
|
536
610
|
|
|
537
|
-
Fired
|
|
611
|
+
Fired before a run starts, after input handling and expansion. Can inject a message and/or modify the system prompt.
|
|
612
|
+
|
|
613
|
+
`event.messageType` says what started the run: `"user"` for a prompt or `pi.sendUserMessage()`, with `prompt` and `images`; `"custom"` for `pi.sendMessage(..., { triggerTurn: true })` while idle, with the starting `message` and no `prompt`.
|
|
538
614
|
|
|
539
615
|
```typescript
|
|
540
616
|
pi.on("before_agent_start", async (event, ctx) => {
|
|
541
|
-
// event.
|
|
542
|
-
// event.images -
|
|
617
|
+
// event.messageType - "user" | "custom"
|
|
618
|
+
// event.prompt, event.images - user's prompt text and images (messageType "user")
|
|
619
|
+
// event.message - the custom message that starts the run (messageType "custom")
|
|
543
620
|
// event.systemPrompt - current chained system prompt for this handler
|
|
544
621
|
// (includes changes from earlier before_agent_start handlers)
|
|
545
622
|
// event.systemPromptOptions - structured options used to build the system prompt
|
|
546
623
|
// .customPrompt - exact prompt prefix from --system-prompt, SYSTEM.md, or custom templates
|
|
547
624
|
// .forceSystemPrompt - optional exact replacement for the complete prompt
|
|
548
625
|
// .selectedTools - tools currently active in the prompt
|
|
626
|
+
// .hiddenTools - selected tools whose declarations requests leave out
|
|
549
627
|
// .toolSnippets - one-line descriptions for each tool
|
|
550
|
-
// .toolGuidelines -
|
|
551
|
-
// .promptGuidelines - additional custom
|
|
628
|
+
// .toolGuidelines - rule bullets keyed by tool name
|
|
629
|
+
// .promptGuidelines - additional custom rule bullets
|
|
552
630
|
// .sections - custom XML-wrapped sections keyed by tag name
|
|
553
631
|
// .appendSystemPrompt - text from --append-system-prompt flags
|
|
554
632
|
// .cwd - working directory
|
|
@@ -568,10 +646,14 @@ pi.on("before_agent_start", async (event, ctx) => {
|
|
|
568
646
|
});
|
|
569
647
|
```
|
|
570
648
|
|
|
649
|
+
A returned `message` is added to either kind of run; check `messageType` to skip runs started by custom messages.
|
|
650
|
+
|
|
571
651
|
The `systemPromptOptions` field gives extensions access to the same structured data Pi uses to build the system prompt. Collections are mutable. Prefer changing `sections`, `selectedTools`, or `promptGuidelines`: Pi diffs the resulting prompt sections against what the model already has and appends one system message patching only the changed sections. Returning `systemPrompt`, or setting `forceSystemPrompt`, replaces the whole prompt for the run: every provider receives the forced text as its leading system prompt (a cache miss when it changes), and the session transcript keeps recording the structured sections. Tool selection changes update both the prompt contributions and executable provider tools; calling `pi.setActiveTools()` inside the handler has the same effect as editing `selectedTools`. Models that accept system messages mid-conversation receive the patch in place and keep their cached prefix; other models get the replayed prompt as their system prompt, which is a cache miss once per change.
|
|
572
652
|
|
|
573
653
|
Inside `before_agent_start`, `event.systemPrompt` and `ctx.getSystemPrompt()` both reflect the chained system prompt as of the current handler. Later `before_agent_start` handlers can still modify it again.
|
|
574
654
|
|
|
655
|
+
<a id="agent_start--agent_end--agent_settled"></a>
|
|
656
|
+
|
|
575
657
|
#### agent_start / agent_end / agent_before_settle / agent_settled
|
|
576
658
|
|
|
577
659
|
`agent_start` fires when a low-level agent run begins. `agent_end` fires when that run ends, but Pi may still auto-retry, auto-compact and retry, or continue with queued follow-up messages. `agent_before_settle` is the final actionable boundary: it can append session entries and request one continuation. `agent_settled` is final and notification-only; use it for status integrations that need to know Pi will not continue running automatically.
|
|
@@ -598,7 +680,8 @@ pi.on("agent_before_settle", async (event, ctx) => {
|
|
|
598
680
|
};
|
|
599
681
|
});
|
|
600
682
|
|
|
601
|
-
pi.on("agent_settled", async (
|
|
683
|
+
pi.on("agent_settled", async (event, ctx) => {
|
|
684
|
+
// event.aborted - true when the run ended because it was aborted, for example with ctx.abort()
|
|
602
685
|
// ctx.isIdle() is true; runs requested here start after all settled handlers finish.
|
|
603
686
|
});
|
|
604
687
|
```
|
|
@@ -607,14 +690,14 @@ If the run is aborted while `agent_before_settle` handlers are running, valid re
|
|
|
607
690
|
|
|
608
691
|
#### ui_prompt_start / ui_prompt_end
|
|
609
692
|
|
|
610
|
-
Notification-only lifecycle events for blocking user-facing extension UI prompts. They fire around `ctx.ui.select()`, `ctx.ui.confirm()`, `ctx.ui.input()`,
|
|
693
|
+
Notification-only lifecycle events for blocking user-facing extension UI prompts. They fire around `ctx.ui.select()`, `ctx.ui.confirm()`, `ctx.ui.input()`, and `ctx.ui.editor()` so host/status integrations can report "waiting for user" instead of just "running".
|
|
611
694
|
|
|
612
695
|
Nested or overlapping prompts are coalesced into one outer waiting span. Handlers are invoked best-effort and are not awaited before showing or closing the prompt.
|
|
613
696
|
|
|
614
697
|
```typescript
|
|
615
698
|
pi.on("ui_prompt_start", async (event, ctx) => {
|
|
616
699
|
// event.reason === "ui_prompt"
|
|
617
|
-
// event.kind: "select" | "confirm" | "input" | "editor"
|
|
700
|
+
// event.kind: "select" | "confirm" | "input" | "editor"
|
|
618
701
|
// event.title: prompt title when available
|
|
619
702
|
});
|
|
620
703
|
|
|
@@ -658,13 +741,13 @@ pi.on("turn_end", async (event, ctx) => {
|
|
|
658
741
|
|
|
659
742
|
`continue: true` ensures one next provider request for that boundary invocation. If tool results, steering, or a follow-up already cause that request, they satisfy the decision and no additional request is made; otherwise Pi makes one context-only request. Error and aborted responses remain hard exits. `continue: false` never suppresses natural work. Guard continuation conditions: an unconditional `continue: true` is evaluated again after the next response and can create an endless loop. A `custom_message` draft contributes a user-role model message but is extension-authored: it does not run human input hooks, slash commands, skills, or prompt templates.
|
|
660
743
|
|
|
661
|
-
Host integrations that construct `TurnEndEvent` values must
|
|
744
|
+
Host integrations that construct `TurnEndEvent` values must provide `messageEntryId`, `toolResultEntryIds`, `outcome`, `entries`, `continue`, and `context`. `ExtensionEvent` exhaustive switches must also handle `agent_before_settle`. `ExtensionRunner.emit()` excludes actionable turn boundaries; dispatch `turn_end` and `agent_before_settle` through `emitBoundary(baseEvent, buildContext)` so handlers receive chained previews. Other dedicated runner methods still return results for events such as `session_before_*`.
|
|
662
745
|
|
|
663
746
|
#### message_start / message_update / message_end
|
|
664
747
|
|
|
665
748
|
Fired for message lifecycle updates.
|
|
666
749
|
|
|
667
|
-
- `message_start` and `message_end` fire for user, assistant, and
|
|
750
|
+
- `message_start` and `message_end` fire for every message, including user, assistant, tool-result, and custom messages.
|
|
668
751
|
- `message_update` fires for assistant streaming updates.
|
|
669
752
|
- `message_end` handlers can return `{ message }` to replace the finalized message. The replacement must keep the same `role`.
|
|
670
753
|
|
|
@@ -717,9 +800,12 @@ pi.on("tool_execution_update", async (event, ctx) => {
|
|
|
717
800
|
|
|
718
801
|
pi.on("tool_execution_end", async (event, ctx) => {
|
|
719
802
|
// event.toolCallId, event.toolName, event.result, event.isError
|
|
803
|
+
// event.durationMs - milliseconds execute() took; absent when the tool did not run
|
|
720
804
|
});
|
|
721
805
|
```
|
|
722
806
|
|
|
807
|
+
All three events, `tool_call`, and `tool_result` carry `parentToolCallId` when another tool made the call; see [Calling Other Tools](#calling-other-tools).
|
|
808
|
+
|
|
723
809
|
#### context
|
|
724
810
|
|
|
725
811
|
Fired before each LLM call. Modify messages non-destructively. See [Session Format](session-format.md) for message types.
|
|
@@ -786,6 +872,8 @@ pi.on("before_provider_request", (event, ctx) => {
|
|
|
786
872
|
|
|
787
873
|
This is mainly useful for debugging provider serialization and cache behavior.
|
|
788
874
|
|
|
875
|
+
The payload is the full request. Providers that continue from a previous response (OpenAI Codex over WebSocket, Anthropic message threads) may send only the part that is new since the previous request.
|
|
876
|
+
|
|
789
877
|
#### after_provider_response
|
|
790
878
|
|
|
791
879
|
Fired after an HTTP response is received and before its stream body is consumed. Handlers run in extension load order.
|
|
@@ -802,6 +890,19 @@ pi.on("after_provider_response", (event, ctx) => {
|
|
|
802
890
|
|
|
803
891
|
Header availability depends on provider and transport. Providers that abstract HTTP responses may not expose headers.
|
|
804
892
|
|
|
893
|
+
#### provider_stream_event
|
|
894
|
+
|
|
895
|
+
Fired for each parsed provider stream event before pi normalizes it. Notification-only and not persisted.
|
|
896
|
+
|
|
897
|
+
```typescript
|
|
898
|
+
pi.on("provider_stream_event", (event, ctx) => {
|
|
899
|
+
// event.provider, event.api, event.model
|
|
900
|
+
// event.data - earliest structured value available to Pi (read-only)
|
|
901
|
+
});
|
|
902
|
+
```
|
|
903
|
+
|
|
904
|
+
`event.data` is not necessarily the original HTTP bytes or SSE frame. Treat it as read-only because mutation can affect normalization. Handlers are awaited in stream order, so slow handlers delay stream consumption. Handler errors are reported without changing the provider response. See [`debug-provider.ts`](../examples/extensions/debug-provider.ts) for an opt-in capture that stores raw events, grouped by assistant message, as custom entries.
|
|
905
|
+
|
|
805
906
|
#### cache_warming_decision
|
|
806
907
|
|
|
807
908
|
Fired before each prompt-cache refresh with pi's decision filled in. The event carries only pi's cost estimates; use `ctx.model`, `ctx.isIdle()`, and `ctx.getContextUsage()` for everything else.
|
|
@@ -825,13 +926,13 @@ Return `{ action: "warm" }` or `{ action: "stop" }` to override; the last handle
|
|
|
825
926
|
|
|
826
927
|
#### model_select
|
|
827
928
|
|
|
828
|
-
Fired when the model changes via
|
|
929
|
+
Fired when the model changes via RPC `set_model`, model cycling (RPC `cycle_model`), or `pi.setModel()`. Restoring a session does not fire it; read `ctx.model` in `session_start` to initialize model-dependent state.
|
|
829
930
|
|
|
830
931
|
```typescript
|
|
831
932
|
pi.on("model_select", async (event, ctx) => {
|
|
832
933
|
// event.model - newly selected model
|
|
833
934
|
// event.previousModel - previous model (undefined if first selection)
|
|
834
|
-
// event.source - "set" | "cycle"
|
|
935
|
+
// event.source - "set" | "cycle"
|
|
835
936
|
|
|
836
937
|
const prev = event.previousModel
|
|
837
938
|
? `${event.previousModel.provider}/${event.previousModel.id}`
|
|
@@ -842,7 +943,7 @@ pi.on("model_select", async (event, ctx) => {
|
|
|
842
943
|
});
|
|
843
944
|
```
|
|
844
945
|
|
|
845
|
-
Use this to update UI elements
|
|
946
|
+
Use this to update UI elements such as status entries or perform model-specific initialization when the active model changes.
|
|
846
947
|
|
|
847
948
|
#### thinking_level_select
|
|
848
949
|
|
|
@@ -859,6 +960,8 @@ pi.on("thinking_level_select", async (event, ctx) => {
|
|
|
859
960
|
|
|
860
961
|
Use this to update extension UI when `pi.setThinkingLevel()`, model changes, or built-in thinking-level controls change the active thinking level.
|
|
861
962
|
|
|
963
|
+
<a id="tool-call-events"></a>
|
|
964
|
+
|
|
862
965
|
### Tool Events
|
|
863
966
|
|
|
864
967
|
#### tool_call
|
|
@@ -908,7 +1011,10 @@ pi.on("tool_call", async (event, ctx) => {
|
|
|
908
1011
|
Custom tools should export their input type:
|
|
909
1012
|
|
|
910
1013
|
```typescript
|
|
911
|
-
// my-
|
|
1014
|
+
// my-tool.ts
|
|
1015
|
+
import { type Static, Type } from "typebox";
|
|
1016
|
+
|
|
1017
|
+
export const myToolSchema = Type.Object({ action: Type.String() });
|
|
912
1018
|
export type MyToolInput = Static<typeof myToolSchema>;
|
|
913
1019
|
```
|
|
914
1020
|
|
|
@@ -916,7 +1022,7 @@ Use `isToolCallEventType` with explicit type parameters:
|
|
|
916
1022
|
|
|
917
1023
|
```typescript
|
|
918
1024
|
import { isToolCallEventType } from "@punch-bot/cli";
|
|
919
|
-
import type { MyToolInput } from "my-
|
|
1025
|
+
import type { MyToolInput } from "./my-tool.ts";
|
|
920
1026
|
|
|
921
1027
|
pi.on("tool_call", (event) => {
|
|
922
1028
|
if (isToolCallEventType<"my_tool", MyToolInput>("my_tool", event)) {
|
|
@@ -934,7 +1040,8 @@ In parallel tool mode, `tool_result` and `tool_execution_end` may interleave in
|
|
|
934
1040
|
`tool_result` handlers chain like middleware:
|
|
935
1041
|
- Handlers run in extension load order
|
|
936
1042
|
- Each handler sees the latest result after previous handler changes
|
|
937
|
-
- Handlers can return partial patches (`content`, `details`, `isError`, or `usage`); omitted fields keep their current values
|
|
1043
|
+
- Handlers can return partial patches (`content`, `details`, `structuredContent`, `isError`, or `usage`); omitted fields keep their current values
|
|
1044
|
+
- Replacing `content` without returning `structuredContent` drops the structured content, because it may no longer match
|
|
938
1045
|
|
|
939
1046
|
Use `ctx.signal` for nested async work inside the handler. This lets Esc cancel model calls, `fetch()`, and other abort-aware operations started by the extension.
|
|
940
1047
|
|
|
@@ -942,8 +1049,8 @@ Use `ctx.signal` for nested async work inside the handler. This lets Esc cancel
|
|
|
942
1049
|
import { isBashToolResult } from "@punch-bot/cli";
|
|
943
1050
|
|
|
944
1051
|
pi.on("tool_result", async (event, ctx) => {
|
|
945
|
-
// event.toolName, event.toolCallId, event.input
|
|
946
|
-
// event.content, event.details, event.isError, event.usage
|
|
1052
|
+
// event.toolName, event.toolCallId, event.input, event.parentToolCallId
|
|
1053
|
+
// event.content, event.details, event.structuredContent, event.isError, event.usage
|
|
947
1054
|
|
|
948
1055
|
if (isBashToolResult(event)) {
|
|
949
1056
|
// event.details is typed as BashToolDetails
|
|
@@ -964,7 +1071,7 @@ pi.on("tool_result", async (event, ctx) => {
|
|
|
964
1071
|
|
|
965
1072
|
#### user_bash
|
|
966
1073
|
|
|
967
|
-
Fired when
|
|
1074
|
+
Fired when an RPC client runs the [`bash`](rpc-commands.md#bash) command. `excludeFromContext` is `true` when the output should stay out of model context. **Can intercept.**
|
|
968
1075
|
|
|
969
1076
|
```typescript
|
|
970
1077
|
import { createLocalBashOperations } from "@punch-bot/cli";
|
|
@@ -1001,7 +1108,7 @@ Returning `undefined` continues to the next handler, then local execution if non
|
|
|
1001
1108
|
Fired when user input is received, after extension commands are checked but before skill and template expansion. The event sees the raw input text, so `/skill:foo` and `/template` are not yet expanded.
|
|
1002
1109
|
|
|
1003
1110
|
**Processing order:**
|
|
1004
|
-
1. Extension commands (`/cmd`) checked first - if found, handler runs and input event is skipped
|
|
1111
|
+
1. Extension commands (`/cmd`) checked first - if found, handler runs and input event is skipped. Messages from `pi.sendUserMessage()` are checked only with `expandPromptTemplates: true`.
|
|
1005
1112
|
2. `input` event fires - can intercept, transform, or handle
|
|
1006
1113
|
3. If not handled: skill commands (`/skill:name`) expanded to skill content
|
|
1007
1114
|
4. If not handled: prompt templates (`/template`) expanded to template content
|
|
@@ -1045,9 +1152,11 @@ pi.on("input", async (event, ctx) => {
|
|
|
1045
1152
|
|
|
1046
1153
|
Transforms chain across handlers. See [input-transform.ts](../examples/extensions/input-transform.ts) and [input-transform-streaming.ts](../examples/extensions/input-transform-streaming.ts) for `streamingBehavior`-aware routing.
|
|
1047
1154
|
|
|
1155
|
+
<a id="use-extension-context"></a>
|
|
1156
|
+
|
|
1048
1157
|
## ExtensionContext
|
|
1049
1158
|
|
|
1050
|
-
All handlers receive `ctx: ExtensionContext`.
|
|
1159
|
+
All handlers receive `ctx: ExtensionContext`. Tool `execute()` receives `ExtensionToolContext`, which adds `ctx.tools` and `ctx.executeTool()` (see [Calling Other Tools](#calling-other-tools)). Command handlers receive [`ExtensionCommandContext`](#extensioncommandcontext).
|
|
1051
1160
|
|
|
1052
1161
|
### ctx.ui
|
|
1053
1162
|
|
|
@@ -1055,11 +1164,11 @@ UI methods for user interaction. See [Custom UI](#custom-ui) for full details.
|
|
|
1055
1164
|
|
|
1056
1165
|
### ctx.mode
|
|
1057
1166
|
|
|
1058
|
-
Current run mode: `"
|
|
1167
|
+
Current run mode: `"rpc"`, `"json"`, or `"print"`. See [Mode Behavior](#mode-behavior).
|
|
1059
1168
|
|
|
1060
1169
|
### ctx.hasUI
|
|
1061
1170
|
|
|
1062
|
-
`true` in
|
|
1171
|
+
`true` in RPC mode. `false` in print mode (`-p`) and JSON mode. Use this to guard dialog methods (`select`, `confirm`, `input`, `editor`) and fire-and-forget methods (`notify`, `setStatus`, `setWidget`, `setTitle`, `setEditorText`). In RPC mode, some methods are no-ops or return defaults (see [RPC Extension UI](rpc-extension-ui.md)).
|
|
1063
1172
|
|
|
1064
1173
|
### ctx.cwd
|
|
1065
1174
|
|
|
@@ -1087,7 +1196,7 @@ Use this before reading project-local extension configuration that should only b
|
|
|
1087
1196
|
|
|
1088
1197
|
### ctx.sessionManager
|
|
1089
1198
|
|
|
1090
|
-
Read-only access to session state
|
|
1199
|
+
Read-only access to session state: `getCwd()`, `getSessionDir()`, `getSessionId()`, `getSessionFile()`, `getSessionName()`, `getHeader()`, `getEntries()`, `getEntry()`, `getBranch()`, `getTree()`, `getLeafId()`, `getLeafEntry()`, `getLabel()`, `buildContextEntries()`, and `buildSessionProjection()`. See [Session Format](session-format.md) for entry types.
|
|
1091
1200
|
|
|
1092
1201
|
For `tool_call`, this state is synchronized through the current assistant message before handlers run. In parallel tool execution mode it is still not guaranteed to include sibling tool results from the same assistant message.
|
|
1093
1202
|
|
|
@@ -1102,13 +1211,15 @@ ctx.sessionManager.getLeafId() // Current leaf entry ID
|
|
|
1102
1211
|
|
|
1103
1212
|
Access to models, providers, and resolved authentication. `ctx.modelRegistry.getProvider(id)` returns the effective pi-ai provider, while `getProviderAuth(id)` resolves its current API key, headers, base URL, and provider-scoped environment without requiring a loaded model. `ctx.model` is the active model, and `ctx.thinkingLevel` is its current effective thinking level.
|
|
1104
1213
|
|
|
1105
|
-
`ctx.scopedModels` is the read-only list of models scoped to the current session — the same set
|
|
1214
|
+
`ctx.scopedModels` is the read-only list of models scoped to the current session — the same set RPC `cycle_model` cycles through. It is resolved at session start from the `--models` CLI flag and the `enabledModels` setting (matched against the available catalogue with minimatch on `provider/modelId` or a bare `modelId`). It is empty when no scoping is configured, meaning every available model is usable. Each entry is `{ model, thinkingLevel? }`, where `thinkingLevel` is set only when a pattern pinned it (e.g. `anthropic/*:high`). Use it to populate a model picker that mirrors the built-in one instead of enumerating the whole catalogue via `ctx.modelRegistry.getAvailable()`.
|
|
1106
1215
|
|
|
1107
1216
|
#### Streaming model calls
|
|
1108
1217
|
|
|
1109
|
-
Use `ctx.modelRegistry.streamSimple(model, context, options)` for provider-neutral options such as `reasoning`, or `
|
|
1218
|
+
Use `ctx.modelRegistry.streamSimple(model, context, options)` for provider-neutral options such as `reasoning`, or `complete(model, context, options)` to await the final assistant message with API-specific options. Both use configured providers and resolve authentication, including for providers registered with `pi.registerProvider()`. Use these instead of `pi-ai/compat` streaming functions, which cannot see extension provider registrations.
|
|
1110
1219
|
|
|
1111
|
-
|
|
1220
|
+
`streamSimple()` returns an `AssistantMessageEventStream`. Iterate it for response events and await `.result()` for the final message. Setup failures produce error events and error results.
|
|
1221
|
+
|
|
1222
|
+
For non-chat models, `findOfType()`, `getModelsOfType()`, `getAvailableOfType()`, and `getModelOfType()` look up image and classifier models, and `classify()` and `generateImages()` call them. See [Use classifier models](models.md#use-classifier-models) and [Use image models](models.md#use-image-models).
|
|
1112
1223
|
|
|
1113
1224
|
### ctx.signal
|
|
1114
1225
|
|
|
@@ -1120,7 +1231,7 @@ Use this for abort-aware nested work started by extension handlers, for example:
|
|
|
1120
1231
|
- file or process helpers that accept `AbortSignal`
|
|
1121
1232
|
|
|
1122
1233
|
`ctx.signal` is typically defined during active turn events such as `tool_call`, `tool_result`, `message_update`, and `turn_end`.
|
|
1123
|
-
It is usually `undefined` in idle or non-turn contexts such as session events
|
|
1234
|
+
It is usually `undefined` in idle or non-turn contexts such as session events and extension commands run while pi is idle.
|
|
1124
1235
|
|
|
1125
1236
|
```typescript
|
|
1126
1237
|
pi.on("tool_result", async (event, ctx) => {
|
|
@@ -1143,11 +1254,10 @@ Control flow helpers. `ctx.isIdle()` is false while Pi is processing an agent ru
|
|
|
1143
1254
|
|
|
1144
1255
|
Request a graceful shutdown of pi.
|
|
1145
1256
|
|
|
1146
|
-
- **
|
|
1147
|
-
- **RPC mode:** Deferred until the next idle state (after completing the current command response, when waiting for the next command).
|
|
1257
|
+
- **RPC mode:** Runs right away when the session is idle and no command is being handled. Otherwise deferred until the current command finishes (including its response) or the active run settles. (A request made while an extension-started compaction is running waits for the next command or run to finish.)
|
|
1148
1258
|
- **Print mode:** No-op. The process exits automatically when all prompts are processed.
|
|
1149
1259
|
|
|
1150
|
-
Emits `session_shutdown` event to all extensions before exiting. Available in all contexts (event handlers, tools, commands
|
|
1260
|
+
Emits `session_shutdown` event to all extensions before exiting. Available in all contexts (event handlers, tools, commands).
|
|
1151
1261
|
|
|
1152
1262
|
```typescript
|
|
1153
1263
|
pi.on("tool_call", (event, ctx) => {
|
|
@@ -1163,7 +1273,7 @@ Returns current context usage for the active model. Uses last assistant usage wh
|
|
|
1163
1273
|
|
|
1164
1274
|
```typescript
|
|
1165
1275
|
const usage = ctx.getContextUsage();
|
|
1166
|
-
if (usage && usage.tokens > 100_000) {
|
|
1276
|
+
if (usage?.tokens != null && usage.tokens > 100_000) {
|
|
1167
1277
|
// ...
|
|
1168
1278
|
}
|
|
1169
1279
|
```
|
|
@@ -1285,13 +1395,13 @@ if (cloneResult.cancelled) {
|
|
|
1285
1395
|
```
|
|
1286
1396
|
|
|
1287
1397
|
Options:
|
|
1288
|
-
- `position`: `"before"` (default) forks before the selected user message
|
|
1289
|
-
- `position`: `"at"` duplicates the active path through the selected entry
|
|
1398
|
+
- `position`: `"before"` (default) forks before the selected user message; RPC `fork` returns that prompt's text
|
|
1399
|
+
- `position`: `"at"` duplicates the active path through the selected entry
|
|
1290
1400
|
- `withSession`: run post-switch work against a fresh replacement-session context. Do not use captured old `pi` / command `ctx`; see [Session replacement lifecycle and footguns](#session-replacement-lifecycle-and-footguns).
|
|
1291
1401
|
|
|
1292
1402
|
### ctx.navigateTree(targetId, options?)
|
|
1293
1403
|
|
|
1294
|
-
Navigate to a different point in the session tree. Rejects while an agent response, manual or automatic compaction, or another tree navigation is active, even with `summarize: false`. These conflicts leave the active branch unchanged and reject the promise rather than returning `{ cancelled: true }`. Wait for the active operation to finish (for example, with `await ctx.waitForIdle()` in a command handler) and retry:
|
|
1404
|
+
Navigate to a different point in the session tree. Rejects while an agent response, manual or automatic compaction, or another tree navigation is active, even with `summarize: false`. These conflicts leave the active branch unchanged and reject the promise rather than returning `{ cancelled: true }`. Wait for the active operation to finish (for example, with `await ctx.waitForIdle()` in a command handler) and retry. It also rejects when `summarize` is set without an available model, or when the target entry does not exist:
|
|
1295
1405
|
|
|
1296
1406
|
```typescript
|
|
1297
1407
|
const result = await ctx.navigateTree("entry-id-456", {
|
|
@@ -1338,7 +1448,7 @@ pi.registerCommand("switch", {
|
|
|
1338
1448
|
if (sessions.length === 0) return;
|
|
1339
1449
|
const choice = await ctx.ui.select(
|
|
1340
1450
|
"Pick session:",
|
|
1341
|
-
sessions.map(s => s.
|
|
1451
|
+
sessions.map((s) => s.path),
|
|
1342
1452
|
);
|
|
1343
1453
|
if (choice) {
|
|
1344
1454
|
await ctx.switchSession(choice, {
|
|
@@ -1396,7 +1506,7 @@ pi.registerCommand("handoff", {
|
|
|
1396
1506
|
|
|
1397
1507
|
### ctx.reload()
|
|
1398
1508
|
|
|
1399
|
-
|
|
1509
|
+
Reload settings, extensions, skills, prompt templates, themes, and context files in the running session.
|
|
1400
1510
|
|
|
1401
1511
|
```typescript
|
|
1402
1512
|
pi.registerCommand("reload-runtime", {
|
|
@@ -1418,38 +1528,35 @@ Important behavior:
|
|
|
1418
1528
|
|
|
1419
1529
|
For predictable behavior, treat reload as terminal for that handler (`await ctx.reload(); return;`).
|
|
1420
1530
|
|
|
1421
|
-
Tools run with `
|
|
1422
|
-
|
|
1423
|
-
Example tool the LLM can call to trigger reload:
|
|
1531
|
+
Tools run with `ExtensionToolContext`, not `ExtensionCommandContext`, so they cannot call `ctx.reload()`, and pi cannot reload while the agent is running. To let the LLM trigger a reload, have the tool record the request and run the command from `agent_settled`, where messages sent by handlers are processed after all settled handlers finish:
|
|
1424
1532
|
|
|
1425
1533
|
```typescript
|
|
1426
|
-
|
|
1427
|
-
import { Type } from "typebox";
|
|
1534
|
+
let reloadRequested = false;
|
|
1428
1535
|
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1536
|
+
pi.registerTool({
|
|
1537
|
+
name: "reload_runtime",
|
|
1538
|
+
label: "Reload Runtime",
|
|
1539
|
+
description: "Reload extensions, skills, prompts, themes, and context files",
|
|
1540
|
+
parameters: Type.Object({}),
|
|
1541
|
+
async execute() {
|
|
1542
|
+
reloadRequested = true;
|
|
1543
|
+
return {
|
|
1544
|
+
content: [{ type: "text", text: "Reload requested. Pi reloads after this response." }],
|
|
1545
|
+
details: {},
|
|
1546
|
+
terminate: true,
|
|
1547
|
+
};
|
|
1548
|
+
},
|
|
1549
|
+
});
|
|
1437
1550
|
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
async execute() {
|
|
1444
|
-
pi.sendUserMessage("/reload-runtime", { deliverAs: "followUp" });
|
|
1445
|
-
return {
|
|
1446
|
-
content: [{ type: "text", text: "Queued /reload-runtime as a follow-up command." }],
|
|
1447
|
-
};
|
|
1448
|
-
},
|
|
1449
|
-
});
|
|
1450
|
-
}
|
|
1551
|
+
pi.on("agent_settled", () => {
|
|
1552
|
+
if (!reloadRequested) return;
|
|
1553
|
+
reloadRequested = false;
|
|
1554
|
+
pi.sendUserMessage("/reload-runtime", { expandPromptTemplates: true });
|
|
1555
|
+
});
|
|
1451
1556
|
```
|
|
1452
1557
|
|
|
1558
|
+
`expandPromptTemplates: true` dispatches the text as a command. Without it, or when queued with `deliverAs`, the text reaches the model as a plain user message. See [reload-runtime.ts](../examples/extensions/reload-runtime.ts).
|
|
1559
|
+
|
|
1453
1560
|
## ExtensionAPI Methods
|
|
1454
1561
|
|
|
1455
1562
|
### pi.on(event, handler)
|
|
@@ -1469,19 +1576,19 @@ Handlers run in extension load order, then registration order within each extens
|
|
|
1469
1576
|
|
|
1470
1577
|
Register a custom tool callable by the LLM. See [Custom Tools](#custom-tools) for full details.
|
|
1471
1578
|
|
|
1472
|
-
`pi.registerTool()` works both during extension load and after startup. You can call it inside `session_start`, command handlers, or other event handlers. New tools are refreshed immediately in the same session, so they appear in `pi.getAllTools()`
|
|
1579
|
+
`pi.registerTool()` works both during extension load and after startup. You can call it inside `session_start`, command handlers, or other event handlers. New tools are refreshed immediately in the same session, so they appear in `pi.getAllTools()` without `/reload`. Registering a tool activates it unless it sets `defaultActive: false` or an [exposure](#tool-exposure) other than `direct` or `model-only`.
|
|
1473
1580
|
|
|
1474
1581
|
Use `pi.setActiveTools()` to enable or disable tools (including dynamically added tools) at runtime.
|
|
1475
1582
|
|
|
1476
|
-
Use `promptSnippet` to opt a custom tool into a one-line entry in
|
|
1583
|
+
Use `promptSnippet` to opt a custom tool into a one-line entry in the `<tools>` section of the default system prompt, and `promptGuidelines` to append tool-specific bullets to its `<rules>` section when the tool is active.
|
|
1477
1584
|
|
|
1478
|
-
**Important:** `promptGuidelines` bullets are appended flat to the
|
|
1585
|
+
**Important:** `promptGuidelines` bullets are appended flat to the `<rules>` section with no tool name prefix. Each guideline must name the tool it refers to — avoid "Use this tool when..." because the LLM cannot tell which tool "this" means. Write "Use my_tool when..." instead.
|
|
1479
1586
|
|
|
1480
1587
|
See [dynamic-tools.ts](../examples/extensions/dynamic-tools.ts) for a full example.
|
|
1481
1588
|
|
|
1482
1589
|
```typescript
|
|
1590
|
+
import { StringEnum } from "@punch-bot/cli";
|
|
1483
1591
|
import { Type } from "typebox";
|
|
1484
|
-
import { StringEnum } from "@punch-bot/ai";
|
|
1485
1592
|
|
|
1486
1593
|
pi.registerTool({
|
|
1487
1594
|
name: "my_tool",
|
|
@@ -1493,32 +1600,22 @@ pi.registerTool({
|
|
|
1493
1600
|
action: StringEnum(["list", "add"] as const),
|
|
1494
1601
|
text: Type.Optional(Type.String()),
|
|
1495
1602
|
}),
|
|
1496
|
-
prepareArguments(args) {
|
|
1497
|
-
// Optional compatibility shim. Runs before schema validation.
|
|
1498
|
-
// Return the current schema shape, for example to fold legacy fields
|
|
1499
|
-
// into the modern parameter object.
|
|
1500
|
-
return args;
|
|
1501
|
-
},
|
|
1502
1603
|
|
|
1503
1604
|
async execute(toolCallId, params, signal, onUpdate, ctx) {
|
|
1504
|
-
// Stream progress
|
|
1505
|
-
onUpdate?.({ content: [{ type: "text", text: "Working..." }] });
|
|
1605
|
+
// Stream progress; partial results also need details
|
|
1606
|
+
onUpdate?.({ content: [{ type: "text", text: "Working..." }], details: { result: "pending" } });
|
|
1506
1607
|
|
|
1507
1608
|
return {
|
|
1508
1609
|
content: [{ type: "text", text: "Done" }],
|
|
1509
1610
|
details: { result: "..." },
|
|
1510
1611
|
};
|
|
1511
1612
|
},
|
|
1512
|
-
|
|
1513
|
-
// Optional: Custom rendering
|
|
1514
|
-
renderCall(args, theme, context) { ... },
|
|
1515
|
-
renderResult(result, options, theme, context) { ... },
|
|
1516
1613
|
});
|
|
1517
1614
|
```
|
|
1518
1615
|
|
|
1519
1616
|
### pi.sendMessage(message, options?)
|
|
1520
1617
|
|
|
1521
|
-
Inject a custom message into the session. Custom messages participate in LLM context. For durable
|
|
1618
|
+
Inject a custom message into the session. Custom messages participate in LLM context. For durable data that should not be sent to the LLM, use [`pi.appendEntry()`](#piappendentrycustomtype-data).
|
|
1522
1619
|
|
|
1523
1620
|
```typescript
|
|
1524
1621
|
pi.sendMessage({
|
|
@@ -1537,11 +1634,12 @@ pi.sendMessage({
|
|
|
1537
1634
|
- `"steer"` (default) - Queues the message while streaming. Delivered after the current assistant turn finishes executing its tool calls, before the next LLM call.
|
|
1538
1635
|
- `"followUp"` - Waits for agent to finish. Delivered only when agent has no more tool calls.
|
|
1539
1636
|
- `"nextTurn"` - Queued for next user prompt. Does not interrupt or trigger anything.
|
|
1540
|
-
- `triggerTurn: true` - If agent is idle, trigger an LLM response immediately. Only applies to `"steer"` and `"followUp"` modes (ignored for `"nextTurn"`).
|
|
1637
|
+
- `triggerTurn: true` - If agent is idle, trigger an LLM response immediately. Only applies to `"steer"` and `"followUp"` modes (ignored for `"nextTurn"`). Without it, an idle session stores the message without starting a turn.
|
|
1638
|
+
- `triggerTurn: false` while streaming - The message is not steered or queued as a follow-up; it is appended after the current turn ends.
|
|
1541
1639
|
|
|
1542
1640
|
### pi.sendUserMessage(content, options?)
|
|
1543
1641
|
|
|
1544
|
-
Send a user message to the agent. Unlike `sendMessage()` which sends custom messages, this sends an actual user message that appears as if typed by the user.
|
|
1642
|
+
Send a user message to the agent. Unlike `sendMessage()` which sends custom messages, this sends an actual user message that appears as if typed by the user. It starts or queues a turn unless an `input` handler handles it or, with `expandPromptTemplates: true`, it runs an extension command.
|
|
1545
1643
|
|
|
1546
1644
|
```typescript
|
|
1547
1645
|
// Simple text message
|
|
@@ -1550,7 +1648,7 @@ pi.sendUserMessage("What is 2+2?");
|
|
|
1550
1648
|
// With content array (text + images)
|
|
1551
1649
|
pi.sendUserMessage([
|
|
1552
1650
|
{ type: "text", text: "Describe this image:" },
|
|
1553
|
-
{ type: "image",
|
|
1651
|
+
{ type: "image", data: "...", mimeType: "image/png" },
|
|
1554
1652
|
]);
|
|
1555
1653
|
|
|
1556
1654
|
// During streaming - must specify delivery mode
|
|
@@ -1567,17 +1665,16 @@ pi.sendUserMessage("/review src/index.ts", { expandPromptTemplates: true });
|
|
|
1567
1665
|
- `"followUp"` - Waits for agent to finish all tools
|
|
1568
1666
|
- `expandPromptTemplates` - Dispatch extension commands and expand skill commands and prompt templates. Defaults to `false`.
|
|
1569
1667
|
|
|
1570
|
-
When not streaming, the message is sent immediately and triggers a new turn. When streaming without `deliverAs`,
|
|
1668
|
+
When not streaming, the message is sent immediately and triggers a new turn. When streaming without `deliverAs`, the message is rejected and pi reports an extension error.
|
|
1571
1669
|
|
|
1572
1670
|
See [send-user-message.ts](../examples/extensions/send-user-message.ts) for a complete example.
|
|
1573
1671
|
|
|
1574
1672
|
### pi.appendEntry(customType, data?)
|
|
1575
1673
|
|
|
1576
|
-
Persist extension data. Custom entries do NOT participate in LLM context.
|
|
1674
|
+
Persist extension data. Custom entries do NOT participate in LLM context.
|
|
1577
1675
|
|
|
1578
1676
|
```typescript
|
|
1579
1677
|
pi.appendEntry("my-state", { count: 42 });
|
|
1580
|
-
pi.appendEntry("status-card", { title: "Indexed files", count: 17 });
|
|
1581
1678
|
|
|
1582
1679
|
// Restore on reload
|
|
1583
1680
|
pi.on("session_start", async (_event, ctx) => {
|
|
@@ -1591,7 +1688,7 @@ pi.on("session_start", async (_event, ctx) => {
|
|
|
1591
1688
|
|
|
1592
1689
|
### pi.setSessionName(name)
|
|
1593
1690
|
|
|
1594
|
-
Set the session display name
|
|
1691
|
+
Set the session display name, returned by RPC `get_state` and stored as a `session_info` entry.
|
|
1595
1692
|
|
|
1596
1693
|
```typescript
|
|
1597
1694
|
pi.setSessionName("Refactor auth module");
|
|
@@ -1610,7 +1707,7 @@ if (name) {
|
|
|
1610
1707
|
|
|
1611
1708
|
### pi.setLabel(entryId, label)
|
|
1612
1709
|
|
|
1613
|
-
Set or clear a label on an entry. Labels are user-defined markers for bookmarking and navigation
|
|
1710
|
+
Set or clear a label on an entry. Labels are user-defined markers for bookmarking and navigation, returned with RPC `get_tree` entries.
|
|
1614
1711
|
|
|
1615
1712
|
```typescript
|
|
1616
1713
|
// Set a label
|
|
@@ -1641,10 +1738,10 @@ pi.registerCommand("stats", {
|
|
|
1641
1738
|
});
|
|
1642
1739
|
```
|
|
1643
1740
|
|
|
1644
|
-
Optional: add argument auto-completion for `/command
|
|
1741
|
+
Optional: add argument auto-completion for `/command ...`. `getArgumentCompletions` can also return a `Promise`:
|
|
1645
1742
|
|
|
1646
1743
|
```typescript
|
|
1647
|
-
import type { AutocompleteItem } from "@punch-bot/
|
|
1744
|
+
import type { AutocompleteItem } from "@punch-bot/cli";
|
|
1648
1745
|
|
|
1649
1746
|
pi.registerCommand("deploy", {
|
|
1650
1747
|
description: "Deploy to an environment",
|
|
@@ -1663,7 +1760,7 @@ pi.registerCommand("deploy", {
|
|
|
1663
1760
|
### pi.getCommands()
|
|
1664
1761
|
|
|
1665
1762
|
Get the slash commands available for invocation via `prompt` in the current session. Includes extension commands, prompt templates, and skill commands.
|
|
1666
|
-
The list matches the RPC `get_commands` ordering: extensions first, then templates, then skills.
|
|
1763
|
+
The list matches the RPC `get_commands` ordering: extensions first, then templates, then skills. Skill commands are named `skill:<name>`.
|
|
1667
1764
|
|
|
1668
1765
|
```typescript
|
|
1669
1766
|
const commands = pi.getCommands();
|
|
@@ -1690,45 +1787,7 @@ Each entry has this shape:
|
|
|
1690
1787
|
|
|
1691
1788
|
Use `sourceInfo` as the canonical provenance field. Do not infer ownership from command names or from ad hoc path parsing.
|
|
1692
1789
|
|
|
1693
|
-
|
|
1694
|
-
mode and would not execute if sent via `prompt`.
|
|
1695
|
-
|
|
1696
|
-
### pi.registerMessageRenderer(customType, renderer)
|
|
1697
|
-
|
|
1698
|
-
Register a custom TUI renderer for custom messages with your `customType`. Custom messages are created with `pi.sendMessage()` and participate in LLM context. See [Custom UI](#custom-ui).
|
|
1699
|
-
|
|
1700
|
-
### pi.registerEntryRenderer(customType, renderer)
|
|
1701
|
-
|
|
1702
|
-
Register a custom TUI renderer for custom entries with your `customType`. Custom entries are created with `pi.appendEntry()` and do not participate in LLM context.
|
|
1703
|
-
|
|
1704
|
-
```typescript
|
|
1705
|
-
import { Box, Text } from "@punch-bot/tui";
|
|
1706
|
-
|
|
1707
|
-
pi.registerEntryRenderer("status-card", (entry, { expanded }, theme) => {
|
|
1708
|
-
const data = entry.data as { title: string; count: number };
|
|
1709
|
-
const box = new Box(1, 1, (text) => theme.bg("customMessageBg", text));
|
|
1710
|
-
box.addChild(new Text(`${theme.bold(data.title)}: ${data.count}`));
|
|
1711
|
-
if (expanded) {
|
|
1712
|
-
box.addChild(new Text(theme.fg("dim", JSON.stringify(data, null, 2))));
|
|
1713
|
-
}
|
|
1714
|
-
return box;
|
|
1715
|
-
});
|
|
1716
|
-
|
|
1717
|
-
pi.appendEntry("status-card", { title: "Indexed files", count: 17 });
|
|
1718
|
-
```
|
|
1719
|
-
|
|
1720
|
-
### pi.registerShortcut(shortcut, options)
|
|
1721
|
-
|
|
1722
|
-
Register a keyboard shortcut. See [keybindings.md](keybindings.md) for the shortcut format and built-in keybindings.
|
|
1723
|
-
|
|
1724
|
-
```typescript
|
|
1725
|
-
pi.registerShortcut("ctrl+shift+p", {
|
|
1726
|
-
description: "Toggle plan mode",
|
|
1727
|
-
handler: async (ctx) => {
|
|
1728
|
-
ctx.ui.notify("Toggled!");
|
|
1729
|
-
},
|
|
1730
|
-
});
|
|
1731
|
-
```
|
|
1790
|
+
Pi has no other slash commands. A prompt such as `/model` that matches no extension command, prompt template, or skill is sent to the model as plain text. Use extension APIs such as `pi.setModel()` instead.
|
|
1732
1791
|
|
|
1733
1792
|
### pi.registerFlag(name, options)
|
|
1734
1793
|
|
|
@@ -1741,21 +1800,25 @@ pi.registerFlag("plan", {
|
|
|
1741
1800
|
default: false,
|
|
1742
1801
|
});
|
|
1743
1802
|
|
|
1744
|
-
// Check value
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1803
|
+
// Check the value after loading; in the factory, getFlag() returns the default
|
|
1804
|
+
pi.on("session_start", () => {
|
|
1805
|
+
if (pi.getFlag("plan")) {
|
|
1806
|
+
// Plan mode enabled
|
|
1807
|
+
}
|
|
1808
|
+
});
|
|
1748
1809
|
```
|
|
1749
1810
|
|
|
1750
1811
|
### pi.exec(command, args, options?)
|
|
1751
1812
|
|
|
1752
|
-
Execute a shell
|
|
1813
|
+
Execute a command without a shell.
|
|
1753
1814
|
|
|
1754
1815
|
```typescript
|
|
1755
1816
|
const result = await pi.exec("git", ["status"], { signal, timeout: 5000 });
|
|
1756
|
-
// result.stdout, result.stderr, result.code, result.killed
|
|
1817
|
+
// result.stdout, result.stderr, result.code, result.killed, result.truncated
|
|
1757
1818
|
```
|
|
1758
1819
|
|
|
1820
|
+
Options: `signal` and `timeout` terminate the command, `cwd` sets the working directory, and `maxBuffer` limits stdout and stderr combined (default 256 MiB). When output exceeds `maxBuffer`, pi terminates the command and returns the output up to the limit with `truncated: true`, `killed: true`, and a nonzero `code`. `killed` is true whenever pi terminated the command: timeout, abort, or `maxBuffer`. A command that ignores SIGTERM gets SIGKILL after 5 seconds.
|
|
1821
|
+
|
|
1759
1822
|
### pi.getActiveTools() / pi.getAllTools() / pi.setActiveTools(names)
|
|
1760
1823
|
|
|
1761
1824
|
Manage active tools. This works for both built-in tools and dynamically registered tools. `pi.getActiveTools()` returns the active tool names as `string[]`; `pi.getAllTools()` returns metadata for all configured tools.
|
|
@@ -1768,21 +1831,26 @@ const all = pi.getAllTools();
|
|
|
1768
1831
|
// description: "Read file contents...",
|
|
1769
1832
|
// parameters: ...,
|
|
1770
1833
|
// promptGuidelines: ["Use read to examine files instead of cat or sed."],
|
|
1771
|
-
//
|
|
1834
|
+
// exposure: "direct",
|
|
1835
|
+
// sourceInfo: { path: "builtin:read", source: "builtin", scope: "temporary", origin: "top-level" }
|
|
1772
1836
|
// }, ...]
|
|
1773
|
-
|
|
1837
|
+
// Tools shipped with Pi: core tools and tools from built-in extensions such as builtin:mcp
|
|
1838
|
+
const shippedTools = all.filter((t) => t.sourceInfo.source === "builtin");
|
|
1839
|
+
// Tools from installed or local extensions
|
|
1774
1840
|
const extensionTools = all.filter((t) => t.sourceInfo.source !== "builtin" && t.sourceInfo.source !== "sdk");
|
|
1775
1841
|
pi.setActiveTools([...new Set([...active, "my_custom_tool"])]); // Keep current tools and enable my_custom_tool
|
|
1776
|
-
pi.setActiveTools(["read", "bash"]); //
|
|
1842
|
+
pi.setActiveTools(["read", "bash"]); // Only read and bash
|
|
1777
1843
|
```
|
|
1778
1844
|
|
|
1779
|
-
`pi.getAllTools()` returns `name`, `description`, `parameters`, `promptGuidelines`, and `
|
|
1845
|
+
`pi.getAllTools()` returns `name`, `description`, `parameters`, `promptGuidelines`, `exposure`, `sourceInfo`, and, when set, `namespace`, `annotations`, and `reachesTools`.
|
|
1780
1846
|
|
|
1781
|
-
Typical `sourceInfo
|
|
1782
|
-
- `builtin` for built-in
|
|
1783
|
-
- `sdk` for tools passed via `createAgentSession({ customTools })`
|
|
1847
|
+
Typical `sourceInfo` values:
|
|
1848
|
+
- `source: "builtin"` for tools shipped with pi: core tools (`path: "builtin:<tool>"`) and tools registered by built-in extensions such as `builtin:mcp` (`path: "builtin:<extension>"`)
|
|
1849
|
+
- `source: "sdk"` for tools passed via `createAgentSession({ customTools })`
|
|
1784
1850
|
- extension source metadata for tools registered by extensions
|
|
1785
1851
|
|
|
1852
|
+
`pi.setActiveTools()` ignores unknown and `hidden` tools. Tools with `codemode` or `deferred` exposure stay callable from codemode scripts whether active or not.
|
|
1853
|
+
|
|
1786
1854
|
### pi.setModel(model)
|
|
1787
1855
|
|
|
1788
1856
|
Set the model for the current session. The change is recorded in session history and restored when that session is resumed, but it does not change the configured `defaultProvider` or `defaultModel` used by new sessions. Returns `false` if authentication is not configured for the model's provider. See [models.md](models.md) for configuring custom models.
|
|
@@ -1821,7 +1889,7 @@ pi.events.emit("my:event", { ... });
|
|
|
1821
1889
|
|
|
1822
1890
|
Register or override a model provider dynamically. Useful for proxies, custom endpoints, or team-wide model configurations.
|
|
1823
1891
|
|
|
1824
|
-
Calls made during the extension factory function are queued and applied once the runner initialises. Calls made after that — for example from a command handler following a user setup flow — take effect immediately without requiring a
|
|
1892
|
+
Calls made during the extension factory function are queued and applied once the runner initialises. Calls made after that — for example from a command handler following a user setup flow — take effect immediately without requiring a reload.
|
|
1825
1893
|
|
|
1826
1894
|
Dynamic providers can implement `refreshModels`. Pi calls it during model refresh, publishes the returned list synchronously through the provider, and passes the canonical credential/stored-catalog/network/signal context. The extension decides whether to persist catalog metadata through generation-checked `context.publish({ persist: entry })`; live servers such as llama.cpp can return models without persisting them.
|
|
1827
1895
|
|
|
@@ -1830,7 +1898,7 @@ Dynamic providers can implement `refreshModels`. Pi calls it during model refres
|
|
|
1830
1898
|
Extensions that need native provider auth, filtering, refresh, or stream behavior can register a complete `Provider` from `@punch-bot/ai`. The provider becomes the composition base and `models.json` overrides still apply above it.
|
|
1831
1899
|
|
|
1832
1900
|
```typescript
|
|
1833
|
-
import { createProvider, openAICompletionsApi } from "@punch-bot/ai";
|
|
1901
|
+
import { createProvider, openAICompletionsApi } from "@punch-bot/ai/compat";
|
|
1834
1902
|
|
|
1835
1903
|
const provider = createProvider({
|
|
1836
1904
|
id: "local-server",
|
|
@@ -1884,7 +1952,7 @@ pi.registerProvider("llama.cpp", {
|
|
|
1884
1952
|
api: "openai-completions",
|
|
1885
1953
|
async refreshModels({ signal }) {
|
|
1886
1954
|
const response = await fetch("http://localhost:8080/v1/models", { signal });
|
|
1887
|
-
const { data } = await response.json();
|
|
1955
|
+
const { data } = (await response.json()) as { data: Array<{ id: string }> };
|
|
1888
1956
|
return data.map(({ id }) => ({
|
|
1889
1957
|
id,
|
|
1890
1958
|
name: id,
|
|
@@ -1902,7 +1970,7 @@ pi.registerProvider("anthropic", {
|
|
|
1902
1970
|
baseUrl: "https://proxy.example.com"
|
|
1903
1971
|
});
|
|
1904
1972
|
|
|
1905
|
-
// Register provider with OAuth support
|
|
1973
|
+
// Register provider with OAuth support
|
|
1906
1974
|
pi.registerProvider("corporate-ai", {
|
|
1907
1975
|
baseUrl: "https://ai.corp.com",
|
|
1908
1976
|
api: "openai-responses",
|
|
@@ -1930,15 +1998,15 @@ pi.registerProvider("corporate-ai", {
|
|
|
1930
1998
|
The object form accepts a complete pi-ai `Provider`, including native `auth`, `getModels`, `refreshModels`, `filterModels`, `stream`, and `streamSimple` behavior.
|
|
1931
1999
|
|
|
1932
2000
|
**Legacy config options:**
|
|
1933
|
-
- `name` - Display name for the provider
|
|
1934
|
-
- `baseUrl` - API endpoint URL.
|
|
1935
|
-
- `apiKey` - API key literal, environment interpolation (`$ENV_VAR` or `${ENV_VAR}`), or leading `!command`.
|
|
2001
|
+
- `name` - Display name for the provider.
|
|
2002
|
+
- `baseUrl` - API endpoint URL. Each defined model needs one, from the model definition or the provider.
|
|
2003
|
+
- `apiKey` - API key literal, environment interpolation (`$ENV_VAR` or `${ENV_VAR}`), or leading `!command`. Optional: without it, users store a key in `auth.json`. `$$` escapes `$`, and `$!` escapes a literal `!` without triggering command execution.
|
|
1936
2004
|
- `api` - API type: `"anthropic-messages"`, `"openai-completions"`, `"openai-responses"`, etc.
|
|
1937
2005
|
- `headers` - Custom headers to include in requests.
|
|
1938
2006
|
- `authHeader` - If true, adds `Authorization: Bearer` header automatically.
|
|
1939
2007
|
- `models` - Array of model definitions. If provided, replaces all existing models for this provider. Model definitions can set `baseUrl` to override the provider endpoint for that model.
|
|
1940
2008
|
- `refreshModels` - Async dynamic discovery callback. Its returned models replace extension-provided models. `context.stored` contains the persisted provider snapshot; use generation-checked `context.publish({ persist: entry })` only when updated catalog data should persist. Use `persist: null` to delete that snapshot.
|
|
1941
|
-
- `oauth` - OAuth provider config
|
|
2009
|
+
- `oauth` - OAuth provider config. `pi auth login <provider>` runs this flow for providers that built-in or user extensions register, but not for those a project's own extensions register. SDK applications can also run it through `session.modelRuntime.login()`.
|
|
1942
2010
|
- `streamSimple` - Custom streaming implementation for non-standard APIs.
|
|
1943
2011
|
|
|
1944
2012
|
See [custom-provider.md](custom-provider.md) for advanced topics: custom streaming APIs, OAuth details, model definition reference.
|
|
@@ -1947,7 +2015,7 @@ See [custom-provider.md](custom-provider.md) for advanced topics: custom streami
|
|
|
1947
2015
|
|
|
1948
2016
|
Remove a previously registered provider and its models. Built-in models that were overridden by the provider are restored. Has no effect if the provider was not registered.
|
|
1949
2017
|
|
|
1950
|
-
Like `registerProvider`, this takes effect immediately when called after the initial load phase, so
|
|
2018
|
+
Like `registerProvider`, this takes effect immediately when called after the initial load phase, so no reload is required.
|
|
1951
2019
|
|
|
1952
2020
|
```typescript
|
|
1953
2021
|
pi.registerCommand("my-setup-teardown", {
|
|
@@ -1958,6 +2026,20 @@ pi.registerCommand("my-setup-teardown", {
|
|
|
1958
2026
|
});
|
|
1959
2027
|
```
|
|
1960
2028
|
|
|
2029
|
+
### pi.registerVirtualModel(model) / pi.unregisterVirtualModel(provider, id)
|
|
2030
|
+
|
|
2031
|
+
Register a selectable catalog entry that routes each request to a physical model. `ctx.model` and the session's model selection name the virtual model; assistant messages record the physical model and thinking level the router picked. Registering the same provider and ID again replaces the virtual model. See [Virtual Models](virtual-models.md).
|
|
2032
|
+
|
|
2033
|
+
### pi.registerMcpServer(name, config) / pi.unregisterMcpServer(name) / pi.getMcpServers()
|
|
2034
|
+
|
|
2035
|
+
Register an MCP server for the current session. See [MCP Servers](#mcp-servers).
|
|
2036
|
+
|
|
2037
|
+
### pi.getSettings()
|
|
2038
|
+
|
|
2039
|
+
Return a copy of the effective settings, with global and project settings merged and overrides applied.
|
|
2040
|
+
|
|
2041
|
+
<a id="persist-state"></a>
|
|
2042
|
+
|
|
1961
2043
|
## State Management
|
|
1962
2044
|
|
|
1963
2045
|
Extensions with state should store it in tool result `details` for proper branching support:
|
|
@@ -1966,17 +2048,19 @@ Extensions with state should store it in tool result `details` for proper branch
|
|
|
1966
2048
|
export default function (pi: ExtensionAPI) {
|
|
1967
2049
|
let items: string[] = [];
|
|
1968
2050
|
|
|
1969
|
-
// Reconstruct state from
|
|
1970
|
-
|
|
2051
|
+
// Reconstruct state from the active branch
|
|
2052
|
+
const reconstruct = (ctx: ExtensionContext) => {
|
|
1971
2053
|
items = [];
|
|
1972
2054
|
for (const entry of ctx.sessionManager.getBranch()) {
|
|
1973
2055
|
if (entry.type === "message" && entry.message.role === "toolResult") {
|
|
1974
2056
|
if (entry.message.toolName === "my_tool") {
|
|
1975
|
-
items = entry.message.details?.items ?? [];
|
|
2057
|
+
items = (entry.message.details as { items?: string[] } | undefined)?.items ?? [];
|
|
1976
2058
|
}
|
|
1977
2059
|
}
|
|
1978
2060
|
}
|
|
1979
|
-
}
|
|
2061
|
+
};
|
|
2062
|
+
pi.on("session_start", async (_event, ctx) => reconstruct(ctx));
|
|
2063
|
+
pi.on("session_tree", async (_event, ctx) => reconstruct(ctx)); // ctx.navigateTree() changes the branch
|
|
1980
2064
|
|
|
1981
2065
|
pi.registerTool({
|
|
1982
2066
|
name: "my_tool",
|
|
@@ -1992,17 +2076,21 @@ export default function (pi: ExtensionAPI) {
|
|
|
1992
2076
|
}
|
|
1993
2077
|
```
|
|
1994
2078
|
|
|
2079
|
+
Rebuild from `getBranch()`, not from every entry: abandoned branches represent alternative histories. Use [`pi.appendEntry()`](#piappendentrycustomtype-data) for durable data that should not reach the model.
|
|
2080
|
+
|
|
2081
|
+
<a id="register-tools"></a>
|
|
2082
|
+
|
|
1995
2083
|
## Custom Tools
|
|
1996
2084
|
|
|
1997
|
-
Register tools the LLM can call via `pi.registerTool()`. Tools appear in the system prompt
|
|
2085
|
+
Register tools the LLM can call via `pi.registerTool()`. Tools appear in the system prompt.
|
|
1998
2086
|
|
|
1999
|
-
Use `promptSnippet` for a short one-line entry in the
|
|
2087
|
+
Use `promptSnippet` for a short one-line entry in the `<tools>` section of the default system prompt. If omitted, custom tools are left out of that section.
|
|
2000
2088
|
|
|
2001
|
-
Use `promptGuidelines` to add tool-specific bullets to the default system prompt
|
|
2089
|
+
Use `promptGuidelines` to add tool-specific bullets to the `<rules>` section of the default system prompt. These bullets are included only while the tool is active (for example, after `pi.setActiveTools([...])`).
|
|
2002
2090
|
|
|
2003
|
-
**Important:** `promptGuidelines` bullets are appended flat to the
|
|
2091
|
+
**Important:** `promptGuidelines` bullets are appended flat to the `<rules>` section with no tool name prefix or grouping. Each guideline must name the tool it refers to — avoid "Use this tool when..." because the LLM cannot tell which tool "this" means. Write "Use my_tool when..." instead.
|
|
2004
2092
|
|
|
2005
|
-
Note: Some models
|
|
2093
|
+
Note: Some models include the @ prefix in tool path arguments. Built-in tools strip a leading @ before resolving paths. If your custom tool accepts a path, normalize a leading @ as well.
|
|
2006
2094
|
|
|
2007
2095
|
If your custom tool mutates files, use `withFileMutationQueue()` so it participates in the same per-file queue as built-in `edit` and `write`. This matters because tool calls run in parallel by default. Without the queue, two tools can read the same old file contents, compute different updates, and then whichever write lands last overwrites the other.
|
|
2008
2096
|
|
|
@@ -2037,9 +2125,13 @@ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
|
2037
2125
|
### Tool Definition
|
|
2038
2126
|
|
|
2039
2127
|
```typescript
|
|
2040
|
-
import {
|
|
2041
|
-
import {
|
|
2042
|
-
|
|
2128
|
+
import { StringEnum } from "@punch-bot/cli";
|
|
2129
|
+
import { type Static, Type } from "typebox";
|
|
2130
|
+
|
|
2131
|
+
const myToolSchema = Type.Object({
|
|
2132
|
+
action: StringEnum(["list", "add"] as const),
|
|
2133
|
+
text: Type.Optional(Type.String()),
|
|
2134
|
+
});
|
|
2043
2135
|
|
|
2044
2136
|
pi.registerTool({
|
|
2045
2137
|
name: "my_tool",
|
|
@@ -2049,29 +2141,26 @@ pi.registerTool({
|
|
|
2049
2141
|
promptGuidelines: [
|
|
2050
2142
|
"Use my_tool for todo planning instead of direct file edits when the user asks for a task list."
|
|
2051
2143
|
],
|
|
2052
|
-
parameters:
|
|
2053
|
-
action: StringEnum(["list", "add"] as const), // Use StringEnum for Google compatibility
|
|
2054
|
-
text: Type.Optional(Type.String()),
|
|
2055
|
-
}),
|
|
2144
|
+
parameters: myToolSchema,
|
|
2056
2145
|
prepareArguments(args) {
|
|
2057
|
-
|
|
2058
|
-
const input = args as { action?:
|
|
2059
|
-
if (
|
|
2060
|
-
return { ...input, action: input.oldAction }
|
|
2146
|
+
// Fold a legacy `oldAction` field into `action`. Schema validation still runs afterwards.
|
|
2147
|
+
const input = (args ?? {}) as { action?: unknown; oldAction?: unknown };
|
|
2148
|
+
if (input.action === undefined && input.oldAction !== undefined) {
|
|
2149
|
+
return { ...input, action: input.oldAction } as Static<typeof myToolSchema>;
|
|
2061
2150
|
}
|
|
2062
|
-
return args
|
|
2151
|
+
return args as Static<typeof myToolSchema>;
|
|
2063
2152
|
},
|
|
2064
2153
|
|
|
2065
2154
|
async execute(toolCallId, params, signal, onUpdate, ctx) {
|
|
2066
2155
|
// Check for cancellation
|
|
2067
2156
|
if (signal?.aborted) {
|
|
2068
|
-
return { content: [{ type: "text", text: "Cancelled" }] };
|
|
2157
|
+
return { content: [{ type: "text", text: "Cancelled" }], details: {} };
|
|
2069
2158
|
}
|
|
2070
2159
|
|
|
2071
|
-
// Stream progress updates
|
|
2160
|
+
// Stream progress updates; partial results also need details
|
|
2072
2161
|
onUpdate?.({
|
|
2073
2162
|
content: [{ type: "text", text: "Working..." }],
|
|
2074
|
-
details: {
|
|
2163
|
+
details: {},
|
|
2075
2164
|
});
|
|
2076
2165
|
|
|
2077
2166
|
// Run commands via pi.exec (captured from extension closure)
|
|
@@ -2087,18 +2176,16 @@ pi.registerTool({
|
|
|
2087
2176
|
terminate: true,
|
|
2088
2177
|
};
|
|
2089
2178
|
},
|
|
2090
|
-
|
|
2091
|
-
// Optional: Custom rendering
|
|
2092
|
-
renderCall(args, theme, context) { ... },
|
|
2093
|
-
renderResult(result, options, theme, context) { ... },
|
|
2094
2179
|
});
|
|
2095
2180
|
```
|
|
2096
2181
|
|
|
2097
|
-
**
|
|
2182
|
+
**Result fields:** Every result, including partial results passed to `onUpdate`, needs model-facing `content` and a `details` value. Use `details: undefined` when there is nothing to store; the type of `details` must match across all results of the tool.
|
|
2098
2183
|
|
|
2099
|
-
**
|
|
2184
|
+
**Usage accounting:** If a tool makes nested LLM calls, return their combined `Usage` as `usage`. Pi persists it on the tool result and includes it in RPC `get_session_stats` and SDK session totals. `tool_result` handlers can inspect or replace this value.
|
|
2100
2185
|
|
|
2101
|
-
**
|
|
2186
|
+
**Signaling errors:** To mark a tool execution as failed, throw an error from `execute`, or return a result with `isError: true`. Both report an error result to the LLM; a returned result also keeps `details` and `structuredContent` for rendering and scripts. Other returned values never set the error flag.
|
|
2187
|
+
|
|
2188
|
+
**Early termination:** Return `terminate: true` from `execute()` to hint that the automatic follow-up LLM call should be skipped after the current tool batch. This only takes effect when every finalized tool result in that batch is terminating.
|
|
2102
2189
|
|
|
2103
2190
|
```typescript
|
|
2104
2191
|
// Correct: throw to signal an error
|
|
@@ -2110,44 +2197,51 @@ async execute(toolCallId, params) {
|
|
|
2110
2197
|
}
|
|
2111
2198
|
```
|
|
2112
2199
|
|
|
2113
|
-
**
|
|
2200
|
+
**String enums:** Prefer `StringEnum` from `@punch-bot/cli`. It produces a plain `enum` schema that every provider accepts, typed for TypeBox so `Type.Object` infers the literal union. `@punch-bot/ai` also exports a `StringEnum`, but it is typed for `@punch-bot/schema`, and inside `Type.Object` its field infers as `unknown`.
|
|
2201
|
+
|
|
2202
|
+
**Structured output:** Declare `outputSchema` and return a matching `structuredContent` when the result is data. The model still receives `content`; programmatic callers such as codemode scripts receive `structuredContent` instead of the text. Tools without `outputSchema` are passed to scripts as their text content. To report a failure that still carries data, return the result with `isError: true` instead of throwing: the model sees an error, and scripts still receive `structuredContent`.
|
|
2203
|
+
|
|
2204
|
+
**Execution mode:** Tool calls from one assistant message run in parallel by default. Set `executionMode: "sequential"` when a tool must not run concurrently with other calls, for example because it shares mutable in-memory state.
|
|
2205
|
+
|
|
2206
|
+
**Other definition fields:**
|
|
2207
|
+
|
|
2208
|
+
| Field | Purpose |
|
|
2209
|
+
|---|---|
|
|
2210
|
+
| `defaultActive` | Set `false` to register the tool inactive; `--tools`, the `defaultTools` setting, or `pi.setActiveTools()` activates it |
|
|
2211
|
+
| `exposure`, `namespace`, `annotations`, `reachesTools`, `prepareLoadout` | Control how the model and other tools reach the tool; see [Tool Exposure](#tool-exposure) |
|
|
2212
|
+
| `constrainedSampling` | Optional provider-side constrained sampling request for the tool's arguments |
|
|
2213
|
+
|
|
2214
|
+
Use `defineTool()` to keep parameter type inference when you assign a tool definition to a variable before registering it.
|
|
2114
2215
|
|
|
2115
2216
|
**Argument preparation:** `prepareArguments(args)` is optional. If defined, it runs before schema validation and before `execute()`. Use it to mimic an older accepted input shape when pi resumes an older session whose stored tool call arguments no longer match the current schema. Return the object you want validated against `parameters`. Keep the public schema strict. Do not add deprecated compatibility fields to `parameters` just to keep old resumed sessions working.
|
|
2116
2217
|
|
|
2117
2218
|
Example: an older session may contain an `edit` tool call with top-level `oldText` and `newText`, while the current schema only accepts `edits: [{ oldText, newText }]`.
|
|
2118
2219
|
|
|
2119
2220
|
```typescript
|
|
2221
|
+
const editSchema = Type.Object({
|
|
2222
|
+
path: Type.String(),
|
|
2223
|
+
edits: Type.Array(
|
|
2224
|
+
Type.Object({
|
|
2225
|
+
oldText: Type.String(),
|
|
2226
|
+
newText: Type.String(),
|
|
2227
|
+
}),
|
|
2228
|
+
),
|
|
2229
|
+
});
|
|
2230
|
+
type EditInput = Static<typeof editSchema>;
|
|
2231
|
+
|
|
2120
2232
|
pi.registerTool({
|
|
2121
2233
|
name: "edit",
|
|
2122
2234
|
label: "Edit",
|
|
2123
2235
|
description: "Edit a single file using exact text replacement",
|
|
2124
|
-
parameters:
|
|
2125
|
-
path: Type.String(),
|
|
2126
|
-
edits: Type.Array(
|
|
2127
|
-
Type.Object({
|
|
2128
|
-
oldText: Type.String(),
|
|
2129
|
-
newText: Type.String(),
|
|
2130
|
-
}),
|
|
2131
|
-
),
|
|
2132
|
-
}),
|
|
2236
|
+
parameters: editSchema,
|
|
2133
2237
|
prepareArguments(args) {
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
const input = args as {
|
|
2137
|
-
path?: string;
|
|
2138
|
-
edits?: Array<{ oldText: string; newText: string }>;
|
|
2139
|
-
oldText?: unknown;
|
|
2140
|
-
newText?: unknown;
|
|
2141
|
-
};
|
|
2142
|
-
|
|
2238
|
+
const input = (args ?? {}) as Partial<EditInput> & { oldText?: unknown; newText?: unknown };
|
|
2143
2239
|
if (typeof input.oldText !== "string" || typeof input.newText !== "string") {
|
|
2144
|
-
return args;
|
|
2240
|
+
return args as EditInput; // validation reports anything still invalid
|
|
2145
2241
|
}
|
|
2146
2242
|
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
edits: [...(input.edits ?? []), { oldText: input.oldText, newText: input.newText }],
|
|
2150
|
-
};
|
|
2243
|
+
const { oldText, newText, ...rest } = input;
|
|
2244
|
+
return { ...rest, edits: [...(input.edits ?? []), { oldText, newText }] } as EditInput;
|
|
2151
2245
|
},
|
|
2152
2246
|
async execute(toolCallId, params, signal, onUpdate, ctx) {
|
|
2153
2247
|
// params now matches the current schema
|
|
@@ -2161,7 +2255,7 @@ pi.registerTool({
|
|
|
2161
2255
|
|
|
2162
2256
|
### Overriding Built-in Tools
|
|
2163
2257
|
|
|
2164
|
-
Extensions can override built-in tools (`read`, `bash`, `powershell`, `edit`, `write`, `grep`, `find`, `ls`) by registering a tool with the same name.
|
|
2258
|
+
Extensions can override built-in tools (`read`, `bash`, `powershell`, `edit`, `write`, `grep`, `find`, `ls`) by registering a tool with the same name. The extension tool replaces the built-in without a warning.
|
|
2165
2259
|
|
|
2166
2260
|
```bash
|
|
2167
2261
|
# Extension's read tool replaces built-in read
|
|
@@ -2176,8 +2270,6 @@ pi --no-builtin-tools -e ./my-extension.ts
|
|
|
2176
2270
|
|
|
2177
2271
|
See [examples/extensions/tool-override.ts](../examples/extensions/tool-override.ts) for a complete example that overrides `read` with logging and access control.
|
|
2178
2272
|
|
|
2179
|
-
**Rendering:** Built-in renderer inheritance is resolved per slot. Execution override and rendering override are independent. If your override omits `renderCall`, the built-in `renderCall` is used. If your override omits `renderResult`, the built-in `renderResult` is used. If your override omits both, the built-in renderer is used automatically (syntax highlighting, diffs, etc.). This lets you wrap built-in tools for logging or access control without reimplementing the UI.
|
|
2180
|
-
|
|
2181
2273
|
**Prompt metadata:** `promptSnippet` and `promptGuidelines` are not inherited from the built-in tool. If your override should keep those prompt instructions, define them on the override explicitly.
|
|
2182
2274
|
|
|
2183
2275
|
**Your implementation must match the exact result shape**, including the `details` type. The UI and session logic depend on these shapes for rendering and state tracking.
|
|
@@ -2197,33 +2289,36 @@ Built-in tool implementations:
|
|
|
2197
2289
|
Built-in tools support pluggable operations for delegating to remote systems (SSH, containers, etc.):
|
|
2198
2290
|
|
|
2199
2291
|
```typescript
|
|
2200
|
-
import { createReadTool,
|
|
2292
|
+
import { createReadTool, type ReadOperations } from "@punch-bot/cli";
|
|
2201
2293
|
|
|
2202
|
-
|
|
2203
|
-
const remoteRead = createReadTool(cwd, {
|
|
2204
|
-
operations: {
|
|
2205
|
-
readFile: (path) => sshExec(remote, `cat ${path}`),
|
|
2206
|
-
access: (path) => sshExec(remote, `test -r ${path}`).then(() => {}),
|
|
2207
|
-
}
|
|
2208
|
-
});
|
|
2294
|
+
const localRead = createReadTool(cwd);
|
|
2209
2295
|
|
|
2210
|
-
// Register, checking
|
|
2296
|
+
// Register, checking the remote configuration at execution time
|
|
2211
2297
|
pi.registerTool({
|
|
2212
|
-
...
|
|
2298
|
+
...localRead,
|
|
2213
2299
|
async execute(id, params, signal, onUpdate, _ctx) {
|
|
2214
2300
|
const ssh = getSshConfig();
|
|
2215
2301
|
if (ssh) {
|
|
2216
|
-
const
|
|
2217
|
-
|
|
2302
|
+
const operations: ReadOperations = {
|
|
2303
|
+
readFile: (path) => sshReadBuffer(ssh, path), // must resolve to a Buffer
|
|
2304
|
+
access: (path) => sshExec(ssh, `test -r ${path}`).then(() => {}),
|
|
2305
|
+
};
|
|
2306
|
+
return createReadTool(cwd, { operations }).execute(id, params, signal, onUpdate);
|
|
2218
2307
|
}
|
|
2219
2308
|
return localRead.execute(id, params, signal, onUpdate);
|
|
2220
2309
|
},
|
|
2221
2310
|
});
|
|
2222
2311
|
```
|
|
2223
2312
|
|
|
2313
|
+
`ReadOperations.createReadStream` is optional. When it returns the file as an async iterable of chunks (a Node `Readable` works), `read` keeps only the lines it shows in memory, so large files can be read with `offset`/`limit`; without it, `read` loads the whole file through `readFile`.
|
|
2314
|
+
|
|
2315
|
+
The `create*ToolDefinition()` factories, such as `createReadToolDefinition()`, return complete tool definitions, including the built-in prompt snippet and guidelines, for the same purpose.
|
|
2316
|
+
|
|
2224
2317
|
**Operations interfaces:** `ReadOperations`, `WriteOperations`, `EditOperations`, `BashOperations`, `PowerShellOperations`, `LsOperations`, `GrepOperations`, `FindOperations`
|
|
2225
2318
|
|
|
2226
|
-
|
|
2319
|
+
`GrepOperations` only covers the directory check: grep always runs the local `rg`. To search a remote system, override grep's `execute()` instead, as the [Gondolin example](../examples/extensions/gondolin/index.ts) does.
|
|
2320
|
+
|
|
2321
|
+
For `user_bash`, extensions can reuse pi's local shell backend via `createLocalBashOperations()` (or `createLocalPowerShellOperations()`) instead of reimplementing local process spawning, shell resolution, and process-tree termination.
|
|
2227
2322
|
|
|
2228
2323
|
The `bash` and `powershell` tools also support a spawn hook to adjust the command, cwd, or env before execution:
|
|
2229
2324
|
|
|
@@ -2262,7 +2357,7 @@ The built-in limit is **50KB** (~10k tokens) and **2000 lines**, whichever is hi
|
|
|
2262
2357
|
import {
|
|
2263
2358
|
truncateHead, // Keep first N lines/bytes (good for file reads, search results)
|
|
2264
2359
|
truncateTail, // Keep last N lines/bytes (good for logs, command output)
|
|
2265
|
-
truncateLine, // Truncate a single line to
|
|
2360
|
+
truncateLine, // Truncate a single line to a character count; returns { text, wasTruncated }
|
|
2266
2361
|
formatSize, // Human-readable size (e.g., "50KB", "1.5MB")
|
|
2267
2362
|
DEFAULT_MAX_BYTES, // 50KB
|
|
2268
2363
|
DEFAULT_MAX_LINES, // 2000
|
|
@@ -2289,7 +2384,7 @@ async execute(toolCallId, params, signal, onUpdate, ctx) {
|
|
|
2289
2384
|
result += ` Full output saved to: ${tempFile}]`;
|
|
2290
2385
|
}
|
|
2291
2386
|
|
|
2292
|
-
return { content: [{ type: "text", text: result }] };
|
|
2387
|
+
return { content: [{ type: "text", text: result }], details: { truncation } };
|
|
2293
2388
|
}
|
|
2294
2389
|
```
|
|
2295
2390
|
|
|
@@ -2299,8 +2394,6 @@ async execute(toolCallId, params, signal, onUpdate, ctx) {
|
|
|
2299
2394
|
- Always inform the LLM when output is truncated and where to find the full version
|
|
2300
2395
|
- Document the truncation limits in your tool's description
|
|
2301
2396
|
|
|
2302
|
-
See [examples/extensions/truncated-tool.ts](../examples/extensions/truncated-tool.ts) for a complete example wrapping `rg` (ripgrep) with proper truncation.
|
|
2303
|
-
|
|
2304
2397
|
### Multiple Tools
|
|
2305
2398
|
|
|
2306
2399
|
One extension can register multiple tools with shared state:
|
|
@@ -2319,389 +2412,114 @@ export default function (pi: ExtensionAPI) {
|
|
|
2319
2412
|
}
|
|
2320
2413
|
```
|
|
2321
2414
|
|
|
2322
|
-
###
|
|
2415
|
+
### Dynamic Tool Loading
|
|
2323
2416
|
|
|
2324
|
-
|
|
2417
|
+
Extensions can register many tools while keeping only a small initial set active. A tool can then change the active set with `pi.setActiveTools()` during execution. pi stores the initial prompt and tool loadout in the transcript's first system message, then appends tool and prompt deltas before the next model request. Providers that cannot represent a transition receive a complete transcript checkpoint, which may invalidate the cached prefix.
|
|
2325
2418
|
|
|
2326
|
-
|
|
2419
|
+
The lifecycle is:
|
|
2327
2420
|
|
|
2328
|
-
|
|
2421
|
+
1. Register every tool with `pi.registerTool()` so it appears in `pi.getAllTools()`. Register searchable tools with `defaultActive: false` so they start inactive.
|
|
2422
|
+
2. Keep loader tools, such as `search_tools`, active.
|
|
2423
|
+
3. During loader execution, call `pi.setActiveTools()` with the desired active tool names. Names must already be registered; unknown and `hidden` names are ignored.
|
|
2329
2424
|
|
|
2330
|
-
|
|
2331
|
-
pi.registerTool({
|
|
2332
|
-
name: "my_tool",
|
|
2333
|
-
label: "My Tool",
|
|
2334
|
-
description: "Custom shell example",
|
|
2335
|
-
parameters: Type.Object({}),
|
|
2336
|
-
renderShell: "self",
|
|
2337
|
-
async execute() {
|
|
2338
|
-
return { content: [{ type: "text", text: "ok" }], details: undefined };
|
|
2339
|
-
},
|
|
2340
|
-
renderCall(args, theme, context) {
|
|
2341
|
-
return new Text(theme.fg("accent", "my custom shell"), 0, 0);
|
|
2342
|
-
},
|
|
2343
|
-
});
|
|
2344
|
-
```
|
|
2425
|
+
pi also ships a built-in `tool_search` tool. Register tools with `exposure: "deferred"` to make them findable by it instead of writing your own loader; see [Tool Exposure](#tool-exposure).
|
|
2345
2426
|
|
|
2346
|
-
|
|
2347
|
-
- `args` - the current tool call arguments
|
|
2348
|
-
- `state` - shared row-local state across `renderCall` and `renderResult`
|
|
2349
|
-
- `lastComponent` - the previously returned component for that slot, if any
|
|
2350
|
-
- `invalidate()` - request a rerender of this tool row
|
|
2351
|
-
- `toolCallId`, `cwd`, `executionStarted`, `argsComplete`, `isPartial`, `expanded`, `showImages`, `isError`
|
|
2427
|
+
#### Search tool example
|
|
2352
2428
|
|
|
2353
|
-
|
|
2354
|
-
|
|
2355
|
-
#### renderCall
|
|
2356
|
-
|
|
2357
|
-
Renders the tool call or header:
|
|
2358
|
-
|
|
2359
|
-
```typescript
|
|
2360
|
-
import { Text } from "@punch-bot/tui";
|
|
2361
|
-
|
|
2362
|
-
renderCall(args, theme, context) {
|
|
2363
|
-
const text = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
|
|
2364
|
-
let content = theme.fg("toolTitle", theme.bold("my_tool "));
|
|
2365
|
-
content += theme.fg("muted", args.action);
|
|
2366
|
-
if (args.text) {
|
|
2367
|
-
content += " " + theme.fg("dim", `"${args.text}"`);
|
|
2368
|
-
}
|
|
2369
|
-
text.setText(content);
|
|
2370
|
-
return text;
|
|
2371
|
-
}
|
|
2372
|
-
```
|
|
2373
|
-
|
|
2374
|
-
#### renderResult
|
|
2375
|
-
|
|
2376
|
-
Renders the tool result or output:
|
|
2377
|
-
|
|
2378
|
-
```typescript
|
|
2379
|
-
renderResult(result, { expanded, isPartial }, theme, context) {
|
|
2380
|
-
if (isPartial) {
|
|
2381
|
-
return new Text(theme.fg("warning", "Processing..."), 0, 0);
|
|
2382
|
-
}
|
|
2383
|
-
|
|
2384
|
-
if (result.details?.error) {
|
|
2385
|
-
return new Text(theme.fg("error", `Error: ${result.details.error}`), 0, 0);
|
|
2386
|
-
}
|
|
2387
|
-
|
|
2388
|
-
let text = theme.fg("success", "✓ Done");
|
|
2389
|
-
if (expanded && result.details?.items) {
|
|
2390
|
-
for (const item of result.details.items) {
|
|
2391
|
-
text += "\n " + theme.fg("dim", item);
|
|
2392
|
-
}
|
|
2393
|
-
}
|
|
2394
|
-
return new Text(text, 0, 0);
|
|
2395
|
-
}
|
|
2396
|
-
```
|
|
2397
|
-
|
|
2398
|
-
If a slot intentionally has no visible content, return an empty `Component` such as an empty `Container`.
|
|
2399
|
-
|
|
2400
|
-
#### Keybinding Hints
|
|
2401
|
-
|
|
2402
|
-
Use `keyHint()` to display keybinding hints that respect the active keybinding configuration:
|
|
2403
|
-
|
|
2404
|
-
```typescript
|
|
2405
|
-
import { keyHint } from "@punch-bot/cli";
|
|
2406
|
-
|
|
2407
|
-
renderResult(result, { expanded }, theme, context) {
|
|
2408
|
-
let text = theme.fg("success", "✓ Done");
|
|
2409
|
-
if (!expanded) {
|
|
2410
|
-
text += ` (${keyHint("app.tools.expand", "to expand")})`;
|
|
2411
|
-
}
|
|
2412
|
-
return new Text(text, 0, 0);
|
|
2413
|
-
}
|
|
2414
|
-
```
|
|
2415
|
-
|
|
2416
|
-
Available functions:
|
|
2417
|
-
- `keyHint(keybinding, description)` - Formats a configured keybinding id such as `"app.tools.expand"` or `"tui.select.confirm"`
|
|
2418
|
-
- `keyText(keybinding)` - Returns the raw configured key text for a keybinding id
|
|
2419
|
-
- `rawKeyHint(key, description)` - Format a raw key string
|
|
2420
|
-
|
|
2421
|
-
Use namespaced keybinding ids:
|
|
2422
|
-
- Coding-agent ids use the `app.*` namespace, for example `app.tools.expand`, `app.editor.external`, `app.session.rename`
|
|
2423
|
-
- Shared TUI ids use the `tui.*` namespace, for example `tui.select.confirm`, `tui.select.cancel`, `tui.input.tab`
|
|
2424
|
-
|
|
2425
|
-
For the exhaustive list of keybinding ids and defaults, see [keybindings.md](keybindings.md). `keybindings.json` uses those same namespaced ids.
|
|
2426
|
-
|
|
2427
|
-
Custom editors and `ctx.ui.custom()` components receive `keybindings: KeybindingsManager` as an injected argument. They should use that injected manager directly instead of calling `getKeybindings()` or `setKeybindings()`.
|
|
2428
|
-
|
|
2429
|
-
#### Best Practices
|
|
2430
|
-
|
|
2431
|
-
- Use `Text` with padding `(0, 0)`. The default Box handles padding.
|
|
2432
|
-
- Use `\n` for multi-line content.
|
|
2433
|
-
- Handle `isPartial` for streaming progress.
|
|
2434
|
-
- Support `expanded` for detail on demand.
|
|
2435
|
-
- Keep default view compact.
|
|
2436
|
-
- Read `context.args` in `renderResult` instead of copying args into `context.state`.
|
|
2437
|
-
- Use `context.state` only for data that must be shared across call and result slots.
|
|
2438
|
-
- Reuse `context.lastComponent` when the same component instance can be updated in place.
|
|
2439
|
-
- Use `renderShell: "self"` only when the default boxed shell gets in the way. In self-shell mode the tool is responsible for its own framing, padding, and background.
|
|
2440
|
-
|
|
2441
|
-
#### Fallback
|
|
2442
|
-
|
|
2443
|
-
Extensions are TypeScript modules that add executable behavior to Pi. Use one when a workflow needs tools, commands, event handlers, model providers, session state, or terminal UI rather than instructions alone.
|
|
2444
|
-
|
|
2445
|
-
An extension runs inside the Pi process with the same operating-system permissions. It can inspect prompts, tool calls, files, credentials, and session history, so load extensions only from sources you trust.
|
|
2446
|
-
|
|
2447
|
-
Typical extensions add an agent tool, protect paths, confirm dangerous commands, react to session events, modify context, expose a command, or display persistent status.
|
|
2448
|
-
|
|
2449
|
-
<a id="quick-start"></a>
|
|
2450
|
-
<a id="writing-an-extension"></a>
|
|
2451
|
-
<a id="create-an-extension"></a>
|
|
2452
|
-
|
|
2453
|
-
## Create and load an extension
|
|
2454
|
-
|
|
2455
|
-
An extension exports a default factory that receives `ExtensionAPI`. The factory registers capabilities for the current extension runtime.
|
|
2456
|
-
|
|
2457
|
-
Create `~/.pi/agent/extensions/hello.ts`:
|
|
2429
|
+
The following extension registers two inactive searchable tools and keeps `search_tools` active as their loader. The example uses simple keyword matching, but the search implementation could use BM25, embeddings, a remote catalog, or project-specific routing.
|
|
2458
2430
|
|
|
2459
2431
|
```typescript
|
|
2460
2432
|
import type { ExtensionAPI } from "@punch-bot/cli";
|
|
2433
|
+
import { Type } from "typebox";
|
|
2434
|
+
|
|
2435
|
+
const SEARCHABLE_TOOL_NAMES = new Set(["lookup_weather", "search_issues"]);
|
|
2461
2436
|
|
|
2462
2437
|
export default function (pi: ExtensionAPI) {
|
|
2463
|
-
pi.
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2438
|
+
pi.registerTool({
|
|
2439
|
+
name: "lookup_weather",
|
|
2440
|
+
label: "Lookup Weather",
|
|
2441
|
+
defaultActive: false,
|
|
2442
|
+
description: "Look up the current weather for a city",
|
|
2443
|
+
parameters: Type.Object({ city: Type.String() }),
|
|
2444
|
+
async execute(_toolCallId, params) {
|
|
2445
|
+
return {
|
|
2446
|
+
content: [{ type: "text", text: `Weather for ${params.city}: sunny` }],
|
|
2447
|
+
details: {},
|
|
2448
|
+
};
|
|
2467
2449
|
},
|
|
2468
2450
|
});
|
|
2469
|
-
}
|
|
2470
|
-
```
|
|
2471
|
-
|
|
2472
|
-
Start Pi and run `/hello`. During development, load a file directly:
|
|
2473
|
-
|
|
2474
|
-
```bash
|
|
2475
|
-
pi --extension ./hello.ts
|
|
2476
|
-
```
|
|
2477
2451
|
|
|
2478
|
-
|
|
2479
|
-
|
|
2480
|
-
|
|
2481
|
-
|
|
2482
|
-
|
|
2483
|
-
|
|
2484
|
-
|
|
2485
|
-
|
|
2486
|
-
|
|
2487
|
-
|
|
2488
|
-
|
|
2489
|
-
|
|
2490
|
-
|
|
2491
|
-
|
|
2492
|
-
<a id="understand-the-lifecycle"></a>
|
|
2493
|
-
|
|
2494
|
-
## Understand the runtime lifecycle
|
|
2495
|
-
|
|
2496
|
-
The factory can be synchronous or asynchronous. Pi waits for an asynchronous factory before startup continues, allowing it to fetch configuration or register providers needed during startup.
|
|
2497
|
-
|
|
2498
|
-
Do not start processes, sockets, watchers, or timers in the factory because some invocations load extensions without starting a session.
|
|
2499
|
-
Start long-lived resources from `session_start` or from the command or tool that needs them.
|
|
2500
|
-
Close session-scoped resources from an idempotent `session_shutdown` handler.
|
|
2501
|
-
|
|
2502
|
-
A normal prompt starts a run. The run repeats turns, then checks whether more work starts another low-level agent run:
|
|
2503
|
-
|
|
2504
|
-
```mermaid
|
|
2505
|
-
flowchart TD
|
|
2506
|
-
Input["input"] --> Before["before_agent_start"]
|
|
2507
|
-
Before --> AgentStart["agent_start"]
|
|
2508
|
-
AgentStart --> Turns[["turns"]]
|
|
2509
|
-
Turns --> AgentEnd["agent_end"]
|
|
2510
|
-
AgentEnd --> MoreRuns{"More work?"}
|
|
2511
|
-
MoreRuns -->|yes| AgentStart
|
|
2512
|
-
MoreRuns -->|no| BeforeSettle["agent_before_settle"]
|
|
2513
|
-
BeforeSettle --> Continue{"Continuation requested?"}
|
|
2514
|
-
Continue -->|yes| AgentStart
|
|
2515
|
-
Continue -->|no| Settled["agent_settled"]
|
|
2516
|
-
```
|
|
2517
|
-
|
|
2518
|
-
More work means a retry, recovery, compaction retry, or queued work.
|
|
2519
|
-
|
|
2520
|
-
Each turn sends one model request and executes the tool calls in the assistant response:
|
|
2521
|
-
|
|
2522
|
-
```mermaid
|
|
2523
|
-
flowchart TD
|
|
2524
|
-
TurnStart["turn_start"] --> Request[["model request"]]
|
|
2525
|
-
Request --> ToolDecision{"Tool calls?"}
|
|
2526
|
-
ToolDecision -->|yes| Tools[["tool execution"]]
|
|
2527
|
-
Tools --> TurnEnd["turn_end"]
|
|
2528
|
-
ToolDecision -->|no| TurnEnd
|
|
2529
|
-
TurnEnd --> MoreTurns{"Another turn?"}
|
|
2530
|
-
MoreTurns -->|yes| TurnStart
|
|
2531
|
-
MoreTurns -->|no| AgentEnd(["agent_end"])
|
|
2532
|
-
```
|
|
2533
|
-
|
|
2534
|
-
The model request runs these hooks in order:
|
|
2535
|
-
|
|
2536
|
-
1. `context`
|
|
2537
|
-
2. `context_with_system`
|
|
2538
|
-
3. `before_provider_headers`
|
|
2539
|
-
4. `before_provider_request`
|
|
2540
|
-
5. `after_provider_response`
|
|
2541
|
-
6. `provider_stream_event` and assistant message events
|
|
2542
|
-
|
|
2543
|
-
Tool execution runs these hooks in order for each tool call:
|
|
2544
|
-
|
|
2545
|
-
1. `tool_execution_start`
|
|
2546
|
-
2. `tool_call`
|
|
2547
|
-
3. `tool_execution_update` while the tool executes
|
|
2548
|
-
4. `tool_result`
|
|
2549
|
-
5. `tool_execution_end`
|
|
2550
|
-
|
|
2551
|
-
The lifecycle involves these event groups:
|
|
2552
|
-
|
|
2553
|
-
| Area | Events |
|
|
2554
|
-
|---|---|
|
|
2555
|
-
| Input preparation | `input`, `before_agent_start` |
|
|
2556
|
-
| Agent run | `agent_start`, `agent_end` |
|
|
2557
|
-
| Model turn | `turn_start`, `context`, `context_with_system`, `turn_end` |
|
|
2558
|
-
| Provider call | `before_provider_headers`, `before_provider_request`, `after_provider_response`, `provider_stream_event` |
|
|
2559
|
-
| Message lifecycle | `message_start`, `message_update`, `message_end` |
|
|
2560
|
-
| Tool execution | `tool_execution_start`, `tool_call`, `tool_execution_update`, `tool_result`, `tool_execution_end` |
|
|
2561
|
-
| Settlement | `agent_before_settle`, `agent_settled` |
|
|
2562
|
-
|
|
2563
|
-
Pi counts as busy while a run starts, including the compaction check and `before_agent_start`, so messages sent meanwhile go into the starting run. Message lifecycle events also cover user and tool-result messages; the model request list places only the assistant stream where it occurs in each turn.
|
|
2452
|
+
pi.registerTool({
|
|
2453
|
+
name: "search_issues",
|
|
2454
|
+
label: "Search Issues",
|
|
2455
|
+
defaultActive: false,
|
|
2456
|
+
description: "Search project issues by keyword",
|
|
2457
|
+
parameters: Type.Object({ query: Type.String() }),
|
|
2458
|
+
async execute(_toolCallId, params) {
|
|
2459
|
+
return {
|
|
2460
|
+
content: [{ type: "text", text: `No open issues matching ${params.query}` }],
|
|
2461
|
+
details: {},
|
|
2462
|
+
};
|
|
2463
|
+
},
|
|
2464
|
+
});
|
|
2564
2465
|
|
|
2565
|
-
|
|
2466
|
+
pi.registerTool({
|
|
2467
|
+
name: "search_tools",
|
|
2468
|
+
label: "Search Tools",
|
|
2469
|
+
description: "Search for and enable tools relevant to a task",
|
|
2470
|
+
promptSnippet: "Search for additional tools when the active tools cannot perform the task",
|
|
2471
|
+
promptGuidelines: [
|
|
2472
|
+
"Use search_tools when a task requires a capability that is not currently available.",
|
|
2473
|
+
],
|
|
2474
|
+
parameters: Type.Object({
|
|
2475
|
+
query: Type.String({ description: "Capability or task to search for" }),
|
|
2476
|
+
limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 10 })),
|
|
2477
|
+
}),
|
|
2478
|
+
async execute(_toolCallId, params) {
|
|
2479
|
+
const terms = params.query.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
|
|
2480
|
+
const matches = pi.getAllTools()
|
|
2481
|
+
.filter((tool) => SEARCHABLE_TOOL_NAMES.has(tool.name))
|
|
2482
|
+
.map((tool) => ({
|
|
2483
|
+
tool,
|
|
2484
|
+
score: terms.reduce(
|
|
2485
|
+
(score, term) =>
|
|
2486
|
+
score + (`${tool.name} ${tool.description}`.toLowerCase().includes(term) ? 1 : 0),
|
|
2487
|
+
0,
|
|
2488
|
+
),
|
|
2489
|
+
}))
|
|
2490
|
+
.filter((match) => match.score > 0)
|
|
2491
|
+
.sort((a, b) => b.score - a.score)
|
|
2492
|
+
.slice(0, params.limit ?? 3)
|
|
2493
|
+
.map((match) => match.tool.name);
|
|
2494
|
+
|
|
2495
|
+
if (matches.length === 0) {
|
|
2496
|
+
return {
|
|
2497
|
+
content: [{ type: "text", text: `No tools found for: ${params.query}` }],
|
|
2498
|
+
details: { matches: [] as string[], added: [] as string[] },
|
|
2499
|
+
};
|
|
2500
|
+
}
|
|
2566
2501
|
|
|
2567
|
-
|
|
2502
|
+
const active = pi.getActiveTools();
|
|
2503
|
+
const added = matches.filter((name) => !active.includes(name));
|
|
2504
|
+
pi.setActiveTools([...new Set([...active, ...added])]);
|
|
2568
2505
|
|
|
2569
|
-
|
|
2570
|
-
|
|
2571
|
-
|
|
2572
|
-
|
|
2573
|
-
|
|
2574
|
-
|
|
2575
|
-
|
|
2576
|
-
|
|
2577
|
-
|
|
2578
|
-
|
|
2579
|
-
|
|
2580
|
-
|
|
2581
|
-
Replacing -->|no| Stop["process exits"]
|
|
2582
|
-
SessionStart --> Discover["resources_discover"]
|
|
2506
|
+
return {
|
|
2507
|
+
content: [{
|
|
2508
|
+
type: "text",
|
|
2509
|
+
text: added.length > 0
|
|
2510
|
+
? `Loaded tools: ${added.join(", ")}`
|
|
2511
|
+
: `Matching tools already active: ${matches.join(", ")}`,
|
|
2512
|
+
}],
|
|
2513
|
+
details: { matches, added },
|
|
2514
|
+
};
|
|
2515
|
+
},
|
|
2516
|
+
});
|
|
2517
|
+
}
|
|
2583
2518
|
```
|
|
2584
2519
|
|
|
2585
|
-
`
|
|
2586
|
-
|
|
2587
|
-
### Choose an event by intent
|
|
2588
|
-
|
|
2589
|
-
| Goal | Event |
|
|
2590
|
-
|---|---|
|
|
2591
|
-
| Inspect, transform, or consume raw user input | `input` |
|
|
2592
|
-
| Change prompt sections, active tools, or add context before a run | `before_agent_start` |
|
|
2593
|
-
| Observe one low-level agent run | `agent_start`, `agent_end` |
|
|
2594
|
-
| Act after one model response and its tool calls | `turn_end` |
|
|
2595
|
-
| Filter conversation messages for one provider request | `context` |
|
|
2596
|
-
| Transform the complete transcript, including system messages | `context_with_system` |
|
|
2597
|
-
| Change request headers or the serialized provider payload | `before_provider_headers`, `before_provider_request` |
|
|
2598
|
-
| Observe provider response metadata or parsed stream events | `after_provider_response`, `provider_stream_event` |
|
|
2599
|
-
| Authorize or modify a tool call | `tool_call` |
|
|
2600
|
-
| Redact, annotate, or replace a tool result | `tool_result` |
|
|
2601
|
-
| Append final entries or request one last continuation | `agent_before_settle` |
|
|
2602
|
-
| Run notification work after automatic processing has stopped | `agent_settled` |
|
|
2603
|
-
| Initialize or release session-scoped resources | `session_start`, `session_shutdown` |
|
|
2604
|
-
|
|
2605
|
-
<a id="agent_start--agent_end--agent_before_settle--agent_settled"></a>
|
|
2606
|
-
|
|
2607
|
-
Use `agent_before_settle` when an extension must append entries or request one final continuation. Use `agent_settled` for notification-only work that should run after Pi has no automatic continuation remaining.
|
|
2608
|
-
|
|
2609
|
-
<a id="extensionapi-methods"></a>
|
|
2610
|
-
|
|
2611
|
-
## Choose an integration point
|
|
2612
|
-
|
|
2613
|
-
| Capability | Main API |
|
|
2614
|
-
|---|---|
|
|
2615
|
-
| Observe or modify lifecycle behavior | `pi.on()` |
|
|
2616
|
-
| Add a model-callable operation | `pi.registerTool()` |
|
|
2617
|
-
| Add a `/` command | `pi.registerCommand()` |
|
|
2618
|
-
| Add a shortcut or CLI flag | `pi.registerShortcut()` or `pi.registerFlag()` |
|
|
2619
|
-
| Send user or custom messages | `pi.sendUserMessage()` or `pi.sendMessage()` |
|
|
2620
|
-
| Persist non-context session data | `pi.appendEntry()` |
|
|
2621
|
-
| Change active tools, model, or thinking level | Session control methods on `pi` |
|
|
2622
|
-
| Add a model provider | `pi.registerProvider()` |
|
|
2623
|
-
| Add an MCP server | `pi.registerMcpServer()` |
|
|
2624
|
-
| Route each request to a model | [`pi.registerVirtualModel()`](virtual-models.md) |
|
|
2625
|
-
| Add terminal rendering | Renderer registration and `ctx.ui` |
|
|
2626
|
-
| Communicate with another extension | `pi.events` |
|
|
2627
|
-
|
|
2628
|
-
Use the exported declarations in [`extensions/types.ts`](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/src/core/extensions/types.ts) for exact event, context, tool, and result types.
|
|
2629
|
-
|
|
2630
|
-
## Follow the extension contracts
|
|
2631
|
-
|
|
2632
|
-
<a id="events"></a>
|
|
2633
|
-
<a id="work-with-events"></a>
|
|
2634
|
-
|
|
2635
|
-
### Events and concurrency
|
|
2636
|
-
|
|
2637
|
-
Handlers run in extension load and registration order. `pi.on()` returns a function that unsubscribes that registration; changes do not affect a dispatch already in progress.
|
|
2638
|
-
Some events notify; others transform data, replace results, or cancel an operation.
|
|
2639
|
-
Use each event’s declared result type rather than assuming every return value has an effect.
|
|
2640
|
-
|
|
2641
|
-
Events cover resource discovery, sessions, agent and message lifecycle, providers, tools, and raw input.
|
|
2642
|
-
|
|
2643
|
-
#### Understand handler composition
|
|
2644
|
-
|
|
2645
|
-
| Pattern | Behavior |
|
|
2646
|
-
|---|---|
|
|
2647
|
-
| Notification | Return values are ignored. Use the event for observation only. |
|
|
2648
|
-
| In-place mutation | Later handlers see changes to values such as `before_provider_headers.headers`, `before_agent_start.systemPromptOptions`, and `tool_call.input`. |
|
|
2649
|
-
| Chained transformation | Later handlers receive the value returned by earlier `input`, `context`, `context_with_system`, `message_end`, `tool_result`, and `before_provider_request` handlers. |
|
|
2650
|
-
| Gate | A handled input, blocked tool call, cancelled session operation, or handled `user_bash` command stops that operation's normal fallback path. |
|
|
2651
|
-
| Actionable boundary | Each `turn_end` or `agent_before_settle` handler sees the entries and continuation decision proposed so far. |
|
|
2652
|
-
| Last override | The last `cache_warming_decision` handler that returns an action wins. |
|
|
2653
|
-
|
|
2654
|
-
Notification handlers should not perform slow work on a streaming event. Transform handlers should preserve fields they do not intentionally own, and gate handlers should fail closed when their safety decision cannot be made.
|
|
2655
|
-
|
|
2656
|
-
`before_agent_start` exposes both the current prompt and its structured `systemPromptOptions`. `event.messageType` says what started the run: `"user"` for a prompt or `pi.sendUserMessage()`, with `prompt` and `images`; `"custom"` for `pi.sendMessage(..., { triggerTurn: true })`, with the starting `message` and no `prompt`. A returned `message` is added to either kind of run; check `messageType` to skip runs started by custom messages. Prefer changing prompt sections, selected tools, or guidelines so Pi can append a transcript delta. Returning `systemPrompt`, or setting `forceSystemPrompt`, replaces the whole prompt for that run while the transcript continues recording the structured sections. Providers receive the forced text as their leading system prompt.
|
|
2520
|
+
When `search_tools` adds a match, the model receives the complete updated tool list on the immediately following request.
|
|
2657
2521
|
|
|
2658
|
-
|
|
2659
|
-
|
|
2660
|
-
<a id="provider_stream_event"></a>
|
|
2661
|
-
|
|
2662
|
-
`provider_stream_event` fires for each parsed provider stream event before Pi normalizes it. The event identifies the provider, API, and model; `event.data` is the earliest structured value available to Pi, not necessarily the original HTTP bytes or SSE frame. Treat it as read-only because mutation can affect normalization. The event is notification-only and is not persisted.
|
|
2663
|
-
|
|
2664
|
-
Handlers are awaited in stream order, so slow handlers delay stream consumption. Handler errors are reported without changing the provider response. See [`debug-provider.ts`](../examples/extensions/debug-provider.ts) for an opt-in viewer that groups raw events by assistant message.
|
|
2665
|
-
|
|
2666
|
-
<a id="context_with_system"></a>
|
|
2667
|
-
|
|
2668
|
-
`context` transforms conversation messages without prompt and tool system messages; Pi restores that state afterward. Use `context_with_system` only when a request-local transformation must own the complete transcript, and keep a system message at index zero.
|
|
2669
|
-
|
|
2670
|
-
`turn_end` and `agent_before_settle` are actionable boundaries. Their handlers can chain proposed `custom`, `custom_message`, `context_edit`, or `compaction` entries and return `continue: true` for one next model request. Guard continuation conditions because an unconditional continuation can loop. Use the exported event declarations for the complete validation and ordering contract.
|
|
2671
|
-
|
|
2672
|
-
<a id="cache_warming_decision"></a>
|
|
2673
|
-
|
|
2674
|
-
`cache_warming_decision` can override an idle prompt-cache refresh with `{ action: "warm" }` or `{ action: "stop" }`. The last handler that returns an action wins.
|
|
2675
|
-
|
|
2676
|
-
Tool calls from one assistant message can run in parallel.
|
|
2677
|
-
Do not assume a sibling call or result exists when another tool event runs.
|
|
2678
|
-
Use `ctx.signal` for nested work owned by an active turn; commands and idle session events often have no operation signal.
|
|
2679
|
-
|
|
2680
|
-
A `user_bash` handler that returns `undefined` passes the command to the next handler and then to local execution if no handler handles it. Returning `operations` or `result` stops propagation. A handler failure blocks the command rather than falling through to local execution.
|
|
2681
|
-
|
|
2682
|
-
<a id="custom-tools"></a>
|
|
2683
|
-
<a id="register-tools"></a>
|
|
2684
|
-
|
|
2685
|
-
### Tools
|
|
2686
|
-
|
|
2687
|
-
A custom tool defines a name, model-facing description, TypeBox parameter schema, and `execute()` function.
|
|
2688
|
-
Its result requires model-facing `content` and a `details` field for rendering or state reconstruction.
|
|
2689
|
-
Use `details: undefined` when there are no structured details. If the tool makes nested model calls, include their `usage` in the result so session totals remain accurate.
|
|
2690
|
-
|
|
2691
|
-
Throw from `execute()` to produce a failed tool result.
|
|
2692
|
-
Returning an object does not mark it as an error.
|
|
2693
|
-
Return `terminate: true` only when the agent should skip its automatic follow-up after every completed tool in that batch agrees to terminate.
|
|
2694
|
-
|
|
2695
|
-
Use sequential execution when tools share mutable in-memory state.
|
|
2696
|
-
File-mutating tools should wrap the complete read-modify-write operation with `withFileMutationQueue()`.
|
|
2697
|
-
Truncate large model-facing results and tell the model where to read the complete output.
|
|
2698
|
-
|
|
2699
|
-
Declare `outputSchema` and return a matching `structuredContent` when the result is data. The model still receives `content`; programmatic callers such as codemode scripts receive `structuredContent` instead of the text. Tools without `outputSchema` are passed to scripts as their text content. To report a failure that still carries data, return the result with `isError: true` instead of throwing: the model sees an error, and scripts still receive `structuredContent`.
|
|
2700
|
-
|
|
2701
|
-
A tool can run other tools with `ctx.executeTool(name, args, { signal, onUpdate })`. Nested calls go through argument validation and the `tool_call` and `tool_result` handlers like model-issued calls, and emit `tool_execution_start`, `tool_execution_update`, and `tool_execution_end`; all of these events carry `parentToolCallId`, and their `toolCallId` is assigned by pi as `<parent id>/<n>`. These ids do not appear as tool calls or tool results in the transcript. Nested calls do not add transcript entries: their results only reach the calling tool, which reports them itself, for example through `onUpdate` and `details`. The session keeps a bounded record of them (name, arguments, status, duration, error; never results) as `nestedCalls` on the calling tool's result message. It is used for compaction file lists and shown in HTML exports. Arguments over 8 KiB per call or 32 KiB per tool result are omitted, at most 256 calls are kept, and `complete: false` marks a record that lost anything. The `usage` of nested results, at every depth, is added to the calling tool's result `usage`, so a tool reports only its own usage, not that of the tools it called. `ctx.tools` lists the tools `ctx.executeTool()` can call. `tool_result` handlers that redact `content` should also replace `structuredContent`; replacing only `content` drops it.
|
|
2702
|
-
|
|
2703
|
-
|
|
2704
|
-
### Tool exposure
|
|
2522
|
+
### Tool Exposure
|
|
2705
2523
|
|
|
2706
2524
|
`exposure` controls how the model reaches a tool. "Callable" means callable from other tools through `ctx.executeTool()` (`ctx.tools`), as the `codemode` tool's scripts do:
|
|
2707
2525
|
|
|
@@ -2713,7 +2531,7 @@ A tool can run other tools with `ctx.executeTool(name, args, { signal, onUpdate
|
|
|
2713
2531
|
|
|
2714
2532
|
`namespace: { name, aliases, description, instructions }` groups related tools, as MCP servers do. Codemode tools list a namespace under one heading with its `description`. `instructions` holds longer usage guidance; it is not listed, and codemode scripts read it with `describeNamespace(name)`. `aliases` are other names scripts may look the namespace up by, for example the server name `docs` for `mcp__docs`; a name and the same name as a script identifier (`my-docs`, `my_docs`) match alike.
|
|
2715
2533
|
|
|
2716
|
-
Registering a `direct` or `model-only` tool activates it
|
|
2534
|
+
Registering a `direct` or `model-only` tool activates it unless it sets `defaultActive: false`; the other exposures are not activated on registration. The active set (`pi.getActiveTools()`, `pi.setActiveTools()`) is the set of tools declared to the model, except active tools whose declarations `prepareLoadout` hides. `pi.getAllTools()` reports each tool's `exposure`, `namespace`, `annotations`, and `reachesTools`.
|
|
2717
2535
|
|
|
2718
2536
|
`annotations` are hints about what a tool does, with the meaning of MCP tool annotations: `readOnlyHint`, `destructiveHint`, `idempotentHint`, and `openWorldHint`. MCP tools carry the hints their server declares. Missing hints take the MCP defaults: a tool is not read-only, and may be destructive and reach an open world. The hints are not verified, but a permission extension can use them to decide which calls to confirm. This confirms the calls Codex asks approval for:
|
|
2719
2537
|
|
|
@@ -2733,13 +2551,17 @@ A tool that orchestrates other tools can adjust what the model sees while it is
|
|
|
2733
2551
|
|
|
2734
2552
|
A tool that reaches other tools declares which ones a call may reach with `reachesTools(input)`: `"all"`, or the words of the input that may name them, where a word refers to every tool or namespace whose name it contains. `codemode` returns `"all"` for scripts that search or list tools and the words of the script otherwise; `tool_search` always returns `"all"`. Extensions that register tools late use it from their `tool_call` handler to finish registering the tools a call needs before it runs, as the MCP extension does for servers that are still connecting. The MCP extension also activates `codemode` or `tool_search` for MCP tools only when the tool of that name declares `reachesTools`.
|
|
2735
2553
|
|
|
2736
|
-
###
|
|
2554
|
+
### Calling Other Tools
|
|
2555
|
+
|
|
2556
|
+
A tool can run other tools with `ctx.executeTool(name, args, { signal, onUpdate })`. `ctx.tools` lists the tools it can call. The call never rejects for tool failures: unknown tools, validation errors, blocked calls, and thrown errors come back as results with `isError: true`.
|
|
2737
2557
|
|
|
2738
|
-
|
|
2558
|
+
Nested calls go through argument validation and the `tool_call` and `tool_result` handlers like model-issued calls, and emit `tool_execution_start`, `tool_execution_update`, and `tool_execution_end`. All of these events carry `parentToolCallId`, and their `toolCallId` is assigned by pi as `<parent id>/<n>`. These IDs do not appear as tool calls or tool results in the transcript.
|
|
2739
2559
|
|
|
2740
|
-
|
|
2560
|
+
Nested calls do not add transcript entries: their results only reach the calling tool, which reports them itself, for example through `onUpdate` and `details`. The session keeps a bounded record of them (name, arguments, status, duration, error; never results) as `nestedCalls` on the calling tool's result message. It is used for compaction file lists and shown in HTML exports. Arguments over 8 KiB per call or 32 KiB per tool result are omitted, at most 256 calls are kept, and `complete: false` marks a record that lost anything.
|
|
2741
2561
|
|
|
2742
|
-
|
|
2562
|
+
The `usage` of nested results, at every depth, is added to the calling tool's result `usage`, so a tool reports only its own usage, not that of the tools it called.
|
|
2563
|
+
|
|
2564
|
+
## MCP Servers
|
|
2743
2565
|
|
|
2744
2566
|
`pi.registerMcpServer(name, config)` adds an MCP server for the current session. `config` has the shape of an `mcpServers` entry in [`mcp.json`](mcp.md): `command`, `args`, `env`, and `cwd` for stdio servers, `url`, `headers`, and `oauth` for HTTP servers, plus `exposure`, `toolExposure`, `description`, `enabled`, and `timeout`.
|
|
2745
2567
|
|
|
@@ -2750,83 +2572,187 @@ pi.unregisterMcpServer("jira");
|
|
|
2750
2572
|
|
|
2751
2573
|
Servers registered while the extension loads connect when the session starts, together with the `mcp.json` servers; servers registered later connect right away, and `pi.unregisterMcpServer()` closes the connection and makes the server's tools unreachable. Registrations are not saved: register again on every load, for example based on the extension's own settings. A server in `mcp.json` with the same name takes precedence, and `/mcp` shows the override. Registering the same name again replaces the extension's earlier registration; names registered by another extension, invalid names, and invalid configs throw.
|
|
2752
2574
|
|
|
2753
|
-
The built-in MCP support connects registered servers. When nothing does, because another extension replaced it (see [MCP](mcp.md#
|
|
2575
|
+
The built-in MCP support connects registered servers. When nothing does, because another extension replaced it (see [MCP](mcp.md#replace-the-built-in-mcp-support)), each registration is reported as an extension error. Other MCP extensions can connect registered servers too: read them with `pi.getMcpServers()` on `session_start` and handle the `mcp_servers_change` event for later changes.
|
|
2754
2576
|
|
|
2755
|
-
<a id="
|
|
2756
|
-
<a id="extensioncommandcontext"></a>
|
|
2757
|
-
<a id="use-extension-context"></a>
|
|
2577
|
+
<a id="interact-with-the-user"></a>
|
|
2758
2578
|
|
|
2759
|
-
|
|
2579
|
+
## Custom UI
|
|
2760
2580
|
|
|
2761
|
-
|
|
2762
|
-
Use `ctx.modelRegistry.streamSimple()` for provider-neutral nested model calls.
|
|
2581
|
+
Extensions interact with users through `ctx.ui`. In RPC mode, dialogs and notifications are sent to the client as `extension_ui_request` messages; see [RPC Extension UI](rpc-extension-ui.md) for the protocol and the methods that are no-ops. In print and JSON modes, `ctx.hasUI` is `false` and dialogs return their default values.
|
|
2763
2582
|
|
|
2764
|
-
|
|
2765
|
-
These operations are command-only because calling them from lifecycle handlers can deadlock the runtime.
|
|
2583
|
+
### Dialogs
|
|
2766
2584
|
|
|
2767
|
-
|
|
2585
|
+
```typescript
|
|
2586
|
+
// Select from options
|
|
2587
|
+
const choice = await ctx.ui.select("Pick one:", ["A", "B", "C"]);
|
|
2768
2588
|
|
|
2769
|
-
|
|
2770
|
-
|
|
2589
|
+
// Confirm dialog
|
|
2590
|
+
const ok = await ctx.ui.confirm("Delete?", "This cannot be undone");
|
|
2771
2591
|
|
|
2772
|
-
|
|
2592
|
+
// Text input
|
|
2593
|
+
const name = await ctx.ui.input("Name:", "placeholder");
|
|
2773
2594
|
|
|
2774
|
-
|
|
2595
|
+
// Multi-line editor
|
|
2596
|
+
const text = await ctx.ui.editor("Edit:", "prefilled text");
|
|
2775
2597
|
|
|
2776
|
-
|
|
2777
|
-
|
|
2778
|
-
|
|
2779
|
-
| Durable data excluded from model context | `pi.appendEntry()` |
|
|
2780
|
-
| Custom content stored and sent to the model | `pi.sendMessage()` |
|
|
2781
|
-
| Data outside one session | External storage |
|
|
2598
|
+
// Notification (non-blocking)
|
|
2599
|
+
ctx.ui.notify("Done!", "info"); // "info" | "warning" | "error"
|
|
2600
|
+
```
|
|
2782
2601
|
|
|
2783
|
-
|
|
2784
|
-
Do not rebuild it from every file entry because abandoned branches represent alternative histories.
|
|
2785
|
-
Register an entry or message renderer when custom stored content should appear in the transcript.
|
|
2602
|
+
#### Timed Dialogs
|
|
2786
2603
|
|
|
2787
|
-
|
|
2788
|
-
|
|
2789
|
-
|
|
2790
|
-
|
|
2604
|
+
`select()`, `confirm()`, and `input()` accept a `timeout` option that dismisses the dialog when it expires. RPC requests carry the `timeout`, so clients can show a countdown:
|
|
2605
|
+
|
|
2606
|
+
```typescript
|
|
2607
|
+
const confirmed = await ctx.ui.confirm(
|
|
2608
|
+
"Timed Confirmation",
|
|
2609
|
+
"This dialog will auto-cancel in 5 seconds. Confirm?",
|
|
2610
|
+
{ timeout: 5000 }
|
|
2611
|
+
);
|
|
2612
|
+
|
|
2613
|
+
if (confirmed) {
|
|
2614
|
+
// User confirmed
|
|
2615
|
+
} else {
|
|
2616
|
+
// User cancelled or timed out
|
|
2617
|
+
}
|
|
2618
|
+
```
|
|
2619
|
+
|
|
2620
|
+
**Return values on timeout:**
|
|
2621
|
+
- `select()` returns `undefined`
|
|
2622
|
+
- `confirm()` returns `false`
|
|
2623
|
+
- `input()` returns `undefined`
|
|
2624
|
+
|
|
2625
|
+
#### Manual Dismissal with AbortSignal
|
|
2626
|
+
|
|
2627
|
+
For more control (e.g., to distinguish timeout from user cancel), use `AbortSignal`:
|
|
2628
|
+
|
|
2629
|
+
```typescript
|
|
2630
|
+
const controller = new AbortController();
|
|
2631
|
+
const timeoutId = setTimeout(() => controller.abort(), 5000);
|
|
2791
2632
|
|
|
2792
|
-
|
|
2633
|
+
const confirmed = await ctx.ui.confirm(
|
|
2634
|
+
"Timed Confirmation",
|
|
2635
|
+
"This dialog will auto-cancel in 5 seconds. Confirm?",
|
|
2636
|
+
{ signal: controller.signal }
|
|
2637
|
+
);
|
|
2793
2638
|
|
|
2794
|
-
|
|
2795
|
-
Use `ctx.ui.custom()` only when the interaction needs its own rendering and input.
|
|
2796
|
-
See [Terminal UI](tui.md) for component, focus, overlay, theme, and performance guidance.
|
|
2639
|
+
clearTimeout(timeoutId);
|
|
2797
2640
|
|
|
2798
|
-
|
|
2799
|
-
|
|
2800
|
-
|
|
2801
|
-
|
|
2641
|
+
if (confirmed) {
|
|
2642
|
+
// User confirmed
|
|
2643
|
+
} else if (controller.signal.aborted) {
|
|
2644
|
+
// Dialog timed out
|
|
2645
|
+
} else {
|
|
2646
|
+
// User cancelled
|
|
2647
|
+
}
|
|
2648
|
+
```
|
|
2649
|
+
|
|
2650
|
+
See [examples/extensions/timed-confirm.ts](../examples/extensions/timed-confirm.ts) for complete examples.
|
|
2651
|
+
|
|
2652
|
+
### Status, Widgets, Title, and Editor Text
|
|
2653
|
+
|
|
2654
|
+
These methods are fire-and-forget. RPC mode forwards them to the client:
|
|
2655
|
+
|
|
2656
|
+
```typescript
|
|
2657
|
+
// Status entry (persistent until cleared)
|
|
2658
|
+
ctx.ui.setStatus("my-ext", "Processing...");
|
|
2659
|
+
ctx.ui.setStatus("my-ext", undefined); // Clear
|
|
2802
2660
|
|
|
2803
|
-
|
|
2661
|
+
// Widget of text lines; placement tells the RPC client where to show it
|
|
2662
|
+
ctx.ui.setWidget("my-widget", ["Line 1", "Line 2"]);
|
|
2663
|
+
ctx.ui.setWidget("my-widget", ["Line 1", "Line 2"], { placement: "belowEditor" });
|
|
2664
|
+
ctx.ui.setWidget("my-widget", undefined); // Clear
|
|
2665
|
+
|
|
2666
|
+
// Window or tab title
|
|
2667
|
+
ctx.ui.setTitle("pi - my-project");
|
|
2668
|
+
|
|
2669
|
+
// Prefill the client's input
|
|
2670
|
+
ctx.ui.setEditorText("Prefill text");
|
|
2671
|
+
```
|
|
2804
2672
|
|
|
2805
|
-
<a id="error-handling"></a>
|
|
2806
2673
|
<a id="handle-errors-and-shutdown"></a>
|
|
2807
2674
|
|
|
2808
|
-
|
|
2675
|
+
## Error Handling
|
|
2809
2676
|
|
|
2810
|
-
|
|
2677
|
+
- Extension errors are logged, agent continues
|
|
2678
|
+
- `tool_call` errors block the tool (fail-safe)
|
|
2679
|
+
- `user_bash` errors block the command instead of falling through to local execution
|
|
2680
|
+
- Tool `execute` errors are signaled by throwing or by returning `isError: true`; a thrown error is caught, reported to the LLM as an error result, and execution continues
|
|
2811
2681
|
|
|
2812
|
-
|
|
2813
|
-
|
|
2814
|
-
Use `ctx.shutdown()` to request an orderly process shutdown.
|
|
2682
|
+
<a id="ui-and-modes"></a>
|
|
2683
|
+
<a id="account-for-each-mode"></a>
|
|
2815
2684
|
|
|
2816
|
-
|
|
2817
|
-
<a id="use-examples-as-the-implementation-reference"></a>
|
|
2685
|
+
## Mode Behavior
|
|
2818
2686
|
|
|
2819
|
-
|
|
2687
|
+
| Mode | `ctx.mode` | `ctx.hasUI` | Notes |
|
|
2688
|
+
|------|------------|-------------|-------|
|
|
2689
|
+
| RPC (`--mode rpc`) | `"rpc"` | `true` | Dialogs and notifications via JSON protocol. See [RPC Extension UI](rpc-extension-ui.md) |
|
|
2690
|
+
| JSON (`--mode json`) | `"json"` | `false` | Event stream to stdout; UI methods are no-ops |
|
|
2691
|
+
| Print (`-p`) | `"print"` | `false` | Extensions run but can't prompt |
|
|
2820
2692
|
|
|
2821
|
-
|
|
2693
|
+
Use `ctx.hasUI` before dialog and notification methods.
|
|
2822
2694
|
|
|
2823
|
-
|
|
2824
|
-
|---|---|---|
|
|
2825
|
-
| Confirm or block tool calls | [`permission-gate.ts`](../examples/extensions/permission-gate.ts) | Combines `tool_call`, mode-aware UI, and fail-closed behavior. |
|
|
2826
|
-
| Modify prompt sections for a run | [`prompt-customizer.ts`](../examples/extensions/prompt-customizer.ts) | Uses structured prompt options instead of replacing the complete prompt. |
|
|
2827
|
-
| Register tools after startup | [`dynamic-tools.ts`](../examples/extensions/dynamic-tools.ts) | Shares registration logic between lifecycle and command handlers. |
|
|
2828
|
-
| Run finalization at shutdown | [`auto-commit-on-exit.ts`](../examples/extensions/auto-commit-on-exit.ts) | Uses the session shutdown hook for finalization work. |
|
|
2829
|
-
| Route built-in tools to another machine | [`ssh.ts`](../examples/extensions/ssh.ts) | Reuses tool operation interfaces instead of recreating tool contracts. |
|
|
2830
|
-
| Add OAuth and provider-specific streaming | [`custom-provider-gitlab-duo/`](../examples/extensions/custom-provider-gitlab-duo/) | Shows a complete provider integration while delegating supported protocols. |
|
|
2695
|
+
<a id="use-examples-as-the-implementation-reference"></a>
|
|
2831
2696
|
|
|
2832
|
-
|
|
2697
|
+
## Examples Reference
|
|
2698
|
+
|
|
2699
|
+
All examples in [examples/extensions/](../examples/extensions/).
|
|
2700
|
+
|
|
2701
|
+
| Example | Description | Key APIs |
|
|
2702
|
+
|---------|-------------|----------|
|
|
2703
|
+
| **Tools** |||
|
|
2704
|
+
| `hello.ts` | Minimal tool registration | `registerTool` |
|
|
2705
|
+
| `dynamic-tools.ts` | Register tools after startup and during commands | `registerTool`, `session_start`, `registerCommand` |
|
|
2706
|
+
| `tool-override.ts` | Override built-in read tool | `registerTool` (same name as built-in) |
|
|
2707
|
+
| **Commands** |||
|
|
2708
|
+
| `pirate.ts` | Modify system prompt per-turn | `registerCommand`, `before_agent_start` |
|
|
2709
|
+
| `send-user-message.ts` | Inject user messages | `registerCommand`, `sendUserMessage` |
|
|
2710
|
+
| `reload-runtime.ts` | Reload command and LLM tool handoff | `registerCommand`, `ctx.reload()`, `on("agent_settled")`, `sendUserMessage` |
|
|
2711
|
+
| `shutdown-command.ts` | Graceful shutdown command | `registerCommand`, `shutdown()` |
|
|
2712
|
+
| **Events & Gates** |||
|
|
2713
|
+
| `permission-gate.ts` | Block dangerous commands | `on("tool_call")`, `ui.select` |
|
|
2714
|
+
| `project-trust.ts` | Decide or defer project trust from a user/global or CLI extension | `on("project_trust")`, trust UI, required trust result |
|
|
2715
|
+
| `protected-paths.ts` | Block writes to specific paths | `on("tool_call")` |
|
|
2716
|
+
| `confirm-destructive.ts` | Confirm session changes | `on("session_before_switch")`, `on("session_before_fork")` |
|
|
2717
|
+
| `dirty-repo-guard.ts` | Warn on dirty git repo | `on("session_before_*")`, `exec` |
|
|
2718
|
+
| `input-transform.ts` | Transform user input | `on("input")` |
|
|
2719
|
+
| `input-transform-streaming.ts` | Streaming-aware input transform | `on("input")`, `streamingBehavior` |
|
|
2720
|
+
| `model-status.ts` | React to model changes | `on("model_select")`, `setStatus` |
|
|
2721
|
+
| `provider-payload.ts` | Inspect payloads and provider response headers | `on("before_provider_request")`, `on("after_provider_response")` |
|
|
2722
|
+
| `debug-provider.ts` | Capture raw provider stream events | `on("provider_stream_event")`, `appendEntry` |
|
|
2723
|
+
| `system-prompt-header.ts` | Display system prompt info | `on("agent_start")`, `getSystemPrompt` |
|
|
2724
|
+
| `claude-rules.ts` | Load rules from files | `on("session_start")`, `on("before_agent_start")` |
|
|
2725
|
+
| `prompt-customizer.ts` | Add context-aware tool guidance using `systemPromptOptions` | `on("before_agent_start")`, `BuildSystemPromptOptions` |
|
|
2726
|
+
| `file-trigger.ts` | File watcher triggers messages | `sendMessage` |
|
|
2727
|
+
| **Compaction & Sessions** |||
|
|
2728
|
+
| `custom-compaction.ts` | Custom compaction summary | `on("session_before_compact")` |
|
|
2729
|
+
| `trigger-compact.ts` | Trigger compaction manually | `compact()` |
|
|
2730
|
+
| `git-checkpoint.ts` | Git stash on turns | `on("turn_start")`, `on("tool_result")`, `on("agent_settled")`, `on("session_before_fork")`, `exec` |
|
|
2731
|
+
| `git-merge-and-resolve.ts` | Fetch, merge, and resolve conflicts | `on("agent_end")`, `exec`, `sendUserMessage` |
|
|
2732
|
+
| `auto-commit-on-exit.ts` | Commit on shutdown | `on("session_shutdown")`, `exec` |
|
|
2733
|
+
| **UI** |||
|
|
2734
|
+
| `status-line.ts` | Status indicator | `setStatus`, session events |
|
|
2735
|
+
| `widget-placement.ts` | Widget above/below editor | `setWidget` |
|
|
2736
|
+
| `notify.ts` | Native terminal notification when the agent is done | `on("agent_settled")` |
|
|
2737
|
+
| `titlebar-spinner.ts` | Spinner in the terminal title while working | `setTitle` |
|
|
2738
|
+
| `rpc-demo.ts` | Every RPC-supported UI method | `ui.*` in RPC mode |
|
|
2739
|
+
| `timed-confirm.ts` | Dialogs with timeout | `ui.confirm` with timeout/signal |
|
|
2740
|
+
| **Remote & Sandbox** |||
|
|
2741
|
+
| `ssh.ts` | SSH remote execution | `registerFlag`, `on("user_bash")`, `on("before_agent_start")`, tool operations |
|
|
2742
|
+
| `gondolin/` | Route built-in tools and user bash commands into a Gondolin micro-VM | Tool operations, built-in tool overrides, `on("user_bash")` |
|
|
2743
|
+
| `subagent/` | Spawn sub-agents | `registerTool`, `exec` |
|
|
2744
|
+
| **Providers** |||
|
|
2745
|
+
| `custom-provider-anthropic/` | Custom Anthropic proxy | `registerProvider` |
|
|
2746
|
+
| `custom-provider-gitlab-duo/` | GitLab Duo integration | `registerProvider` with OAuth |
|
|
2747
|
+
| `jev-router.ts` | Virtual model that routes planning and implementation to different models | `registerVirtualModel` |
|
|
2748
|
+
| **Messages & Communication** |||
|
|
2749
|
+
| `event-bus.ts` | Inter-extension events | `pi.events` |
|
|
2750
|
+
| **Session Metadata** |||
|
|
2751
|
+
| `session-name.ts` | Name sessions | `setSessionName`, `getSessionName` |
|
|
2752
|
+
| `bookmark.ts` | Bookmark entries for tree navigation | `setLabel` |
|
|
2753
|
+
| **Misc** |||
|
|
2754
|
+
| `commands.ts` | List available slash commands | `getCommands` |
|
|
2755
|
+
| `dynamic-resources/` | Add skills, prompts, and themes at runtime | `on("resources_discover")` |
|
|
2756
|
+
| `inline-bash.ts` | Expand inline `!{command}` in user prompts | `on("input")`, `exec` |
|
|
2757
|
+
| `bash-spawn-hook.ts` | Adjust bash command, cwd, and env before execution | `createBashTool`, `spawnHook` |
|
|
2758
|
+
| `with-deps/` | Extension with npm dependencies | Package structure with `package.json` |
|