@draht/coding-agent 2026.9.5-1 → 2026.10.4-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 +458 -0
- package/dist/bun/cli.d.ts +1 -1
- package/dist/bun/cli.d.ts.map +1 -1
- package/dist/bun/cli.js +6 -3
- package/dist/bun/cli.js.map +1 -1
- package/dist/bun/sandbox-env-setup.d.ts +2 -0
- package/dist/bun/sandbox-env-setup.d.ts.map +1 -0
- package/dist/bun/sandbox-env-setup.js +4 -0
- package/dist/bun/sandbox-env-setup.js.map +1 -0
- package/dist/bundle/chunks/anthropic-messages-E2P6C3P7.js +6 -0
- package/dist/bundle/chunks/anthropic.js +75 -0
- package/dist/bundle/chunks/azure-openai-responses-JZMSTDIM.js +2 -0
- package/dist/bundle/chunks/bedrock-converse-stream.js +79 -0
- package/dist/bundle/chunks/chunk-2E5VODES.js +2 -0
- package/dist/bundle/chunks/chunk-2FBJKY7F.js +2 -0
- package/dist/bundle/chunks/chunk-2JZLKNZ4.js +3 -0
- package/dist/bundle/chunks/chunk-2N4I6WXC.js +2 -0
- package/dist/bundle/chunks/chunk-3HF756LN.js +1472 -0
- package/dist/bundle/chunks/chunk-5QJFWTKA.js +4 -0
- package/dist/bundle/chunks/chunk-63BK6WK2.js +2 -0
- package/dist/bundle/chunks/chunk-A4OX5CPR.js +146 -0
- package/dist/bundle/chunks/chunk-AFL4IDSI.js +82 -0
- package/dist/bundle/chunks/chunk-D3HO453P.js +42 -0
- package/dist/bundle/chunks/chunk-EBVYI75P.js +2 -0
- package/dist/bundle/chunks/chunk-FBU742QF.js +2 -0
- package/dist/bundle/chunks/chunk-FHX2S5IG.js +31 -0
- package/dist/bundle/chunks/chunk-GBFVS2SF.js +12 -0
- package/dist/bundle/chunks/chunk-GVXA72ZA.js +2 -0
- package/dist/bundle/chunks/chunk-HJ72RANT.js +2 -0
- package/dist/bundle/chunks/chunk-HTJ3L72O.js +2 -0
- package/dist/bundle/chunks/chunk-HZ2UHMBT.js +2 -0
- package/dist/bundle/chunks/chunk-I5OKY6RH.js +11 -0
- package/dist/bundle/chunks/chunk-JTLUBTZT.js +2 -0
- package/dist/bundle/chunks/chunk-KPO5375S.js +2 -0
- package/dist/bundle/chunks/chunk-KY2BG6BC.js +11 -0
- package/dist/bundle/chunks/chunk-LO6CVU2L.js +6 -0
- package/dist/bundle/chunks/chunk-QMN7OD6G.js +2 -0
- package/dist/bundle/chunks/chunk-SDRCE6OP.js +2 -0
- package/dist/bundle/chunks/chunk-SPZUYYP5.js +170 -0
- package/dist/bundle/chunks/chunk-UTRX2VHB.js +44 -0
- package/dist/bundle/chunks/chunk-V5HG6S2T.js +4 -0
- package/dist/bundle/chunks/chunk-VPYAVQLP.js +137 -0
- package/dist/bundle/chunks/chunk-VXUJMEMO.js +2 -0
- package/dist/bundle/chunks/chunk-XBUEMKIY.js +2 -0
- package/dist/bundle/chunks/chunk-XHCO4PPH.js +8 -0
- package/dist/bundle/chunks/chunk-XO3IECI5.js +18 -0
- package/dist/bundle/chunks/chunk-XOGEYN4Q.js +2 -0
- package/dist/bundle/chunks/cli-L74YA5GF.js +51 -0
- package/dist/bundle/chunks/cloudflare-workers-ai-system-one-MJKOAE5S.js +2 -0
- package/dist/bundle/chunks/codemode-worker.js +315 -0
- package/dist/bundle/chunks/execute-EMOVNTD6.js +328 -0
- package/dist/bundle/chunks/github-copilot.js +2 -0
- package/dist/bundle/chunks/google-antigravity.js +75 -0
- package/dist/bundle/chunks/google-gemini-cli.js +75 -0
- package/dist/bundle/chunks/google-generative-ai-HPNDIAZD.js +2 -0
- package/dist/bundle/chunks/google-vertex-KPAWJ4SP.js +2 -0
- package/dist/bundle/chunks/https-proxy-agent-WQIRL24U.js +13 -0
- package/dist/bundle/chunks/image-resize-worker.js +2 -0
- package/dist/bundle/chunks/jiti-loader-RKXLMQV2.js +2 -0
- package/dist/bundle/chunks/kimi-coding.js +2 -0
- package/dist/bundle/chunks/lib-ULKZYRGD.js +9 -0
- package/dist/bundle/chunks/llama-cpp-classify-EJ5XMSQL.js +22 -0
- package/dist/bundle/chunks/meta.js +2 -0
- package/dist/bundle/chunks/mistral-conversations-FMSPWQ7A.js +5 -0
- package/dist/bundle/chunks/multipart-parser-HMCXZ4BD.js +3 -0
- package/dist/bundle/chunks/node-4JNG6XQO.js +16 -0
- package/dist/bundle/chunks/node-6IIDYB3K.js +2 -0
- package/dist/bundle/chunks/openai-chatgpt.js +75 -0
- package/dist/bundle/chunks/openai-codex-responses-TU7NGPXE.js +10 -0
- package/dist/bundle/chunks/openai-codex.js +75 -0
- package/dist/bundle/chunks/openai-completions-GANCQQO5.js +7 -0
- package/dist/bundle/chunks/openai-responses-ASDPAX3E.js +3 -0
- package/dist/bundle/chunks/opencode-go.js +2 -0
- package/dist/bundle/chunks/openrouter-images-NROSQXMZ.js +2 -0
- package/dist/bundle/chunks/openrouter.js +75 -0
- package/dist/bundle/chunks/pi-messages-2QEJYOAO.js +8 -0
- package/dist/bundle/chunks/radius.js +75 -0
- package/dist/bundle/chunks/runtime-RYUR6LRB.js +2 -0
- package/dist/bundle/chunks/settings-manager-CHEMMAGQ.js +2 -0
- package/dist/bundle/chunks/src-KDGO7EGF.js +4 -0
- package/dist/bundle/chunks/typesafe-system-one-YBEEY5XU.js +2 -0
- package/dist/bundle/chunks/virtual-modules-OC56AAJ7.js +2 -0
- package/dist/bundle/chunks/xai.js +75 -0
- package/dist/bundle/cli-runtime.js +3 -0
- package/dist/bundle/cli.js +5 -0
- package/dist/bundle/index.js +2 -0
- package/dist/bundle/rpc-entry.js +3 -0
- package/dist/cli/args.d.ts +4 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +72 -21
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/auth-check.d.ts +19 -0
- package/dist/cli/auth-check.d.ts.map +1 -0
- package/dist/cli/auth-check.js +50 -0
- package/dist/cli/auth-check.js.map +1 -0
- package/dist/cli/auth-command.d.ts +24 -0
- package/dist/cli/auth-command.d.ts.map +1 -0
- package/dist/cli/auth-command.js +103 -0
- package/dist/cli/auth-command.js.map +1 -0
- package/dist/cli/config-selector.d.ts.map +1 -1
- package/dist/cli/config-selector.js +3 -2
- package/dist/cli/config-selector.js.map +1 -1
- package/dist/cli/credential-print.d.ts +5 -3
- package/dist/cli/credential-print.d.ts.map +1 -1
- package/dist/cli/credential-print.js +42 -30
- package/dist/cli/credential-print.js.map +1 -1
- package/dist/cli/file-processor.d.ts +1 -1
- package/dist/cli/file-processor.d.ts.map +1 -1
- package/dist/cli/file-processor.js +2 -1
- package/dist/cli/file-processor.js.map +1 -1
- package/dist/cli/list-models.d.ts +1 -1
- package/dist/cli/list-models.d.ts.map +1 -1
- package/dist/cli/list-models.js +2 -2
- package/dist/cli/list-models.js.map +1 -1
- package/dist/cli/session-picker.d.ts +1 -1
- package/dist/cli/session-picker.d.ts.map +1 -1
- package/dist/cli/session-picker.js.map +1 -1
- package/dist/cli/setup.d.ts +2 -0
- package/dist/cli/setup.d.ts.map +1 -0
- package/dist/cli/setup.js +12 -0
- package/dist/cli/setup.js.map +1 -0
- package/dist/cli/startup-ui.d.ts +2 -2
- package/dist/cli/startup-ui.d.ts.map +1 -1
- package/dist/cli/startup-ui.js +42 -33
- package/dist/cli/startup-ui.js.map +1 -1
- package/dist/cli.js +3 -12
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +20 -4
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +42 -6
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +12 -3
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session-services.d.ts +1 -0
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +14 -0
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +237 -39
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +1386 -565
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth-storage.d.ts +20 -8
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js +199 -56
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/bug-report-upload.d.ts +11 -0
- package/dist/core/bug-report-upload.d.ts.map +1 -0
- package/dist/core/bug-report-upload.js +20 -0
- package/dist/core/bug-report-upload.js.map +1 -0
- package/dist/core/bug-report.d.ts +176 -0
- package/dist/core/bug-report.d.ts.map +1 -0
- package/dist/core/bug-report.js +292 -0
- package/dist/core/bug-report.js.map +1 -0
- package/dist/core/builtins/duet.js +2 -2
- package/dist/core/builtins/duet.js.map +1 -1
- package/dist/core/cache-stats.d.ts.map +1 -1
- package/dist/core/cache-stats.js +12 -1
- package/dist/core/cache-stats.js.map +1 -1
- package/dist/core/cache-warmer.d.ts +103 -0
- package/dist/core/cache-warmer.d.ts.map +1 -0
- package/dist/core/cache-warmer.js +356 -0
- package/dist/core/cache-warmer.js.map +1 -0
- package/dist/core/checkpoints/checkpoint-manager.d.ts +8 -4
- package/dist/core/checkpoints/checkpoint-manager.d.ts.map +1 -1
- package/dist/core/checkpoints/checkpoint-manager.js +46 -10
- package/dist/core/checkpoints/checkpoint-manager.js.map +1 -1
- package/dist/core/checkpoints/rewind.d.ts +4 -2
- package/dist/core/checkpoints/rewind.d.ts.map +1 -1
- package/dist/core/checkpoints/rewind.js +4 -3
- package/dist/core/checkpoints/rewind.js.map +1 -1
- package/dist/core/compaction/branch-summarization.js +2 -2
- package/dist/core/compaction/branch-summarization.js.map +1 -1
- package/dist/core/compaction/compaction.d.ts +9 -6
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +196 -118
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/compaction/utils.d.ts +2 -1
- package/dist/core/compaction/utils.d.ts.map +1 -1
- package/dist/core/compaction/utils.js +25 -18
- package/dist/core/compaction/utils.js.map +1 -1
- package/dist/core/context-windows.d.ts.map +1 -1
- package/dist/core/context-windows.js +13 -3
- package/dist/core/context-windows.js.map +1 -1
- package/dist/core/crash-log.d.ts +27 -0
- package/dist/core/crash-log.d.ts.map +1 -0
- package/dist/core/crash-log.js +140 -0
- package/dist/core/crash-log.js.map +1 -0
- package/dist/core/defaults.d.ts +1 -0
- package/dist/core/defaults.d.ts.map +1 -1
- package/dist/core/defaults.js +9 -0
- package/dist/core/defaults.js.map +1 -1
- package/dist/core/experimental.js +1 -1
- package/dist/core/experimental.js.map +1 -1
- package/dist/core/export-html/template.css +10 -0
- package/dist/core/export-html/template.js +72 -18
- package/dist/core/extensions/index.d.ts +2 -2
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/jiti-loader.d.ts +2 -0
- package/dist/core/extensions/jiti-loader.d.ts.map +1 -0
- package/dist/core/extensions/jiti-loader.js +5 -0
- package/dist/core/extensions/jiti-loader.js.map +1 -0
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +228 -89
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +47 -8
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +376 -104
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +521 -88
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js +3 -0
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/extensions/virtual-modules.d.ts +3 -0
- package/dist/core/extensions/virtual-modules.d.ts.map +1 -0
- package/dist/core/extensions/virtual-modules.js +37 -0
- package/dist/core/extensions/virtual-modules.js.map +1 -0
- package/dist/core/extensions/wrapper.d.ts +2 -2
- package/dist/core/extensions/wrapper.d.ts.map +1 -1
- package/dist/core/extensions/wrapper.js +3 -22
- package/dist/core/extensions/wrapper.js.map +1 -1
- package/dist/core/footer-data-provider.d.ts +1 -1
- package/dist/core/footer-data-provider.js +19 -18
- package/dist/core/footer-data-provider.js.map +1 -1
- package/dist/core/index.d.ts +2 -1
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js.map +1 -1
- package/dist/core/keybindings.d.ts +83 -13
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +33 -7
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/mcp-servers.d.ts +119 -0
- package/dist/core/mcp-servers.d.ts.map +1 -0
- package/dist/core/mcp-servers.js +191 -0
- package/dist/core/mcp-servers.js.map +1 -0
- package/dist/core/messages.d.ts +1 -1
- package/dist/core/messages.d.ts.map +1 -1
- package/dist/core/messages.js +1 -0
- package/dist/core/messages.js.map +1 -1
- package/dist/core/model-config.d.ts +202 -20
- package/dist/core/model-config.d.ts.map +1 -1
- package/dist/core/model-config.js +53 -18
- package/dist/core/model-config.js.map +1 -1
- package/dist/core/model-registry.d.ts +19 -2
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +39 -2
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-resolver.d.ts +7 -5
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +29 -17
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/model-runtime.d.ts +79 -20
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +460 -134
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/models-store.d.ts +12 -7
- package/dist/core/models-store.d.ts.map +1 -1
- package/dist/core/models-store.js +87 -18
- package/dist/core/models-store.js.map +1 -1
- package/dist/core/multi-agent/fsm.js +8 -3
- package/dist/core/multi-agent/fsm.js.map +1 -1
- package/dist/core/multi-agent/mailbox.js +1 -3
- package/dist/core/multi-agent/mailbox.js.map +1 -1
- package/dist/core/multi-agent/permission-gate.d.ts +5 -2
- package/dist/core/multi-agent/permission-gate.d.ts.map +1 -1
- package/dist/core/multi-agent/permission-gate.js +597 -34
- package/dist/core/multi-agent/permission-gate.js.map +1 -1
- package/dist/core/multi-agent/task-board.js +2 -4
- package/dist/core/multi-agent/task-board.js.map +1 -1
- package/dist/core/multi-agent/worktree.js +1 -3
- package/dist/core/multi-agent/worktree.js.map +1 -1
- package/dist/core/nested-tool-calls.d.ts +102 -0
- package/dist/core/nested-tool-calls.d.ts.map +1 -0
- package/dist/core/nested-tool-calls.js +178 -0
- package/dist/core/nested-tool-calls.js.map +1 -0
- package/dist/core/package-manager.d.ts +10 -0
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +149 -33
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/pi-manifest.d.ts.map +1 -1
- package/dist/core/pi-manifest.js +13 -12
- package/dist/core/pi-manifest.js.map +1 -1
- package/dist/core/prompt-templates.d.ts +6 -1
- package/dist/core/prompt-templates.d.ts.map +1 -1
- package/dist/core/prompt-templates.js +63 -37
- package/dist/core/prompt-templates.js.map +1 -1
- package/dist/core/provider-attribution.js +5 -5
- package/dist/core/provider-attribution.js.map +1 -1
- package/dist/core/provider-composer.d.ts +44 -20
- package/dist/core/provider-composer.d.ts.map +1 -1
- package/dist/core/provider-composer.js +151 -51
- package/dist/core/provider-composer.js.map +1 -1
- package/dist/core/radius.d.ts +13 -0
- package/dist/core/radius.d.ts.map +1 -1
- package/dist/core/radius.js +19 -0
- package/dist/core/radius.js.map +1 -1
- package/dist/core/remote-catalog-provider.d.ts +10 -3
- package/dist/core/remote-catalog-provider.d.ts.map +1 -1
- package/dist/core/remote-catalog-provider.js +105 -81
- package/dist/core/remote-catalog-provider.js.map +1 -1
- package/dist/core/resource-loader.d.ts +7 -1
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +219 -42
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/runtime-credentials.d.ts +5 -5
- package/dist/core/runtime-credentials.d.ts.map +1 -1
- package/dist/core/runtime-credentials.js +13 -9
- package/dist/core/runtime-credentials.js.map +1 -1
- package/dist/core/sandbox/executor.js +1 -0
- package/dist/core/sandbox/executor.js.map +1 -1
- package/dist/core/sdk.d.ts +7 -5
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +100 -52
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-cwd.js +1 -0
- package/dist/core/session-cwd.js.map +1 -1
- package/dist/core/session-export.d.ts +8 -0
- package/dist/core/session-export.d.ts.map +1 -0
- package/dist/core/session-export.js +33 -0
- package/dist/core/session-export.js.map +1 -0
- package/dist/core/session-manager.d.ts +75 -15
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +314 -144
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/settings-diagnostics.d.ts +9 -0
- package/dist/core/settings-diagnostics.d.ts.map +1 -0
- package/dist/core/settings-diagnostics.js +21 -0
- package/dist/core/settings-diagnostics.js.map +1 -0
- package/dist/core/settings-manager.d.ts +84 -4
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +239 -25
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/skills.d.ts.map +1 -1
- package/dist/core/skills.js +51 -33
- package/dist/core/skills.js.map +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +3 -1
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/soak/soak-log.js +6 -0
- package/dist/core/soak/soak-log.js.map +1 -1
- package/dist/core/socket-server/socket-server.js +11 -0
- package/dist/core/socket-server/socket-server.js.map +1 -1
- package/dist/core/socket-server/types.d.ts +2 -1
- package/dist/core/socket-server/types.d.ts.map +1 -1
- package/dist/core/socket-server/types.js.map +1 -1
- package/dist/core/source-info.d.ts +8 -0
- package/dist/core/source-info.d.ts.map +1 -1
- package/dist/core/source-info.js +16 -0
- package/dist/core/source-info.js.map +1 -1
- package/dist/core/system-prompt.d.ts +49 -6
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +126 -89
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tools/bash.d.ts +32 -2
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +82 -143
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/edit-diff.d.ts +0 -5
- package/dist/core/tools/edit-diff.d.ts.map +1 -1
- package/dist/core/tools/edit-diff.js +2 -5
- package/dist/core/tools/edit-diff.js.map +1 -1
- package/dist/core/tools/edit.d.ts +5 -12
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +19 -171
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/find.d.ts +4 -0
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +11 -58
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/grep.d.ts +4 -0
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +10 -62
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/index.d.ts +4 -1
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +18 -1
- package/dist/core/tools/index.js.map +1 -1
- package/dist/core/tools/ls.d.ts +4 -0
- package/dist/core/tools/ls.d.ts.map +1 -1
- package/dist/core/tools/ls.js +9 -50
- package/dist/core/tools/ls.js.map +1 -1
- package/dist/core/tools/output-accumulator.d.ts +11 -0
- package/dist/core/tools/output-accumulator.d.ts.map +1 -1
- package/dist/core/tools/output-accumulator.js +54 -12
- package/dist/core/tools/output-accumulator.js.map +1 -1
- package/dist/core/tools/powershell.d.ts +16 -0
- package/dist/core/tools/powershell.d.ts.map +1 -0
- package/dist/core/tools/powershell.js +39 -0
- package/dist/core/tools/powershell.js.map +1 -0
- package/dist/core/tools/read.d.ts +8 -1
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +16 -123
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/render-utils.d.ts +6 -0
- package/dist/core/tools/render-utils.d.ts.map +1 -1
- package/dist/core/tools/render-utils.js +26 -0
- package/dist/core/tools/render-utils.js.map +1 -1
- package/dist/core/tools/renderers/bash.d.ts +12 -0
- package/dist/core/tools/renderers/bash.d.ts.map +1 -0
- package/dist/core/tools/renderers/bash.js +117 -0
- package/dist/core/tools/renderers/bash.js.map +1 -0
- package/dist/core/tools/renderers/edit.d.ts +23 -0
- package/dist/core/tools/renderers/edit.d.ts.map +1 -0
- package/dist/core/tools/renderers/edit.js +167 -0
- package/dist/core/tools/renderers/edit.js.map +1 -0
- package/dist/core/tools/renderers/find.d.ts +10 -0
- package/dist/core/tools/renderers/find.d.ts.map +1 -0
- package/dist/core/tools/renderers/find.js +64 -0
- package/dist/core/tools/renderers/find.js.map +1 -0
- package/dist/core/tools/renderers/grep.d.ts +10 -0
- package/dist/core/tools/renderers/grep.d.ts.map +1 -0
- package/dist/core/tools/renderers/grep.js +69 -0
- package/dist/core/tools/renderers/grep.js.map +1 -0
- package/dist/core/tools/renderers/index.d.ts +28 -0
- package/dist/core/tools/renderers/index.d.ts.map +1 -0
- package/dist/core/tools/renderers/index.js +47 -0
- package/dist/core/tools/renderers/index.js.map +1 -0
- package/dist/core/tools/renderers/ls.d.ts +10 -0
- package/dist/core/tools/renderers/ls.d.ts.map +1 -0
- package/dist/core/tools/renderers/ls.js +58 -0
- package/dist/core/tools/renderers/ls.js.map +1 -0
- package/dist/core/tools/renderers/read.d.ts +11 -0
- package/dist/core/tools/renderers/read.d.ts.map +1 -0
- package/dist/core/tools/renderers/read.js +130 -0
- package/dist/core/tools/renderers/read.js.map +1 -0
- package/dist/core/tools/renderers/write.d.ts +10 -0
- package/dist/core/tools/renderers/write.d.ts.map +1 -0
- package/dist/core/tools/renderers/write.js +153 -0
- package/dist/core/tools/renderers/write.js.map +1 -0
- package/dist/core/tools/tool-definition-wrapper.d.ts +5 -3
- package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.js +3 -1
- package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
- package/dist/core/tools/truncate.d.ts +14 -0
- package/dist/core/tools/truncate.d.ts.map +1 -1
- package/dist/core/tools/truncate.js +29 -0
- package/dist/core/tools/truncate.js.map +1 -1
- package/dist/core/tools/write.d.ts +4 -0
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js +12 -147
- 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 +4 -1
- package/dist/core/trust-manager.js.map +1 -1
- package/dist/core/usage-totals.d.ts +3 -1
- package/dist/core/usage-totals.d.ts.map +1 -1
- package/dist/core/usage-totals.js +28 -1
- package/dist/core/usage-totals.js.map +1 -1
- package/dist/core/virtual-models.d.ts +117 -0
- package/dist/core/virtual-models.d.ts.map +1 -0
- package/dist/core/virtual-models.js +124 -0
- package/dist/core/virtual-models.js.map +1 -0
- package/dist/experimental/micro/api.d.ts +81 -0
- package/dist/experimental/micro/api.d.ts.map +1 -0
- package/dist/experimental/micro/api.js +2 -0
- package/dist/experimental/micro/api.js.map +1 -0
- package/dist/experimental/micro/main.d.ts +3 -0
- package/dist/experimental/micro/main.d.ts.map +1 -0
- package/dist/experimental/micro/main.js +21 -0
- package/dist/experimental/micro/main.js.map +1 -0
- package/dist/experimental/micro/models.d.ts +11 -0
- package/dist/experimental/micro/models.d.ts.map +1 -0
- package/dist/experimental/micro/models.js +95 -0
- package/dist/experimental/micro/models.js.map +1 -0
- package/dist/experimental/micro/runtime.d.ts +12 -0
- package/dist/experimental/micro/runtime.d.ts.map +1 -0
- package/dist/experimental/micro/runtime.js +465 -0
- package/dist/experimental/micro/runtime.js.map +1 -0
- package/dist/experimental/micro/sessions.d.ts +10 -0
- package/dist/experimental/micro/sessions.d.ts.map +1 -0
- package/dist/experimental/micro/sessions.js +41 -0
- package/dist/experimental/micro/sessions.js.map +1 -0
- package/dist/experimental/micro/tools.d.ts +10 -0
- package/dist/experimental/micro/tools.d.ts.map +1 -0
- package/dist/experimental/micro/tools.js +96 -0
- package/dist/experimental/micro/tools.js.map +1 -0
- package/dist/experimental/micro/tui.d.ts +3 -0
- package/dist/experimental/micro/tui.d.ts.map +1 -0
- package/dist/experimental/micro/tui.js +510 -0
- package/dist/experimental/micro/tui.js.map +1 -0
- package/dist/experimental/mini/main.d.ts +7 -0
- package/dist/experimental/mini/main.d.ts.map +1 -0
- package/dist/experimental/mini/main.js +21 -0
- package/dist/experimental/mini/main.js.map +1 -0
- package/dist/experimental/mini/server/entry.d.ts +3 -0
- package/dist/experimental/mini/server/entry.d.ts.map +1 -0
- package/dist/experimental/mini/server/entry.js +11 -0
- package/dist/experimental/mini/server/entry.js.map +1 -0
- package/dist/experimental/mini/server/run.d.ts +13 -0
- package/dist/experimental/mini/server/run.d.ts.map +1 -0
- package/dist/experimental/mini/server/run.js +150 -0
- package/dist/experimental/mini/server/run.js.map +1 -0
- package/dist/experimental/mini/shared/protocol.d.ts +127 -0
- package/dist/experimental/mini/shared/protocol.d.ts.map +1 -0
- package/dist/experimental/mini/shared/protocol.js +13 -0
- package/dist/experimental/mini/shared/protocol.js.map +1 -0
- package/dist/experimental/mini/shared/rpc.d.ts +49 -0
- package/dist/experimental/mini/shared/rpc.d.ts.map +1 -0
- package/dist/experimental/mini/shared/rpc.js +171 -0
- package/dist/experimental/mini/shared/rpc.js.map +1 -0
- package/dist/experimental/mini/shared/transport.d.ts +35 -0
- package/dist/experimental/mini/shared/transport.d.ts.map +1 -0
- package/dist/experimental/mini/shared/transport.js +94 -0
- package/dist/experimental/mini/shared/transport.js.map +1 -0
- package/dist/experimental/mini/tui/run.d.ts +9 -0
- package/dist/experimental/mini/tui/run.d.ts.map +1 -0
- package/dist/experimental/mini/tui/run.js +62 -0
- package/dist/experimental/mini/tui/run.js.map +1 -0
- package/dist/experimental/mini/tui/session.d.ts +26 -0
- package/dist/experimental/mini/tui/session.d.ts.map +1 -0
- package/dist/experimental/mini/tui/session.js +94 -0
- package/dist/experimental/mini/tui/session.js.map +1 -0
- package/dist/experimental/mini/tui/view.d.ts +10 -0
- package/dist/experimental/mini/tui/view.d.ts.map +1 -0
- package/dist/experimental/mini/tui/view.js +461 -0
- package/dist/experimental/mini/tui/view.js.map +1 -0
- package/dist/experimental/mini/worker/entry.d.ts +3 -0
- package/dist/experimental/mini/worker/entry.d.ts.map +1 -0
- package/dist/experimental/mini/worker/entry.js +10 -0
- package/dist/experimental/mini/worker/entry.js.map +1 -0
- package/dist/experimental/mini/worker/lane-service.d.ts +44 -0
- package/dist/experimental/mini/worker/lane-service.d.ts.map +1 -0
- package/dist/experimental/mini/worker/lane-service.js +97 -0
- package/dist/experimental/mini/worker/lane-service.js.map +1 -0
- package/dist/experimental/mini/worker/models-service.d.ts +19 -0
- package/dist/experimental/mini/worker/models-service.d.ts.map +1 -0
- package/dist/experimental/mini/worker/models-service.js +136 -0
- package/dist/experimental/mini/worker/models-service.js.map +1 -0
- package/dist/experimental/mini/worker/run.d.ts +14 -0
- package/dist/experimental/mini/worker/run.d.ts.map +1 -0
- package/dist/experimental/mini/worker/run.js +88 -0
- package/dist/experimental/mini/worker/run.js.map +1 -0
- package/dist/extensions/codemode/execute.d.ts +16 -0
- package/dist/extensions/codemode/execute.d.ts.map +1 -0
- package/dist/extensions/codemode/execute.js +429 -0
- package/dist/extensions/codemode/execute.js.map +1 -0
- package/dist/extensions/codemode/execute.lazy.d.ts +3 -0
- package/dist/extensions/codemode/execute.lazy.d.ts.map +1 -0
- package/dist/extensions/codemode/execute.lazy.js +3 -0
- package/dist/extensions/codemode/execute.lazy.js.map +1 -0
- package/dist/extensions/codemode/index.d.ts +21 -0
- package/dist/extensions/codemode/index.d.ts.map +1 -0
- package/dist/extensions/codemode/index.js +31 -0
- package/dist/extensions/codemode/index.js.map +1 -0
- package/dist/extensions/codemode/renderer.d.ts +12 -0
- package/dist/extensions/codemode/renderer.d.ts.map +1 -0
- package/dist/extensions/codemode/renderer.js +137 -0
- package/dist/extensions/codemode/renderer.js.map +1 -0
- package/dist/extensions/codemode/tool.d.ts +123 -0
- package/dist/extensions/codemode/tool.d.ts.map +1 -0
- package/dist/extensions/codemode/tool.js +315 -0
- package/dist/extensions/codemode/tool.js.map +1 -0
- package/dist/extensions/codemode/worker.d.ts +7 -0
- package/dist/extensions/codemode/worker.d.ts.map +1 -0
- package/dist/extensions/codemode/worker.js +7 -0
- package/dist/extensions/codemode/worker.js.map +1 -0
- package/dist/extensions/index.d.ts.map +1 -1
- package/dist/extensions/index.js +9 -1
- package/dist/extensions/index.js.map +1 -1
- package/dist/extensions/llama/client.d.ts +8 -0
- package/dist/extensions/llama/client.d.ts.map +1 -1
- package/dist/extensions/llama/client.js +13 -0
- package/dist/extensions/llama/client.js.map +1 -1
- package/dist/extensions/llama/huggingface.js +2 -0
- package/dist/extensions/llama/huggingface.js.map +1 -1
- package/dist/extensions/llama/index.d.ts.map +1 -1
- package/dist/extensions/llama/index.js +13 -2
- package/dist/extensions/llama/index.js.map +1 -1
- package/dist/extensions/llama/provider.d.ts +4 -2
- package/dist/extensions/llama/provider.d.ts.map +1 -1
- package/dist/extensions/llama/provider.js +119 -17
- package/dist/extensions/llama/provider.js.map +1 -1
- package/dist/extensions/llama/ui.js +28 -12
- package/dist/extensions/llama/ui.js.map +1 -1
- package/dist/extensions/mcp/cli.d.ts +21 -0
- package/dist/extensions/mcp/cli.d.ts.map +1 -0
- package/dist/extensions/mcp/cli.js +500 -0
- package/dist/extensions/mcp/cli.js.map +1 -0
- package/dist/extensions/mcp/cli.lazy.d.ts +3 -0
- package/dist/extensions/mcp/cli.lazy.d.ts.map +1 -0
- package/dist/extensions/mcp/cli.lazy.js +3 -0
- package/dist/extensions/mcp/cli.lazy.js.map +1 -0
- package/dist/extensions/mcp/config.d.ts +72 -0
- package/dist/extensions/mcp/config.d.ts.map +1 -0
- package/dist/extensions/mcp/config.js +158 -0
- package/dist/extensions/mcp/config.js.map +1 -0
- package/dist/extensions/mcp/index.d.ts +76 -0
- package/dist/extensions/mcp/index.d.ts.map +1 -0
- package/dist/extensions/mcp/index.js +1055 -0
- package/dist/extensions/mcp/index.js.map +1 -0
- package/dist/extensions/mcp/log.d.ts +16 -0
- package/dist/extensions/mcp/log.d.ts.map +1 -0
- package/dist/extensions/mcp/log.js +66 -0
- package/dist/extensions/mcp/log.js.map +1 -0
- package/dist/extensions/mcp/oauth.d.ts +96 -0
- package/dist/extensions/mcp/oauth.d.ts.map +1 -0
- package/dist/extensions/mcp/oauth.js +333 -0
- package/dist/extensions/mcp/oauth.js.map +1 -0
- package/dist/extensions/mcp/resources.d.ts +43 -0
- package/dist/extensions/mcp/resources.d.ts.map +1 -0
- package/dist/extensions/mcp/resources.js +262 -0
- package/dist/extensions/mcp/resources.js.map +1 -0
- package/dist/extensions/mcp/runtime.d.ts +98 -0
- package/dist/extensions/mcp/runtime.d.ts.map +1 -0
- package/dist/extensions/mcp/runtime.js +394 -0
- package/dist/extensions/mcp/runtime.js.map +1 -0
- package/dist/extensions/mcp/runtime.lazy.d.ts +3 -0
- package/dist/extensions/mcp/runtime.lazy.d.ts.map +1 -0
- package/dist/extensions/mcp/runtime.lazy.js +3 -0
- package/dist/extensions/mcp/runtime.lazy.js.map +1 -0
- package/dist/extensions/mcp/tools.d.ts +84 -0
- package/dist/extensions/mcp/tools.d.ts.map +1 -0
- package/dist/extensions/mcp/tools.js +251 -0
- package/dist/extensions/mcp/tools.js.map +1 -0
- package/dist/extensions/mcp/ui.d.ts +60 -0
- package/dist/extensions/mcp/ui.d.ts.map +1 -0
- package/dist/extensions/mcp/ui.js +174 -0
- package/dist/extensions/mcp/ui.js.map +1 -0
- package/dist/extensions/stub-provider/provider.d.ts +2 -2
- package/dist/extensions/stub-provider/provider.d.ts.map +1 -1
- package/dist/extensions/stub-provider/provider.js +2 -1
- package/dist/extensions/stub-provider/provider.js.map +1 -1
- package/dist/extensions/tool-search/index.d.ts +12 -0
- package/dist/extensions/tool-search/index.d.ts.map +1 -0
- package/dist/extensions/tool-search/index.js +15 -0
- package/dist/extensions/tool-search/index.js.map +1 -0
- package/dist/extensions/tool-search/tool.d.ts +73 -0
- package/dist/extensions/tool-search/tool.d.ts.map +1 -0
- package/dist/extensions/tool-search/tool.js +189 -0
- package/dist/extensions/tool-search/tool.js.map +1 -0
- package/dist/index.d.ts +20 -11
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +12 -6
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts +4 -0
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +123 -51
- package/dist/main.js.map +1 -1
- package/dist/migrations.d.ts +1 -1
- package/dist/migrations.js +7 -6
- package/dist/migrations.js.map +1 -1
- package/dist/modes/index.d.ts +1 -0
- package/dist/modes/index.d.ts.map +1 -1
- package/dist/modes/index.js.map +1 -1
- package/dist/modes/interactive/bug-report.d.ts +19 -0
- package/dist/modes/interactive/bug-report.d.ts.map +1 -0
- package/dist/modes/interactive/bug-report.js +211 -0
- package/dist/modes/interactive/bug-report.js.map +1 -0
- package/dist/modes/interactive/chat-viewport.d.ts +20 -0
- package/dist/modes/interactive/chat-viewport.d.ts.map +1 -0
- package/dist/modes/interactive/chat-viewport.js +28 -0
- package/dist/modes/interactive/chat-viewport.js.map +1 -0
- package/dist/modes/interactive/components/armin.js +10 -6
- package/dist/modes/interactive/components/armin.js.map +1 -1
- package/dist/modes/interactive/components/assistant-message.d.ts +6 -2
- package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/assistant-message.js +38 -15
- package/dist/modes/interactive/components/assistant-message.js.map +1 -1
- package/dist/modes/interactive/components/bash-execution.js +9 -4
- package/dist/modes/interactive/components/bash-execution.js.map +1 -1
- package/dist/modes/interactive/components/bordered-loader.js +3 -0
- package/dist/modes/interactive/components/bordered-loader.js.map +1 -1
- package/dist/modes/interactive/components/branch-summary-message.d.ts +1 -1
- package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/branch-summary-message.js +15 -6
- package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
- package/dist/modes/interactive/components/compaction-summary-message.d.ts +1 -1
- package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/compaction-summary-message.js +15 -6
- package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -1
- package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/config-selector.js +35 -8
- package/dist/modes/interactive/components/config-selector.js.map +1 -1
- package/dist/modes/interactive/components/countdown-timer.js +5 -0
- package/dist/modes/interactive/components/countdown-timer.js.map +1 -1
- package/dist/modes/interactive/components/custom-editor.d.ts +10 -1
- package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-editor.js +54 -2
- package/dist/modes/interactive/components/custom-editor.js.map +1 -1
- package/dist/modes/interactive/components/custom-entry.js +4 -1
- package/dist/modes/interactive/components/custom-entry.js.map +1 -1
- package/dist/modes/interactive/components/custom-message.js +7 -1
- package/dist/modes/interactive/components/custom-message.js.map +1 -1
- package/dist/modes/interactive/components/daxnuts.js +8 -6
- package/dist/modes/interactive/components/daxnuts.js.map +1 -1
- package/dist/modes/interactive/components/dynamic-border.js +1 -0
- package/dist/modes/interactive/components/dynamic-border.js.map +1 -1
- package/dist/modes/interactive/components/extension-editor.d.ts +4 -1
- package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-editor.js +14 -3
- package/dist/modes/interactive/components/extension-editor.js.map +1 -1
- package/dist/modes/interactive/components/extension-input.d.ts +2 -0
- package/dist/modes/interactive/components/extension-input.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-input.js +14 -2
- package/dist/modes/interactive/components/extension-input.js.map +1 -1
- package/dist/modes/interactive/components/extension-selector.d.ts +1 -0
- package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-selector.js +16 -1
- package/dist/modes/interactive/components/extension-selector.js.map +1 -1
- package/dist/modes/interactive/components/first-time-setup.d.ts +4 -4
- package/dist/modes/interactive/components/first-time-setup.d.ts.map +1 -1
- package/dist/modes/interactive/components/first-time-setup.js +12 -4
- package/dist/modes/interactive/components/first-time-setup.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts +7 -0
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +51 -6
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/index.d.ts +1 -1
- package/dist/modes/interactive/components/index.d.ts.map +1 -1
- package/dist/modes/interactive/components/index.js.map +1 -1
- package/dist/modes/interactive/components/login-dialog.js +9 -3
- package/dist/modes/interactive/components/login-dialog.js.map +1 -1
- package/dist/modes/interactive/components/markdown-transform.d.ts +3 -0
- package/dist/modes/interactive/components/markdown-transform.d.ts.map +1 -0
- package/dist/modes/interactive/components/markdown-transform.js +19 -0
- package/dist/modes/interactive/components/markdown-transform.js.map +1 -0
- package/dist/modes/interactive/components/mermaid.d.ts +11 -0
- package/dist/modes/interactive/components/mermaid.d.ts.map +1 -0
- package/dist/modes/interactive/components/mermaid.js +75 -0
- package/dist/modes/interactive/components/mermaid.js.map +1 -0
- package/dist/modes/interactive/components/model-selector.d.ts +10 -4
- package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/model-selector.js +101 -40
- package/dist/modes/interactive/components/model-selector.js.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.js +11 -3
- package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.d.ts +4 -0
- package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.js +60 -32
- package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
- package/dist/modes/interactive/components/session-selector.d.ts +5 -5
- package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector.js +128 -78
- package/dist/modes/interactive/components/session-selector.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +23 -4
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +230 -67
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/settings-submenu.d.ts +72 -0
- package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -0
- package/dist/modes/interactive/components/settings-submenu.js +165 -0
- package/dist/modes/interactive/components/settings-submenu.js.map +1 -0
- package/dist/modes/interactive/components/show-images-selector.js +1 -0
- package/dist/modes/interactive/components/show-images-selector.js.map +1 -1
- package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/skill-invocation-message.js +14 -5
- package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
- package/dist/modes/interactive/components/status-indicator.d.ts +3 -1
- package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
- package/dist/modes/interactive/components/status-indicator.js +12 -3
- package/dist/modes/interactive/components/status-indicator.js.map +1 -1
- package/dist/modes/interactive/components/theme-selector.js +2 -0
- package/dist/modes/interactive/components/theme-selector.js.map +1 -1
- package/dist/modes/interactive/components/themed-text.d.ts +17 -0
- package/dist/modes/interactive/components/themed-text.d.ts.map +1 -0
- package/dist/modes/interactive/components/themed-text.js +29 -0
- package/dist/modes/interactive/components/themed-text.js.map +1 -0
- package/dist/modes/interactive/components/thinking-selector.d.ts +15 -3
- package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/thinking-selector.js +76 -18
- package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +21 -4
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +78 -52
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector.js +44 -18
- package/dist/modes/interactive/components/tree-selector.js.map +1 -1
- package/dist/modes/interactive/components/trust-selector.js +8 -2
- package/dist/modes/interactive/components/trust-selector.js.map +1 -1
- package/dist/modes/interactive/components/user-message-selector.js +6 -3
- package/dist/modes/interactive/components/user-message-selector.js.map +1 -1
- package/dist/modes/interactive/components/user-message.d.ts +3 -1
- package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/user-message.js +12 -2
- package/dist/modes/interactive/components/user-message.js.map +1 -1
- package/dist/modes/interactive/components/visual-truncate.d.ts +27 -3
- package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
- package/dist/modes/interactive/components/visual-truncate.js +39 -6
- package/dist/modes/interactive/components/visual-truncate.js.map +1 -1
- package/dist/modes/interactive/external-editor.d.ts.map +1 -1
- package/dist/modes/interactive/external-editor.js +2 -1
- package/dist/modes/interactive/external-editor.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +69 -5
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +1314 -593
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/model-catalog-refresh.d.ts +7 -0
- package/dist/modes/interactive/model-catalog-refresh.d.ts.map +1 -0
- package/dist/modes/interactive/model-catalog-refresh.js +34 -0
- package/dist/modes/interactive/model-catalog-refresh.js.map +1 -0
- package/dist/modes/interactive/session-share.d.ts +23 -0
- package/dist/modes/interactive/session-share.d.ts.map +1 -0
- package/dist/modes/interactive/session-share.js +130 -0
- package/dist/modes/interactive/session-share.js.map +1 -0
- package/dist/modes/interactive/theme/dark.json +54 -63
- package/dist/modes/interactive/theme/light.json +52 -60
- package/dist/modes/interactive/theme/system-theme.d.ts +54 -0
- package/dist/modes/interactive/theme/system-theme.d.ts.map +1 -0
- package/dist/modes/interactive/theme/system-theme.js +535 -0
- package/dist/modes/interactive/theme/system-theme.js.map +1 -0
- package/dist/modes/interactive/theme/theme-controller.d.ts +59 -7
- package/dist/modes/interactive/theme/theme-controller.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme-controller.js +164 -51
- package/dist/modes/interactive/theme/theme-controller.js.map +1 -1
- package/dist/modes/interactive/theme/theme-json.d.ts +85 -0
- package/dist/modes/interactive/theme/theme-json.d.ts.map +1 -0
- package/dist/modes/interactive/theme/theme-json.js +132 -0
- package/dist/modes/interactive/theme/theme-json.js.map +1 -0
- package/dist/modes/interactive/theme/theme-schema.json +24 -3
- package/dist/modes/interactive/theme/theme.d.ts +80 -42
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme.js +274 -417
- package/dist/modes/interactive/theme/theme.js.map +1 -1
- package/dist/modes/interactive/tui-renderer.d.ts +22 -0
- package/dist/modes/interactive/tui-renderer.d.ts.map +1 -0
- package/dist/modes/interactive/tui-renderer.js +67 -0
- package/dist/modes/interactive/tui-renderer.js.map +1 -0
- package/dist/modes/json-event.d.ts +34 -0
- package/dist/modes/json-event.d.ts.map +1 -0
- package/dist/modes/json-event.js +29 -0
- package/dist/modes/json-event.js.map +1 -0
- package/dist/modes/print-mode.d.ts +1 -1
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +12 -2
- package/dist/modes/print-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts +17 -9
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +27 -15
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +14 -12
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +22 -1
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/package-manager-cli.d.ts +1 -0
- package/dist/package-manager-cli.d.ts.map +1 -1
- package/dist/package-manager-cli.js +217 -63
- package/dist/package-manager-cli.js.map +1 -1
- package/dist/prompts/commands/plan-phase.md +1 -0
- package/dist/prompts/commands/review.md +2 -0
- package/dist/prompts/commands/verify-work.md +1 -0
- package/dist/prompts/commands/why.md +4 -0
- package/dist/rpc-entry.js +1 -0
- package/dist/rpc-entry.js.map +1 -1
- package/dist/skills/blast-radius/SKILL.md +1 -0
- package/dist/skills/explainers/SKILL.md +65 -0
- package/dist/skills/unslop/SKILL.md +19 -1
- package/dist/utils/abort.d.ts +5 -0
- package/dist/utils/abort.d.ts.map +1 -0
- package/dist/utils/abort.js +48 -0
- package/dist/utils/abort.js.map +1 -0
- package/dist/utils/changelog.js +1 -1
- package/dist/utils/changelog.js.map +1 -1
- package/dist/utils/child-process.d.ts +1 -1
- package/dist/utils/child-process.js +1 -1
- package/dist/utils/child-process.js.map +1 -1
- package/dist/utils/clipboard-command.d.ts +7 -0
- package/dist/utils/clipboard-command.d.ts.map +1 -0
- package/dist/utils/clipboard-command.js +45 -0
- package/dist/utils/clipboard-command.js.map +1 -0
- package/dist/utils/clipboard-image.d.ts.map +1 -1
- package/dist/utils/clipboard-image.js +60 -91
- package/dist/utils/clipboard-image.js.map +1 -1
- package/dist/utils/clipboard.d.ts +2 -0
- package/dist/utils/clipboard.d.ts.map +1 -1
- package/dist/utils/clipboard.js +116 -121
- package/dist/utils/clipboard.js.map +1 -1
- package/dist/utils/draht-user-agent.d.ts +2 -0
- package/dist/utils/draht-user-agent.d.ts.map +1 -0
- package/dist/utils/draht-user-agent.js +5 -0
- package/dist/utils/draht-user-agent.js.map +1 -0
- package/dist/utils/exif-orientation.d.ts +2 -1
- package/dist/utils/exif-orientation.d.ts.map +1 -1
- package/dist/utils/exif-orientation.js.map +1 -1
- package/dist/utils/frontmatter.d.ts.map +1 -1
- package/dist/utils/frontmatter.js +2 -1
- package/dist/utils/frontmatter.js.map +1 -1
- package/dist/utils/management-http.d.ts +25 -0
- package/dist/utils/management-http.d.ts.map +1 -0
- package/dist/utils/management-http.js +54 -0
- package/dist/utils/management-http.js.map +1 -0
- package/dist/utils/mime.js +1 -1
- package/dist/utils/mime.js.map +1 -1
- package/dist/utils/paths.d.ts +4 -3
- package/dist/utils/paths.d.ts.map +1 -1
- package/dist/utils/paths.js +15 -4
- package/dist/utils/paths.js.map +1 -1
- package/dist/utils/photon.d.ts +2 -1
- package/dist/utils/photon.d.ts.map +1 -1
- package/dist/utils/photon.js.map +1 -1
- package/dist/utils/shell.d.ts +4 -3
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +20 -35
- package/dist/utils/shell.js.map +1 -1
- package/dist/utils/syntax-highlight.d.ts +1 -0
- package/dist/utils/syntax-highlight.d.ts.map +1 -1
- package/dist/utils/syntax-highlight.js +62 -1
- package/dist/utils/syntax-highlight.js.map +1 -1
- package/dist/utils/text.d.ts +8 -0
- package/dist/utils/text.d.ts.map +1 -0
- package/dist/utils/text.js +9 -0
- package/dist/utils/text.js.map +1 -0
- package/dist/utils/tool-result-images.d.ts +21 -0
- package/dist/utils/tool-result-images.d.ts.map +1 -0
- package/dist/utils/tool-result-images.js +48 -0
- package/dist/utils/tool-result-images.js.map +1 -0
- package/dist/utils/tools-manager.d.ts +11 -1
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +53 -36
- package/dist/utils/tools-manager.js.map +1 -1
- package/dist/utils/version-check.d.ts +4 -1
- package/dist/utils/version-check.d.ts.map +1 -1
- package/dist/utils/version-check.js +30 -9
- package/dist/utils/version-check.js.map +1 -1
- package/dist/utils/wsl.d.ts +3 -0
- package/dist/utils/wsl.d.ts.map +1 -0
- package/dist/utils/wsl.js +15 -0
- package/dist/utils/wsl.js.map +1 -0
- package/dist/utils/zip.d.ts +7 -0
- package/dist/utils/zip.d.ts.map +1 -0
- package/dist/utils/zip.js +60 -0
- package/dist/utils/zip.js.map +1 -0
- package/docs/cli-integration.md +106 -0
- package/docs/cli.md +374 -0
- package/docs/compaction.md +91 -29
- package/docs/configuration.md +47 -0
- package/docs/containerization.md +100 -66
- package/docs/custom-provider.md +109 -707
- package/docs/docs.json +155 -99
- package/docs/environment-variables.md +30 -17
- package/docs/extensions.md +169 -2811
- package/docs/how-pi-works.md +53 -0
- package/docs/images/interactive-mode.png +0 -0
- package/docs/index.md +25 -69
- package/docs/json.md +197 -56
- package/docs/keybindings.md +89 -93
- package/docs/llama-cpp.md +18 -3
- package/docs/mcp.md +231 -0
- package/docs/message-types.md +261 -0
- package/docs/models.md +94 -478
- package/docs/packages.md +67 -163
- package/docs/prompt-templates.md +31 -68
- package/docs/providers.md +118 -215
- package/docs/quickstart.md +55 -108
- package/docs/rpc-commands.md +860 -0
- package/docs/rpc-extension-ui.md +200 -0
- package/docs/rpc.md +139 -1518
- package/docs/sdk.md +79 -1127
- package/docs/security.md +76 -32
- package/docs/session-format.md +73 -219
- package/docs/sessions.md +36 -116
- package/docs/settings.md +124 -257
- package/docs/shell-aliases.md +85 -5
- package/docs/skills.md +52 -189
- package/docs/slash-commands.md +61 -0
- package/docs/terminal-setup.md +132 -61
- package/docs/termux.md +74 -84
- package/docs/themes.md +91 -252
- package/docs/tmux.md +31 -39
- package/docs/tui.md +74 -891
- package/docs/usage.md +54 -255
- package/docs/virtual-models.md +114 -0
- package/docs/windows.md +57 -7
- package/examples/extensions/antigravity-image-gen.ts +9 -9
- package/examples/extensions/bash-spawn-hook.ts +1 -1
- package/examples/extensions/border-status-editor.ts +1 -1
- package/examples/extensions/built-in-tool-renderer.ts +16 -40
- package/examples/extensions/custom-compaction.ts +1 -16
- package/examples/extensions/custom-provider-anthropic/index.ts +20 -13
- package/examples/extensions/custom-provider-gitlab-duo/index.ts +4 -3
- package/examples/extensions/custom-provider-gitlab-duo/test.ts +5 -5
- package/examples/extensions/debug-provider.ts +90 -0
- package/examples/extensions/doom-overlay/wad-finder.ts +7 -3
- package/examples/extensions/dynamic-resources/dynamic.json +3 -1
- package/examples/extensions/git-checkpoint.ts +2 -2
- package/examples/extensions/handoff.ts +2 -11
- package/examples/extensions/jev-router.ts +113 -0
- package/examples/extensions/minimal-mode.ts +24 -96
- package/examples/extensions/notify.ts +3 -1
- package/examples/extensions/prompt-customizer.ts +19 -67
- package/examples/extensions/qna.ts +3 -7
- package/examples/extensions/subagent/agents.ts +40 -9
- package/examples/extensions/subagent/index.ts +27 -4
- package/examples/extensions/summarize.ts +7 -18
- package/examples/extensions/titlebar-spinner.ts +1 -1
- package/examples/rpc-client.ts +35 -0
- package/examples/rpc-extension-ui.ts +38 -9
- package/examples/sdk/02-custom-model.ts +1 -2
- package/examples/sdk/06-extensions.ts +1 -1
- package/examples/sdk/09-api-keys-and-oauth.ts +1 -1
- package/examples/sdk/12-full-control.ts +1 -1
- package/examples/sdk/14-codemode-mcp.ts +61 -0
- package/package.json +25 -30
- package/prompts/commands/plan-phase.md +1 -0
- package/prompts/commands/review.md +2 -0
- package/prompts/commands/verify-work.md +1 -0
- package/prompts/commands/why.md +4 -0
- package/skills/blast-radius/SKILL.md +1 -0
- package/skills/explainers/SKILL.md +65 -0
- package/skills/unslop/SKILL.md +19 -1
- package/dist/utils/clipboard-native.d.ts +0 -11
- package/dist/utils/clipboard-native.d.ts.map +0 -1
- package/dist/utils/clipboard-native.js +0 -20
- package/dist/utils/clipboard-native.js.map +0 -1
- package/dist/utils/pi-user-agent.d.ts +0 -2
- package/dist/utils/pi-user-agent.d.ts.map +0 -1
- package/dist/utils/pi-user-agent.js +0 -5
- package/dist/utils/pi-user-agent.js.map +0 -1
- package/docs/development.md +0 -71
- package/docs/tree.md +0 -231
- package/examples/extensions/kimi-deferred-tools.ts +0 -61
package/docs/extensions.md
CHANGED
|
@@ -1,2921 +1,279 @@
|
|
|
1
|
-
> draht can create extensions. Ask it to build one for your use case.
|
|
2
|
-
|
|
3
1
|
# Extensions
|
|
4
2
|
|
|
5
|
-
Extensions are TypeScript modules that
|
|
6
|
-
|
|
7
|
-
> **Placement for /reload:** Put extensions in `~/.draht/agent/extensions/` (global) or `.draht/extensions/` (project-local) for auto-discovery. Use `draht -e ./path.ts` only for quick tests. Extensions in auto-discovered locations can be hot-reloaded with `/reload`.
|
|
8
|
-
|
|
9
|
-
**Key capabilities:**
|
|
10
|
-
- **Custom tools** - Register tools the LLM can call via `pi.registerTool()`
|
|
11
|
-
- **Event interception** - Block or modify tool calls, inject context, customize compaction
|
|
12
|
-
- **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
|
-
- **Custom commands** - Register commands like `/mycommand` via `pi.registerCommand()`
|
|
15
|
-
- **Session persistence** - Store state that survives restarts via `pi.appendEntry()`
|
|
16
|
-
- **Custom rendering** - Control how tool calls/results and messages appear in TUI
|
|
17
|
-
|
|
18
|
-
**Example use cases:**
|
|
19
|
-
- Permission gates (confirm before `rm -rf`, `sudo`, etc.)
|
|
20
|
-
- Git checkpointing (stash at each turn, restore on branch)
|
|
21
|
-
- Path protection (block writes to `.env`, `node_modules/`)
|
|
22
|
-
- Custom compaction (summarize conversation your way)
|
|
23
|
-
- Conversation summaries (see `summarize.ts` example)
|
|
24
|
-
- Interactive tools (questions, wizards, custom dialogs)
|
|
25
|
-
- Stateful tools (todo lists, connection pools)
|
|
26
|
-
- External integrations (file watchers, webhooks, CI triggers)
|
|
27
|
-
- Games while you wait (see `snake.ts` example)
|
|
28
|
-
|
|
29
|
-
See [examples/extensions/](../examples/extensions/) for working implementations.
|
|
30
|
-
|
|
31
|
-
## Table of Contents
|
|
32
|
-
|
|
33
|
-
- [Quick Start](#quick-start)
|
|
34
|
-
- [Extension Locations](#extension-locations)
|
|
35
|
-
- [Available Imports](#available-imports)
|
|
36
|
-
- [Writing an Extension](#writing-an-extension)
|
|
37
|
-
- [Extension Styles](#extension-styles)
|
|
38
|
-
- [Events](#events)
|
|
39
|
-
- [Lifecycle Overview](#lifecycle-overview)
|
|
40
|
-
- [Resource Events](#resource-events)
|
|
41
|
-
- [Session Events](#session-events)
|
|
42
|
-
- [Agent Events](#agent-events)
|
|
43
|
-
- [Model Events](#model-events)
|
|
44
|
-
- [Tool Events](#tool-events)
|
|
45
|
-
- [ExtensionContext](#extensioncontext)
|
|
46
|
-
- [ExtensionCommandContext](#extensioncommandcontext)
|
|
47
|
-
- [ExtensionAPI Methods](#extensionapi-methods)
|
|
48
|
-
- [State Management](#state-management)
|
|
49
|
-
- [Custom Tools](#custom-tools)
|
|
50
|
-
- [Dynamic Tool Loading](#dynamic-tool-loading)
|
|
51
|
-
- [Custom UI](#custom-ui)
|
|
52
|
-
- [Error Handling](#error-handling)
|
|
53
|
-
- [Mode Behavior](#mode-behavior)
|
|
54
|
-
- [Examples Reference](#examples-reference)
|
|
55
|
-
|
|
56
|
-
## Quick Start
|
|
57
|
-
|
|
58
|
-
Create `~/.draht/agent/extensions/my-extension.ts`:
|
|
59
|
-
|
|
60
|
-
```typescript
|
|
61
|
-
import type { ExtensionAPI } from "@draht/coding-agent";
|
|
62
|
-
import { Type } from "typebox";
|
|
63
|
-
|
|
64
|
-
export default function (pi: ExtensionAPI) {
|
|
65
|
-
// React to events
|
|
66
|
-
pi.on("session_start", async (_event, ctx) => {
|
|
67
|
-
ctx.ui.notify("Extension loaded!", "info");
|
|
68
|
-
});
|
|
69
|
-
|
|
70
|
-
pi.on("tool_call", async (event, ctx) => {
|
|
71
|
-
if (event.toolName === "bash" && event.input.command?.includes("rm -rf")) {
|
|
72
|
-
const ok = await ctx.ui.confirm("Dangerous!", "Allow rm -rf?");
|
|
73
|
-
if (!ok) return { block: true, reason: "Blocked by user" };
|
|
74
|
-
}
|
|
75
|
-
});
|
|
76
|
-
|
|
77
|
-
// Register a custom tool
|
|
78
|
-
pi.registerTool({
|
|
79
|
-
name: "greet",
|
|
80
|
-
label: "Greet",
|
|
81
|
-
description: "Greet someone by name",
|
|
82
|
-
parameters: Type.Object({
|
|
83
|
-
name: Type.String({ description: "Name to greet" }),
|
|
84
|
-
}),
|
|
85
|
-
async execute(toolCallId, params, signal, onUpdate, ctx) {
|
|
86
|
-
return {
|
|
87
|
-
content: [{ type: "text", text: `Hello, ${params.name}!` }],
|
|
88
|
-
details: {},
|
|
89
|
-
};
|
|
90
|
-
},
|
|
91
|
-
});
|
|
92
|
-
|
|
93
|
-
// Register a command
|
|
94
|
-
pi.registerCommand("hello", {
|
|
95
|
-
description: "Say hello",
|
|
96
|
-
handler: async (args, ctx) => {
|
|
97
|
-
ctx.ui.notify(`Hello ${args || "world"}!`, "info");
|
|
98
|
-
},
|
|
99
|
-
});
|
|
100
|
-
}
|
|
101
|
-
```
|
|
102
|
-
|
|
103
|
-
Test with `--extension` (or `-e`) flag:
|
|
104
|
-
|
|
105
|
-
```bash
|
|
106
|
-
draht -e ./my-extension.ts
|
|
107
|
-
```
|
|
108
|
-
|
|
109
|
-
## Extension Locations
|
|
110
|
-
|
|
111
|
-
> **Security:** Extensions run with your full system permissions and can execute arbitrary code. Only install from sources you trust.
|
|
112
|
-
|
|
113
|
-
Extensions are auto-discovered from trusted locations. Project-local `.draht/extensions` entries load only after the project is trusted.
|
|
114
|
-
|
|
115
|
-
| Location | Scope |
|
|
116
|
-
|----------|-------|
|
|
117
|
-
| `~/.draht/agent/extensions/*.ts` | Global (all projects) |
|
|
118
|
-
| `~/.draht/agent/extensions/*/index.ts` | Global (subdirectory) |
|
|
119
|
-
| `.draht/extensions/*.ts` | Project-local |
|
|
120
|
-
| `.draht/extensions/*/index.ts` | Project-local (subdirectory) |
|
|
121
|
-
|
|
122
|
-
Additional paths via `settings.json`:
|
|
123
|
-
|
|
124
|
-
```json
|
|
125
|
-
{
|
|
126
|
-
"packages": [
|
|
127
|
-
"npm:@foo/bar@1.0.0",
|
|
128
|
-
"git:github.com/user/repo@v1"
|
|
129
|
-
],
|
|
130
|
-
"extensions": [
|
|
131
|
-
"/path/to/local/extension.ts",
|
|
132
|
-
"/path/to/local/extension/dir"
|
|
133
|
-
]
|
|
134
|
-
}
|
|
135
|
-
```
|
|
136
|
-
|
|
137
|
-
To share extensions via npm or git as draht packages, see [packages.md](packages.md).
|
|
138
|
-
|
|
139
|
-
## Available Imports
|
|
3
|
+
Extensions are TypeScript modules that add executable behavior to draht. Use one when a workflow needs tools, commands, event handlers, model providers, session state, or terminal UI rather than instructions alone.
|
|
140
4
|
|
|
141
|
-
|
|
142
|
-
|---------|---------|
|
|
143
|
-
| `@draht/coding-agent` | Extension types (`ExtensionAPI`, `ExtensionContext`, events) |
|
|
144
|
-
| `typebox` | Schema definitions for tool parameters |
|
|
145
|
-
| `@draht/ai` | AI utilities (`StringEnum` for Google-compatible enums) |
|
|
146
|
-
| `@draht/tui` | TUI components for custom rendering |
|
|
5
|
+
An extension runs inside the draht 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.
|
|
147
6
|
|
|
148
|
-
|
|
7
|
+
Typical extensions add an agent tool, protect paths, confirm dangerous commands, react to session events, modify context, expose a command, or display persistent status.
|
|
149
8
|
|
|
150
|
-
|
|
9
|
+
<a id="quick-start"></a>
|
|
10
|
+
<a id="writing-an-extension"></a>
|
|
11
|
+
<a id="create-an-extension"></a>
|
|
151
12
|
|
|
152
|
-
|
|
13
|
+
## Create and load an extension
|
|
153
14
|
|
|
154
|
-
|
|
15
|
+
An extension exports a default factory that receives `ExtensionAPI`. The factory registers capabilities for the current extension runtime.
|
|
155
16
|
|
|
156
|
-
|
|
17
|
+
Create `~/.draht/agent/extensions/hello.ts`:
|
|
157
18
|
|
|
158
19
|
```typescript
|
|
159
20
|
import type { ExtensionAPI } from "@draht/coding-agent";
|
|
160
21
|
|
|
161
22
|
export default function (pi: ExtensionAPI) {
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
ctx.ui.setStatus("my-ext", "Processing..."); // Footer status
|
|
168
|
-
ctx.ui.setWidget("my-ext", ["Line 1", "Line 2"]); // Widget above editor (default)
|
|
169
|
-
});
|
|
170
|
-
|
|
171
|
-
// Register tools, commands, shortcuts, flags
|
|
172
|
-
pi.registerTool({ ... });
|
|
173
|
-
pi.registerCommand("name", { ... });
|
|
174
|
-
pi.registerShortcut("ctrl+x", { ... });
|
|
175
|
-
pi.registerFlag("my-flag", { ... });
|
|
176
|
-
}
|
|
177
|
-
```
|
|
178
|
-
|
|
179
|
-
Extensions are loaded via [jiti](https://github.com/unjs/jiti), so TypeScript works without compilation.
|
|
180
|
-
|
|
181
|
-
If the factory returns a `Promise`, draht awaits it before continuing startup. That means async initialization completes before `session_start`, before `resources_discover`, and before provider registrations queued via `pi.registerProvider()` are flushed.
|
|
182
|
-
|
|
183
|
-
### Async factory functions
|
|
184
|
-
|
|
185
|
-
Use an async factory for one-time startup work such as fetching remote configuration or dynamically discovering available models.
|
|
186
|
-
|
|
187
|
-
```typescript
|
|
188
|
-
import type { ExtensionAPI } from "@draht/coding-agent";
|
|
189
|
-
|
|
190
|
-
export default async function (pi: ExtensionAPI) {
|
|
191
|
-
const response = await fetch("http://localhost:1234/v1/models");
|
|
192
|
-
const payload = (await response.json()) as {
|
|
193
|
-
data: Array<{
|
|
194
|
-
id: string;
|
|
195
|
-
name?: string;
|
|
196
|
-
context_window?: number;
|
|
197
|
-
max_tokens?: number;
|
|
198
|
-
}>;
|
|
199
|
-
};
|
|
200
|
-
|
|
201
|
-
pi.registerProvider("local-openai", {
|
|
202
|
-
baseUrl: "http://localhost:1234/v1",
|
|
203
|
-
apiKey: "$LOCAL_OPENAI_API_KEY",
|
|
204
|
-
api: "openai-completions",
|
|
205
|
-
models: payload.data.map((model) => ({
|
|
206
|
-
id: model.id,
|
|
207
|
-
name: model.name ?? model.id,
|
|
208
|
-
reasoning: false,
|
|
209
|
-
input: ["text"],
|
|
210
|
-
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
211
|
-
contextWindow: model.context_window ?? 128000,
|
|
212
|
-
maxTokens: model.max_tokens ?? 4096,
|
|
213
|
-
})),
|
|
23
|
+
pi.registerCommand("hello", {
|
|
24
|
+
description: "Show a greeting",
|
|
25
|
+
handler: async (name, ctx) => {
|
|
26
|
+
ctx.ui.notify(`Hello, ${name || "world"}!`, "info");
|
|
27
|
+
},
|
|
214
28
|
});
|
|
215
29
|
}
|
|
216
30
|
```
|
|
217
31
|
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
### Extension Styles
|
|
221
|
-
|
|
222
|
-
**Single file** - simplest, for small extensions:
|
|
223
|
-
|
|
224
|
-
```
|
|
225
|
-
~/.draht/agent/extensions/
|
|
226
|
-
└── my-extension.ts
|
|
227
|
-
```
|
|
228
|
-
|
|
229
|
-
**Directory with index.ts** - for multi-file extensions:
|
|
230
|
-
|
|
231
|
-
```
|
|
232
|
-
~/.draht/agent/extensions/
|
|
233
|
-
└── my-extension/
|
|
234
|
-
├── index.ts # Entry point (exports default function)
|
|
235
|
-
├── tools.ts # Helper module
|
|
236
|
-
└── utils.ts # Helper module
|
|
237
|
-
```
|
|
238
|
-
|
|
239
|
-
**Package with dependencies** - for extensions that need npm packages:
|
|
240
|
-
|
|
241
|
-
```
|
|
242
|
-
~/.draht/agent/extensions/
|
|
243
|
-
└── my-extension/
|
|
244
|
-
├── package.json # Declares dependencies and entry points
|
|
245
|
-
├── package-lock.json
|
|
246
|
-
├── node_modules/ # After npm install
|
|
247
|
-
└── src/
|
|
248
|
-
└── index.ts
|
|
249
|
-
```
|
|
250
|
-
|
|
251
|
-
```json
|
|
252
|
-
// package.json
|
|
253
|
-
{
|
|
254
|
-
"name": "my-extension",
|
|
255
|
-
"dependencies": {
|
|
256
|
-
"zod": "^3.0.0",
|
|
257
|
-
"chalk": "^5.0.0"
|
|
258
|
-
},
|
|
259
|
-
"draht": {
|
|
260
|
-
"extensions": ["./src/index.ts"]
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
```
|
|
264
|
-
|
|
265
|
-
The manifest key is `draht`. Upstream's `pi` key is still read as a fallback, so extension packages written for pi work unchanged.
|
|
266
|
-
|
|
267
|
-
Run `npm install` in the extension directory, then imports from `node_modules/` work automatically.
|
|
268
|
-
|
|
269
|
-
## Events
|
|
270
|
-
|
|
271
|
-
### Lifecycle Overview
|
|
272
|
-
|
|
273
|
-
```
|
|
274
|
-
draht starts
|
|
275
|
-
│
|
|
276
|
-
├─► project_trust (user/global and CLI extensions only, before project resources load)
|
|
277
|
-
├─► session_start { reason: "startup" }
|
|
278
|
-
└─► resources_discover { reason: "startup" }
|
|
279
|
-
│
|
|
280
|
-
▼
|
|
281
|
-
user sends prompt ─────────────────────────────────────────┐
|
|
282
|
-
│ │
|
|
283
|
-
├─► (extension commands checked first, bypass if found) │
|
|
284
|
-
├─► input (can intercept, transform, or handle) │
|
|
285
|
-
├─► (skill/template expansion if not handled) │
|
|
286
|
-
├─► before_agent_start (can inject message, modify system prompt)
|
|
287
|
-
├─► agent_start │
|
|
288
|
-
├─► message_start / message_update / message_end │
|
|
289
|
-
│ │
|
|
290
|
-
│ ┌─── turn (repeats while LLM calls tools) ───┐ │
|
|
291
|
-
│ │ │ │
|
|
292
|
-
│ ├─► turn_start │ │
|
|
293
|
-
│ ├─► context (can modify messages) │ │
|
|
294
|
-
│ ├─► before_provider_request (can inspect or replace payload)
|
|
295
|
-
│ ├─► after_provider_response (status + headers, before stream consume)
|
|
296
|
-
│ │ │ │
|
|
297
|
-
│ │ LLM responds, may call tools: │ │
|
|
298
|
-
│ │ ├─► tool_execution_start │ │
|
|
299
|
-
│ │ ├─► tool_call (can block) │ │
|
|
300
|
-
│ │ ├─► tool_execution_update │ │
|
|
301
|
-
│ │ ├─► tool_result (can modify) │ │
|
|
302
|
-
│ │ └─► tool_execution_end │ │
|
|
303
|
-
│ │ │ │
|
|
304
|
-
│ └─► turn_end │ │
|
|
305
|
-
│ │
|
|
306
|
-
├─► agent_end │
|
|
307
|
-
└─► agent_settled (no retry/compaction/follow-up left) │
|
|
308
|
-
│
|
|
309
|
-
user sends another prompt ◄────────────────────────────────┘
|
|
310
|
-
|
|
311
|
-
/new (new session) or /resume (switch session)
|
|
312
|
-
├─► session_before_switch (can cancel)
|
|
313
|
-
├─► session_shutdown
|
|
314
|
-
├─► session_start { reason: "new" | "resume", previousSessionFile? }
|
|
315
|
-
└─► resources_discover { reason: "startup" }
|
|
316
|
-
|
|
317
|
-
/fork or /clone
|
|
318
|
-
├─► session_before_fork (can cancel)
|
|
319
|
-
├─► session_shutdown
|
|
320
|
-
├─► session_start { reason: "fork", previousSessionFile }
|
|
321
|
-
└─► resources_discover { reason: "startup" }
|
|
322
|
-
|
|
323
|
-
/name or pi.setSessionName()
|
|
324
|
-
└─► session_info_changed
|
|
325
|
-
|
|
326
|
-
/compact or auto-compaction
|
|
327
|
-
├─► session_before_compact (can cancel or customize)
|
|
328
|
-
└─► session_compact
|
|
329
|
-
|
|
330
|
-
/tree navigation
|
|
331
|
-
├─► session_before_tree (can cancel or customize)
|
|
332
|
-
└─► session_tree
|
|
333
|
-
|
|
334
|
-
/model or Ctrl+P (model selection/cycling)
|
|
335
|
-
├─► thinking_level_select (if model change changes/clamps thinking level)
|
|
336
|
-
└─► model_select
|
|
337
|
-
|
|
338
|
-
thinking level changes (settings, keybinding, pi.setThinkingLevel())
|
|
339
|
-
└─► thinking_level_select
|
|
340
|
-
|
|
341
|
-
exit (Ctrl+C, Ctrl+D, SIGHUP, SIGTERM)
|
|
342
|
-
└─► session_shutdown
|
|
343
|
-
```
|
|
344
|
-
|
|
345
|
-
### Startup Events
|
|
346
|
-
|
|
347
|
-
#### project_trust
|
|
348
|
-
|
|
349
|
-
Fired before draht decides whether to trust a project with dynamic configs (`.draht` or `.agents/skills`). It runs during startup and when session replacement (for example `/resume`) 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.
|
|
350
|
-
|
|
351
|
-
```typescript
|
|
352
|
-
pi.on("project_trust", async (event, ctx) => {
|
|
353
|
-
// event.cwd - current working directory
|
|
354
|
-
// ctx has a limited trust context: cwd, mode, hasUI, and select/confirm/input/notify UI helpers
|
|
355
|
-
if (await ctx.ui.confirm("Trust project?", event.cwd)) {
|
|
356
|
-
return { trusted: "yes", remember: true };
|
|
357
|
-
}
|
|
358
|
-
return { trusted: "undecided" };
|
|
359
|
-
});
|
|
360
|
-
```
|
|
361
|
-
|
|
362
|
-
A `project_trust` handler must return `{ trusted: "yes" | "no" | "undecided" }`. A user/global or CLI extension that returns `"yes"` or `"no"` owns the decision; the first yes/no decision wins and suppresses the built-in trust prompt. Use `remember: true` to persist a yes/no decision; otherwise it applies only to the current process. Return `"undecided"` to let later handlers or the built-in trust flow decide. Check `ctx.hasUI` before prompting. If no handler returns yes/no, normal trust resolution continues: saved `trust.json` decisions apply first, then `defaultProjectTrust` controls whether draht asks, trusts, or declines by default.
|
|
363
|
-
|
|
364
|
-
### Resource Events
|
|
365
|
-
|
|
366
|
-
#### resources_discover
|
|
367
|
-
|
|
368
|
-
Fired after `session_start` so extensions can contribute additional skill, prompt, and theme paths.
|
|
369
|
-
The startup path uses `reason: "startup"`. Reload uses `reason: "reload"`.
|
|
370
|
-
|
|
371
|
-
```typescript
|
|
372
|
-
pi.on("resources_discover", async (event, _ctx) => {
|
|
373
|
-
// event.cwd - current working directory
|
|
374
|
-
// event.reason - "startup" | "reload"
|
|
375
|
-
return {
|
|
376
|
-
skillPaths: ["/path/to/skills"],
|
|
377
|
-
promptPaths: ["/path/to/prompts"],
|
|
378
|
-
themePaths: ["/path/to/themes"],
|
|
379
|
-
};
|
|
380
|
-
});
|
|
381
|
-
```
|
|
382
|
-
|
|
383
|
-
### Session Events
|
|
384
|
-
|
|
385
|
-
See [Session Format](session-format.md) for session storage internals and the SessionManager API.
|
|
386
|
-
|
|
387
|
-
#### session_start
|
|
388
|
-
|
|
389
|
-
Fired when a session is started, loaded, or reloaded.
|
|
390
|
-
|
|
391
|
-
```typescript
|
|
392
|
-
pi.on("session_start", async (event, ctx) => {
|
|
393
|
-
// event.reason - "startup" | "reload" | "new" | "resume" | "fork"
|
|
394
|
-
// event.previousSessionFile - present for "new", "resume", and "fork"
|
|
395
|
-
ctx.ui.notify(`Session: ${ctx.sessionManager.getSessionFile() ?? "ephemeral"}`, "info");
|
|
396
|
-
});
|
|
397
|
-
```
|
|
398
|
-
|
|
399
|
-
#### session_info_changed
|
|
400
|
-
|
|
401
|
-
Fired when the current session display name is set via `/name`, RPC, or `pi.setSessionName()`.
|
|
402
|
-
|
|
403
|
-
```typescript
|
|
404
|
-
pi.on("session_info_changed", async (event, ctx) => {
|
|
405
|
-
// event.name - current normalized name, or undefined if cleared
|
|
406
|
-
ctx.ui.notify(`Session renamed: ${event.name ?? "(none)"}`, "info");
|
|
407
|
-
});
|
|
408
|
-
```
|
|
409
|
-
|
|
410
|
-
#### session_before_switch
|
|
411
|
-
|
|
412
|
-
Fired before starting a new session (`/new`) or switching sessions (`/resume`).
|
|
413
|
-
|
|
414
|
-
```typescript
|
|
415
|
-
pi.on("session_before_switch", async (event, ctx) => {
|
|
416
|
-
// event.reason - "new" or "resume"
|
|
417
|
-
// event.targetSessionFile - session we're switching to (only for "resume")
|
|
418
|
-
|
|
419
|
-
if (event.reason === "new") {
|
|
420
|
-
const ok = await ctx.ui.confirm("Clear?", "Delete all messages?");
|
|
421
|
-
if (!ok) return { cancel: true };
|
|
422
|
-
}
|
|
423
|
-
});
|
|
424
|
-
```
|
|
425
|
-
|
|
426
|
-
After a successful switch or new-session action, draht emits `session_shutdown` for the old extension instance, reloads and rebinds extensions for the new session, then emits `session_start` with `reason: "new" | "resume"` and `previousSessionFile`.
|
|
427
|
-
Do cleanup work in `session_shutdown`, then reestablish any in-memory state in `session_start`.
|
|
428
|
-
|
|
429
|
-
#### session_before_fork
|
|
430
|
-
|
|
431
|
-
Fired when forking via `/fork` or cloning via `/clone`.
|
|
432
|
-
|
|
433
|
-
```typescript
|
|
434
|
-
pi.on("session_before_fork", async (event, ctx) => {
|
|
435
|
-
// event.entryId - ID of the selected entry
|
|
436
|
-
// event.position - "before" for /fork, "at" for /clone
|
|
437
|
-
return { cancel: true }; // Cancel fork/clone
|
|
438
|
-
// OR
|
|
439
|
-
return { skipConversationRestore: true }; // Reserved for future conversation restore control
|
|
440
|
-
});
|
|
441
|
-
```
|
|
442
|
-
|
|
443
|
-
After a successful fork or clone, draht 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`.
|
|
444
|
-
Do cleanup work in `session_shutdown`, then reestablish any in-memory state in `session_start`.
|
|
445
|
-
|
|
446
|
-
#### session_before_compact / session_compact
|
|
447
|
-
|
|
448
|
-
Fired on compaction. See [compaction.md](compaction.md) for details.
|
|
449
|
-
|
|
450
|
-
```typescript
|
|
451
|
-
pi.on("session_before_compact", async (event, ctx) => {
|
|
452
|
-
const { preparation, branchEntries, customInstructions, signal } = event;
|
|
453
|
-
|
|
454
|
-
// Cancel:
|
|
455
|
-
return { cancel: true };
|
|
456
|
-
|
|
457
|
-
// Custom summary:
|
|
458
|
-
return {
|
|
459
|
-
compaction: {
|
|
460
|
-
summary: "...",
|
|
461
|
-
firstKeptEntryId: preparation.firstKeptEntryId,
|
|
462
|
-
tokensBefore: preparation.tokensBefore,
|
|
463
|
-
// usage: summaryResponse.usage, // Optional; included in session totals
|
|
464
|
-
}
|
|
465
|
-
};
|
|
466
|
-
});
|
|
467
|
-
|
|
468
|
-
pi.on("session_compact", async (event, ctx) => {
|
|
469
|
-
// event.compactionEntry - the saved compaction
|
|
470
|
-
// event.fromExtension - whether extension provided it
|
|
471
|
-
});
|
|
472
|
-
```
|
|
473
|
-
|
|
474
|
-
#### session_before_tree / session_tree
|
|
475
|
-
|
|
476
|
-
Fired on `/tree` navigation. See [Sessions](sessions.md) for tree navigation concepts.
|
|
477
|
-
|
|
478
|
-
```typescript
|
|
479
|
-
pi.on("session_before_tree", async (event, ctx) => {
|
|
480
|
-
const { preparation, signal } = event;
|
|
481
|
-
return { cancel: true };
|
|
482
|
-
// OR provide custom summary:
|
|
483
|
-
return {
|
|
484
|
-
summary: {
|
|
485
|
-
summary: "...",
|
|
486
|
-
// usage: summaryResponse.usage, // Optional; included in session totals
|
|
487
|
-
details: {},
|
|
488
|
-
},
|
|
489
|
-
};
|
|
490
|
-
});
|
|
491
|
-
|
|
492
|
-
pi.on("session_tree", async (event, ctx) => {
|
|
493
|
-
// event.newLeafId, oldLeafId, summaryEntry, fromExtension
|
|
494
|
-
});
|
|
495
|
-
```
|
|
496
|
-
|
|
497
|
-
#### session_shutdown
|
|
498
|
-
|
|
499
|
-
Fired before an extension runtime is torn down.
|
|
500
|
-
|
|
501
|
-
```typescript
|
|
502
|
-
pi.on("session_shutdown", async (event, ctx) => {
|
|
503
|
-
// event.reason - "quit" | "reload" | "new" | "resume" | "fork"
|
|
504
|
-
// event.targetSessionFile - destination session for session replacement flows
|
|
505
|
-
// Cleanup, save state, etc.
|
|
506
|
-
});
|
|
507
|
-
```
|
|
508
|
-
|
|
509
|
-
### Agent Events
|
|
510
|
-
|
|
511
|
-
#### before_agent_start
|
|
512
|
-
|
|
513
|
-
Fired after user submits prompt, before agent loop. Can inject a message and/or modify the system prompt.
|
|
514
|
-
|
|
515
|
-
```typescript
|
|
516
|
-
pi.on("before_agent_start", async (event, ctx) => {
|
|
517
|
-
// event.prompt - user's prompt text
|
|
518
|
-
// event.images - attached images (if any)
|
|
519
|
-
// event.systemPrompt - current chained system prompt for this handler
|
|
520
|
-
// (includes changes from earlier before_agent_start handlers)
|
|
521
|
-
// event.systemPromptOptions - structured options used to build the system prompt
|
|
522
|
-
// .customPrompt - any custom system prompt (from --system-prompt, SYSTEM.md, or custom templates)
|
|
523
|
-
// .selectedTools - tools currently active in the prompt
|
|
524
|
-
// .toolSnippets - one-line descriptions for each tool
|
|
525
|
-
// .promptGuidelines - custom guideline bullets
|
|
526
|
-
// .appendSystemPrompt - text from --append-system-prompt flags
|
|
527
|
-
// .cwd - working directory
|
|
528
|
-
// .contextFiles - AGENTS.md files and other loaded context files
|
|
529
|
-
// .skills - loaded skills
|
|
530
|
-
|
|
531
|
-
return {
|
|
532
|
-
// Inject a persistent message (stored in session, sent to LLM)
|
|
533
|
-
message: {
|
|
534
|
-
customType: "my-extension",
|
|
535
|
-
content: "Additional context for the LLM",
|
|
536
|
-
display: true,
|
|
537
|
-
},
|
|
538
|
-
// Replace the system prompt for this turn (chained across extensions)
|
|
539
|
-
systemPrompt: event.systemPrompt + "\n\nExtra instructions for this turn...",
|
|
540
|
-
};
|
|
541
|
-
});
|
|
542
|
-
```
|
|
543
|
-
|
|
544
|
-
The `systemPromptOptions` field gives extensions access to the same structured data draht uses to build the system prompt. This lets you inspect what draht has loaded — custom prompts, guidelines, tool snippets, context files, skills — without re-discovering resources or re-parsing flags. Use it when your extension needs to make deep, informed changes to the system prompt while respecting user-provided configuration.
|
|
545
|
-
|
|
546
|
-
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.
|
|
547
|
-
|
|
548
|
-
#### agent_start / agent_end / agent_settled
|
|
549
|
-
|
|
550
|
-
`agent_start` fires when a low-level agent run begins. `agent_end` fires when that run ends, but draht may still auto-retry, auto-compact and retry, or continue with queued follow-up messages. Use `agent_settled` for status integrations that need to know draht will not continue running automatically.
|
|
551
|
-
|
|
552
|
-
```typescript
|
|
553
|
-
pi.on("agent_start", async (_event, ctx) => {});
|
|
554
|
-
|
|
555
|
-
pi.on("agent_end", async (event, ctx) => {
|
|
556
|
-
// event.messages - messages from this low-level run
|
|
557
|
-
});
|
|
32
|
+
Start draht and run `/hello`. During development, load a file directly:
|
|
558
33
|
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
});
|
|
34
|
+
```bash
|
|
35
|
+
draht --extension ./hello.ts
|
|
562
36
|
```
|
|
563
37
|
|
|
564
|
-
|
|
38
|
+
draht uses `jiti`, so local TypeScript extensions do not need a separate compilation step. Use [draht packages](packages.md) for distributed extensions and dependencies.
|
|
565
39
|
|
|
566
|
-
|
|
40
|
+
<a id="extension-locations"></a>
|
|
41
|
+
<a id="available-imports"></a>
|
|
42
|
+
<a id="choose-where-it-loads"></a>
|
|
567
43
|
|
|
568
|
-
|
|
569
|
-
pi.on("turn_start", async (event, ctx) => {
|
|
570
|
-
// event.turnIndex, event.timestamp
|
|
571
|
-
});
|
|
44
|
+
## Add it to draht
|
|
572
45
|
|
|
573
|
-
|
|
574
|
-
// event.turnIndex, event.message, event.toolResults
|
|
575
|
-
});
|
|
576
|
-
```
|
|
46
|
+
Place the extension in your user or project extensions directory. draht loads direct TypeScript or JavaScript files and subdirectories containing an `index.ts` or `index.js` entry point.
|
|
577
47
|
|
|
578
|
-
|
|
48
|
+
Use a single file for a small extension and a directory for a multi-file implementation. Put npm dependencies in a nearby `package.json`. A package declares its extensions under the `draht` key in `package.json`; draht falls back to the `pi` key, so extension packages written for pi work unchanged. See [Configuration](configuration.md) for conventional locations and [Settings](settings.md#resources) for additional paths.
|
|
579
49
|
|
|
580
|
-
|
|
50
|
+
Reload replaces the extension runtime, so code after `await ctx.reload()` must not reuse state from the old runtime. Only personal and explicit command-line extensions can participate in the `project_trust` event that runs before project extensions load.
|
|
581
51
|
|
|
582
|
-
-
|
|
583
|
-
- `message_update` fires for assistant streaming updates.
|
|
584
|
-
- `message_end` handlers can return `{ message }` to replace the finalized message. The replacement must keep the same `role`.
|
|
52
|
+
<a id="understand-the-lifecycle"></a>
|
|
585
53
|
|
|
586
|
-
|
|
587
|
-
pi.on("message_start", async (event, ctx) => {
|
|
588
|
-
// event.message
|
|
589
|
-
});
|
|
54
|
+
## Respect the runtime lifecycle
|
|
590
55
|
|
|
591
|
-
|
|
592
|
-
// event.message
|
|
593
|
-
// event.assistantMessageEvent (token-by-token stream event)
|
|
594
|
-
});
|
|
56
|
+
The factory can be synchronous or asynchronous. draht waits for an asynchronous factory before startup continues, allowing it to fetch configuration or register providers needed during startup.
|
|
595
57
|
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
return {
|
|
600
|
-
message: {
|
|
601
|
-
...event.message,
|
|
602
|
-
usage: {
|
|
603
|
-
...event.message.usage,
|
|
604
|
-
cost: {
|
|
605
|
-
...event.message.usage.cost,
|
|
606
|
-
total: 0.123,
|
|
607
|
-
},
|
|
608
|
-
},
|
|
609
|
-
},
|
|
610
|
-
};
|
|
611
|
-
});
|
|
612
|
-
```
|
|
58
|
+
Do not start processes, sockets, watchers, or timers in the factory because some invocations load extensions without starting a session.
|
|
59
|
+
Start long-lived resources from `session_start` or from the command or tool that needs them.
|
|
60
|
+
Close session-scoped resources from an idempotent `session_shutdown` handler.
|
|
613
61
|
|
|
614
|
-
|
|
62
|
+
A run proceeds from input and `before_agent_start`, through model, message, and tool events, to `agent_end`.
|
|
63
|
+
Automatic retries, recovery, compaction, or queued work can continue afterward.
|
|
64
|
+
<a id="agent_start--agent_end--agent_before_settle--agent_settled"></a>
|
|
615
65
|
|
|
616
|
-
|
|
66
|
+
`agent_before_settle` is the final actionable boundary: it can append entries and request one continuation.
|
|
67
|
+
`agent_settled` is final and notification-only; use it when an integration needs to know draht will not continue automatically.
|
|
617
68
|
|
|
618
|
-
|
|
619
|
-
- `tool_execution_start` is emitted in assistant source order during the preflight phase
|
|
620
|
-
- `tool_execution_update` events may interleave across tools
|
|
621
|
-
- `tool_execution_end` is emitted in tool completion order after each tool is finalized
|
|
622
|
-
- final `toolResult` message events are still emitted later in assistant source order
|
|
69
|
+
<a id="extensionapi-methods"></a>
|
|
623
70
|
|
|
624
|
-
|
|
625
|
-
pi.on("tool_execution_start", async (event, ctx) => {
|
|
626
|
-
// event.toolCallId, event.toolName, event.args
|
|
627
|
-
});
|
|
71
|
+
## Choose an integration point
|
|
628
72
|
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
73
|
+
| Capability | Main API |
|
|
74
|
+
|---|---|
|
|
75
|
+
| Observe or modify lifecycle behavior | `pi.on()` |
|
|
76
|
+
| Add a model-callable operation | `pi.registerTool()` |
|
|
77
|
+
| Add a `/` command | `pi.registerCommand()` |
|
|
78
|
+
| Add a shortcut or CLI flag | `pi.registerShortcut()` or `pi.registerFlag()` |
|
|
79
|
+
| Send user or custom messages | `pi.sendUserMessage()` or `pi.sendMessage()` |
|
|
80
|
+
| Persist non-context session data | `pi.appendEntry()` |
|
|
81
|
+
| Change active tools, model, or thinking level | Session control methods on `pi` |
|
|
82
|
+
| Read or restore working-tree checkpoints | `pi.checkpoints` |
|
|
83
|
+
| Add a model provider | `pi.registerProvider()` |
|
|
84
|
+
| Add an MCP server | `pi.registerMcpServer()` |
|
|
85
|
+
| Route each request to a model | [`pi.registerVirtualModel()`](virtual-models.md) |
|
|
86
|
+
| Add terminal rendering | Renderer registration and `ctx.ui` |
|
|
87
|
+
| Communicate with another extension | `pi.events` |
|
|
632
88
|
|
|
633
|
-
pi.
|
|
634
|
-
// event.toolCallId, event.toolName, event.result, event.isError
|
|
635
|
-
});
|
|
636
|
-
```
|
|
89
|
+
`pi.setModel()` and `pi.setThinkingLevel()` change only the current session by default; pass `{ persist: true }` to also update the user's global default.
|
|
637
90
|
|
|
638
|
-
|
|
91
|
+
Use the exported declarations in [`extensions/types.ts`](https://github.com/draht-dev/draht/blob/main/packages/coding-agent/src/core/extensions/types.ts) for exact event, context, tool, and result types.
|
|
639
92
|
|
|
640
|
-
|
|
93
|
+
## Follow the extension contracts
|
|
641
94
|
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
// event.messages - deep copy, safe to modify
|
|
645
|
-
const filtered = event.messages.filter(m => !shouldPrune(m));
|
|
646
|
-
return { messages: filtered };
|
|
647
|
-
});
|
|
648
|
-
```
|
|
95
|
+
<a id="events"></a>
|
|
96
|
+
<a id="work-with-events"></a>
|
|
649
97
|
|
|
650
|
-
|
|
98
|
+
### Events and concurrency
|
|
651
99
|
|
|
652
|
-
|
|
100
|
+
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.
|
|
101
|
+
Some events notify; others transform data, replace results, or cancel an operation.
|
|
102
|
+
Use each event’s declared result type rather than assuming every return value has an effect.
|
|
653
103
|
|
|
654
|
-
|
|
104
|
+
Events cover resource discovery, sessions, agent and message lifecycle, providers, tools, and raw input.
|
|
655
105
|
|
|
656
|
-
|
|
657
|
-
pi.on("before_provider_request", (event, ctx) => {
|
|
658
|
-
console.log(JSON.stringify(event.payload, null, 2));
|
|
106
|
+
`before_agent_start` exposes both the current prompt and its structured `systemPromptOptions`. Prefer changing prompt sections, selected tools, or guidelines so draht 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.
|
|
659
107
|
|
|
660
|
-
|
|
661
|
-
// return { ...event.payload, temperature: 0 };
|
|
662
|
-
});
|
|
663
|
-
```
|
|
108
|
+
`message_end` can replace a finalized message while preserving its role. `tool_call` can mutate input or block execution. `tool_result` handlers compose, with each handler seeing prior changes.
|
|
664
109
|
|
|
665
|
-
|
|
110
|
+
<a id="provider_stream_event"></a>
|
|
666
111
|
|
|
667
|
-
|
|
112
|
+
`provider_stream_event` fires for each parsed provider stream event before draht normalizes it. The event identifies the provider, API, and model; `event.data` is the earliest structured value available to draht, 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.
|
|
668
113
|
|
|
669
|
-
|
|
114
|
+
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.
|
|
670
115
|
|
|
671
|
-
|
|
672
|
-
pi.on("after_provider_response", (event, ctx) => {
|
|
673
|
-
// event.status - HTTP status code
|
|
674
|
-
// event.headers - normalized response headers
|
|
675
|
-
if (event.status === 429) {
|
|
676
|
-
console.log("rate limited", event.headers["retry-after"]);
|
|
677
|
-
}
|
|
678
|
-
});
|
|
679
|
-
```
|
|
116
|
+
<a id="context_with_system"></a>
|
|
680
117
|
|
|
681
|
-
|
|
118
|
+
`context` transforms conversation messages without prompt and tool system messages; draht 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.
|
|
682
119
|
|
|
683
|
-
|
|
120
|
+
`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.
|
|
684
121
|
|
|
685
|
-
|
|
122
|
+
<a id="cache_warming_decision"></a>
|
|
686
123
|
|
|
687
|
-
|
|
124
|
+
`cache_warming_decision` can override an idle prompt-cache refresh with `{ action: "warm" }` or `{ action: "stop" }`. The last handler that returns an action wins.
|
|
688
125
|
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
// event.previousModel - previous model (undefined if first selection)
|
|
693
|
-
// event.source - "set" | "cycle" | "restore"
|
|
126
|
+
Tool calls from one assistant message can run in parallel.
|
|
127
|
+
Do not assume a sibling call or result exists when another tool event runs.
|
|
128
|
+
Use `ctx.signal` for nested work owned by an active turn; commands and idle session events often have no operation signal.
|
|
694
129
|
|
|
695
|
-
|
|
696
|
-
? `${event.previousModel.provider}/${event.previousModel.id}`
|
|
697
|
-
: "none";
|
|
698
|
-
const next = `${event.model.provider}/${event.model.id}`;
|
|
130
|
+
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.
|
|
699
131
|
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
```
|
|
132
|
+
<a id="custom-tools"></a>
|
|
133
|
+
<a id="register-tools"></a>
|
|
703
134
|
|
|
704
|
-
|
|
135
|
+
### Tools
|
|
705
136
|
|
|
706
|
-
|
|
137
|
+
A custom tool defines a name, model-facing description, TypeBox parameter schema, and `execute()` function.
|
|
138
|
+
Its result requires model-facing `content` and a `details` field for rendering or state reconstruction.
|
|
139
|
+
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.
|
|
707
140
|
|
|
708
|
-
|
|
141
|
+
Throw from `execute()` to produce a failed tool result.
|
|
142
|
+
Returning an object does not mark it as an error.
|
|
143
|
+
Return `terminate: true` only when the agent should skip its automatic follow-up after every completed tool in that batch agrees to terminate.
|
|
709
144
|
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
// event.previousLevel - previous thinking level
|
|
145
|
+
Use sequential execution when tools share mutable in-memory state.
|
|
146
|
+
File-mutating tools should wrap the complete read-modify-write operation with `withFileMutationQueue()`.
|
|
147
|
+
Truncate large model-facing results and tell the model where to read the complete output.
|
|
714
148
|
|
|
715
|
-
|
|
716
|
-
});
|
|
717
|
-
```
|
|
149
|
+
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`.
|
|
718
150
|
|
|
719
|
-
|
|
151
|
+
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 draht 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.
|
|
720
152
|
|
|
721
|
-
|
|
153
|
+
See [`hello.ts`](../examples/extensions/hello.ts), [`todo.ts`](../examples/extensions/todo.ts), [`dynamic-tools.ts`](../examples/extensions/dynamic-tools.ts), and [`truncated-tool.ts`](../examples/extensions/truncated-tool.ts).
|
|
722
154
|
|
|
723
|
-
|
|
155
|
+
### Tool exposure
|
|
724
156
|
|
|
725
|
-
|
|
157
|
+
`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:
|
|
726
158
|
|
|
727
|
-
|
|
159
|
+
- `direct` (default): declared to the model while active, and callable while active.
|
|
160
|
+
- `model-only`: declared to the model while active, never callable. Use it for tools that orchestrate other tools or ask the user.
|
|
161
|
+
- `codemode`: callable whenever registered, and listed by the `codemode` tool. Not declared to the model unless activated explicitly.
|
|
162
|
+
- `deferred`: like `codemode`, but codemode tools do not list it; `tool_search` can find and activate it.
|
|
163
|
+
- `hidden`: registered but unreachable. Re-register a tool with `exposure: "hidden"` to withdraw it, since tools cannot be unregistered.
|
|
728
164
|
|
|
729
|
-
|
|
165
|
+
`namespace: { name, 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)`.
|
|
730
166
|
|
|
731
|
-
`
|
|
167
|
+
Registering a `direct` or `model-only` tool activates it; the other exposures are not activated on registration. The active set (`pi.getActiveTools()`, `pi.setActiveTools()`) is the set of tools declared to the model. `pi.getAllTools()` reports each tool's `exposure`, `namespace`, and `annotations`.
|
|
732
168
|
|
|
733
|
-
|
|
734
|
-
- Mutations to `event.input` affect the actual tool execution
|
|
735
|
-
- Later `tool_call` handlers see mutations made by earlier handlers
|
|
736
|
-
- No re-validation is performed after your mutation
|
|
737
|
-
- Return values from `tool_call` only control blocking via `{ block: true, reason?: string }`
|
|
169
|
+
`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:
|
|
738
170
|
|
|
739
171
|
```typescript
|
|
740
|
-
import { isToolCallEventType } from "@draht/coding-agent";
|
|
741
|
-
|
|
742
172
|
pi.on("tool_call", async (event, ctx) => {
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
// event.input is { command: string; timeout?: number }
|
|
750
|
-
event.input.command = `source ~/.profile\n${event.input.command}`;
|
|
751
|
-
|
|
752
|
-
if (event.input.command.includes("rm -rf")) {
|
|
753
|
-
return { block: true, reason: "Dangerous command" };
|
|
754
|
-
}
|
|
755
|
-
}
|
|
756
|
-
|
|
757
|
-
if (isToolCallEventType("read", event)) {
|
|
758
|
-
// event.input is { path: string; offset?: number; limit?: number }
|
|
759
|
-
console.log(`Reading: ${event.input.path}`);
|
|
760
|
-
}
|
|
761
|
-
});
|
|
762
|
-
```
|
|
763
|
-
|
|
764
|
-
#### Typing custom tool input
|
|
765
|
-
|
|
766
|
-
Custom tools should export their input type:
|
|
767
|
-
|
|
768
|
-
```typescript
|
|
769
|
-
// my-extension.ts
|
|
770
|
-
export type MyToolInput = Static<typeof myToolSchema>;
|
|
771
|
-
```
|
|
772
|
-
|
|
773
|
-
Use `isToolCallEventType` with explicit type parameters:
|
|
774
|
-
|
|
775
|
-
```typescript
|
|
776
|
-
import { isToolCallEventType } from "@draht/coding-agent";
|
|
777
|
-
import type { MyToolInput } from "my-extension";
|
|
778
|
-
|
|
779
|
-
pi.on("tool_call", (event) => {
|
|
780
|
-
if (isToolCallEventType<"my_tool", MyToolInput>("my_tool", event)) {
|
|
781
|
-
event.input.action; // typed
|
|
173
|
+
const hints = pi.getAllTools().find((tool) => tool.name === event.toolName)?.annotations;
|
|
174
|
+
const needsApproval =
|
|
175
|
+
hints?.destructiveHint === true ||
|
|
176
|
+
(!hints?.readOnlyHint && ((hints?.destructiveHint ?? true) || (hints?.openWorldHint ?? true)));
|
|
177
|
+
if (needsApproval && !(await ctx.ui.confirm("Allow tool call?", event.toolName))) {
|
|
178
|
+
return { block: true, reason: `${event.toolName} was not approved` };
|
|
782
179
|
}
|
|
783
180
|
});
|
|
784
181
|
```
|
|
785
182
|
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
Fired after tool execution finishes and before `tool_execution_end` plus the final tool result message events are emitted. **Can modify result.**
|
|
789
|
-
|
|
790
|
-
In parallel tool mode, `tool_result` and `tool_execution_end` may interleave in tool completion order, while final `toolResult` message events are still emitted later in assistant source order.
|
|
791
|
-
|
|
792
|
-
`tool_result` handlers chain like middleware:
|
|
793
|
-
- Handlers run in extension load order
|
|
794
|
-
- Each handler sees the latest result after previous handler changes
|
|
795
|
-
- Handlers can return partial patches (`content`, `details`, `isError`, or `usage`); omitted fields keep their current values
|
|
796
|
-
|
|
797
|
-
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.
|
|
798
|
-
|
|
799
|
-
```typescript
|
|
800
|
-
import { isBashToolResult } from "@draht/coding-agent";
|
|
801
|
-
|
|
802
|
-
pi.on("tool_result", async (event, ctx) => {
|
|
803
|
-
// event.toolName, event.toolCallId, event.input
|
|
804
|
-
// event.content, event.details, event.isError, event.usage
|
|
805
|
-
|
|
806
|
-
if (isBashToolResult(event)) {
|
|
807
|
-
// event.details is typed as BashToolDetails
|
|
808
|
-
}
|
|
809
|
-
|
|
810
|
-
const response = await fetch("https://example.com/summarize", {
|
|
811
|
-
method: "POST",
|
|
812
|
-
body: JSON.stringify({ content: event.content }),
|
|
813
|
-
signal: ctx.signal,
|
|
814
|
-
});
|
|
815
|
-
|
|
816
|
-
// Modify result:
|
|
817
|
-
return { content: [...], details: {...}, isError: false, usage: nestedModelUsage };
|
|
818
|
-
});
|
|
819
|
-
```
|
|
183
|
+
A tool that orchestrates other tools can adjust what the model sees while it is active with `prepareLoadout(loadout)`. It runs whenever the active tools change and receives the declared tools, the callable tools, and every registered tool with its exposure and namespace. It returns replacement `descriptions` for declared tools (including its own) and `hiddenDeclarations`: active tools whose declarations requests leave out while they stay active and callable. `codemode` uses only this hook, `exposure`, and `ctx.executeTool()`, so another tool can implement the same behavior under a different name.
|
|
820
184
|
|
|
821
|
-
###
|
|
185
|
+
### Activate tools dynamically
|
|
822
186
|
|
|
823
|
-
|
|
187
|
+
Register every tool first, keep optional tools inactive, and use `pi.setActiveTools()` from a loader tool to select the desired active tools. Names must already be registered; unknown names are ignored.
|
|
824
188
|
|
|
825
|
-
|
|
189
|
+
draht records the initial prompt and tool set in the transcript's first system message, then appends tool and prompt changes before the next model request. Providers that cannot represent the transition receive a complete transcript checkpoint, which can invalidate the cached prefix.
|
|
826
190
|
|
|
827
|
-
|
|
828
|
-
import { createLocalBashOperations } from "@draht/coding-agent";
|
|
829
|
-
|
|
830
|
-
pi.on("user_bash", (event, ctx) => {
|
|
831
|
-
// event.command - the bash command
|
|
832
|
-
// event.excludeFromContext - true if !! prefix
|
|
833
|
-
// event.cwd - working directory
|
|
834
|
-
|
|
835
|
-
// Option 1: Provide custom operations (e.g., SSH)
|
|
836
|
-
return { operations: remoteBashOps };
|
|
837
|
-
|
|
838
|
-
// Option 2: Wrap draht's built-in local bash backend
|
|
839
|
-
const local = createLocalBashOperations();
|
|
840
|
-
return {
|
|
841
|
-
operations: {
|
|
842
|
-
exec(command, cwd, options) {
|
|
843
|
-
return local.exec(`source ~/.profile\n${command}`, cwd, options);
|
|
844
|
-
}
|
|
845
|
-
}
|
|
846
|
-
};
|
|
847
|
-
|
|
848
|
-
// Option 3: Full replacement - return result directly
|
|
849
|
-
return { result: { output: "...", exitCode: 0, cancelled: false, truncated: false } };
|
|
850
|
-
});
|
|
851
|
-
```
|
|
191
|
+
### Checkpoints and rewind
|
|
852
192
|
|
|
853
|
-
|
|
193
|
+
draht snapshots the working tree per session so `/rewind` can restore conversation and files. `pi.checkpoints` exposes that store: `list()` and `get(entryId)` read recorded checkpoints, `restore()` restores an entry's checkpoint after taking a safety snapshot, and `capture(entryId)` records a new one. The calls never throw and degrade quietly when checkpoints are unavailable, such as before the session has a file or outside a git repository.
|
|
854
194
|
|
|
855
|
-
|
|
195
|
+
`checkpoint_created` fires after every capture. `session_before_rewind` reports the target entry and scope (`conversation-and-files`, `conversation-only`, or `files-only`) and can return `{ cancel: true }`. Retention is configured in [Settings](settings.md).
|
|
856
196
|
|
|
857
|
-
|
|
197
|
+
### MCP servers
|
|
858
198
|
|
|
859
|
-
|
|
860
|
-
1. Extension commands (`/cmd`) checked first - if found, handler runs and input event is skipped
|
|
861
|
-
2. `input` event fires - can intercept, transform, or handle
|
|
862
|
-
3. If not handled: skill commands (`/skill:name`) expanded to skill content
|
|
863
|
-
4. If not handled: prompt templates (`/template`) expanded to template content
|
|
864
|
-
5. Agent processing begins (`before_agent_start`, etc.)
|
|
199
|
+
`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`.
|
|
865
200
|
|
|
866
201
|
```typescript
|
|
867
|
-
pi.
|
|
868
|
-
|
|
869
|
-
// event.images - attached images, if any
|
|
870
|
-
// event.source - "interactive" (typed), "rpc" (API), or "extension" (via sendUserMessage)
|
|
871
|
-
// event.streamingBehavior - "steer" | "followUp" | undefined
|
|
872
|
-
// undefined when idle, "steer" for mid-stream interrupts,
|
|
873
|
-
// "followUp" for messages queued until the agent finishes
|
|
874
|
-
|
|
875
|
-
// Transform: rewrite input before expansion
|
|
876
|
-
if (event.text.startsWith("?quick "))
|
|
877
|
-
return { action: "transform", text: `Respond briefly: ${event.text.slice(7)}` };
|
|
878
|
-
|
|
879
|
-
// Handle: respond without LLM (extension shows its own feedback)
|
|
880
|
-
if (event.text === "ping") {
|
|
881
|
-
ctx.ui.notify("pong", "info");
|
|
882
|
-
return { action: "handled" };
|
|
883
|
-
}
|
|
884
|
-
|
|
885
|
-
// Route by source: skip processing for extension-injected messages
|
|
886
|
-
if (event.source === "extension") return { action: "continue" };
|
|
887
|
-
|
|
888
|
-
// Intercept skill commands before expansion
|
|
889
|
-
if (event.text.startsWith("/skill:")) {
|
|
890
|
-
// Could transform, block, or let pass through
|
|
891
|
-
}
|
|
892
|
-
|
|
893
|
-
return { action: "continue" }; // Default: pass through to expansion
|
|
894
|
-
});
|
|
202
|
+
pi.registerMcpServer("jira", { url: "https://mcp.example.com/jira", exposure: "codemode" });
|
|
203
|
+
pi.unregisterMcpServer("jira");
|
|
895
204
|
```
|
|
896
205
|
|
|
897
|
-
|
|
898
|
-
- `continue` - pass through unchanged (default if handler returns nothing)
|
|
899
|
-
- `transform` - modify text/images, then continue to expansion
|
|
900
|
-
- `handled` - skip agent entirely (first handler to return this wins)
|
|
901
|
-
|
|
902
|
-
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.
|
|
903
|
-
|
|
904
|
-
## ExtensionContext
|
|
905
|
-
|
|
906
|
-
All handlers receive `ctx: ExtensionContext`.
|
|
907
|
-
|
|
908
|
-
### ctx.ui
|
|
909
|
-
|
|
910
|
-
UI methods for user interaction. See [Custom UI](#custom-ui) for full details.
|
|
911
|
-
|
|
912
|
-
### ctx.mode
|
|
913
|
-
|
|
914
|
-
Current run mode: `"tui"`, `"rpc"`, `"json"`, or `"print"`. Use `ctx.mode === "tui"` to guard terminal-only features such as `custom()`, component factories, terminal input, and direct TUI rendering.
|
|
915
|
-
|
|
916
|
-
### ctx.hasUI
|
|
917
|
-
|
|
918
|
-
`true` in TUI and RPC modes. `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`) that work in both TUI and RPC modes. In RPC mode, some TUI-specific methods are no-ops or return defaults (see [rpc.md](rpc.md#extension-ui-protocol)).
|
|
919
|
-
|
|
920
|
-
### ctx.cwd
|
|
921
|
-
|
|
922
|
-
Current working directory.
|
|
923
|
-
|
|
924
|
-
### ctx.isProjectTrusted()
|
|
925
|
-
|
|
926
|
-
Returns whether project-local trust is active for the current session context. This includes temporary trust decisions and CLI trust overrides, not just saved decisions in the global trust store.
|
|
927
|
-
|
|
928
|
-
Use this before reading project-local extension configuration that should only be honored for trusted projects.
|
|
206
|
+
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.
|
|
929
207
|
|
|
930
|
-
|
|
208
|
+
The built-in MCP support connects registered servers. When nothing does, because another extension replaced it (see [MCP](mcp.md#other-mcp-extensions)), 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.
|
|
931
209
|
|
|
932
|
-
|
|
210
|
+
<a id="extensioncontext"></a>
|
|
211
|
+
<a id="extensioncommandcontext"></a>
|
|
212
|
+
<a id="use-extension-context"></a>
|
|
933
213
|
|
|
934
|
-
|
|
214
|
+
### Context and session changes
|
|
935
215
|
|
|
936
|
-
|
|
937
|
-
ctx.
|
|
938
|
-
ctx.sessionManager.getBranch() // Current branch
|
|
939
|
-
ctx.sessionManager.buildContextEntries() // Active branch entries with compaction applied
|
|
940
|
-
ctx.sessionManager.getLeafId() // Current leaf entry ID
|
|
941
|
-
```
|
|
942
|
-
|
|
943
|
-
### ctx.modelRegistry / ctx.model / ctx.thinkingLevel / ctx.scopedModels
|
|
944
|
-
|
|
945
|
-
Access to models, providers, and resolved authentication. `ctx.modelRegistry.getProvider(id)` returns the effective @draht/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.
|
|
216
|
+
`ExtensionContext` provides the working directory, mode, UI, session manager, model runtime, abort signal, context usage, and controls for compaction and shutdown.
|
|
217
|
+
Use `ctx.modelRegistry.streamSimple()` for provider-neutral nested model calls.
|
|
946
218
|
|
|
947
|
-
|
|
219
|
+
Command handlers receive `ExtensionCommandContext`, which adds operations for waiting until idle, reloading, tree navigation, and session replacement.
|
|
220
|
+
These operations are command-only because calling them from lifecycle handlers can deadlock the runtime.
|
|
948
221
|
|
|
949
|
-
|
|
222
|
+
Session replacement invalidates the old context. Capture only plain data before switching, then use the fresh context supplied to `withSession` for session-bound work.
|
|
950
223
|
|
|
951
|
-
|
|
224
|
+
<a id="state-management"></a>
|
|
225
|
+
<a id="persist-state"></a>
|
|
952
226
|
|
|
953
|
-
|
|
954
|
-
- `fetch(..., { signal: ctx.signal })`
|
|
955
|
-
- model calls that accept `signal`
|
|
956
|
-
- file or process helpers that accept `AbortSignal`
|
|
227
|
+
### State
|
|
957
228
|
|
|
958
|
-
|
|
959
|
-
It is usually `undefined` in idle or non-turn contexts such as session events, extension commands, and shortcuts fired while draht is idle.
|
|
229
|
+
Choose storage based on how state participates in the conversation:
|
|
960
230
|
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
});
|
|
968
|
-
|
|
969
|
-
const data = await response.json();
|
|
970
|
-
return { details: data };
|
|
971
|
-
});
|
|
972
|
-
```
|
|
231
|
+
| State | Storage |
|
|
232
|
+
|---|---|
|
|
233
|
+
| Tool state that follows the active branch | Tool-result `details` |
|
|
234
|
+
| Durable data excluded from model context | `pi.appendEntry()` |
|
|
235
|
+
| Custom content stored and sent to the model | `pi.sendMessage()` |
|
|
236
|
+
| Data outside one session | External storage |
|
|
973
237
|
|
|
974
|
-
|
|
238
|
+
Reconstruct branch-sensitive state from `ctx.sessionManager.getBranch()` during `session_start`.
|
|
239
|
+
Do not rebuild it from every file entry because abandoned branches represent alternative histories.
|
|
240
|
+
Register an entry or message renderer when custom stored content should appear in the transcript.
|
|
975
241
|
|
|
976
|
-
|
|
242
|
+
<a id="custom-ui"></a>
|
|
243
|
+
<a id="mode-behavior"></a>
|
|
244
|
+
<a id="interact-with-the-user"></a>
|
|
245
|
+
<a id="account-for-each-mode"></a>
|
|
977
246
|
|
|
978
|
-
###
|
|
247
|
+
### UI and modes
|
|
979
248
|
|
|
980
|
-
|
|
249
|
+
`ctx.ui` provides dialogs, notifications, status text, widgets, titles, editor access, and custom components.
|
|
250
|
+
Use `ctx.ui.custom()` only when the interaction needs its own rendering and input.
|
|
251
|
+
See [Terminal UI](tui.md) for component, focus, overlay, theme, and performance guidance.
|
|
981
252
|
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
253
|
+
Extensions load in interactive, RPC, JSON, and print modes.
|
|
254
|
+
Interactive mode provides the complete terminal UI.
|
|
255
|
+
RPC can forward supported dialogs and notifications through the [RPC Extension UI protocol](rpc-extension-ui.md), but not custom terminal components; JSON and print modes have no UI.
|
|
256
|
+
Guard terminal-only behavior with `ctx.mode === "tui"` and use `ctx.hasUI` for interactions supported by interactive and RPC clients.
|
|
985
257
|
|
|
986
|
-
|
|
258
|
+
Keep tool and event behavior independent from rendering so non-interactive modes remain functional.
|
|
987
259
|
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
if (isFatal(event.input)) {
|
|
991
|
-
ctx.shutdown();
|
|
992
|
-
}
|
|
993
|
-
});
|
|
994
|
-
```
|
|
260
|
+
<a id="error-handling"></a>
|
|
261
|
+
<a id="handle-errors-and-shutdown"></a>
|
|
995
262
|
|
|
996
|
-
###
|
|
263
|
+
### Errors and cleanup
|
|
997
264
|
|
|
998
|
-
|
|
265
|
+
draht reports handler errors and continues where possible. A `tool_call` handler failure blocks the tool as a fail-safe; a tool execution failure becomes an error result for the model.
|
|
999
266
|
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
// ...
|
|
1004
|
-
}
|
|
1005
|
-
```
|
|
267
|
+
Release resources in `session_shutdown` even when normal operation attempted cleanup.
|
|
268
|
+
Keep cleanup idempotent because cancellation, reload, session replacement, and process exit can converge on the same path.
|
|
269
|
+
Use `ctx.shutdown()` to request an orderly process shutdown.
|
|
1006
270
|
|
|
1007
|
-
|
|
271
|
+
<a id="examples-reference"></a>
|
|
272
|
+
<a id="use-examples-as-the-implementation-reference"></a>
|
|
1008
273
|
|
|
1009
|
-
|
|
274
|
+
## Examples and reference
|
|
1010
275
|
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
customInstructions: "Focus on recent changes",
|
|
1014
|
-
onComplete: (result) => {
|
|
1015
|
-
ctx.ui.notify("Compaction completed", "info");
|
|
1016
|
-
},
|
|
1017
|
-
onError: (error) => {
|
|
1018
|
-
ctx.ui.notify(`Compaction failed: ${error.message}`, "error");
|
|
1019
|
-
},
|
|
1020
|
-
});
|
|
1021
|
-
```
|
|
1022
|
-
|
|
1023
|
-
### ctx.getSystemPrompt()
|
|
1024
|
-
|
|
1025
|
-
Returns draht's current system prompt string.
|
|
1026
|
-
|
|
1027
|
-
- During `before_agent_start`, this reflects chained system-prompt changes made so far for the current turn.
|
|
1028
|
-
- It does not include later `context` message mutations.
|
|
1029
|
-
- It does not include `before_provider_request` payload rewrites.
|
|
1030
|
-
- If later-loaded extensions run after yours, they can still change what is ultimately sent.
|
|
1031
|
-
|
|
1032
|
-
```typescript
|
|
1033
|
-
pi.on("before_agent_start", (event, ctx) => {
|
|
1034
|
-
const prompt = ctx.getSystemPrompt();
|
|
1035
|
-
console.log(`System prompt length: ${prompt.length}`);
|
|
1036
|
-
});
|
|
1037
|
-
```
|
|
1038
|
-
|
|
1039
|
-
## ExtensionCommandContext
|
|
1040
|
-
|
|
1041
|
-
Command handlers receive `ExtensionCommandContext`, which extends `ExtensionContext` with session control methods. These are only available in commands because they can deadlock if called from event handlers.
|
|
1042
|
-
|
|
1043
|
-
### ctx.getSystemPromptOptions()
|
|
1044
|
-
|
|
1045
|
-
Returns the base inputs draht currently uses to build the system prompt.
|
|
1046
|
-
|
|
1047
|
-
```typescript
|
|
1048
|
-
const options = ctx.getSystemPromptOptions();
|
|
1049
|
-
const contextPaths = options.contextFiles?.map((file) => file.path) ?? [];
|
|
1050
|
-
```
|
|
1051
|
-
|
|
1052
|
-
This has the same shape and mutability as `before_agent_start` `event.systemPromptOptions`: custom prompt, active tools, tool snippets, prompt guidelines, appended system prompt text, cwd, loaded context files, and loaded skills. It may include full context file contents, so treat it as sensitive extension-local data and avoid exposing it through command lists, logs, or autocomplete metadata.
|
|
1053
|
-
|
|
1054
|
-
This reports the current base prompt inputs. It does not include per-turn `before_agent_start` chained system-prompt changes, later `context` event message mutations, or `before_provider_request` payload rewrites.
|
|
1055
|
-
|
|
1056
|
-
### ctx.waitForIdle()
|
|
1057
|
-
|
|
1058
|
-
Wait for the agent to fully settle, including automatic retries, auto-compaction retries, and queued continuations:
|
|
1059
|
-
|
|
1060
|
-
```typescript
|
|
1061
|
-
pi.registerCommand("my-cmd", {
|
|
1062
|
-
handler: async (args, ctx) => {
|
|
1063
|
-
await ctx.waitForIdle();
|
|
1064
|
-
// Agent is now idle, safe to modify session
|
|
1065
|
-
},
|
|
1066
|
-
});
|
|
1067
|
-
```
|
|
1068
|
-
|
|
1069
|
-
### ctx.newSession(options?)
|
|
1070
|
-
|
|
1071
|
-
Create a new session:
|
|
1072
|
-
|
|
1073
|
-
```typescript
|
|
1074
|
-
const parentSession = ctx.sessionManager.getSessionFile();
|
|
1075
|
-
const kickoff = "Continue in the replacement session";
|
|
1076
|
-
|
|
1077
|
-
const result = await ctx.newSession({
|
|
1078
|
-
parentSession,
|
|
1079
|
-
setup: async (sm) => {
|
|
1080
|
-
sm.appendMessage({
|
|
1081
|
-
role: "user",
|
|
1082
|
-
content: [{ type: "text", text: "Context from previous session..." }],
|
|
1083
|
-
timestamp: Date.now(),
|
|
1084
|
-
});
|
|
1085
|
-
},
|
|
1086
|
-
withSession: async (ctx) => {
|
|
1087
|
-
// Use only the replacement-session ctx here.
|
|
1088
|
-
await ctx.sendUserMessage(kickoff);
|
|
1089
|
-
},
|
|
1090
|
-
});
|
|
1091
|
-
|
|
1092
|
-
if (result.cancelled) {
|
|
1093
|
-
// An extension cancelled the new session
|
|
1094
|
-
}
|
|
1095
|
-
```
|
|
1096
|
-
|
|
1097
|
-
Options:
|
|
1098
|
-
- `parentSession`: parent session file to record in the new session header
|
|
1099
|
-
- `setup`: mutate the new session's `SessionManager` before `withSession` runs
|
|
1100
|
-
- `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).
|
|
1101
|
-
|
|
1102
|
-
### ctx.fork(entryId, options?)
|
|
1103
|
-
|
|
1104
|
-
Fork from a specific entry, creating a new session file:
|
|
1105
|
-
|
|
1106
|
-
```typescript
|
|
1107
|
-
const result = await ctx.fork("entry-id-123", {
|
|
1108
|
-
withSession: async (ctx) => {
|
|
1109
|
-
// Use only the replacement-session ctx here.
|
|
1110
|
-
ctx.ui.notify("Now in the forked session", "info");
|
|
1111
|
-
},
|
|
1112
|
-
});
|
|
1113
|
-
if (result.cancelled) {
|
|
1114
|
-
// An extension cancelled the fork
|
|
1115
|
-
}
|
|
1116
|
-
|
|
1117
|
-
const cloneResult = await ctx.fork("entry-id-456", { position: "at" });
|
|
1118
|
-
if (cloneResult.cancelled) {
|
|
1119
|
-
// An extension cancelled the clone
|
|
1120
|
-
}
|
|
1121
|
-
```
|
|
1122
|
-
|
|
1123
|
-
Options:
|
|
1124
|
-
- `position`: `"before"` (default) forks before the selected user message, restoring that prompt into the editor
|
|
1125
|
-
- `position`: `"at"` duplicates the active path through the selected entry without restoring editor text
|
|
1126
|
-
- `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).
|
|
1127
|
-
|
|
1128
|
-
### ctx.navigateTree(targetId, options?)
|
|
1129
|
-
|
|
1130
|
-
Navigate to a different point in the session tree:
|
|
1131
|
-
|
|
1132
|
-
```typescript
|
|
1133
|
-
const result = await ctx.navigateTree("entry-id-456", {
|
|
1134
|
-
summarize: true,
|
|
1135
|
-
customInstructions: "Focus on error handling changes",
|
|
1136
|
-
replaceInstructions: false, // true = replace default prompt entirely
|
|
1137
|
-
label: "review-checkpoint",
|
|
1138
|
-
});
|
|
1139
|
-
```
|
|
1140
|
-
|
|
1141
|
-
Options:
|
|
1142
|
-
- `summarize`: Whether to generate a summary of the abandoned branch
|
|
1143
|
-
- `customInstructions`: Custom instructions for the summarizer
|
|
1144
|
-
- `replaceInstructions`: If true, `customInstructions` replaces the default prompt instead of being appended
|
|
1145
|
-
- `label`: Label to attach to the branch summary entry (or target entry if not summarizing)
|
|
1146
|
-
|
|
1147
|
-
### ctx.switchSession(sessionPath, options?)
|
|
1148
|
-
|
|
1149
|
-
Switch to a different session file:
|
|
1150
|
-
|
|
1151
|
-
```typescript
|
|
1152
|
-
const result = await ctx.switchSession("/path/to/session.jsonl", {
|
|
1153
|
-
withSession: async (ctx) => {
|
|
1154
|
-
await ctx.sendUserMessage("Resume work in the replacement session");
|
|
1155
|
-
},
|
|
1156
|
-
});
|
|
1157
|
-
if (result.cancelled) {
|
|
1158
|
-
// An extension cancelled the switch via session_before_switch
|
|
1159
|
-
}
|
|
1160
|
-
```
|
|
1161
|
-
|
|
1162
|
-
Options:
|
|
1163
|
-
- `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).
|
|
1164
|
-
|
|
1165
|
-
To discover available sessions, use the static `SessionManager.list()` or `SessionManager.listAll()` methods:
|
|
1166
|
-
|
|
1167
|
-
```typescript
|
|
1168
|
-
import { SessionManager } from "@draht/coding-agent";
|
|
1169
|
-
|
|
1170
|
-
pi.registerCommand("switch", {
|
|
1171
|
-
description: "Switch to another session",
|
|
1172
|
-
handler: async (args, ctx) => {
|
|
1173
|
-
const sessions = await SessionManager.list(ctx.cwd);
|
|
1174
|
-
if (sessions.length === 0) return;
|
|
1175
|
-
const choice = await ctx.ui.select(
|
|
1176
|
-
"Pick session:",
|
|
1177
|
-
sessions.map(s => s.file),
|
|
1178
|
-
);
|
|
1179
|
-
if (choice) {
|
|
1180
|
-
await ctx.switchSession(choice, {
|
|
1181
|
-
withSession: async (ctx) => {
|
|
1182
|
-
ctx.ui.notify("Switched session", "info");
|
|
1183
|
-
},
|
|
1184
|
-
});
|
|
1185
|
-
}
|
|
1186
|
-
},
|
|
1187
|
-
});
|
|
1188
|
-
```
|
|
1189
|
-
|
|
1190
|
-
### Session replacement lifecycle and footguns
|
|
1191
|
-
|
|
1192
|
-
`withSession` receives a fresh `ReplacedSessionContext`, which extends `ExtensionCommandContext` with async `sendMessage()` and `sendUserMessage()` helpers bound to the replacement session.
|
|
1193
|
-
|
|
1194
|
-
Lifecycle and footguns:
|
|
1195
|
-
- `withSession` runs only after the old session has emitted `session_shutdown`, the old runtime has been torn down, the replacement session has been rebound, and the new extension instance has already received `session_start`.
|
|
1196
|
-
- The callback still executes in the original closure, not inside the new extension instance. That means your old extension instance may already have run its shutdown cleanup before `withSession` starts.
|
|
1197
|
-
- Captured old `pi` / old command `ctx` session-bound objects are stale after replacement and will throw if used. Use only the `ctx` passed to `withSession` for session-bound work.
|
|
1198
|
-
- Previously extracted raw objects are still your responsibility. For example, if you capture `const sm = ctx.sessionManager` before replacement, `sm` is still the old `SessionManager` object. Do not reuse it after replacement.
|
|
1199
|
-
- Code in `withSession` should assume any state invalidated by your `session_shutdown` handler is already gone. Only capture plain data that survives shutdown cleanly, such as strings, ids, and serialized config.
|
|
1200
|
-
|
|
1201
|
-
Safe pattern:
|
|
1202
|
-
|
|
1203
|
-
```typescript
|
|
1204
|
-
pi.registerCommand("handoff", {
|
|
1205
|
-
handler: async (_args, ctx) => {
|
|
1206
|
-
const kickoff = "Continue from the replacement session";
|
|
1207
|
-
await ctx.newSession({
|
|
1208
|
-
withSession: async (ctx) => {
|
|
1209
|
-
await ctx.sendUserMessage(kickoff);
|
|
1210
|
-
},
|
|
1211
|
-
});
|
|
1212
|
-
},
|
|
1213
|
-
});
|
|
1214
|
-
```
|
|
1215
|
-
|
|
1216
|
-
Unsafe pattern:
|
|
1217
|
-
|
|
1218
|
-
```typescript
|
|
1219
|
-
pi.registerCommand("handoff", {
|
|
1220
|
-
handler: async (_args, ctx) => {
|
|
1221
|
-
const oldSessionManager = ctx.sessionManager;
|
|
1222
|
-
await ctx.newSession({
|
|
1223
|
-
withSession: async (_ctx) => {
|
|
1224
|
-
// stale old objects: do not do this
|
|
1225
|
-
oldSessionManager.getSessionFile();
|
|
1226
|
-
pi.sendUserMessage("wrong");
|
|
1227
|
-
},
|
|
1228
|
-
});
|
|
1229
|
-
},
|
|
1230
|
-
});
|
|
1231
|
-
```
|
|
1232
|
-
|
|
1233
|
-
### ctx.reload()
|
|
1234
|
-
|
|
1235
|
-
Run the same reload flow as `/reload`.
|
|
1236
|
-
|
|
1237
|
-
```typescript
|
|
1238
|
-
pi.registerCommand("reload-runtime", {
|
|
1239
|
-
description: "Reload extensions, skills, prompts, themes, and context files",
|
|
1240
|
-
handler: async (_args, ctx) => {
|
|
1241
|
-
await ctx.reload();
|
|
1242
|
-
return;
|
|
1243
|
-
},
|
|
1244
|
-
});
|
|
1245
|
-
```
|
|
1246
|
-
|
|
1247
|
-
Important behavior:
|
|
1248
|
-
- `await ctx.reload()` emits `session_shutdown` for the current extension runtime
|
|
1249
|
-
- It then reloads resources and emits `session_start` with `reason: "reload"` and `resources_discover` with reason `"reload"`
|
|
1250
|
-
- The currently running command handler still continues in the old call frame
|
|
1251
|
-
- Code after `await ctx.reload()` still runs from the pre-reload version
|
|
1252
|
-
- Code after `await ctx.reload()` must not assume old in-memory extension state is still valid
|
|
1253
|
-
- After the handler returns, future commands/events/tool calls use the new extension version
|
|
1254
|
-
|
|
1255
|
-
For predictable behavior, treat reload as terminal for that handler (`await ctx.reload(); return;`).
|
|
1256
|
-
|
|
1257
|
-
Tools run with `ExtensionContext`, so they cannot call `ctx.reload()` directly. Use a command as the reload entrypoint, then expose a tool that queues that command as a follow-up user message.
|
|
1258
|
-
|
|
1259
|
-
Example tool the LLM can call to trigger reload:
|
|
1260
|
-
|
|
1261
|
-
```typescript
|
|
1262
|
-
import type { ExtensionAPI } from "@draht/coding-agent";
|
|
1263
|
-
import { Type } from "typebox";
|
|
1264
|
-
|
|
1265
|
-
export default function (pi: ExtensionAPI) {
|
|
1266
|
-
pi.registerCommand("reload-runtime", {
|
|
1267
|
-
description: "Reload extensions, skills, prompts, themes, and context files",
|
|
1268
|
-
handler: async (_args, ctx) => {
|
|
1269
|
-
await ctx.reload();
|
|
1270
|
-
return;
|
|
1271
|
-
},
|
|
1272
|
-
});
|
|
1273
|
-
|
|
1274
|
-
pi.registerTool({
|
|
1275
|
-
name: "reload_runtime",
|
|
1276
|
-
label: "Reload Runtime",
|
|
1277
|
-
description: "Reload extensions, skills, prompts, themes, and context files",
|
|
1278
|
-
parameters: Type.Object({}),
|
|
1279
|
-
async execute() {
|
|
1280
|
-
pi.sendUserMessage("/reload-runtime", { deliverAs: "followUp" });
|
|
1281
|
-
return {
|
|
1282
|
-
content: [{ type: "text", text: "Queued /reload-runtime as a follow-up command." }],
|
|
1283
|
-
};
|
|
1284
|
-
},
|
|
1285
|
-
});
|
|
1286
|
-
}
|
|
1287
|
-
```
|
|
1288
|
-
|
|
1289
|
-
## ExtensionAPI Methods
|
|
1290
|
-
|
|
1291
|
-
### pi.on(event, handler)
|
|
1292
|
-
|
|
1293
|
-
Subscribe to events. See [Events](#events) for event types and return values.
|
|
1294
|
-
|
|
1295
|
-
### pi.registerTool(definition)
|
|
1296
|
-
|
|
1297
|
-
Register a custom tool callable by the LLM. See [Custom Tools](#custom-tools) for full details.
|
|
1298
|
-
|
|
1299
|
-
`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()` and are callable by the LLM without `/reload`.
|
|
1300
|
-
|
|
1301
|
-
Use `pi.setActiveTools()` to enable or disable tools (including dynamically added tools) at runtime.
|
|
1302
|
-
|
|
1303
|
-
Use `promptSnippet` to opt a custom tool into a one-line entry in `Available tools`, and `promptGuidelines` to append tool-specific bullets to the default `Guidelines` section when the tool is active.
|
|
1304
|
-
|
|
1305
|
-
**Important:** `promptGuidelines` bullets are appended flat to the `Guidelines` 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.
|
|
1306
|
-
|
|
1307
|
-
See [dynamic-tools.ts](../examples/extensions/dynamic-tools.ts) for a full example.
|
|
1308
|
-
|
|
1309
|
-
```typescript
|
|
1310
|
-
import { Type } from "typebox";
|
|
1311
|
-
import { StringEnum } from "@draht/ai";
|
|
1312
|
-
|
|
1313
|
-
pi.registerTool({
|
|
1314
|
-
name: "my_tool",
|
|
1315
|
-
label: "My Tool",
|
|
1316
|
-
description: "What this tool does",
|
|
1317
|
-
promptSnippet: "Summarize or transform text according to action",
|
|
1318
|
-
promptGuidelines: ["Use my_tool when the user asks to summarize previously generated text."],
|
|
1319
|
-
parameters: Type.Object({
|
|
1320
|
-
action: StringEnum(["list", "add"] as const),
|
|
1321
|
-
text: Type.Optional(Type.String()),
|
|
1322
|
-
}),
|
|
1323
|
-
prepareArguments(args) {
|
|
1324
|
-
// Optional compatibility shim. Runs before schema validation.
|
|
1325
|
-
// Return the current schema shape, for example to fold legacy fields
|
|
1326
|
-
// into the modern parameter object.
|
|
1327
|
-
return args;
|
|
1328
|
-
},
|
|
1329
|
-
|
|
1330
|
-
async execute(toolCallId, params, signal, onUpdate, ctx) {
|
|
1331
|
-
// Stream progress
|
|
1332
|
-
onUpdate?.({ content: [{ type: "text", text: "Working..." }] });
|
|
1333
|
-
|
|
1334
|
-
return {
|
|
1335
|
-
content: [{ type: "text", text: "Done" }],
|
|
1336
|
-
details: { result: "..." },
|
|
1337
|
-
};
|
|
1338
|
-
},
|
|
1339
|
-
|
|
1340
|
-
// Optional: Custom rendering
|
|
1341
|
-
renderCall(args, theme, context) { ... },
|
|
1342
|
-
renderResult(result, options, theme, context) { ... },
|
|
1343
|
-
});
|
|
1344
|
-
```
|
|
1345
|
-
|
|
1346
|
-
### pi.sendMessage(message, options?)
|
|
1347
|
-
|
|
1348
|
-
Inject a custom message into the session. Custom messages participate in LLM context. For durable TUI-only content that should not be sent to the LLM, use [`pi.appendEntry()`](#piappendentrycustomtype-data) with [`pi.registerEntryRenderer()`](#piregisterentryrenderercustomtype-renderer).
|
|
1349
|
-
|
|
1350
|
-
```typescript
|
|
1351
|
-
pi.sendMessage({
|
|
1352
|
-
customType: "my-extension",
|
|
1353
|
-
content: "Message text",
|
|
1354
|
-
display: true,
|
|
1355
|
-
details: { ... },
|
|
1356
|
-
}, {
|
|
1357
|
-
triggerTurn: true,
|
|
1358
|
-
deliverAs: "steer",
|
|
1359
|
-
});
|
|
1360
|
-
```
|
|
1361
|
-
|
|
1362
|
-
**Options:**
|
|
1363
|
-
- `deliverAs` - Delivery mode:
|
|
1364
|
-
- `"steer"` (default) - Queues the message while streaming. Delivered after the current assistant turn finishes executing its tool calls, before the next LLM call.
|
|
1365
|
-
- `"followUp"` - Waits for agent to finish. Delivered only when agent has no more tool calls.
|
|
1366
|
-
- `"nextTurn"` - Queued for next user prompt. Does not interrupt or trigger anything.
|
|
1367
|
-
- `triggerTurn: true` - If agent is idle, trigger an LLM response immediately. Only applies to `"steer"` and `"followUp"` modes (ignored for `"nextTurn"`).
|
|
1368
|
-
|
|
1369
|
-
### pi.sendUserMessage(content, options?)
|
|
1370
|
-
|
|
1371
|
-
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. Always triggers a turn.
|
|
1372
|
-
|
|
1373
|
-
```typescript
|
|
1374
|
-
// Simple text message
|
|
1375
|
-
pi.sendUserMessage("What is 2+2?");
|
|
1376
|
-
|
|
1377
|
-
// With content array (text + images)
|
|
1378
|
-
pi.sendUserMessage([
|
|
1379
|
-
{ type: "text", text: "Describe this image:" },
|
|
1380
|
-
{ type: "image", source: { type: "base64", mediaType: "image/png", data: "..." } },
|
|
1381
|
-
]);
|
|
1382
|
-
|
|
1383
|
-
// During streaming - must specify delivery mode
|
|
1384
|
-
pi.sendUserMessage("Focus on error handling", { deliverAs: "steer" });
|
|
1385
|
-
pi.sendUserMessage("And then summarize", { deliverAs: "followUp" });
|
|
1386
|
-
```
|
|
1387
|
-
|
|
1388
|
-
**Options:**
|
|
1389
|
-
- `deliverAs` - Required when agent is streaming:
|
|
1390
|
-
- `"steer"` - Queues the message for delivery after the current assistant turn finishes executing its tool calls
|
|
1391
|
-
- `"followUp"` - Waits for agent to finish all tools
|
|
1392
|
-
|
|
1393
|
-
When not streaming, the message is sent immediately and triggers a new turn. When streaming without `deliverAs`, throws an error.
|
|
1394
|
-
|
|
1395
|
-
See [send-user-message.ts](../examples/extensions/send-user-message.ts) for a complete example.
|
|
1396
|
-
|
|
1397
|
-
### pi.appendEntry(customType, data?)
|
|
1398
|
-
|
|
1399
|
-
Persist extension data. Custom entries do NOT participate in LLM context. In interactive mode, they can also render inside the chat transcript when paired with `pi.registerEntryRenderer()`.
|
|
1400
|
-
|
|
1401
|
-
```typescript
|
|
1402
|
-
pi.appendEntry("my-state", { count: 42 });
|
|
1403
|
-
pi.appendEntry("status-card", { title: "Indexed files", count: 17 });
|
|
1404
|
-
|
|
1405
|
-
// Restore on reload
|
|
1406
|
-
pi.on("session_start", async (_event, ctx) => {
|
|
1407
|
-
for (const entry of ctx.sessionManager.getEntries()) {
|
|
1408
|
-
if (entry.type === "custom" && entry.customType === "my-state") {
|
|
1409
|
-
// Reconstruct from entry.data
|
|
1410
|
-
}
|
|
1411
|
-
}
|
|
1412
|
-
});
|
|
1413
|
-
```
|
|
1414
|
-
|
|
1415
|
-
### pi.setSessionName(name)
|
|
1416
|
-
|
|
1417
|
-
Set the session display name (shown in session selector instead of first message).
|
|
1418
|
-
|
|
1419
|
-
```typescript
|
|
1420
|
-
pi.setSessionName("Refactor auth module");
|
|
1421
|
-
```
|
|
1422
|
-
|
|
1423
|
-
### pi.getSessionName()
|
|
1424
|
-
|
|
1425
|
-
Get the current session name, if set.
|
|
1426
|
-
|
|
1427
|
-
```typescript
|
|
1428
|
-
const name = pi.getSessionName();
|
|
1429
|
-
if (name) {
|
|
1430
|
-
console.log(`Session: ${name}`);
|
|
1431
|
-
}
|
|
1432
|
-
```
|
|
1433
|
-
|
|
1434
|
-
### pi.setLabel(entryId, label)
|
|
1435
|
-
|
|
1436
|
-
Set or clear a label on an entry. Labels are user-defined markers for bookmarking and navigation (shown in `/tree` selector).
|
|
1437
|
-
|
|
1438
|
-
```typescript
|
|
1439
|
-
// Set a label
|
|
1440
|
-
pi.setLabel(entryId, "checkpoint-before-refactor");
|
|
1441
|
-
|
|
1442
|
-
// Clear a label
|
|
1443
|
-
pi.setLabel(entryId, undefined);
|
|
1444
|
-
|
|
1445
|
-
// Read labels via sessionManager
|
|
1446
|
-
const label = ctx.sessionManager.getLabel(entryId);
|
|
1447
|
-
```
|
|
1448
|
-
|
|
1449
|
-
Labels persist in the session and survive restarts. Use them to mark important points (turns, checkpoints) in the conversation tree.
|
|
1450
|
-
|
|
1451
|
-
### pi.registerCommand(name, options)
|
|
1452
|
-
|
|
1453
|
-
Register a command.
|
|
1454
|
-
|
|
1455
|
-
If multiple extensions register the same command name, draht keeps them all and assigns numeric invocation suffixes in load order, for example `/review:1` and `/review:2`.
|
|
1456
|
-
|
|
1457
|
-
```typescript
|
|
1458
|
-
pi.registerCommand("stats", {
|
|
1459
|
-
description: "Show session statistics",
|
|
1460
|
-
handler: async (args, ctx) => {
|
|
1461
|
-
const count = ctx.sessionManager.getEntries().length;
|
|
1462
|
-
ctx.ui.notify(`${count} entries`, "info");
|
|
1463
|
-
}
|
|
1464
|
-
});
|
|
1465
|
-
```
|
|
1466
|
-
|
|
1467
|
-
Optional: add argument auto-completion for `/command ...`:
|
|
1468
|
-
|
|
1469
|
-
```typescript
|
|
1470
|
-
import type { AutocompleteItem } from "@draht/tui";
|
|
1471
|
-
|
|
1472
|
-
pi.registerCommand("deploy", {
|
|
1473
|
-
description: "Deploy to an environment",
|
|
1474
|
-
getArgumentCompletions: (prefix: string): AutocompleteItem[] | null => {
|
|
1475
|
-
const envs = ["dev", "staging", "prod"];
|
|
1476
|
-
const items = envs.map((e) => ({ value: e, label: e }));
|
|
1477
|
-
const filtered = items.filter((i) => i.value.startsWith(prefix));
|
|
1478
|
-
return filtered.length > 0 ? filtered : null;
|
|
1479
|
-
},
|
|
1480
|
-
handler: async (args, ctx) => {
|
|
1481
|
-
ctx.ui.notify(`Deploying: ${args}`, "info");
|
|
1482
|
-
},
|
|
1483
|
-
});
|
|
1484
|
-
```
|
|
1485
|
-
|
|
1486
|
-
### pi.getCommands()
|
|
1487
|
-
|
|
1488
|
-
Get the slash commands available for invocation via `prompt` in the current session. Includes extension commands, prompt templates, and skill commands.
|
|
1489
|
-
The list matches the RPC `get_commands` ordering: extensions first, then templates, then skills.
|
|
1490
|
-
|
|
1491
|
-
```typescript
|
|
1492
|
-
const commands = pi.getCommands();
|
|
1493
|
-
const bySource = commands.filter((command) => command.source === "extension");
|
|
1494
|
-
const userScoped = commands.filter((command) => command.sourceInfo.scope === "user");
|
|
1495
|
-
```
|
|
1496
|
-
|
|
1497
|
-
Each entry has this shape:
|
|
1498
|
-
|
|
1499
|
-
```typescript
|
|
1500
|
-
{
|
|
1501
|
-
name: string; // Invokable command name without the leading slash. May be suffixed like "review:1"
|
|
1502
|
-
description?: string;
|
|
1503
|
-
source: "extension" | "prompt" | "skill";
|
|
1504
|
-
sourceInfo: {
|
|
1505
|
-
path: string;
|
|
1506
|
-
source: string;
|
|
1507
|
-
scope: "user" | "project" | "temporary";
|
|
1508
|
-
origin: "package" | "top-level";
|
|
1509
|
-
baseDir?: string;
|
|
1510
|
-
};
|
|
1511
|
-
}
|
|
1512
|
-
```
|
|
1513
|
-
|
|
1514
|
-
Use `sourceInfo` as the canonical provenance field. Do not infer ownership from command names or from ad hoc path parsing.
|
|
1515
|
-
|
|
1516
|
-
Built-in interactive commands (like `/model` and `/settings`) are not included here. They are handled only in interactive
|
|
1517
|
-
mode and would not execute if sent via `prompt`.
|
|
1518
|
-
|
|
1519
|
-
### pi.registerMessageRenderer(customType, renderer)
|
|
1520
|
-
|
|
1521
|
-
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).
|
|
1522
|
-
|
|
1523
|
-
### pi.registerEntryRenderer(customType, renderer)
|
|
1524
|
-
|
|
1525
|
-
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.
|
|
1526
|
-
|
|
1527
|
-
```typescript
|
|
1528
|
-
import { Box, Text } from "@draht/tui";
|
|
1529
|
-
|
|
1530
|
-
pi.registerEntryRenderer("status-card", (entry, { expanded }, theme) => {
|
|
1531
|
-
const data = entry.data as { title: string; count: number };
|
|
1532
|
-
const box = new Box(1, 1, (text) => theme.bg("customMessageBg", text));
|
|
1533
|
-
box.addChild(new Text(`${theme.bold(data.title)}: ${data.count}`));
|
|
1534
|
-
if (expanded) {
|
|
1535
|
-
box.addChild(new Text(theme.fg("dim", JSON.stringify(data, null, 2))));
|
|
1536
|
-
}
|
|
1537
|
-
return box;
|
|
1538
|
-
});
|
|
1539
|
-
|
|
1540
|
-
pi.appendEntry("status-card", { title: "Indexed files", count: 17 });
|
|
1541
|
-
```
|
|
1542
|
-
|
|
1543
|
-
### pi.registerShortcut(shortcut, options)
|
|
1544
|
-
|
|
1545
|
-
Register a keyboard shortcut. See [keybindings.md](keybindings.md) for the shortcut format and built-in keybindings.
|
|
1546
|
-
|
|
1547
|
-
```typescript
|
|
1548
|
-
pi.registerShortcut("ctrl+shift+p", {
|
|
1549
|
-
description: "Toggle plan mode",
|
|
1550
|
-
handler: async (ctx) => {
|
|
1551
|
-
ctx.ui.notify("Toggled!");
|
|
1552
|
-
},
|
|
1553
|
-
});
|
|
1554
|
-
```
|
|
1555
|
-
|
|
1556
|
-
### pi.registerFlag(name, options)
|
|
1557
|
-
|
|
1558
|
-
Register a CLI flag.
|
|
1559
|
-
|
|
1560
|
-
```typescript
|
|
1561
|
-
pi.registerFlag("plan", {
|
|
1562
|
-
description: "Start in plan mode",
|
|
1563
|
-
type: "boolean",
|
|
1564
|
-
default: false,
|
|
1565
|
-
});
|
|
1566
|
-
|
|
1567
|
-
// Check value
|
|
1568
|
-
if (pi.getFlag("plan")) {
|
|
1569
|
-
// Plan mode enabled
|
|
1570
|
-
}
|
|
1571
|
-
```
|
|
1572
|
-
|
|
1573
|
-
### pi.exec(command, args, options?)
|
|
1574
|
-
|
|
1575
|
-
Execute a shell command.
|
|
1576
|
-
|
|
1577
|
-
```typescript
|
|
1578
|
-
const result = await pi.exec("git", ["status"], { signal, timeout: 5000 });
|
|
1579
|
-
// result.stdout, result.stderr, result.code, result.killed
|
|
1580
|
-
```
|
|
1581
|
-
|
|
1582
|
-
### pi.getActiveTools() / pi.getAllTools() / pi.setActiveTools(names)
|
|
1583
|
-
|
|
1584
|
-
Manage active tools. This works for both built-in tools and dynamically registered tools.
|
|
1585
|
-
|
|
1586
|
-
```typescript
|
|
1587
|
-
const active = pi.getActiveTools();
|
|
1588
|
-
const all = pi.getAllTools();
|
|
1589
|
-
// [{
|
|
1590
|
-
// name: "read",
|
|
1591
|
-
// description: "Read file contents...",
|
|
1592
|
-
// parameters: ...,
|
|
1593
|
-
// promptGuidelines: ["Use read to examine files instead of cat or sed."],
|
|
1594
|
-
// sourceInfo: { path: "<builtin:read>", source: "builtin", scope: "temporary", origin: "top-level" }
|
|
1595
|
-
// }, ...]
|
|
1596
|
-
const names = all.map(t => t.name);
|
|
1597
|
-
const builtinTools = all.filter((t) => t.sourceInfo.source === "builtin");
|
|
1598
|
-
const extensionTools = all.filter((t) => t.sourceInfo.source !== "builtin" && t.sourceInfo.source !== "sdk");
|
|
1599
|
-
pi.setActiveTools(["read", "bash"]); // Switch to read-only
|
|
1600
|
-
```
|
|
1601
|
-
|
|
1602
|
-
`pi.getAllTools()` returns `name`, `description`, `parameters`, `promptGuidelines`, and `sourceInfo`.
|
|
1603
|
-
|
|
1604
|
-
Typical `sourceInfo.source` values:
|
|
1605
|
-
- `builtin` for built-in tools
|
|
1606
|
-
- `sdk` for tools passed via `createAgentSession({ customTools })`
|
|
1607
|
-
- extension source metadata for tools registered by extensions
|
|
1608
|
-
|
|
1609
|
-
### pi.setModel(model, options?)
|
|
1610
|
-
|
|
1611
|
-
Set the current model. Returns `false` if no API key is available for the model. See [models.md](models.md) for configuring custom models. Pass `{ persistDefault: false }` for session-scoped orchestration that must not replace the user's global default model.
|
|
1612
|
-
|
|
1613
|
-
```typescript
|
|
1614
|
-
const model = ctx.modelRegistry.find("anthropic", "claude-sonnet-4-5");
|
|
1615
|
-
if (model) {
|
|
1616
|
-
const success = await pi.setModel(model);
|
|
1617
|
-
if (!success) {
|
|
1618
|
-
ctx.ui.notify("No API key for this model", "error");
|
|
1619
|
-
}
|
|
1620
|
-
}
|
|
1621
|
-
```
|
|
1622
|
-
|
|
1623
|
-
### pi.getThinkingLevel() / pi.setThinkingLevel(level, options?)
|
|
1624
|
-
|
|
1625
|
-
Get or set the thinking level. Level is clamped to model capabilities (non-reasoning models always use "off"). Changes emit `thinking_level_select`. Pass `{ persistDefault: false }` when the change should remain session-scoped.
|
|
1626
|
-
|
|
1627
|
-
```typescript
|
|
1628
|
-
const current = pi.getThinkingLevel(); // "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"
|
|
1629
|
-
pi.setThinkingLevel("high");
|
|
1630
|
-
```
|
|
1631
|
-
|
|
1632
|
-
### pi.events
|
|
1633
|
-
|
|
1634
|
-
Shared event bus for communication between extensions:
|
|
1635
|
-
|
|
1636
|
-
```typescript
|
|
1637
|
-
pi.events.on("my:event", (data) => { ... });
|
|
1638
|
-
pi.events.emit("my:event", { ... });
|
|
1639
|
-
```
|
|
1640
|
-
|
|
1641
|
-
### pi.registerProvider(name, config)
|
|
1642
|
-
|
|
1643
|
-
Register or override a model provider dynamically. Useful for proxies, custom endpoints, or team-wide model configurations.
|
|
1644
|
-
|
|
1645
|
-
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`.
|
|
1646
|
-
|
|
1647
|
-
Dynamic providers can implement `refreshModels`. draht calls it during model refresh, publishes the returned list synchronously through the provider, and passes the canonical credential/store/network/signal context. The extension decides whether to persist the catalog through `context.store`; live servers such as llama.cpp can ignore it.
|
|
1648
|
-
|
|
1649
|
-
Extensions that need native provider auth, filtering, refresh, or stream behavior can register a complete `Provider` from `@draht/ai`. The provider becomes the composition base and `models.json` overrides still apply above it.
|
|
1650
|
-
|
|
1651
|
-
```typescript
|
|
1652
|
-
import { createProvider, openAICompletionsApi } from "@draht/ai";
|
|
1653
|
-
|
|
1654
|
-
const provider = createProvider({
|
|
1655
|
-
id: "local-server",
|
|
1656
|
-
name: "Local Server",
|
|
1657
|
-
baseUrl: "http://localhost:8080/v1",
|
|
1658
|
-
auth: {
|
|
1659
|
-
apiKey: {
|
|
1660
|
-
name: "Local server setup",
|
|
1661
|
-
async login(interaction) {
|
|
1662
|
-
return {
|
|
1663
|
-
type: "api_key",
|
|
1664
|
-
key: await interaction.prompt({ type: "secret", message: "API key" }),
|
|
1665
|
-
};
|
|
1666
|
-
},
|
|
1667
|
-
async resolve({ credential }) {
|
|
1668
|
-
return credential?.key
|
|
1669
|
-
? { auth: { apiKey: credential.key }, source: "stored API key" }
|
|
1670
|
-
: undefined;
|
|
1671
|
-
},
|
|
1672
|
-
},
|
|
1673
|
-
},
|
|
1674
|
-
models: [],
|
|
1675
|
-
api: openAICompletionsApi(),
|
|
1676
|
-
});
|
|
1677
|
-
|
|
1678
|
-
pi.registerProvider(provider);
|
|
1679
|
-
|
|
1680
|
-
// Register a new provider with custom models
|
|
1681
|
-
pi.registerProvider("my-proxy", {
|
|
1682
|
-
name: "My Proxy",
|
|
1683
|
-
baseUrl: "https://proxy.example.com",
|
|
1684
|
-
apiKey: "$PROXY_API_KEY", // env var reference
|
|
1685
|
-
api: "anthropic-messages",
|
|
1686
|
-
models: [
|
|
1687
|
-
{
|
|
1688
|
-
id: "claude-sonnet-4-20250514",
|
|
1689
|
-
name: "Claude 4 Sonnet (proxy)",
|
|
1690
|
-
reasoning: false,
|
|
1691
|
-
input: ["text", "image"],
|
|
1692
|
-
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
1693
|
-
contextWindow: 200000,
|
|
1694
|
-
maxTokens: 16384
|
|
1695
|
-
}
|
|
1696
|
-
]
|
|
1697
|
-
});
|
|
1698
|
-
|
|
1699
|
-
// Register a live llama.cpp catalog without persisting discovered models
|
|
1700
|
-
pi.registerProvider("llama.cpp", {
|
|
1701
|
-
baseUrl: "http://localhost:8080/v1",
|
|
1702
|
-
apiKey: "local",
|
|
1703
|
-
api: "openai-completions",
|
|
1704
|
-
async refreshModels({ signal }) {
|
|
1705
|
-
const response = await fetch("http://localhost:8080/v1/models", { signal });
|
|
1706
|
-
const { data } = await response.json();
|
|
1707
|
-
return data.map(({ id }) => ({
|
|
1708
|
-
id,
|
|
1709
|
-
name: id,
|
|
1710
|
-
reasoning: false,
|
|
1711
|
-
input: ["text"],
|
|
1712
|
-
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
1713
|
-
contextWindow: 128000,
|
|
1714
|
-
maxTokens: 16384
|
|
1715
|
-
}));
|
|
1716
|
-
}
|
|
1717
|
-
});
|
|
1718
|
-
|
|
1719
|
-
// Override baseUrl for an existing provider (keeps all models)
|
|
1720
|
-
pi.registerProvider("anthropic", {
|
|
1721
|
-
baseUrl: "https://proxy.example.com"
|
|
1722
|
-
});
|
|
1723
|
-
|
|
1724
|
-
// Register provider with OAuth support for /login
|
|
1725
|
-
pi.registerProvider("corporate-ai", {
|
|
1726
|
-
baseUrl: "https://ai.corp.com",
|
|
1727
|
-
api: "openai-responses",
|
|
1728
|
-
models: [...],
|
|
1729
|
-
oauth: {
|
|
1730
|
-
name: "Corporate AI (SSO)",
|
|
1731
|
-
async login(callbacks) {
|
|
1732
|
-
// Custom OAuth flow
|
|
1733
|
-
callbacks.onAuth({ url: "https://sso.corp.com/..." });
|
|
1734
|
-
const code = await callbacks.onPrompt({ message: "Enter code:" });
|
|
1735
|
-
return { refresh: code, access: code, expires: Date.now() + 3600000 };
|
|
1736
|
-
},
|
|
1737
|
-
async refreshToken(credentials) {
|
|
1738
|
-
// Refresh logic
|
|
1739
|
-
return credentials;
|
|
1740
|
-
},
|
|
1741
|
-
getApiKey(credentials) {
|
|
1742
|
-
return credentials.access;
|
|
1743
|
-
}
|
|
1744
|
-
}
|
|
1745
|
-
});
|
|
1746
|
-
```
|
|
1747
|
-
|
|
1748
|
-
The object form accepts a complete `@draht/ai` `Provider`, including native `auth`, `getModels`, `refreshModels`, `filterModels`, `stream`, and `streamSimple` behavior.
|
|
1749
|
-
|
|
1750
|
-
**Legacy config options:**
|
|
1751
|
-
- `name` - Display name for the provider in UI such as `/login`.
|
|
1752
|
-
- `baseUrl` - API endpoint URL. Required when defining models.
|
|
1753
|
-
- `apiKey` - API key literal, environment interpolation (`$ENV_VAR` or `${ENV_VAR}`), or leading `!command`. Required when defining models (unless `oauth` provided). `$$` escapes `$`, and `$!` escapes a literal `!` without triggering command execution.
|
|
1754
|
-
- `api` - API type: `"anthropic-messages"`, `"openai-completions"`, `"openai-responses"`, etc.
|
|
1755
|
-
- `headers` - Custom headers to include in requests.
|
|
1756
|
-
- `authHeader` - If true, adds `Authorization: Bearer` header automatically.
|
|
1757
|
-
- `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.
|
|
1758
|
-
- `refreshModels` - Async dynamic discovery callback. Its returned models replace extension-provided models. Use the scoped `context.store` only when results should persist.
|
|
1759
|
-
- `oauth` - OAuth provider config for `/login` support. When provided, the provider appears in the login menu.
|
|
1760
|
-
- `streamSimple` - Custom streaming implementation for non-standard APIs.
|
|
1761
|
-
|
|
1762
|
-
See [custom-provider.md](custom-provider.md) for advanced topics: custom streaming APIs, OAuth details, model definition reference.
|
|
1763
|
-
|
|
1764
|
-
### pi.unregisterProvider(name)
|
|
1765
|
-
|
|
1766
|
-
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.
|
|
1767
|
-
|
|
1768
|
-
Like `registerProvider`, this takes effect immediately when called after the initial load phase, so a `/reload` is not required.
|
|
1769
|
-
|
|
1770
|
-
```typescript
|
|
1771
|
-
pi.registerCommand("my-setup-teardown", {
|
|
1772
|
-
description: "Remove the custom proxy provider",
|
|
1773
|
-
handler: async (_args, _ctx) => {
|
|
1774
|
-
pi.unregisterProvider("my-proxy");
|
|
1775
|
-
},
|
|
1776
|
-
});
|
|
1777
|
-
```
|
|
1778
|
-
|
|
1779
|
-
## State Management
|
|
1780
|
-
|
|
1781
|
-
Extensions with state should store it in tool result `details` for proper branching support:
|
|
1782
|
-
|
|
1783
|
-
```typescript
|
|
1784
|
-
export default function (pi: ExtensionAPI) {
|
|
1785
|
-
let items: string[] = [];
|
|
1786
|
-
|
|
1787
|
-
// Reconstruct state from session
|
|
1788
|
-
pi.on("session_start", async (_event, ctx) => {
|
|
1789
|
-
items = [];
|
|
1790
|
-
for (const entry of ctx.sessionManager.getBranch()) {
|
|
1791
|
-
if (entry.type === "message" && entry.message.role === "toolResult") {
|
|
1792
|
-
if (entry.message.toolName === "my_tool") {
|
|
1793
|
-
items = entry.message.details?.items ?? [];
|
|
1794
|
-
}
|
|
1795
|
-
}
|
|
1796
|
-
}
|
|
1797
|
-
});
|
|
1798
|
-
|
|
1799
|
-
pi.registerTool({
|
|
1800
|
-
name: "my_tool",
|
|
1801
|
-
// ...
|
|
1802
|
-
async execute(toolCallId, params, signal, onUpdate, ctx) {
|
|
1803
|
-
items.push("new item");
|
|
1804
|
-
return {
|
|
1805
|
-
content: [{ type: "text", text: "Added" }],
|
|
1806
|
-
details: { items: [...items] }, // Store for reconstruction
|
|
1807
|
-
};
|
|
1808
|
-
},
|
|
1809
|
-
});
|
|
1810
|
-
}
|
|
1811
|
-
```
|
|
1812
|
-
|
|
1813
|
-
## Custom Tools
|
|
1814
|
-
|
|
1815
|
-
Register tools the LLM can call via `pi.registerTool()`. Tools appear in the system prompt and can have custom rendering.
|
|
1816
|
-
|
|
1817
|
-
Use `promptSnippet` for a short one-line entry in the `Available tools` section in the default system prompt. If omitted, custom tools are left out of that section.
|
|
1818
|
-
|
|
1819
|
-
Use `promptGuidelines` to add tool-specific bullets to the default system prompt `Guidelines` section. These bullets are included only while the tool is active (for example, after `pi.setActiveTools([...])`).
|
|
1820
|
-
|
|
1821
|
-
**Important:** `promptGuidelines` bullets are appended flat to the `Guidelines` 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.
|
|
1822
|
-
|
|
1823
|
-
Note: Some models are idiots and 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.
|
|
1824
|
-
|
|
1825
|
-
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.
|
|
1826
|
-
|
|
1827
|
-
Example failure case: your custom tool edits `foo.ts` while built-in `edit` also changes `foo.ts` in the same assistant turn. If your tool does not participate in the queue, both can read the original `foo.ts`, apply separate changes, and one of those changes is lost.
|
|
1828
|
-
|
|
1829
|
-
Pass the real target file path to `withFileMutationQueue()`, not the raw user argument. Resolve it to an absolute path first, relative to `ctx.cwd` or your tool's working directory. For existing files, the helper canonicalizes through `realpath()`, so symlink aliases for the same file share one queue. For new files, it falls back to the resolved absolute path because there is nothing to `realpath()` yet.
|
|
1830
|
-
|
|
1831
|
-
Queue the entire mutation window on that target path. That includes read-modify-write logic, not just the final write.
|
|
1832
|
-
|
|
1833
|
-
```typescript
|
|
1834
|
-
import { withFileMutationQueue } from "@draht/coding-agent";
|
|
1835
|
-
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
1836
|
-
import { dirname, resolve } from "node:path";
|
|
1837
|
-
|
|
1838
|
-
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1839
|
-
const absolutePath = resolve(ctx.cwd, params.path);
|
|
1840
|
-
|
|
1841
|
-
return withFileMutationQueue(absolutePath, async () => {
|
|
1842
|
-
await mkdir(dirname(absolutePath), { recursive: true });
|
|
1843
|
-
const current = await readFile(absolutePath, "utf8");
|
|
1844
|
-
const next = current.replace(params.oldText, params.newText);
|
|
1845
|
-
await writeFile(absolutePath, next, "utf8");
|
|
1846
|
-
|
|
1847
|
-
return {
|
|
1848
|
-
content: [{ type: "text", text: `Updated ${params.path}` }],
|
|
1849
|
-
details: {},
|
|
1850
|
-
};
|
|
1851
|
-
});
|
|
1852
|
-
}
|
|
1853
|
-
```
|
|
1854
|
-
|
|
1855
|
-
### Tool Definition
|
|
1856
|
-
|
|
1857
|
-
```typescript
|
|
1858
|
-
import { Type } from "typebox";
|
|
1859
|
-
import { StringEnum } from "@draht/ai";
|
|
1860
|
-
import { Text } from "@draht/tui";
|
|
1861
|
-
|
|
1862
|
-
pi.registerTool({
|
|
1863
|
-
name: "my_tool",
|
|
1864
|
-
label: "My Tool",
|
|
1865
|
-
description: "What this tool does (shown to LLM)",
|
|
1866
|
-
promptSnippet: "List or add items in the project todo list",
|
|
1867
|
-
promptGuidelines: [
|
|
1868
|
-
"Use my_tool for todo planning instead of direct file edits when the user asks for a task list."
|
|
1869
|
-
],
|
|
1870
|
-
parameters: Type.Object({
|
|
1871
|
-
action: StringEnum(["list", "add"] as const), // Use StringEnum for Google compatibility
|
|
1872
|
-
text: Type.Optional(Type.String()),
|
|
1873
|
-
}),
|
|
1874
|
-
prepareArguments(args) {
|
|
1875
|
-
if (!args || typeof args !== "object") return args;
|
|
1876
|
-
const input = args as { action?: string; oldAction?: string };
|
|
1877
|
-
if (typeof input.oldAction === "string" && input.action === undefined) {
|
|
1878
|
-
return { ...input, action: input.oldAction };
|
|
1879
|
-
}
|
|
1880
|
-
return args;
|
|
1881
|
-
},
|
|
1882
|
-
|
|
1883
|
-
async execute(toolCallId, params, signal, onUpdate, ctx) {
|
|
1884
|
-
// Check for cancellation
|
|
1885
|
-
if (signal?.aborted) {
|
|
1886
|
-
return { content: [{ type: "text", text: "Cancelled" }] };
|
|
1887
|
-
}
|
|
1888
|
-
|
|
1889
|
-
// Stream progress updates
|
|
1890
|
-
onUpdate?.({
|
|
1891
|
-
content: [{ type: "text", text: "Working..." }],
|
|
1892
|
-
details: { progress: 50 },
|
|
1893
|
-
});
|
|
1894
|
-
|
|
1895
|
-
// Run commands via pi.exec (captured from extension closure)
|
|
1896
|
-
const result = await pi.exec("some-command", [], { signal });
|
|
1897
|
-
|
|
1898
|
-
// Return result
|
|
1899
|
-
return {
|
|
1900
|
-
content: [{ type: "text", text: "Done" }], // Sent to LLM
|
|
1901
|
-
details: { data: result }, // For rendering & state
|
|
1902
|
-
// usage: nestedModelResponse.usage, // Optional nested LLM usage
|
|
1903
|
-
// Optional: stop after this tool batch when every finalized tool result
|
|
1904
|
-
// in the batch also returns terminate: true.
|
|
1905
|
-
terminate: true,
|
|
1906
|
-
};
|
|
1907
|
-
},
|
|
1908
|
-
|
|
1909
|
-
// Optional: Custom rendering
|
|
1910
|
-
renderCall(args, theme, context) { ... },
|
|
1911
|
-
renderResult(result, options, theme, context) { ... },
|
|
1912
|
-
});
|
|
1913
|
-
```
|
|
1914
|
-
|
|
1915
|
-
**Usage accounting:** If a tool makes nested LLM calls, return their combined `Usage` as `usage`. draht persists it on the tool result and includes it in footer, `/session`, and RPC session totals. `tool_result` handlers can inspect or replace this value.
|
|
1916
|
-
|
|
1917
|
-
**Signaling errors:** To mark a tool execution as failed (sets `isError: true` on the result and reports it to the LLM), throw an error from `execute`. Returning a value never sets the error flag regardless of what properties you include in the return object.
|
|
1918
|
-
|
|
1919
|
-
**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. See [examples/extensions/structured-output.ts](../examples/extensions/structured-output.ts) for a minimal example where the agent ends on a final structured-output tool call.
|
|
1920
|
-
|
|
1921
|
-
```typescript
|
|
1922
|
-
// Correct: throw to signal an error
|
|
1923
|
-
async execute(toolCallId, params) {
|
|
1924
|
-
if (!isValid(params.input)) {
|
|
1925
|
-
throw new Error(`Invalid input: ${params.input}`);
|
|
1926
|
-
}
|
|
1927
|
-
return { content: [{ type: "text", text: "OK" }], details: {} };
|
|
1928
|
-
}
|
|
1929
|
-
```
|
|
1930
|
-
|
|
1931
|
-
**Important:** Use `StringEnum` from `@draht/ai` for string enums. `Type.Union`/`Type.Literal` doesn't work with Google's API.
|
|
1932
|
-
|
|
1933
|
-
**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 draht 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.
|
|
1934
|
-
|
|
1935
|
-
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 }]`.
|
|
1936
|
-
|
|
1937
|
-
```typescript
|
|
1938
|
-
pi.registerTool({
|
|
1939
|
-
name: "edit",
|
|
1940
|
-
label: "Edit",
|
|
1941
|
-
description: "Edit a single file using exact text replacement",
|
|
1942
|
-
parameters: Type.Object({
|
|
1943
|
-
path: Type.String(),
|
|
1944
|
-
edits: Type.Array(
|
|
1945
|
-
Type.Object({
|
|
1946
|
-
oldText: Type.String(),
|
|
1947
|
-
newText: Type.String(),
|
|
1948
|
-
}),
|
|
1949
|
-
),
|
|
1950
|
-
}),
|
|
1951
|
-
prepareArguments(args) {
|
|
1952
|
-
if (!args || typeof args !== "object") return args;
|
|
1953
|
-
|
|
1954
|
-
const input = args as {
|
|
1955
|
-
path?: string;
|
|
1956
|
-
edits?: Array<{ oldText: string; newText: string }>;
|
|
1957
|
-
oldText?: unknown;
|
|
1958
|
-
newText?: unknown;
|
|
1959
|
-
};
|
|
1960
|
-
|
|
1961
|
-
if (typeof input.oldText !== "string" || typeof input.newText !== "string") {
|
|
1962
|
-
return args;
|
|
1963
|
-
}
|
|
1964
|
-
|
|
1965
|
-
return {
|
|
1966
|
-
...input,
|
|
1967
|
-
edits: [...(input.edits ?? []), { oldText: input.oldText, newText: input.newText }],
|
|
1968
|
-
};
|
|
1969
|
-
},
|
|
1970
|
-
async execute(toolCallId, params, signal, onUpdate, ctx) {
|
|
1971
|
-
// params now matches the current schema
|
|
1972
|
-
return {
|
|
1973
|
-
content: [{ type: "text", text: `Applying ${params.edits.length} edit block(s)` }],
|
|
1974
|
-
details: {},
|
|
1975
|
-
};
|
|
1976
|
-
},
|
|
1977
|
-
});
|
|
1978
|
-
```
|
|
1979
|
-
|
|
1980
|
-
### Overriding Built-in Tools
|
|
1981
|
-
|
|
1982
|
-
Extensions can override built-in tools (`read`, `bash`, `edit`, `write`, `grep`, `find`, `ls`) by registering a tool with the same name. Interactive mode displays a warning when this happens.
|
|
1983
|
-
|
|
1984
|
-
```bash
|
|
1985
|
-
# Extension's read tool replaces built-in read
|
|
1986
|
-
draht -e ./tool-override.ts
|
|
1987
|
-
```
|
|
1988
|
-
|
|
1989
|
-
Alternatively, use `--no-builtin-tools` to start without any built-in tools while keeping extension tools enabled:
|
|
1990
|
-
```bash
|
|
1991
|
-
# No built-in tools, only extension tools
|
|
1992
|
-
draht --no-builtin-tools -e ./my-extension.ts
|
|
1993
|
-
```
|
|
1994
|
-
|
|
1995
|
-
See [examples/extensions/tool-override.ts](../examples/extensions/tool-override.ts) for a complete example that overrides `read` with logging and access control.
|
|
1996
|
-
|
|
1997
|
-
**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.
|
|
1998
|
-
|
|
1999
|
-
**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.
|
|
2000
|
-
|
|
2001
|
-
**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.
|
|
2002
|
-
|
|
2003
|
-
Built-in tool implementations:
|
|
2004
|
-
- [read.ts](https://github.com/draht-dev/draht/blob/main/packages/coding-agent/src/core/tools/read.ts) - `ReadToolDetails`
|
|
2005
|
-
- [bash.ts](https://github.com/draht-dev/draht/blob/main/packages/coding-agent/src/core/tools/bash.ts) - `BashToolDetails`
|
|
2006
|
-
- [edit.ts](https://github.com/draht-dev/draht/blob/main/packages/coding-agent/src/core/tools/edit.ts)
|
|
2007
|
-
- [write.ts](https://github.com/draht-dev/draht/blob/main/packages/coding-agent/src/core/tools/write.ts)
|
|
2008
|
-
- [grep.ts](https://github.com/draht-dev/draht/blob/main/packages/coding-agent/src/core/tools/grep.ts) - `GrepToolDetails`
|
|
2009
|
-
- [find.ts](https://github.com/draht-dev/draht/blob/main/packages/coding-agent/src/core/tools/find.ts) - `FindToolDetails`
|
|
2010
|
-
- [ls.ts](https://github.com/draht-dev/draht/blob/main/packages/coding-agent/src/core/tools/ls.ts) - `LsToolDetails`
|
|
2011
|
-
|
|
2012
|
-
### Remote Execution
|
|
2013
|
-
|
|
2014
|
-
Built-in tools support pluggable operations for delegating to remote systems (SSH, containers, etc.):
|
|
2015
|
-
|
|
2016
|
-
```typescript
|
|
2017
|
-
import { createReadTool, createBashTool, type ReadOperations } from "@draht/coding-agent";
|
|
2018
|
-
|
|
2019
|
-
// Create tool with custom operations
|
|
2020
|
-
const remoteRead = createReadTool(cwd, {
|
|
2021
|
-
operations: {
|
|
2022
|
-
readFile: (path) => sshExec(remote, `cat ${path}`),
|
|
2023
|
-
access: (path) => sshExec(remote, `test -r ${path}`).then(() => {}),
|
|
2024
|
-
}
|
|
2025
|
-
});
|
|
2026
|
-
|
|
2027
|
-
// Register, checking flag at execution time
|
|
2028
|
-
pi.registerTool({
|
|
2029
|
-
...remoteRead,
|
|
2030
|
-
async execute(id, params, signal, onUpdate, _ctx) {
|
|
2031
|
-
const ssh = getSshConfig();
|
|
2032
|
-
if (ssh) {
|
|
2033
|
-
const tool = createReadTool(cwd, { operations: createRemoteOps(ssh) });
|
|
2034
|
-
return tool.execute(id, params, signal, onUpdate);
|
|
2035
|
-
}
|
|
2036
|
-
return localRead.execute(id, params, signal, onUpdate);
|
|
2037
|
-
},
|
|
2038
|
-
});
|
|
2039
|
-
```
|
|
2040
|
-
|
|
2041
|
-
**Operations interfaces:** `ReadOperations`, `WriteOperations`, `EditOperations`, `BashOperations`, `LsOperations`, `GrepOperations`, `FindOperations`
|
|
2042
|
-
|
|
2043
|
-
For `user_bash`, extensions can reuse draht's local shell backend via `createLocalBashOperations()` instead of reimplementing local process spawning, shell resolution, and process-tree termination.
|
|
2044
|
-
|
|
2045
|
-
The bash tool also supports a spawn hook to adjust the command, cwd, or env before execution:
|
|
2046
|
-
|
|
2047
|
-
```typescript
|
|
2048
|
-
import { createBashTool } from "@draht/coding-agent";
|
|
2049
|
-
|
|
2050
|
-
const bashTool = createBashTool(cwd, {
|
|
2051
|
-
spawnHook: ({ command, cwd, env }) => ({
|
|
2052
|
-
command: `source ~/.profile\n${command}`,
|
|
2053
|
-
cwd: `/mnt/sandbox${cwd}`,
|
|
2054
|
-
env: { ...env, CI: "1" },
|
|
2055
|
-
}),
|
|
2056
|
-
});
|
|
2057
|
-
```
|
|
2058
|
-
|
|
2059
|
-
`createBashTool()` exposes the current session to commands through `DRAHT_SESSION_ID`, `DRAHT_SESSION_FILE`, `DRAHT_PROVIDER`, `DRAHT_MODEL`, and `DRAHT_REASONING_LEVEL`. Injection happens before `spawnHook`, so hooks receive these values in `env` and preserve them when they spread the existing environment as above. Set `exposeSessionEnvironment: false` to disable them:
|
|
2060
|
-
|
|
2061
|
-
```typescript
|
|
2062
|
-
const bashTool = createBashTool(cwd, {
|
|
2063
|
-
exposeSessionEnvironment: false,
|
|
2064
|
-
});
|
|
2065
|
-
```
|
|
2066
|
-
|
|
2067
|
-
See [Bash tool session environment](environment-variables.md#bash-tool-session-environment) for variable semantics. See [examples/extensions/ssh.ts](../examples/extensions/ssh.ts) for a complete SSH example with `--ssh` flag.
|
|
2068
|
-
|
|
2069
|
-
### Output Truncation
|
|
2070
|
-
|
|
2071
|
-
**Tools MUST truncate their output** to avoid overwhelming the LLM context. Large outputs can cause:
|
|
2072
|
-
- Context overflow errors (prompt too long)
|
|
2073
|
-
- Compaction failures
|
|
2074
|
-
- Degraded model performance
|
|
2075
|
-
|
|
2076
|
-
The built-in limit is **50KB** (~10k tokens) and **2000 lines**, whichever is hit first. Use the exported truncation utilities:
|
|
2077
|
-
|
|
2078
|
-
```typescript
|
|
2079
|
-
import {
|
|
2080
|
-
truncateHead, // Keep first N lines/bytes (good for file reads, search results)
|
|
2081
|
-
truncateTail, // Keep last N lines/bytes (good for logs, command output)
|
|
2082
|
-
truncateLine, // Truncate a single line to maxBytes with ellipsis
|
|
2083
|
-
formatSize, // Human-readable size (e.g., "50KB", "1.5MB")
|
|
2084
|
-
DEFAULT_MAX_BYTES, // 50KB
|
|
2085
|
-
DEFAULT_MAX_LINES, // 2000
|
|
2086
|
-
} from "@draht/coding-agent";
|
|
2087
|
-
|
|
2088
|
-
async execute(toolCallId, params, signal, onUpdate, ctx) {
|
|
2089
|
-
const output = await runCommand();
|
|
2090
|
-
|
|
2091
|
-
// Apply truncation
|
|
2092
|
-
const truncation = truncateHead(output, {
|
|
2093
|
-
maxLines: DEFAULT_MAX_LINES,
|
|
2094
|
-
maxBytes: DEFAULT_MAX_BYTES,
|
|
2095
|
-
});
|
|
2096
|
-
|
|
2097
|
-
let result = truncation.content;
|
|
2098
|
-
|
|
2099
|
-
if (truncation.truncated) {
|
|
2100
|
-
// Write full output to temp file
|
|
2101
|
-
const tempFile = writeTempFile(output);
|
|
2102
|
-
|
|
2103
|
-
// Inform the LLM where to find complete output
|
|
2104
|
-
result += `\n\n[Output truncated: ${truncation.outputLines} of ${truncation.totalLines} lines`;
|
|
2105
|
-
result += ` (${formatSize(truncation.outputBytes)} of ${formatSize(truncation.totalBytes)}).`;
|
|
2106
|
-
result += ` Full output saved to: ${tempFile}]`;
|
|
2107
|
-
}
|
|
2108
|
-
|
|
2109
|
-
return { content: [{ type: "text", text: result }] };
|
|
2110
|
-
}
|
|
2111
|
-
```
|
|
2112
|
-
|
|
2113
|
-
**Key points:**
|
|
2114
|
-
- Use `truncateHead` for content where the beginning matters (search results, file reads)
|
|
2115
|
-
- Use `truncateTail` for content where the end matters (logs, command output)
|
|
2116
|
-
- Always inform the LLM when output is truncated and where to find the full version
|
|
2117
|
-
- Document the truncation limits in your tool's description
|
|
2118
|
-
|
|
2119
|
-
See [examples/extensions/truncated-tool.ts](../examples/extensions/truncated-tool.ts) for a complete example wrapping `rg` (ripgrep) with proper truncation.
|
|
2120
|
-
|
|
2121
|
-
### Multiple Tools
|
|
2122
|
-
|
|
2123
|
-
One extension can register multiple tools with shared state:
|
|
2124
|
-
|
|
2125
|
-
```typescript
|
|
2126
|
-
export default function (pi: ExtensionAPI) {
|
|
2127
|
-
let connection = null;
|
|
2128
|
-
|
|
2129
|
-
pi.registerTool({ name: "db_connect", ... });
|
|
2130
|
-
pi.registerTool({ name: "db_query", ... });
|
|
2131
|
-
pi.registerTool({ name: "db_close", ... });
|
|
2132
|
-
|
|
2133
|
-
pi.on("session_shutdown", async () => {
|
|
2134
|
-
connection?.close();
|
|
2135
|
-
});
|
|
2136
|
-
}
|
|
2137
|
-
```
|
|
2138
|
-
|
|
2139
|
-
### Custom Rendering
|
|
2140
|
-
|
|
2141
|
-
Tools can provide `renderCall` and `renderResult` for custom TUI display. See [tui.md](tui.md) for the full component API and [tool-execution.ts](https://github.com/draht-dev/draht/blob/main/packages/coding-agent/src/modes/interactive/components/tool-execution.ts) for how tool rows are composed.
|
|
2142
|
-
|
|
2143
|
-
By default, tool output is wrapped in a `Box` that handles padding and background. A defined `renderCall` or `renderResult` must return a `Component`. If a slot renderer is not defined, `tool-execution.ts` uses fallback rendering for that slot.
|
|
2144
|
-
|
|
2145
|
-
Set `renderShell: "self"` when the tool should render its own shell instead of using the default `Box`. This is useful for tools that need complete control over framing or background behavior, for example large previews that must stay visually stable after the tool settles.
|
|
2146
|
-
|
|
2147
|
-
```typescript
|
|
2148
|
-
pi.registerTool({
|
|
2149
|
-
name: "my_tool",
|
|
2150
|
-
label: "My Tool",
|
|
2151
|
-
description: "Custom shell example",
|
|
2152
|
-
parameters: Type.Object({}),
|
|
2153
|
-
renderShell: "self",
|
|
2154
|
-
async execute() {
|
|
2155
|
-
return { content: [{ type: "text", text: "ok" }], details: undefined };
|
|
2156
|
-
},
|
|
2157
|
-
renderCall(args, theme, context) {
|
|
2158
|
-
return new Text(theme.fg("accent", "my custom shell"), 0, 0);
|
|
2159
|
-
},
|
|
2160
|
-
});
|
|
2161
|
-
```
|
|
2162
|
-
|
|
2163
|
-
`renderCall` and `renderResult` each receive a `context` object with:
|
|
2164
|
-
- `args` - the current tool call arguments
|
|
2165
|
-
- `state` - shared row-local state across `renderCall` and `renderResult`
|
|
2166
|
-
- `lastComponent` - the previously returned component for that slot, if any
|
|
2167
|
-
- `invalidate()` - request a rerender of this tool row
|
|
2168
|
-
- `toolCallId`, `cwd`, `executionStarted`, `argsComplete`, `isPartial`, `expanded`, `showImages`, `isError`
|
|
2169
|
-
|
|
2170
|
-
Use `context.state` for cross-slot shared state. Keep slot-local caches on the returned component instance when you want to reuse and mutate the same component across renders.
|
|
2171
|
-
|
|
2172
|
-
#### renderCall
|
|
2173
|
-
|
|
2174
|
-
Renders the tool call or header:
|
|
2175
|
-
|
|
2176
|
-
```typescript
|
|
2177
|
-
import { Text } from "@draht/tui";
|
|
2178
|
-
|
|
2179
|
-
renderCall(args, theme, context) {
|
|
2180
|
-
const text = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
|
|
2181
|
-
let content = theme.fg("toolTitle", theme.bold("my_tool "));
|
|
2182
|
-
content += theme.fg("muted", args.action);
|
|
2183
|
-
if (args.text) {
|
|
2184
|
-
content += " " + theme.fg("dim", `"${args.text}"`);
|
|
2185
|
-
}
|
|
2186
|
-
text.setText(content);
|
|
2187
|
-
return text;
|
|
2188
|
-
}
|
|
2189
|
-
```
|
|
2190
|
-
|
|
2191
|
-
#### renderResult
|
|
2192
|
-
|
|
2193
|
-
Renders the tool result or output:
|
|
2194
|
-
|
|
2195
|
-
```typescript
|
|
2196
|
-
renderResult(result, { expanded, isPartial }, theme, context) {
|
|
2197
|
-
if (isPartial) {
|
|
2198
|
-
return new Text(theme.fg("warning", "Processing..."), 0, 0);
|
|
2199
|
-
}
|
|
2200
|
-
|
|
2201
|
-
if (result.details?.error) {
|
|
2202
|
-
return new Text(theme.fg("error", `Error: ${result.details.error}`), 0, 0);
|
|
2203
|
-
}
|
|
2204
|
-
|
|
2205
|
-
let text = theme.fg("success", "✓ Done");
|
|
2206
|
-
if (expanded && result.details?.items) {
|
|
2207
|
-
for (const item of result.details.items) {
|
|
2208
|
-
text += "\n " + theme.fg("dim", item);
|
|
2209
|
-
}
|
|
2210
|
-
}
|
|
2211
|
-
return new Text(text, 0, 0);
|
|
2212
|
-
}
|
|
2213
|
-
```
|
|
2214
|
-
|
|
2215
|
-
If a slot intentionally has no visible content, return an empty `Component` such as an empty `Container`.
|
|
2216
|
-
|
|
2217
|
-
#### Keybinding Hints
|
|
2218
|
-
|
|
2219
|
-
Use `keyHint()` to display keybinding hints that respect the active keybinding configuration:
|
|
2220
|
-
|
|
2221
|
-
```typescript
|
|
2222
|
-
import { keyHint } from "@draht/coding-agent";
|
|
2223
|
-
|
|
2224
|
-
renderResult(result, { expanded }, theme, context) {
|
|
2225
|
-
let text = theme.fg("success", "✓ Done");
|
|
2226
|
-
if (!expanded) {
|
|
2227
|
-
text += ` (${keyHint("app.tools.expand", "to expand")})`;
|
|
2228
|
-
}
|
|
2229
|
-
return new Text(text, 0, 0);
|
|
2230
|
-
}
|
|
2231
|
-
```
|
|
2232
|
-
|
|
2233
|
-
Available functions:
|
|
2234
|
-
- `keyHint(keybinding, description)` - Formats a configured keybinding id such as `"app.tools.expand"` or `"tui.select.confirm"`
|
|
2235
|
-
- `keyText(keybinding)` - Returns the raw configured key text for a keybinding id
|
|
2236
|
-
- `rawKeyHint(key, description)` - Format a raw key string
|
|
2237
|
-
|
|
2238
|
-
Use namespaced keybinding ids:
|
|
2239
|
-
- Coding-agent ids use the `app.*` namespace, for example `app.tools.expand`, `app.editor.external`, `app.session.rename`
|
|
2240
|
-
- Shared TUI ids use the `tui.*` namespace, for example `tui.select.confirm`, `tui.select.cancel`, `tui.input.tab`
|
|
2241
|
-
|
|
2242
|
-
For the exhaustive list of keybinding ids and defaults, see [keybindings.md](keybindings.md). `keybindings.json` uses those same namespaced ids.
|
|
2243
|
-
|
|
2244
|
-
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()`.
|
|
2245
|
-
|
|
2246
|
-
#### Best Practices
|
|
2247
|
-
|
|
2248
|
-
- Use `Text` with padding `(0, 0)`. The default Box handles padding.
|
|
2249
|
-
- Use `\n` for multi-line content.
|
|
2250
|
-
- Handle `isPartial` for streaming progress.
|
|
2251
|
-
- Support `expanded` for detail on demand.
|
|
2252
|
-
- Keep default view compact.
|
|
2253
|
-
- Read `context.args` in `renderResult` instead of copying args into `context.state`.
|
|
2254
|
-
- Use `context.state` only for data that must be shared across call and result slots.
|
|
2255
|
-
- Reuse `context.lastComponent` when the same component instance can be updated in place.
|
|
2256
|
-
- 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.
|
|
2257
|
-
|
|
2258
|
-
#### Fallback
|
|
2259
|
-
|
|
2260
|
-
If a slot renderer is not defined or throws:
|
|
2261
|
-
- `renderCall`: Shows the tool name
|
|
2262
|
-
- `renderResult`: Shows raw text from `content`
|
|
2263
|
-
|
|
2264
|
-
### Dynamic Tool Loading
|
|
2265
|
-
|
|
2266
|
-
Extensions can register many tools while keeping only a small initial set active. A tool can then add more tools with `pi.setActiveTools()` during execution. draht detects purely additive changes, records the newly available tool names on that tool result, and applies the updated active set before the next model request.
|
|
2267
|
-
|
|
2268
|
-
This works with every model. Models with native deferred-loading support preserve the stable prompt prefix and load the new definitions at the tool-result position. Other models use the fallback described below.
|
|
2269
|
-
|
|
2270
|
-
The lifecycle is:
|
|
2271
|
-
|
|
2272
|
-
1. Register every tool with `pi.registerTool()` so it appears in `pi.getAllTools()`.
|
|
2273
|
-
2. Keep loader tools, such as `search_tools`, active and leave searchable tools inactive.
|
|
2274
|
-
3. During loader execution, call `pi.setActiveTools([...currentTools, ...matchingTools])`. The change must be additive: do not remove currently active tools in the same call.
|
|
2275
|
-
4. draht records which tools were added on the loader's tool result.
|
|
2276
|
-
5. Before the next model response, draht exposes the added definitions using native deferred loading when supported, or the normal active tool list otherwise.
|
|
2277
|
-
|
|
2278
|
-
You do not need to return provider-specific tool references or mark the loader as a special search tool. The active-tool change is the signal. Names passed to `pi.setActiveTools()` must already be registered; unknown names are ignored.
|
|
2279
|
-
|
|
2280
|
-
#### Models with native deferred loading
|
|
2281
|
-
|
|
2282
|
-
- **Anthropic**
|
|
2283
|
-
- **Models:** Sonnet, Opus, Fable version 4.5 or newer (without Haiku)
|
|
2284
|
-
- **Native representation:** Deferred definitions use `defer_loading`; the load point uses `tool_reference` content.
|
|
2285
|
-
- **OpenAI**
|
|
2286
|
-
- **Models:** `gpt-5.4` and newer family
|
|
2287
|
-
- **Native representation:** draht adds completed client `tool_search_call` and `tool_search_output` items at the load point.
|
|
2288
|
-
|
|
2289
|
-
For a verified custom model or proxy, native handling can be enabled with `compat.supportsToolReferences: true` for `anthropic-messages`, or `compat.supportsToolSearch: true` for `openai-responses` and `openai-codex-responses`. Leave these disabled unless the endpoint and model accept the corresponding native protocol.
|
|
2290
|
-
|
|
2291
|
-
#### Fallback behavior
|
|
2292
|
-
|
|
2293
|
-
For all other models and providers, dynamic activation still works: draht sends the complete current active tool list normally on the next request. The model can call the newly activated tools, but adding their definitions may invalidate the provider's cached prompt prefix.
|
|
2294
|
-
|
|
2295
|
-
draht also uses this safe fallback when the active set is not purely additive, such as replacing one group of tools with another. Tool removals therefore work, but they do not use deferred loading.
|
|
2296
|
-
|
|
2297
|
-
For the best cache behavior, keep the loader tool active for the whole session and add tools instead of replacing the active set. Also note that activating a tool with `promptSnippet` or `promptGuidelines` rebuilds the system prompt; that system-prompt change can invalidate the prefix even when the provider supports deferred schemas. Lazily loaded tools should usually rely on their tool `description` and omit active-only prompt metadata.
|
|
2298
|
-
|
|
2299
|
-
#### Search tool example
|
|
2300
|
-
|
|
2301
|
-
The following extension registers two searchable tools, removes them from the initial active set, and keeps only `search_tools` as their loader. The example uses simple keyword matching, but the search implementation could use BM25, embeddings, a remote catalog, or project-specific routing.
|
|
2302
|
-
|
|
2303
|
-
```typescript
|
|
2304
|
-
import type { ExtensionAPI } from "@draht/coding-agent";
|
|
2305
|
-
import { Type } from "typebox";
|
|
2306
|
-
|
|
2307
|
-
const SEARCHABLE_TOOL_NAMES = new Set(["lookup_weather", "search_issues"]);
|
|
2308
|
-
|
|
2309
|
-
export default function (pi: ExtensionAPI) {
|
|
2310
|
-
pi.registerTool({
|
|
2311
|
-
name: "lookup_weather",
|
|
2312
|
-
label: "Lookup Weather",
|
|
2313
|
-
description: "Look up the current weather for a city",
|
|
2314
|
-
parameters: Type.Object({ city: Type.String() }),
|
|
2315
|
-
async execute(_toolCallId, params) {
|
|
2316
|
-
return {
|
|
2317
|
-
content: [{ type: "text", text: `Weather for ${params.city}: sunny` }],
|
|
2318
|
-
details: {},
|
|
2319
|
-
};
|
|
2320
|
-
},
|
|
2321
|
-
});
|
|
2322
|
-
|
|
2323
|
-
pi.registerTool({
|
|
2324
|
-
name: "search_issues",
|
|
2325
|
-
label: "Search Issues",
|
|
2326
|
-
description: "Search project issues by keyword",
|
|
2327
|
-
parameters: Type.Object({ query: Type.String() }),
|
|
2328
|
-
async execute(_toolCallId, params) {
|
|
2329
|
-
return {
|
|
2330
|
-
content: [{ type: "text", text: `No open issues matching ${params.query}` }],
|
|
2331
|
-
details: {},
|
|
2332
|
-
};
|
|
2333
|
-
},
|
|
2334
|
-
});
|
|
2335
|
-
|
|
2336
|
-
pi.registerTool({
|
|
2337
|
-
name: "search_tools",
|
|
2338
|
-
label: "Search Tools",
|
|
2339
|
-
description: "Search for and enable tools relevant to a task",
|
|
2340
|
-
promptSnippet: "Search for additional tools when the active tools cannot perform the task",
|
|
2341
|
-
promptGuidelines: [
|
|
2342
|
-
"Use search_tools when a task requires a capability that is not currently available.",
|
|
2343
|
-
],
|
|
2344
|
-
parameters: Type.Object({
|
|
2345
|
-
query: Type.String({ description: "Capability or task to search for" }),
|
|
2346
|
-
limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 10 })),
|
|
2347
|
-
}),
|
|
2348
|
-
async execute(_toolCallId, params) {
|
|
2349
|
-
const terms = params.query.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
|
|
2350
|
-
const matches = pi.getAllTools()
|
|
2351
|
-
.filter((tool) => SEARCHABLE_TOOL_NAMES.has(tool.name))
|
|
2352
|
-
.map((tool) => ({
|
|
2353
|
-
tool,
|
|
2354
|
-
score: terms.reduce(
|
|
2355
|
-
(score, term) =>
|
|
2356
|
-
score + (`${tool.name} ${tool.description}`.toLowerCase().includes(term) ? 1 : 0),
|
|
2357
|
-
0,
|
|
2358
|
-
),
|
|
2359
|
-
}))
|
|
2360
|
-
.filter((match) => match.score > 0)
|
|
2361
|
-
.sort((a, b) => b.score - a.score)
|
|
2362
|
-
.slice(0, params.limit ?? 3)
|
|
2363
|
-
.map((match) => match.tool.name);
|
|
2364
|
-
|
|
2365
|
-
if (matches.length === 0) {
|
|
2366
|
-
return {
|
|
2367
|
-
content: [{ type: "text", text: `No tools found for: ${params.query}` }],
|
|
2368
|
-
details: { matches: [] },
|
|
2369
|
-
};
|
|
2370
|
-
}
|
|
2371
|
-
|
|
2372
|
-
const active = pi.getActiveTools();
|
|
2373
|
-
const added = matches.filter((name) => !active.includes(name));
|
|
2374
|
-
pi.setActiveTools([...new Set([...active, ...added])]);
|
|
2375
|
-
|
|
2376
|
-
return {
|
|
2377
|
-
content: [{
|
|
2378
|
-
type: "text",
|
|
2379
|
-
text: added.length > 0
|
|
2380
|
-
? `Loaded tools: ${added.join(", ")}`
|
|
2381
|
-
: `Matching tools already active: ${matches.join(", ")}`,
|
|
2382
|
-
}],
|
|
2383
|
-
details: { matches, added },
|
|
2384
|
-
};
|
|
2385
|
-
},
|
|
2386
|
-
});
|
|
2387
|
-
|
|
2388
|
-
pi.on("session_start", () => {
|
|
2389
|
-
// Keep searchable tools registered but initially inactive. Preserve built-ins
|
|
2390
|
-
// and tools owned by other extensions, and keep the loader itself active.
|
|
2391
|
-
const initialTools = pi.getActiveTools().filter(
|
|
2392
|
-
(name) => !SEARCHABLE_TOOL_NAMES.has(name),
|
|
2393
|
-
);
|
|
2394
|
-
pi.setActiveTools([...new Set([...initialTools, "search_tools"])]);
|
|
2395
|
-
});
|
|
2396
|
-
}
|
|
2397
|
-
```
|
|
2398
|
-
|
|
2399
|
-
When `search_tools` adds a match, the model receives that definition on the immediately following request. On a native-capable model the definition is anchored after the search result without changing the initial tool-schema prefix. On other models it appears in the normal tool list on that same following request.
|
|
2400
|
-
|
|
2401
|
-
## Custom UI
|
|
2402
|
-
|
|
2403
|
-
Extensions can interact with users via `ctx.ui` methods and customize how messages/tools render.
|
|
2404
|
-
|
|
2405
|
-
**For custom components, see [tui.md](tui.md)** which has copy-paste patterns for:
|
|
2406
|
-
- Selection dialogs (SelectList)
|
|
2407
|
-
- Async operations with cancel (BorderedLoader)
|
|
2408
|
-
- Settings toggles (SettingsList)
|
|
2409
|
-
- Status indicators (setStatus)
|
|
2410
|
-
- Working message, visibility, and indicator during streaming (`setWorkingMessage`, `setWorkingVisible`, `setWorkingIndicator`)
|
|
2411
|
-
- Widgets above/below editor (setWidget)
|
|
2412
|
-
- Autocomplete providers layered on top of built-in slash/path completion (addAutocompleteProvider)
|
|
2413
|
-
- Custom footers (setFooter)
|
|
2414
|
-
|
|
2415
|
-
### Dialogs
|
|
2416
|
-
|
|
2417
|
-
```typescript
|
|
2418
|
-
// Select from options
|
|
2419
|
-
const choice = await ctx.ui.select("Pick one:", ["A", "B", "C"]);
|
|
2420
|
-
|
|
2421
|
-
// Confirm dialog
|
|
2422
|
-
const ok = await ctx.ui.confirm("Delete?", "This cannot be undone");
|
|
2423
|
-
|
|
2424
|
-
// Text input
|
|
2425
|
-
const name = await ctx.ui.input("Name:", "placeholder");
|
|
2426
|
-
|
|
2427
|
-
// Multi-line editor
|
|
2428
|
-
const text = await ctx.ui.editor("Edit:", "prefilled text");
|
|
2429
|
-
|
|
2430
|
-
// Notification (non-blocking)
|
|
2431
|
-
ctx.ui.notify("Done!", "info"); // "info" | "warning" | "error"
|
|
2432
|
-
```
|
|
2433
|
-
|
|
2434
|
-
#### Timed Dialogs with Countdown
|
|
2435
|
-
|
|
2436
|
-
Dialogs support a `timeout` option that auto-dismisses with a live countdown display:
|
|
2437
|
-
|
|
2438
|
-
```typescript
|
|
2439
|
-
// Dialog shows "Title (5s)" → "Title (4s)" → ... → auto-dismisses at 0
|
|
2440
|
-
const confirmed = await ctx.ui.confirm(
|
|
2441
|
-
"Timed Confirmation",
|
|
2442
|
-
"This dialog will auto-cancel in 5 seconds. Confirm?",
|
|
2443
|
-
{ timeout: 5000 }
|
|
2444
|
-
);
|
|
2445
|
-
|
|
2446
|
-
if (confirmed) {
|
|
2447
|
-
// User confirmed
|
|
2448
|
-
} else {
|
|
2449
|
-
// User cancelled or timed out
|
|
2450
|
-
}
|
|
2451
|
-
```
|
|
2452
|
-
|
|
2453
|
-
**Return values on timeout:**
|
|
2454
|
-
- `select()` returns `undefined`
|
|
2455
|
-
- `confirm()` returns `false`
|
|
2456
|
-
- `input()` returns `undefined`
|
|
2457
|
-
|
|
2458
|
-
#### Manual Dismissal with AbortSignal
|
|
2459
|
-
|
|
2460
|
-
For more control (e.g., to distinguish timeout from user cancel), use `AbortSignal`:
|
|
2461
|
-
|
|
2462
|
-
```typescript
|
|
2463
|
-
const controller = new AbortController();
|
|
2464
|
-
const timeoutId = setTimeout(() => controller.abort(), 5000);
|
|
2465
|
-
|
|
2466
|
-
const confirmed = await ctx.ui.confirm(
|
|
2467
|
-
"Timed Confirmation",
|
|
2468
|
-
"This dialog will auto-cancel in 5 seconds. Confirm?",
|
|
2469
|
-
{ signal: controller.signal }
|
|
2470
|
-
);
|
|
2471
|
-
|
|
2472
|
-
clearTimeout(timeoutId);
|
|
2473
|
-
|
|
2474
|
-
if (confirmed) {
|
|
2475
|
-
// User confirmed
|
|
2476
|
-
} else if (controller.signal.aborted) {
|
|
2477
|
-
// Dialog timed out
|
|
2478
|
-
} else {
|
|
2479
|
-
// User cancelled (pressed Escape or selected "No")
|
|
2480
|
-
}
|
|
2481
|
-
```
|
|
2482
|
-
|
|
2483
|
-
See [examples/extensions/timed-confirm.ts](../examples/extensions/timed-confirm.ts) for complete examples.
|
|
2484
|
-
|
|
2485
|
-
### Widgets, Status, and Footer
|
|
2486
|
-
|
|
2487
|
-
```typescript
|
|
2488
|
-
// Status in footer (persistent until cleared)
|
|
2489
|
-
ctx.ui.setStatus("my-ext", "Processing...");
|
|
2490
|
-
ctx.ui.setStatus("my-ext", undefined); // Clear
|
|
2491
|
-
|
|
2492
|
-
// Working loader (shown during streaming)
|
|
2493
|
-
ctx.ui.setWorkingMessage("Thinking deeply...");
|
|
2494
|
-
ctx.ui.setWorkingMessage(); // Restore default
|
|
2495
|
-
ctx.ui.setWorkingVisible(false); // Hide the built-in working loader row entirely
|
|
2496
|
-
ctx.ui.setWorkingVisible(true); // Show the built-in working loader row
|
|
2497
|
-
|
|
2498
|
-
// Working indicator (shown during streaming)
|
|
2499
|
-
ctx.ui.setWorkingIndicator({ frames: [ctx.ui.theme.fg("accent", "●")] }); // Static dot
|
|
2500
|
-
ctx.ui.setWorkingIndicator({
|
|
2501
|
-
frames: [
|
|
2502
|
-
ctx.ui.theme.fg("dim", "·"),
|
|
2503
|
-
ctx.ui.theme.fg("muted", "•"),
|
|
2504
|
-
ctx.ui.theme.fg("accent", "●"),
|
|
2505
|
-
ctx.ui.theme.fg("muted", "•"),
|
|
2506
|
-
],
|
|
2507
|
-
intervalMs: 120,
|
|
2508
|
-
});
|
|
2509
|
-
ctx.ui.setWorkingIndicator({ frames: [] }); // Hide indicator
|
|
2510
|
-
ctx.ui.setWorkingIndicator(); // Restore default spinner
|
|
2511
|
-
|
|
2512
|
-
// Widget above editor (default)
|
|
2513
|
-
ctx.ui.setWidget("my-widget", ["Line 1", "Line 2"]);
|
|
2514
|
-
// Widget below editor
|
|
2515
|
-
ctx.ui.setWidget("my-widget", ["Line 1", "Line 2"], { placement: "belowEditor" });
|
|
2516
|
-
ctx.ui.setWidget("my-widget", (tui, theme) => new Text(theme.fg("accent", "Custom"), 0, 0));
|
|
2517
|
-
ctx.ui.setWidget("my-widget", undefined); // Clear
|
|
2518
|
-
|
|
2519
|
-
// Custom footer (replaces built-in footer entirely)
|
|
2520
|
-
ctx.ui.setFooter((tui, theme) => ({
|
|
2521
|
-
render(width) { return [theme.fg("dim", "Custom footer")]; },
|
|
2522
|
-
invalidate() {},
|
|
2523
|
-
}));
|
|
2524
|
-
ctx.ui.setFooter(undefined); // Restore built-in footer
|
|
2525
|
-
|
|
2526
|
-
// Terminal title
|
|
2527
|
-
ctx.ui.setTitle("draht - my-project");
|
|
2528
|
-
|
|
2529
|
-
// Editor text
|
|
2530
|
-
ctx.ui.setEditorText("Prefill text");
|
|
2531
|
-
const current = ctx.ui.getEditorText();
|
|
2532
|
-
|
|
2533
|
-
// Paste into editor (triggers paste handling, including collapse for large content)
|
|
2534
|
-
ctx.ui.pasteToEditor("pasted content");
|
|
2535
|
-
|
|
2536
|
-
// Stack custom autocomplete behavior on top of the built-in provider
|
|
2537
|
-
ctx.ui.addAutocompleteProvider((current) => ({
|
|
2538
|
-
triggerCharacters: ["#"],
|
|
2539
|
-
async getSuggestions(lines, line, col, options) {
|
|
2540
|
-
const beforeCursor = (lines[line] ?? "").slice(0, col);
|
|
2541
|
-
const match = beforeCursor.match(/(?:^|[ \t])#([^\s#]*)$/);
|
|
2542
|
-
if (!match) {
|
|
2543
|
-
return current.getSuggestions(lines, line, col, options);
|
|
2544
|
-
}
|
|
2545
|
-
|
|
2546
|
-
return {
|
|
2547
|
-
prefix: `#${match[1] ?? ""}`,
|
|
2548
|
-
items: [{ value: "#2983", label: "#2983", description: "Extension API for autocomplete" }],
|
|
2549
|
-
};
|
|
2550
|
-
},
|
|
2551
|
-
applyCompletion(lines, line, col, item, prefix) {
|
|
2552
|
-
return current.applyCompletion(lines, line, col, item, prefix);
|
|
2553
|
-
},
|
|
2554
|
-
shouldTriggerFileCompletion(lines, line, col) {
|
|
2555
|
-
return current.shouldTriggerFileCompletion?.(lines, line, col) ?? true;
|
|
2556
|
-
},
|
|
2557
|
-
}));
|
|
2558
|
-
|
|
2559
|
-
// Tool output expansion
|
|
2560
|
-
const wasExpanded = ctx.ui.getToolsExpanded();
|
|
2561
|
-
ctx.ui.setToolsExpanded(true);
|
|
2562
|
-
ctx.ui.setToolsExpanded(wasExpanded);
|
|
2563
|
-
|
|
2564
|
-
// Custom editor (vim mode, emacs mode, etc.)
|
|
2565
|
-
ctx.ui.setEditorComponent((tui, theme, keybindings) => new VimEditor(tui, theme, keybindings));
|
|
2566
|
-
const currentEditor = ctx.ui.getEditorComponent();
|
|
2567
|
-
ctx.ui.setEditorComponent((tui, theme, keybindings) =>
|
|
2568
|
-
new WrappedEditor(tui, theme, keybindings, currentEditor?.(tui, theme, keybindings))
|
|
2569
|
-
);
|
|
2570
|
-
ctx.ui.setEditorComponent(undefined); // Restore default editor
|
|
2571
|
-
|
|
2572
|
-
// Theme management (see themes.md for creating themes)
|
|
2573
|
-
const themes = ctx.ui.getAllThemes(); // [{ name: "dark", path: "/..." | undefined }, ...]
|
|
2574
|
-
const lightTheme = ctx.ui.getTheme("light"); // Load without switching
|
|
2575
|
-
const result = ctx.ui.setTheme("light"); // Switch by name
|
|
2576
|
-
if (!result.success) {
|
|
2577
|
-
ctx.ui.notify(`Failed: ${result.error}`, "error");
|
|
2578
|
-
}
|
|
2579
|
-
ctx.ui.setTheme(lightTheme!); // Or switch by Theme object
|
|
2580
|
-
ctx.ui.theme.fg("accent", "styled text"); // Access current theme
|
|
2581
|
-
```
|
|
2582
|
-
|
|
2583
|
-
Custom working-indicator frames are rendered verbatim. If you want colors, add them to the frame strings yourself, for example with `ctx.ui.theme.fg(...)`.
|
|
2584
|
-
|
|
2585
|
-
### Autocomplete Providers
|
|
2586
|
-
|
|
2587
|
-
Use `ctx.ui.addAutocompleteProvider()` to stack custom autocomplete logic on top of the built-in slash-command and path provider. Set `triggerCharacters` for custom natural triggers such as `$`.
|
|
2588
|
-
|
|
2589
|
-
Typical pattern:
|
|
2590
|
-
|
|
2591
|
-
- inspect the text before the cursor
|
|
2592
|
-
- return your own suggestions when your extension-specific syntax matches
|
|
2593
|
-
- otherwise delegate to `current.getSuggestions(...)`
|
|
2594
|
-
- delegate `applyCompletion(...)` unless you need custom insertion behavior
|
|
2595
|
-
|
|
2596
|
-
```typescript
|
|
2597
|
-
pi.on("session_start", (_event, ctx) => {
|
|
2598
|
-
ctx.ui.addAutocompleteProvider((current) => ({
|
|
2599
|
-
triggerCharacters: ["#"],
|
|
2600
|
-
async getSuggestions(lines, cursorLine, cursorCol, options) {
|
|
2601
|
-
const line = lines[cursorLine] ?? "";
|
|
2602
|
-
const beforeCursor = line.slice(0, cursorCol);
|
|
2603
|
-
const match = beforeCursor.match(/(?:^|[ \t])#([^\s#]*)$/);
|
|
2604
|
-
if (!match) {
|
|
2605
|
-
return current.getSuggestions(lines, cursorLine, cursorCol, options);
|
|
2606
|
-
}
|
|
2607
|
-
|
|
2608
|
-
return {
|
|
2609
|
-
prefix: `#${match[1] ?? ""}`,
|
|
2610
|
-
items: [
|
|
2611
|
-
{ value: "#2983", label: "#2983", description: "Extension API for registering custom @ autocomplete providers" },
|
|
2612
|
-
{ value: "#2753", label: "#2753", description: "Reload stale resource settings" },
|
|
2613
|
-
],
|
|
2614
|
-
};
|
|
2615
|
-
},
|
|
2616
|
-
|
|
2617
|
-
applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
|
|
2618
|
-
return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
|
|
2619
|
-
},
|
|
2620
|
-
|
|
2621
|
-
shouldTriggerFileCompletion(lines, cursorLine, cursorCol) {
|
|
2622
|
-
return current.shouldTriggerFileCompletion?.(lines, cursorLine, cursorCol) ?? true;
|
|
2623
|
-
},
|
|
2624
|
-
}));
|
|
2625
|
-
});
|
|
2626
|
-
```
|
|
2627
|
-
|
|
2628
|
-
See [github-issue-autocomplete.ts](../examples/extensions/github-issue-autocomplete.ts) for a complete example that preloads the latest open GitHub issues with `gh issue list` and filters them locally for fast `#...` completion. It requires GitHub CLI (`gh`) and a GitHub repository checkout.
|
|
2629
|
-
|
|
2630
|
-
### Custom Components
|
|
2631
|
-
|
|
2632
|
-
For complex UI, use `ctx.ui.custom()`. This temporarily replaces the editor with your component until `done()` is called:
|
|
2633
|
-
|
|
2634
|
-
```typescript
|
|
2635
|
-
import { Text, Component } from "@draht/tui";
|
|
2636
|
-
|
|
2637
|
-
const result = await ctx.ui.custom<boolean>((tui, theme, keybindings, done) => {
|
|
2638
|
-
const text = new Text("Press Enter to confirm, Escape to cancel", 1, 1);
|
|
2639
|
-
|
|
2640
|
-
text.onKey = (key) => {
|
|
2641
|
-
if (key === "return") done(true);
|
|
2642
|
-
if (key === "escape") done(false);
|
|
2643
|
-
return true;
|
|
2644
|
-
};
|
|
2645
|
-
|
|
2646
|
-
return text;
|
|
2647
|
-
});
|
|
2648
|
-
|
|
2649
|
-
if (result) {
|
|
2650
|
-
// User pressed Enter
|
|
2651
|
-
}
|
|
2652
|
-
```
|
|
2653
|
-
|
|
2654
|
-
The callback receives:
|
|
2655
|
-
- `tui` - TUI instance (for screen dimensions, focus management)
|
|
2656
|
-
- `theme` - Current theme for styling
|
|
2657
|
-
- `keybindings` - App keybinding manager (for checking shortcuts)
|
|
2658
|
-
- `done(value)` - Call to close component and return value
|
|
2659
|
-
|
|
2660
|
-
See [tui.md](tui.md) for the full component API.
|
|
2661
|
-
|
|
2662
|
-
#### Overlay Mode (Experimental)
|
|
2663
|
-
|
|
2664
|
-
Pass `{ overlay: true }` to render the component as a floating modal on top of existing content, without clearing the screen:
|
|
2665
|
-
|
|
2666
|
-
```typescript
|
|
2667
|
-
const result = await ctx.ui.custom<string | null>(
|
|
2668
|
-
(tui, theme, keybindings, done) => new MyOverlayComponent({ onClose: done }),
|
|
2669
|
-
{ overlay: true }
|
|
2670
|
-
);
|
|
2671
|
-
```
|
|
2672
|
-
|
|
2673
|
-
For advanced positioning (anchors, margins, percentages, responsive visibility), pass `overlayOptions`. Use `onHandle` to control focus or visibility programmatically:
|
|
2674
|
-
|
|
2675
|
-
```typescript
|
|
2676
|
-
const result = await ctx.ui.custom<string | null>(
|
|
2677
|
-
(tui, theme, keybindings, done) => new MyOverlayComponent({ onClose: done }),
|
|
2678
|
-
{
|
|
2679
|
-
overlay: true,
|
|
2680
|
-
overlayOptions: { anchor: "top-right", width: "50%", margin: 2 },
|
|
2681
|
-
onHandle: (handle) => {
|
|
2682
|
-
handle.focus(); // focus this overlay and bring it to the visual front
|
|
2683
|
-
// handle.unfocus({ target: editorComponent }); // release input to a specific component
|
|
2684
|
-
// handle.setHidden(true/false); // toggle visibility
|
|
2685
|
-
// handle.hide(); // permanently remove
|
|
2686
|
-
}
|
|
2687
|
-
}
|
|
2688
|
-
);
|
|
2689
|
-
```
|
|
2690
|
-
|
|
2691
|
-
A focused visible overlay can reclaim input after temporary non-overlay custom UI closes. If you intentionally want another component to keep input while the overlay stays visible, call `handle.unfocus({ target })`. Passing `{ target: null }` releases the overlay without focusing another component.
|
|
2692
|
-
|
|
2693
|
-
See [tui.md](tui.md) for the full `OverlayOptions` and `OverlayHandle` API and [overlay-qa-tests.ts](../examples/extensions/overlay-qa-tests.ts) for examples.
|
|
2694
|
-
|
|
2695
|
-
### Custom Editor
|
|
2696
|
-
|
|
2697
|
-
Replace the main input editor with a custom implementation (vim mode, emacs mode, etc.):
|
|
2698
|
-
|
|
2699
|
-
```typescript
|
|
2700
|
-
import { CustomEditor, type ExtensionAPI } from "@draht/coding-agent";
|
|
2701
|
-
import { matchesKey } from "@draht/tui";
|
|
2702
|
-
|
|
2703
|
-
class VimEditor extends CustomEditor {
|
|
2704
|
-
private mode: "normal" | "insert" = "insert";
|
|
2705
|
-
|
|
2706
|
-
handleInput(data: string): void {
|
|
2707
|
-
if (matchesKey(data, "escape") && this.mode === "insert") {
|
|
2708
|
-
this.mode = "normal";
|
|
2709
|
-
return;
|
|
2710
|
-
}
|
|
2711
|
-
if (this.mode === "normal" && data === "i") {
|
|
2712
|
-
this.mode = "insert";
|
|
2713
|
-
return;
|
|
2714
|
-
}
|
|
2715
|
-
super.handleInput(data); // App keybindings + text editing
|
|
2716
|
-
}
|
|
2717
|
-
}
|
|
2718
|
-
|
|
2719
|
-
export default function (pi: ExtensionAPI) {
|
|
2720
|
-
pi.on("session_start", (_event, ctx) => {
|
|
2721
|
-
ctx.ui.setEditorComponent((tui, theme, keybindings) =>
|
|
2722
|
-
new VimEditor(tui, theme, keybindings)
|
|
2723
|
-
);
|
|
2724
|
-
});
|
|
2725
|
-
}
|
|
2726
|
-
```
|
|
2727
|
-
|
|
2728
|
-
**Key points:**
|
|
2729
|
-
- Extend `CustomEditor` (not base `Editor`) to get app keybindings (escape to abort, ctrl+d, model switching)
|
|
2730
|
-
- Call `super.handleInput(data)` for keys you don't handle
|
|
2731
|
-
- Factory receives `tui`, `theme`, and `keybindings` from the app
|
|
2732
|
-
- Use `ctx.ui.getEditorComponent()` before `setEditorComponent()` to wrap the previously configured custom editor
|
|
2733
|
-
- Pass `undefined` to restore default: `ctx.ui.setEditorComponent(undefined)`
|
|
2734
|
-
|
|
2735
|
-
To compose with another extension that already replaced the editor, capture the previous factory before setting yours:
|
|
2736
|
-
|
|
2737
|
-
```typescript
|
|
2738
|
-
const previous = ctx.ui.getEditorComponent();
|
|
2739
|
-
ctx.ui.setEditorComponent((tui, theme, keybindings) =>
|
|
2740
|
-
new MyEditor(tui, theme, keybindings, { base: previous?.(tui, theme, keybindings) })
|
|
2741
|
-
);
|
|
2742
|
-
```
|
|
2743
|
-
|
|
2744
|
-
See [tui.md](tui.md) Pattern 7 for a complete example with mode indicator.
|
|
2745
|
-
|
|
2746
|
-
### Message and Entry Rendering
|
|
2747
|
-
|
|
2748
|
-
Register a custom renderer for messages with your `customType`. Use message renderers for content that should participate in LLM context:
|
|
2749
|
-
|
|
2750
|
-
```typescript
|
|
2751
|
-
import { Text } from "@draht/tui";
|
|
2752
|
-
|
|
2753
|
-
pi.registerMessageRenderer("my-extension", (message, options, theme) => {
|
|
2754
|
-
const { expanded, outputPad } = options;
|
|
2755
|
-
let text = theme.fg("accent", `[${message.customType}] `);
|
|
2756
|
-
text += message.content;
|
|
2757
|
-
|
|
2758
|
-
if (expanded && message.details) {
|
|
2759
|
-
text += "\n" + theme.fg("dim", JSON.stringify(message.details, null, 2));
|
|
2760
|
-
}
|
|
2761
|
-
|
|
2762
|
-
return new Text(text, outputPad, 0);
|
|
2763
|
-
});
|
|
2764
|
-
```
|
|
2765
|
-
|
|
2766
|
-
Messages are sent via `pi.sendMessage()`:
|
|
2767
|
-
|
|
2768
|
-
```typescript
|
|
2769
|
-
pi.sendMessage({
|
|
2770
|
-
customType: "my-extension", // Matches registerMessageRenderer
|
|
2771
|
-
content: "Status update",
|
|
2772
|
-
display: true, // Show in TUI
|
|
2773
|
-
details: { ... }, // Available in renderer
|
|
2774
|
-
});
|
|
2775
|
-
```
|
|
2776
|
-
|
|
2777
|
-
For TUI-only content that should not be sent to the LLM, render custom entries instead:
|
|
2778
|
-
|
|
2779
|
-
```typescript
|
|
2780
|
-
pi.registerEntryRenderer("my-card", (entry, options, theme) => {
|
|
2781
|
-
return new Text(theme.fg("accent", JSON.stringify(entry.data)));
|
|
2782
|
-
});
|
|
2783
|
-
|
|
2784
|
-
pi.appendEntry("my-card", { status: "done" });
|
|
2785
|
-
```
|
|
2786
|
-
|
|
2787
|
-
### Theme Colors
|
|
2788
|
-
|
|
2789
|
-
All render functions receive a `theme` object. See [themes.md](themes.md) for creating custom themes and the full color palette.
|
|
2790
|
-
|
|
2791
|
-
```typescript
|
|
2792
|
-
// Foreground colors
|
|
2793
|
-
theme.fg("toolTitle", text) // Tool names
|
|
2794
|
-
theme.fg("accent", text) // Highlights
|
|
2795
|
-
theme.fg("success", text) // Success (green)
|
|
2796
|
-
theme.fg("error", text) // Errors (red)
|
|
2797
|
-
theme.fg("warning", text) // Warnings (yellow)
|
|
2798
|
-
theme.fg("muted", text) // Secondary text
|
|
2799
|
-
theme.fg("dim", text) // Tertiary text
|
|
2800
|
-
|
|
2801
|
-
// Text styles
|
|
2802
|
-
theme.bold(text)
|
|
2803
|
-
theme.italic(text)
|
|
2804
|
-
theme.strikethrough(text)
|
|
2805
|
-
```
|
|
2806
|
-
|
|
2807
|
-
For syntax highlighting in custom tool renderers:
|
|
2808
|
-
|
|
2809
|
-
```typescript
|
|
2810
|
-
import { highlightCode, getLanguageFromPath } from "@draht/coding-agent";
|
|
2811
|
-
|
|
2812
|
-
// Highlight code with explicit language
|
|
2813
|
-
const highlighted = highlightCode("const x = 1;", "typescript", theme);
|
|
2814
|
-
|
|
2815
|
-
// Auto-detect language from file path
|
|
2816
|
-
const lang = getLanguageFromPath("/path/to/file.rs"); // "rust"
|
|
2817
|
-
const highlighted = highlightCode(code, lang, theme);
|
|
2818
|
-
```
|
|
276
|
+
The checked [extension examples](../examples/extensions/) cover tools, lifecycle events, commands, flags, shortcuts, state, rendering, providers, OAuth, remote execution, and terminal components.
|
|
277
|
+
Start with the smallest example matching your integration point.
|
|
2819
278
|
|
|
2820
|
-
|
|
2821
|
-
|
|
2822
|
-
- Extension errors are logged, agent continues
|
|
2823
|
-
- `tool_call` errors block the tool (fail-safe)
|
|
2824
|
-
- Tool `execute` errors must be signaled by throwing; the thrown error is caught, reported to the LLM with `isError: true`, and execution continues
|
|
2825
|
-
|
|
2826
|
-
## Mode Behavior
|
|
2827
|
-
|
|
2828
|
-
| Mode | `ctx.mode` | `ctx.hasUI` | Notes |
|
|
2829
|
-
|------|------------|-------------|-------|
|
|
2830
|
-
| Interactive | `"tui"` | `true` | Full TUI with terminal rendering |
|
|
2831
|
-
| RPC (`--mode rpc`) | `"rpc"` | `true` | Dialogs and notifications via JSON protocol; `custom()` returns `undefined`. See [rpc.md](rpc.md) |
|
|
2832
|
-
| JSON (`--mode json`) | `"json"` | `false` | Event stream to stdout; UI methods are no-ops |
|
|
2833
|
-
| Print (`-p`) | `"print"` | `false` | Extensions run but can't prompt |
|
|
2834
|
-
|
|
2835
|
-
Use `ctx.mode === "tui"` before TUI-specific features (`custom()`, component factories, terminal input). Use `ctx.hasUI` before dialog and notification methods that work in both TUI and RPC modes.
|
|
2836
|
-
|
|
2837
|
-
## Examples Reference
|
|
2838
|
-
|
|
2839
|
-
All examples in [examples/extensions/](../examples/extensions/).
|
|
2840
|
-
|
|
2841
|
-
| Example | Description | Key APIs |
|
|
2842
|
-
|---------|-------------|----------|
|
|
2843
|
-
| **Tools** |||
|
|
2844
|
-
| `hello.ts` | Minimal tool registration | `registerTool` |
|
|
2845
|
-
| `question.ts` | Tool with user interaction | `registerTool`, `ui.select` |
|
|
2846
|
-
| `questionnaire.ts` | Multi-step wizard tool | `registerTool`, `ui.custom` |
|
|
2847
|
-
| `todo.ts` | Stateful tool with persistence | `registerTool`, `appendEntry`, `renderResult`, session events |
|
|
2848
|
-
| `dynamic-tools.ts` | Register tools after startup and during commands | `registerTool`, `session_start`, `registerCommand` |
|
|
2849
|
-
| `structured-output.ts` | Final structured-output tool with `terminate: true` | `registerTool`, terminating tool results |
|
|
2850
|
-
| `truncated-tool.ts` | Output truncation example | `registerTool`, `truncateHead` |
|
|
2851
|
-
| `tool-override.ts` | Override built-in read tool | `registerTool` (same name as built-in) |
|
|
2852
|
-
| **Commands** |||
|
|
2853
|
-
| `pirate.ts` | Modify system prompt per-turn | `registerCommand`, `before_agent_start` |
|
|
2854
|
-
| `summarize.ts` | Conversation summary command | `registerCommand`, `ui.custom` |
|
|
2855
|
-
| `handoff.ts` | Cross-provider model handoff | `registerCommand`, `ui.editor`, `ui.custom` |
|
|
2856
|
-
| `qna.ts` | Q&A with custom UI | `registerCommand`, `ui.custom`, `setEditorText` |
|
|
2857
|
-
| `send-user-message.ts` | Inject user messages | `registerCommand`, `sendUserMessage` |
|
|
2858
|
-
| `reload-runtime.ts` | Reload command and LLM tool handoff | `registerCommand`, `ctx.reload()`, `sendUserMessage` |
|
|
2859
|
-
| `shutdown-command.ts` | Graceful shutdown command | `registerCommand`, `shutdown()` |
|
|
2860
|
-
| **Events & Gates** |||
|
|
2861
|
-
| `permission-gate.ts` | Block dangerous commands | `on("tool_call")`, `ui.confirm` |
|
|
2862
|
-
| `project-trust.ts` | Decide or defer project trust from a user/global or CLI extension | `on("project_trust")`, trust UI, required trust result |
|
|
2863
|
-
| `protected-paths.ts` | Block writes to specific paths | `on("tool_call")` |
|
|
2864
|
-
| `confirm-destructive.ts` | Confirm session changes | `on("session_before_switch")`, `on("session_before_fork")` |
|
|
2865
|
-
| `dirty-repo-guard.ts` | Warn on dirty git repo | `on("session_before_*")`, `exec` |
|
|
2866
|
-
| `input-transform.ts` | Transform user input | `on("input")` |
|
|
2867
|
-
| `input-transform-streaming.ts` | Streaming-aware input transform | `on("input")`, `streamingBehavior` |
|
|
2868
|
-
| `model-status.ts` | React to model changes | `on("model_select")`, `setStatus` |
|
|
2869
|
-
| `provider-payload.ts` | Inspect payloads and provider response headers | `on("before_provider_request")`, `on("after_provider_response")` |
|
|
2870
|
-
| `system-prompt-header.ts` | Display system prompt info | `on("agent_start")`, `getSystemPrompt` |
|
|
2871
|
-
| `claude-rules.ts` | Load rules from files | `on("session_start")`, `on("before_agent_start")` |
|
|
2872
|
-
| `prompt-customizer.ts` | Add context-aware tool guidance using `systemPromptOptions` | `on("before_agent_start")`, `BuildSystemPromptOptions` |
|
|
2873
|
-
| `file-trigger.ts` | File watcher triggers messages | `sendMessage` |
|
|
2874
|
-
| **Compaction & Sessions** |||
|
|
2875
|
-
| `custom-compaction.ts` | Custom compaction summary | `on("session_before_compact")` |
|
|
2876
|
-
| `trigger-compact.ts` | Trigger compaction manually | `compact()` |
|
|
2877
|
-
| `git-checkpoint.ts` | Git stash on turns | `on("turn_start")`, `on("session_before_fork")`, `exec` |
|
|
2878
|
-
| `git-merge-and-resolve.ts` | Fetch, merge, and resolve conflicts | `on("agent_end")`, `exec`, `sendUserMessage` |
|
|
2879
|
-
| `auto-commit-on-exit.ts` | Commit on shutdown | `on("session_shutdown")`, `exec` |
|
|
2880
|
-
| **UI Components** |||
|
|
2881
|
-
| `status-line.ts` | Footer status indicator | `setStatus`, session events |
|
|
2882
|
-
| `working-indicator.ts` | Customize the streaming working indicator | `setWorkingIndicator`, `registerCommand` |
|
|
2883
|
-
| `github-issue-autocomplete.ts` | Add `#1234` issue completions on top of built-in autocomplete by preloading recent open issues from `gh issue list` | `addAutocompleteProvider`, `on("session_start")`, `exec` |
|
|
2884
|
-
| `custom-footer.ts` | Replace footer entirely | `registerCommand`, `setFooter` |
|
|
2885
|
-
| `custom-header.ts` | Replace startup header | `on("session_start")`, `setHeader` |
|
|
2886
|
-
| `modal-editor.ts` | Vim-style modal editor | `setEditorComponent`, `CustomEditor` |
|
|
2887
|
-
| `rainbow-editor.ts` | Custom editor styling | `setEditorComponent` |
|
|
2888
|
-
| `widget-placement.ts` | Widget above/below editor | `setWidget` |
|
|
2889
|
-
| `overlay-test.ts` | Overlay components | `ui.custom` with overlay options |
|
|
2890
|
-
| `overlay-qa-tests.ts` | Comprehensive overlay tests | `ui.custom`, all overlay options |
|
|
2891
|
-
| `notify.ts` | Simple notifications | `ui.notify` |
|
|
2892
|
-
| `timed-confirm.ts` | Dialogs with timeout | `ui.confirm` with timeout/signal |
|
|
2893
|
-
| `mac-system-theme.ts` | Auto-switch theme | `setTheme`, `exec` |
|
|
2894
|
-
| **Complex Extensions** |||
|
|
2895
|
-
| `plan-mode/` | Full plan mode implementation | All event types, `registerCommand`, `registerShortcut`, `registerFlag`, `setStatus`, `setWidget`, `sendMessage`, `setActiveTools` |
|
|
2896
|
-
| `preset.ts` | Saveable presets (model, tools, thinking) | `registerCommand`, `registerShortcut`, `registerFlag`, `setModel`, `setActiveTools`, `setThinkingLevel`, `appendEntry` |
|
|
2897
|
-
| `tools.ts` | Toggle tools on/off UI | `registerCommand`, `setActiveTools`, `SettingsList`, session events |
|
|
2898
|
-
| **Remote & Sandbox** |||
|
|
2899
|
-
| `ssh.ts` | SSH remote execution | `registerFlag`, `on("user_bash")`, `on("before_agent_start")`, tool operations |
|
|
2900
|
-
| `interactive-shell.ts` | Persistent shell session | `on("user_bash")` |
|
|
2901
|
-
| `sandbox/` | Sandboxed tool execution | Tool operations |
|
|
2902
|
-
| `gondolin/` | Route built-in tools and `!` commands into a Gondolin micro-VM | Tool operations, built-in tool overrides, `on("user_bash")` |
|
|
2903
|
-
| `subagent/` | Spawn sub-agents | `registerTool`, `exec` |
|
|
2904
|
-
| **Games** |||
|
|
2905
|
-
| `snake.ts` | Snake game | `registerCommand`, `ui.custom`, keyboard handling |
|
|
2906
|
-
| `space-invaders.ts` | Space Invaders game | `registerCommand`, `ui.custom` |
|
|
2907
|
-
| `doom-overlay/` | Doom in overlay | `ui.custom` with overlay |
|
|
2908
|
-
| **Providers** |||
|
|
2909
|
-
| `custom-provider-anthropic/` | Custom Anthropic proxy | `registerProvider` |
|
|
2910
|
-
| `custom-provider-gitlab-duo/` | GitLab Duo integration | `registerProvider` with OAuth |
|
|
2911
|
-
| **Messages & Communication** |||
|
|
2912
|
-
| `message-renderer.ts` | Custom message rendering | `registerMessageRenderer`, `sendMessage` |
|
|
2913
|
-
| `entry-renderer.ts` | TUI-only custom entry rendering | `registerEntryRenderer`, `appendEntry` |
|
|
2914
|
-
| `event-bus.ts` | Inter-extension events | `pi.events` |
|
|
2915
|
-
| **Session Metadata** |||
|
|
2916
|
-
| `session-name.ts` | Name sessions for selector | `setSessionName`, `getSessionName` |
|
|
2917
|
-
| `bookmark.ts` | Bookmark entries for /tree | `setLabel` |
|
|
2918
|
-
| **Misc** |||
|
|
2919
|
-
| `inline-bash.ts` | Inline bash in tool calls | `on("tool_call")` |
|
|
2920
|
-
| `bash-spawn-hook.ts` | Adjust bash command, cwd, and env before execution | `createBashTool`, `spawnHook` |
|
|
2921
|
-
| `with-deps/` | Extension with npm dependencies | Package structure with `package.json` |
|
|
279
|
+
Use [Custom Providers](custom-provider.md) for model-service integrations, [Terminal UI](tui.md) for custom components, and [draht Packages](packages.md) to install or distribute extensions with other resources.
|