@astralyn/pi 1.4.11 → 1.5.1
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 +79 -0
- package/dist/bundle/chunks/anthropic-messages-G5ZGBHOH.js +6 -0
- package/dist/bundle/chunks/azure-openai-responses-EMPTMYNF.js +2 -0
- package/dist/bundle/chunks/bedrock-converse-stream.js +22 -15
- package/dist/bundle/chunks/{chunk-TH3QDDPD.js → chunk-3YGNXVKM.js} +1 -1
- package/dist/bundle/chunks/chunk-AXX7FFFD.js +2 -0
- package/dist/bundle/chunks/chunk-FNGB3ASD.js +2 -0
- package/dist/bundle/chunks/chunk-FPALVF3F.js +4 -0
- package/dist/bundle/chunks/chunk-H3UF54OB.js +9 -0
- package/dist/bundle/chunks/{chunk-NUQMVNKQ.js → chunk-HLVMLRZJ.js} +58 -62
- package/dist/bundle/chunks/chunk-IC6JXX2J.js +10 -0
- package/dist/bundle/chunks/{chunk-MZJC45TM.js → chunk-J7L6O5XA.js} +3 -3
- package/dist/bundle/chunks/{chunk-DLVLAQEG.js → chunk-KBFO53OG.js} +3 -3
- package/dist/bundle/chunks/chunk-M3D4ADUT.js +1503 -0
- package/dist/bundle/chunks/{chunk-TPVFPFJP.js → chunk-P7VXFB2M.js} +1 -1
- package/dist/bundle/chunks/chunk-PSYLMRL6.js +9 -0
- package/dist/bundle/chunks/chunk-QNZARXLE.js +82 -0
- package/dist/bundle/chunks/chunk-RAIYJ5FC.js +4 -0
- package/dist/bundle/chunks/{chunk-OV2VMHBX.js → chunk-SR6EWNPW.js} +1 -1
- package/dist/bundle/chunks/chunk-TA3YH2ZI.js +16 -0
- package/dist/bundle/chunks/{chunk-24FY4C5S.js → chunk-TRSJS3FM.js} +1 -1
- package/dist/bundle/chunks/chunk-ZRI3ICDE.js +2 -0
- package/dist/bundle/chunks/{cli-MBFCFGI2.js → cli-LAZQG54B.js} +11 -9
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-7BKATOEJ.js → cloudflare-workers-ai-system-one-4L2ABUJE.js} +1 -1
- package/dist/bundle/chunks/{execute-VLAIP26K.js → execute-SSRW6NGS.js} +1 -1
- package/dist/bundle/chunks/github-copilot.js +1 -1
- package/dist/bundle/chunks/{google-generative-ai-HTUSU45F.js → google-generative-ai-OOVDGS5W.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-AVQV4P76.js → google-vertex-IK5RNG7J.js} +1 -1
- package/dist/bundle/chunks/image-resize-worker.js +1 -1
- package/dist/bundle/chunks/kimi-coding.js +1 -1
- package/dist/bundle/chunks/{llama-cpp-classify-27QYLJZY.js → llama-cpp-classify-XHAVT37C.js} +1 -1
- package/dist/bundle/chunks/meta.js +1 -1
- package/dist/bundle/chunks/mistral-conversations-Z56KY4OJ.js +5 -0
- package/dist/bundle/chunks/{openai-codex-responses-Q25MHDFX.js → openai-codex-responses-5NAH3SK6.js} +1 -1
- package/dist/bundle/chunks/openai-completions-S7S6PO3J.js +7 -0
- package/dist/bundle/chunks/{openai-decisions-3WYFPGSK.js → openai-decisions-7A36EAHE.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-E4BNZIQK.js → openai-responses-ZQRZJKH4.js} +1 -1
- package/dist/bundle/chunks/{openrouter-images-CBP3OPOD.js → openrouter-images-X7PX72ON.js} +1 -1
- package/dist/bundle/chunks/pi-messages-TXNWPLI4.js +8 -0
- package/dist/bundle/chunks/radius.js +1 -1
- package/dist/bundle/chunks/{runtime-3RPOJS5T.js → runtime-X3XOMNXQ.js} +1 -1
- package/dist/bundle/chunks/{typesafe-system-one-BNICP2LS.js → typesafe-system-one-XJGMSHWL.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-NFDW2JKH.js +2 -0
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +8 -7
- package/dist/cli/args.js.map +1 -1
- package/dist/config.d.ts +10 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +24 -5
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts +0 -5
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +12 -28
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session.d.ts +21 -14
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +67 -93
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/compaction/branch-summarization.d.ts +4 -2
- package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
- package/dist/core/compaction/branch-summarization.js +16 -4
- package/dist/core/compaction/branch-summarization.js.map +1 -1
- package/dist/core/exec.d.ts +9 -1
- package/dist/core/exec.d.ts.map +1 -1
- package/dist/core/exec.js +104 -60
- package/dist/core/exec.js.map +1 -1
- package/dist/core/export-html/template.css +9 -0
- package/dist/core/export-html/template.js +165 -45
- package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
- package/dist/core/export-html/tool-renderer.js +5 -0
- package/dist/core/export-html/tool-renderer.js.map +1 -1
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +7 -6
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/pi-ai-extension-view.d.ts +19 -0
- package/dist/core/extensions/pi-ai-extension-view.d.ts.map +1 -0
- package/dist/core/extensions/pi-ai-extension-view.js +22 -0
- package/dist/core/extensions/pi-ai-extension-view.js.map +1 -0
- package/dist/core/extensions/runner.d.ts +0 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +7 -12
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +41 -23
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/extensions/virtual-modules.d.ts.map +1 -1
- package/dist/core/extensions/virtual-modules.js +8 -7
- package/dist/core/extensions/virtual-modules.js.map +1 -1
- package/dist/core/mcp-servers.d.ts +11 -4
- package/dist/core/mcp-servers.d.ts.map +1 -1
- package/dist/core/mcp-servers.js +15 -5
- package/dist/core/mcp-servers.js.map +1 -1
- package/dist/core/model-config.d.ts +1678 -2029
- package/dist/core/model-config.d.ts.map +1 -1
- package/dist/core/model-config.js +2 -3
- package/dist/core/model-config.js.map +1 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +16 -10
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/package-manager.d.ts +14 -0
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +160 -46
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/pi-ai-schemas.d.ts +163 -0
- package/dist/core/pi-ai-schemas.d.ts.map +1 -0
- package/dist/core/pi-ai-schemas.js +21 -0
- package/dist/core/pi-ai-schemas.js.map +1 -0
- package/dist/core/pi-manifest.d.ts +1 -0
- package/dist/core/pi-manifest.d.ts.map +1 -1
- package/dist/core/pi-manifest.js +4 -0
- package/dist/core/pi-manifest.js.map +1 -1
- package/dist/core/project-trust.js +1 -1
- package/dist/core/project-trust.js.map +1 -1
- package/dist/core/quiescence.d.ts +24 -0
- package/dist/core/quiescence.d.ts.map +1 -0
- package/dist/core/quiescence.js +81 -0
- package/dist/core/quiescence.js.map +1 -0
- package/dist/core/resource-loader.d.ts +4 -1
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +41 -28
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +3 -1
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-manager.d.ts +7 -0
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +32 -13
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/settings-manager.d.ts +2 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +11 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/settings-schema.d.ts +4 -2
- package/dist/core/settings-schema.d.ts.map +1 -1
- package/dist/core/settings-schema.js +8 -1
- package/dist/core/settings-schema.js.map +1 -1
- package/dist/core/skills.d.ts.map +1 -1
- package/dist/core/skills.js +6 -14
- package/dist/core/skills.js.map +1 -1
- package/dist/core/slash-command-name.d.ts +6 -0
- package/dist/core/slash-command-name.d.ts.map +1 -0
- package/dist/core/slash-command-name.js +11 -0
- package/dist/core/slash-command-name.js.map +1 -0
- package/dist/core/slash-commands.js +2 -2
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/source-info.d.ts +9 -0
- package/dist/core/source-info.d.ts.map +1 -1
- package/dist/core/source-info.js +13 -0
- package/dist/core/source-info.js.map +1 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +5 -6
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tasks/activity.d.ts +14 -0
- package/dist/core/tasks/activity.d.ts.map +1 -0
- package/dist/core/tasks/activity.js +58 -0
- package/dist/core/tasks/activity.js.map +1 -0
- package/dist/core/tasks/codec.d.ts +14 -0
- package/dist/core/tasks/codec.d.ts.map +1 -1
- package/dist/core/tasks/codec.js +57 -4
- package/dist/core/tasks/codec.js.map +1 -1
- package/dist/core/tasks/execution.d.ts.map +1 -1
- package/dist/core/tasks/execution.js +2 -2
- package/dist/core/tasks/execution.js.map +1 -1
- package/dist/core/tasks/output.d.ts +4 -1
- package/dist/core/tasks/output.d.ts.map +1 -1
- package/dist/core/tasks/output.js +33 -0
- package/dist/core/tasks/output.js.map +1 -1
- package/dist/core/tasks/record.d.ts +1 -7
- package/dist/core/tasks/record.d.ts.map +1 -1
- package/dist/core/tasks/record.js +0 -18
- package/dist/core/tasks/record.js.map +1 -1
- package/dist/core/tasks/reminder.d.ts +3 -2
- package/dist/core/tasks/reminder.d.ts.map +1 -1
- package/dist/core/tasks/reminder.js +4 -3
- package/dist/core/tasks/reminder.js.map +1 -1
- package/dist/core/tasks/runtime.d.ts +0 -2
- package/dist/core/tasks/runtime.d.ts.map +1 -1
- package/dist/core/tasks/runtime.js +2 -15
- package/dist/core/tasks/runtime.js.map +1 -1
- package/dist/core/tasks/session.d.ts +9 -2
- package/dist/core/tasks/session.d.ts.map +1 -1
- package/dist/core/tasks/session.js +23 -9
- package/dist/core/tasks/session.js.map +1 -1
- package/dist/core/tasks/types.d.ts +20 -20
- package/dist/core/tasks/types.d.ts.map +1 -1
- package/dist/core/tasks/types.js +1 -1
- package/dist/core/tasks/types.js.map +1 -1
- package/dist/core/tools/bash.d.ts +8 -7
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +6 -5
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/edit.d.ts +3 -3
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +2 -4
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/find.d.ts +2 -2
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/grep.d.ts +2 -2
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +1 -1
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/ls.d.ts +2 -2
- package/dist/core/tools/ls.d.ts.map +1 -1
- package/dist/core/tools/ls.js.map +1 -1
- package/dist/core/tools/powershell.d.ts +1 -5
- package/dist/core/tools/powershell.d.ts.map +1 -1
- package/dist/core/tools/read.d.ts +2 -2
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/render-utils.d.ts +4 -6
- package/dist/core/tools/render-utils.d.ts.map +1 -1
- package/dist/core/tools/render-utils.js +19 -41
- package/dist/core/tools/render-utils.js.map +1 -1
- package/dist/core/tools/renderers/bash.d.ts.map +1 -1
- package/dist/core/tools/renderers/bash.js +3 -25
- package/dist/core/tools/renderers/bash.js.map +1 -1
- package/dist/core/tools/renderers/write.d.ts.map +1 -1
- package/dist/core/tools/renderers/write.js +18 -19
- package/dist/core/tools/renderers/write.js.map +1 -1
- package/dist/core/tools/shell-execution.d.ts +20 -13
- package/dist/core/tools/shell-execution.d.ts.map +1 -1
- package/dist/core/tools/shell-execution.js +165 -183
- package/dist/core/tools/shell-execution.js.map +1 -1
- package/dist/core/tools/shell-tool.d.ts +9 -14
- package/dist/core/tools/shell-tool.d.ts.map +1 -1
- package/dist/core/tools/shell-tool.js +38 -66
- package/dist/core/tools/shell-tool.js.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.d.ts +14 -4
- package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.js +2 -3
- package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
- package/dist/core/tools/write.d.ts +2 -2
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js.map +1 -1
- package/dist/core/trust-manager.d.ts.map +1 -1
- package/dist/core/trust-manager.js +30 -13
- package/dist/core/trust-manager.js.map +1 -1
- package/dist/core/usage-totals.d.ts +0 -9
- package/dist/core/usage-totals.d.ts.map +1 -1
- package/dist/core/usage-totals.js +24 -91
- package/dist/core/usage-totals.js.map +1 -1
- package/dist/extensions/agent/activity-lines.d.ts +2 -7
- package/dist/extensions/agent/activity-lines.d.ts.map +1 -1
- package/dist/extensions/agent/activity-lines.js +6 -74
- package/dist/extensions/agent/activity-lines.js.map +1 -1
- package/dist/extensions/agent/activity.d.ts +0 -21
- package/dist/extensions/agent/activity.d.ts.map +1 -1
- package/dist/extensions/agent/activity.js +0 -63
- package/dist/extensions/agent/activity.js.map +1 -1
- package/dist/extensions/agent/progress.d.ts +0 -3
- package/dist/extensions/agent/progress.d.ts.map +1 -1
- package/dist/extensions/agent/progress.js +11 -10
- package/dist/extensions/agent/progress.js.map +1 -1
- package/dist/extensions/agent/render.js +1 -1
- package/dist/extensions/agent/render.js.map +1 -1
- package/dist/extensions/agent/tool.d.ts.map +1 -1
- package/dist/extensions/agent/tool.js +0 -6
- package/dist/extensions/agent/tool.js.map +1 -1
- package/dist/extensions/agent/types.d.ts +3 -11
- package/dist/extensions/agent/types.d.ts.map +1 -1
- package/dist/extensions/agent/types.js.map +1 -1
- package/dist/{core/isolated-session.d.ts → extensions/agent/worker-session.d.ts} +6 -6
- package/dist/extensions/agent/worker-session.d.ts.map +1 -0
- package/dist/{core/isolated-session.js → extensions/agent/worker-session.js} +9 -9
- package/dist/extensions/agent/worker-session.js.map +1 -0
- package/dist/extensions/agent/worker.d.ts +0 -3
- package/dist/extensions/agent/worker.d.ts.map +1 -1
- package/dist/extensions/agent/worker.js +2 -3
- package/dist/extensions/agent/worker.js.map +1 -1
- package/dist/extensions/btw/agent.d.ts.map +1 -1
- package/dist/extensions/btw/agent.js +2 -1
- package/dist/extensions/btw/agent.js.map +1 -1
- package/dist/extensions/cached-compaction/render.d.ts.map +1 -1
- package/dist/extensions/cached-compaction/render.js +3 -3
- package/dist/extensions/cached-compaction/render.js.map +1 -1
- package/dist/extensions/codemode/renderer.d.ts.map +1 -1
- package/dist/extensions/codemode/renderer.js +6 -2
- package/dist/extensions/codemode/renderer.js.map +1 -1
- package/dist/extensions/codemode/tool.d.ts +2 -1
- package/dist/extensions/codemode/tool.d.ts.map +1 -1
- package/dist/extensions/codemode/tool.js +33 -8
- package/dist/extensions/codemode/tool.js.map +1 -1
- package/dist/extensions/deepwiki/schema.d.ts.map +1 -1
- package/dist/extensions/deepwiki/schema.js +1 -1
- package/dist/extensions/deepwiki/schema.js.map +1 -1
- package/dist/extensions/llama/ui.d.ts.map +1 -1
- package/dist/extensions/llama/ui.js +16 -4
- package/dist/extensions/llama/ui.js.map +1 -1
- package/dist/extensions/mcp/cli.d.ts.map +1 -1
- package/dist/extensions/mcp/cli.js +34 -8
- package/dist/extensions/mcp/cli.js.map +1 -1
- package/dist/extensions/mcp/oauth.d.ts +1 -1
- package/dist/extensions/mcp/oauth.d.ts.map +1 -1
- package/dist/extensions/mcp/oauth.js +36 -13
- package/dist/extensions/mcp/oauth.js.map +1 -1
- package/dist/extensions/mcp/ui.d.ts +1 -0
- package/dist/extensions/mcp/ui.d.ts.map +1 -1
- package/dist/extensions/mcp/ui.js +33 -24
- package/dist/extensions/mcp/ui.js.map +1 -1
- package/dist/extensions/run-summary/index.d.ts +1 -1
- package/dist/extensions/run-summary/index.d.ts.map +1 -1
- package/dist/extensions/run-summary/index.js +11 -23
- package/dist/extensions/run-summary/index.js.map +1 -1
- package/dist/extensions/statusline/usage.d.ts.map +1 -1
- package/dist/extensions/statusline/usage.js +2 -1
- package/dist/extensions/statusline/usage.js.map +1 -1
- package/dist/extensions/tasks/tool/schema.d.ts.map +1 -1
- package/dist/extensions/tasks/tool/schema.js +1 -1
- package/dist/extensions/tasks/tool/schema.js.map +1 -1
- package/dist/extensions/tasks/ui/completion-render.d.ts +5 -1
- package/dist/extensions/tasks/ui/completion-render.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/completion-render.js +25 -70
- package/dist/extensions/tasks/ui/completion-render.js.map +1 -1
- package/dist/extensions/tasks/ui/inspector.d.ts +1 -1
- package/dist/extensions/tasks/ui/inspector.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/inspector.js +3 -7
- package/dist/extensions/tasks/ui/inspector.js.map +1 -1
- package/dist/extensions/tasks/ui/manager.d.ts +1 -1
- package/dist/extensions/tasks/ui/manager.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/manager.js.map +1 -1
- package/dist/extensions/tasks/ui/views.d.ts +3 -4
- package/dist/extensions/tasks/ui/views.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/views.js +15 -14
- package/dist/extensions/tasks/ui/views.js.map +1 -1
- package/dist/extensions/tool-presentation/fallback.d.ts.map +1 -0
- package/dist/{modes/interactive/tool-view → extensions/tool-presentation}/fallback.js +5 -5
- package/dist/extensions/tool-presentation/fallback.js.map +1 -0
- package/dist/extensions/tool-presentation/index.js +1 -1
- package/dist/extensions/tool-presentation/index.js.map +1 -1
- package/dist/{modes/interactive/tool-view → extensions/tool-presentation}/shell.d.ts +1 -1
- package/dist/extensions/tool-presentation/shell.d.ts.map +1 -0
- package/dist/{modes/interactive/tool-view → extensions/tool-presentation}/shell.js +3 -3
- package/dist/extensions/tool-presentation/shell.js.map +1 -0
- package/dist/extensions/tool-search/tool.d.ts +21 -6
- package/dist/extensions/tool-search/tool.d.ts.map +1 -1
- package/dist/extensions/tool-search/tool.js +104 -36
- package/dist/extensions/tool-search/tool.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +15 -8
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/assistant-message.d.ts +5 -3
- package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/assistant-message.js +61 -45
- package/dist/modes/interactive/components/assistant-message.js.map +1 -1
- package/dist/modes/interactive/components/config-selector-skills.d.ts +54 -0
- package/dist/modes/interactive/components/config-selector-skills.d.ts.map +1 -0
- package/dist/modes/interactive/components/config-selector-skills.js +178 -0
- package/dist/modes/interactive/components/config-selector-skills.js.map +1 -0
- package/dist/modes/interactive/components/config-selector.d.ts +2 -11
- package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/config-selector.js +31 -181
- package/dist/modes/interactive/components/config-selector.js.map +1 -1
- package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-editor.js +7 -0
- package/dist/modes/interactive/components/custom-editor.js.map +1 -1
- package/dist/modes/interactive/components/custom-entry.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-entry.js +2 -1
- package/dist/modes/interactive/components/custom-entry.js.map +1 -1
- package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-message.js +2 -1
- package/dist/modes/interactive/components/custom-message.js.map +1 -1
- package/dist/modes/interactive/components/extension-editor.d.ts +2 -0
- package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-editor.js +4 -0
- package/dist/modes/interactive/components/extension-editor.js.map +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts +5 -0
- package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
- package/dist/modes/interactive/components/login-dialog.js +103 -10
- package/dist/modes/interactive/components/login-dialog.js.map +1 -1
- package/dist/modes/interactive/components/markdown-transform.d.ts +2 -1
- package/dist/modes/interactive/components/markdown-transform.d.ts.map +1 -1
- package/dist/modes/interactive/components/markdown-transform.js +3 -2
- package/dist/modes/interactive/components/markdown-transform.js.map +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts +1 -0
- package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/model-selector.js +17 -6
- package/dist/modes/interactive/components/model-selector.js.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.d.ts +1 -0
- package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.js +13 -4
- package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.d.ts +1 -0
- package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.js +14 -3
- package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
- package/dist/modes/interactive/components/session-selector-search.d.ts +4 -0
- package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector-search.js +86 -22
- package/dist/modes/interactive/components/session-selector-search.js.map +1 -1
- package/dist/modes/interactive/components/session-selector.d.ts +2 -1
- package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector.js +15 -23
- package/dist/modes/interactive/components/session-selector.js.map +1 -1
- package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-submenu.js +2 -0
- package/dist/modes/interactive/components/settings-submenu.js.map +1 -1
- package/dist/modes/interactive/components/task-activity-list.d.ts +5 -0
- package/dist/modes/interactive/components/task-activity-list.d.ts.map +1 -0
- package/dist/modes/interactive/components/task-activity-list.js +68 -0
- package/dist/modes/interactive/components/task-activity-list.js.map +1 -0
- package/dist/modes/interactive/components/tool-execution.d.ts +7 -0
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +48 -9
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/components/tree-selector.d.ts +1 -0
- package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector.js +5 -6
- package/dist/modes/interactive/components/tree-selector.js.map +1 -1
- package/dist/modes/interactive/components/user-message-selector.d.ts +1 -0
- package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/user-message-selector.js +9 -1
- 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 +4 -2
- package/dist/modes/interactive/components/user-message.js.map +1 -1
- package/dist/modes/interactive/editor-host.d.ts.map +1 -1
- package/dist/modes/interactive/editor-host.js +3 -2
- package/dist/modes/interactive/editor-host.js.map +1 -1
- package/dist/modes/interactive/external-editor.d.ts +1 -0
- package/dist/modes/interactive/external-editor.d.ts.map +1 -1
- package/dist/modes/interactive/external-editor.js +17 -5
- package/dist/modes/interactive/external-editor.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +8 -12
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +169 -112
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/model-search.d.ts +10 -0
- package/dist/modes/interactive/model-search.d.ts.map +1 -1
- package/dist/modes/interactive/model-search.js +21 -0
- package/dist/modes/interactive/model-search.js.map +1 -1
- package/dist/modes/interactive/theme/theme.d.ts +10 -0
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme.js +30 -23
- package/dist/modes/interactive/theme/theme.js.map +1 -1
- package/dist/modes/interactive/tool-view/chat.d.ts +2 -2
- package/dist/modes/interactive/tool-view/chat.d.ts.map +1 -1
- package/dist/modes/interactive/tool-view/chat.js +22 -19
- package/dist/modes/interactive/tool-view/chat.js.map +1 -1
- package/dist/modes/interactive/transcript-layout.d.ts +2 -0
- package/dist/modes/interactive/transcript-layout.d.ts.map +1 -1
- package/dist/modes/interactive/transcript-layout.js +5 -2
- package/dist/modes/interactive/transcript-layout.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts +9 -1
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +23 -23
- 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 +0 -3
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/package-manager-cli.d.ts.map +1 -1
- package/dist/package-manager-cli.js +55 -4
- package/dist/package-manager-cli.js.map +1 -1
- package/dist/utils/ansi.d.ts.map +1 -1
- package/dist/utils/ansi.js +5 -2
- package/dist/utils/ansi.js.map +1 -1
- package/dist/utils/clipboard-command.d.ts.map +1 -1
- package/dist/utils/clipboard-command.js +4 -0
- package/dist/utils/clipboard-command.js.map +1 -1
- package/dist/utils/git.d.ts +1 -1
- package/dist/utils/git.d.ts.map +1 -1
- package/dist/utils/git.js.map +1 -1
- package/dist/utils/image-resize-core.d.ts.map +1 -1
- package/dist/utils/image-resize-core.js +5 -3
- package/dist/utils/image-resize-core.js.map +1 -1
- package/dist/utils/open-browser.d.ts.map +1 -1
- package/dist/utils/open-browser.js +4 -1
- package/dist/utils/open-browser.js.map +1 -1
- package/dist/utils/paths.d.ts +17 -0
- package/dist/utils/paths.d.ts.map +1 -1
- package/dist/utils/paths.js +42 -1
- package/dist/utils/paths.js.map +1 -1
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +14 -0
- package/dist/utils/shell.js.map +1 -1
- package/dist/utils/syntax-highlight.d.ts +5 -0
- package/dist/utils/syntax-highlight.d.ts.map +1 -1
- package/dist/utils/syntax-highlight.js +7 -0
- package/dist/utils/syntax-highlight.js.map +1 -1
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +30 -35
- package/dist/utils/tools-manager.js.map +1 -1
- package/dist/utils/usage.d.ts +5 -0
- package/dist/utils/usage.d.ts.map +1 -0
- package/dist/utils/usage.js +16 -0
- package/dist/utils/usage.js.map +1 -0
- package/docs/bundled/README.md +1 -1
- package/docs/bundled/extensions/agent.md +5 -5
- package/docs/bundled/extensions/run-summary.md +4 -4
- package/docs/bundled/tasks.md +2 -4
- package/docs/bundled/tool-presentation.md +2 -2
- package/docs/custom-provider.md +1 -1
- package/docs/environment-variables.md +2 -0
- package/docs/extensions.md +38 -21
- package/docs/keybindings.md +1 -1
- package/docs/llama-cpp.md +17 -12
- package/docs/mcp.md +6 -4
- package/docs/packages.md +26 -1
- package/docs/rpc.md +1 -1
- package/docs/sdk.md +7 -5
- package/docs/session-format.md +2 -2
- package/docs/sessions.md +10 -0
- package/docs/settings.md +5 -4
- package/docs/terminal-setup.md +2 -2
- package/docs/tmux.md +6 -0
- package/docs/tui.md +12 -7
- package/docs/usage.md +19 -9
- package/docs/windows.md +29 -0
- package/examples/extensions/README.md +2 -1
- package/examples/extensions/custom-provider-anthropic/index.ts +27 -31
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/debug-provider.ts +2 -2
- package/examples/extensions/gondolin/package-lock.json +19 -29
- package/examples/extensions/gondolin/package.json +2 -2
- package/examples/extensions/preset.ts +2 -0
- package/examples/extensions/reload-runtime.ts +17 -5
- package/examples/extensions/tools.ts +2 -0
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/package.json +9 -9
- package/schemas/models.schema.json +36 -36
- package/schemas/settings.schema.json +17 -0
- package/dist/bundle/chunks/anthropic-messages-HWL6AS7T.js +0 -6
- package/dist/bundle/chunks/azure-openai-responses-4YYPDYV5.js +0 -2
- package/dist/bundle/chunks/chunk-6JS2SOFO.js +0 -11
- package/dist/bundle/chunks/chunk-ANCZPKX7.js +0 -2
- package/dist/bundle/chunks/chunk-FEZ5RM2B.js +0 -2
- package/dist/bundle/chunks/chunk-LPF7HQ3S.js +0 -4
- package/dist/bundle/chunks/chunk-MMNIHCU7.js +0 -2
- package/dist/bundle/chunks/chunk-PUU43PDV.js +0 -1484
- package/dist/bundle/chunks/chunk-R267VV5T.js +0 -82
- package/dist/bundle/chunks/chunk-RVKT7OUB.js +0 -9
- package/dist/bundle/chunks/chunk-SA2AQYEI.js +0 -7
- package/dist/bundle/chunks/chunk-ZAIGBRV5.js +0 -16
- package/dist/bundle/chunks/mistral-conversations-V2JJTMJ5.js +0 -5
- package/dist/bundle/chunks/openai-completions-TXZXILJR.js +0 -7
- package/dist/bundle/chunks/pi-messages-LBJQ4NGP.js +0 -8
- package/dist/bundle/chunks/virtual-modules-63XNTSVN.js +0 -2
- package/dist/core/isolated-session.d.ts.map +0 -1
- package/dist/core/isolated-session.js.map +0 -1
- package/dist/modes/interactive/tool-view/fallback.d.ts.map +0 -1
- package/dist/modes/interactive/tool-view/fallback.js.map +0 -1
- package/dist/modes/interactive/tool-view/shell.d.ts.map +0 -1
- package/dist/modes/interactive/tool-view/shell.js.map +0 -1
- package/dist/utils/path-identity.d.ts +0 -12
- package/dist/utils/path-identity.d.ts.map +0 -1
- package/dist/utils/path-identity.js +0 -63
- package/dist/utils/path-identity.js.map +0 -1
- package/examples/extensions/sandbox/index.ts +0 -321
- package/examples/extensions/sandbox/package-lock.json +0 -92
- package/examples/extensions/sandbox/package.json +0 -19
- /package/dist/{modes/interactive/tool-view → extensions/tool-presentation}/fallback.d.ts +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shell-tool.d.ts","sourceRoot":"","sources":["../../../src/core/tools/shell-tool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"shell-tool.d.ts","sourceRoot":"","sources":["../../../src/core/tools/shell-tool.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAO7D,OAAO,EACN,KAAK,cAAc,EACnB,KAAK,eAAe,EACpB,KAAK,eAAe,EAEpB,KAAK,eAAe,IAAI,qBAAqB,EAG7C,KAAK,eAAe,EACpB,MAAM,WAAW,CAAC;AAKnB,QAAA,MAAM,UAAU;;;;EAQd,CAAC;AAEH,eAAO,MAAM,gCAAgC;;;CAGnC,CAAC;AAEX,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAOtD,MAAM,WAAW,eAAgB,SAAQ,qBAAqB;IAC7D,uEAAuE;IACvE,UAAU,CAAC,EAAE;QAAE,IAAI,EAAE,YAAY,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC;CACpD;AA2BD,wBAAgB,yBAAyB,CACxC,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,eAAe,EACvB,OAAO,EAAE,eAAe,GAAG;IAAE,UAAU,EAAE,cAAc,CAAA;CAAE,GACvD,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,EAAE,eAAe,CAAC,CAiEjF;AAYD,wBAAgB,wBAAwB,CACvC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,eAAe,GACvB,UAAU,CAAC,OAAO,yBAAyB,CAAC,CAK9C;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,uFAQpE"}
|
|
@@ -1,15 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The managed shell tools: the native shell definition (`bash.ts`) plus a `background` parameter,
|
|
3
|
+
* adapted to the session's Tasks. The native body stays the one owner of execution, progress,
|
|
4
|
+
* output formatting and results; outside a session it runs unchanged.
|
|
5
|
+
*/
|
|
1
6
|
import { Type } from "typebox";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { createShellRenderers } from "./renderers/bash.js";
|
|
6
|
-
import { runShellCommand } from "./shell-execution.js";
|
|
7
|
+
import { TASK_BACKGROUND_REJECTION, TASKS_TOOL_NAME, } from "../tasks/types.js";
|
|
8
|
+
import { createShellToolDefinition as createNativeShellToolDefinition, bashOutputSchema as nativeOutputSchema, bashSchema as nativeSchema, } from "./bash.js";
|
|
9
|
+
import { runShellTask } from "./shell-execution.js";
|
|
7
10
|
import { createLocalBashOperations } from "./shell-operations.js";
|
|
8
11
|
import { wrapToolDefinition } from "./tool-definition-wrapper.js";
|
|
9
|
-
import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES } from "./truncate.js";
|
|
10
12
|
const bashSchema = Type.Object({
|
|
11
|
-
|
|
12
|
-
timeout: Type.Optional(Type.Number({ description: "Timeout in seconds (optional, no default timeout)" })),
|
|
13
|
+
...nativeSchema.properties,
|
|
13
14
|
background: Type.Optional(Type.Boolean({
|
|
14
15
|
description: "true returns a managed task ID immediately and runs the command in the background, and you are notified when it completes — do not poll for its result; omit or false to block until exit",
|
|
15
16
|
})),
|
|
@@ -19,17 +20,10 @@ export const bashToolSystemPromptContribution = {
|
|
|
19
20
|
guidelines: ["You can inspect PI_* environment variables for current model and session details."],
|
|
20
21
|
};
|
|
21
22
|
const bashOutputSchema = Type.Union([
|
|
22
|
-
|
|
23
|
-
output: Type.String({
|
|
24
|
-
description: "Combined stdout and stderr, up to 1 MiB, keeping head and tail when truncated.",
|
|
25
|
-
}),
|
|
26
|
-
truncated: Type.Boolean(),
|
|
27
|
-
full_output_path: Type.Optional(Type.String()),
|
|
28
|
-
exit_code: Type.Number(),
|
|
29
|
-
wall_time_seconds: Type.Number(),
|
|
30
|
-
}),
|
|
23
|
+
nativeOutputSchema,
|
|
31
24
|
Type.Object({ task_id: Type.String(), status: Type.String() }),
|
|
32
25
|
]);
|
|
26
|
+
const BACKGROUND_GUIDANCE = `Choose the mode per call: foreground (default) blocks until the command exits — use it when your next step needs the output; background: true returns immediately with a task ID — use it for long-running work (builds, servers, watchers, big test suites) or when you have independent work to continue. A handoff is not completion: the result arrives later as an automatic completion notification; meanwhile use ${TASKS_TOOL_NAME} read to inspect output and ${TASKS_TOOL_NAME} kill to stop it. Background output is limited to 20 MiB.`;
|
|
33
27
|
/**
|
|
34
28
|
* Translate terminal shell failures to the native foreground tool contract once. A task result
|
|
35
29
|
* holds the command's output only; the foreground text is that output followed by the failure.
|
|
@@ -52,61 +46,40 @@ function shellToolResult(completion) {
|
|
|
52
46
|
return completion.result;
|
|
53
47
|
}
|
|
54
48
|
export function createShellToolDefinition(cwd, config, options) {
|
|
55
|
-
const
|
|
56
|
-
const commandPrefix = options?.commandPrefix;
|
|
57
|
-
const exposeSessionEnvironment = options?.exposeSessionEnvironment ?? true;
|
|
58
|
-
const spawnHook = options?.spawnHook;
|
|
49
|
+
const native = createNativeShellToolDefinition(cwd, config, options);
|
|
59
50
|
return {
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
description: `Execute a ${config.shellName} command in the current working directory. Returns stdout and stderr, truncated to the last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first); the full output is saved to a temp file. Optionally provide a timeout in seconds (no default). Choose the mode per call: foreground (default) blocks until the command exits — use it when your next step needs the output; background: true returns immediately with a task ID — use it for long-running work (builds, servers, watchers, big test suites) or when you have independent work to continue. A handoff is not completion: the result arrives later as an automatic completion notification; meanwhile use ${TASKS_TOOL_NAME} read to inspect output and ${TASKS_TOOL_NAME} kill to stop it. Background output is limited to 20 MiB.`,
|
|
63
|
-
promptSnippet: config.promptSnippet,
|
|
64
|
-
promptGuidelines: exposeSessionEnvironment && config.promptGuidelines ? [...config.promptGuidelines] : undefined,
|
|
51
|
+
...native,
|
|
52
|
+
description: `${native.description} ${BACKGROUND_GUIDANCE}`,
|
|
65
53
|
parameters: bashSchema,
|
|
66
54
|
outputSchema: bashOutputSchema,
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
55
|
+
async execute(toolCallId, { command, timeout, background }, parentSignal, onUpdate, ctx) {
|
|
56
|
+
const tasks = ctx?.tasks;
|
|
57
|
+
if (!tasks) {
|
|
58
|
+
if (background)
|
|
59
|
+
throw new Error(TASK_BACKGROUND_REJECTION);
|
|
60
|
+
return native.execute(toolCallId, { command, timeout }, parentSignal, onUpdate, ctx);
|
|
61
|
+
}
|
|
62
|
+
if (tasks.closed)
|
|
71
63
|
throw new Error("Task service is closed");
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
64
|
+
const outcome = await tasks.execute({
|
|
65
|
+
kind: config.name,
|
|
66
|
+
label: config.shellName[0].toUpperCase() + config.shellName.slice(1),
|
|
67
|
+
title: command,
|
|
68
|
+
input: { label: "Command", text: command, truncated: false, language: config.name },
|
|
69
|
+
facts: [["Directory", ctx.cwd || cwd]],
|
|
70
|
+
toolCallId,
|
|
71
|
+
background,
|
|
72
|
+
signal: parentSignal,
|
|
73
|
+
onUpdate,
|
|
82
74
|
// A setup throw settles the task as failed, or cancelled once its signal fired.
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
75
|
+
run: (control) => runShellTask({
|
|
76
|
+
control,
|
|
77
|
+
operations: options.operations,
|
|
86
78
|
tempFilePrefix: config.tempFilePrefix,
|
|
87
79
|
timeout,
|
|
88
|
-
control,
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
};
|
|
92
|
-
let outcome;
|
|
93
|
-
try {
|
|
94
|
-
outcome = await (sessionTasks ?? standalone).execute({
|
|
95
|
-
kind: config.name,
|
|
96
|
-
label: config.shellName[0].toUpperCase() + config.shellName.slice(1),
|
|
97
|
-
title: command,
|
|
98
|
-
input: { label: "Command", text: command, truncated: false, language: config.name },
|
|
99
|
-
facts: [["Directory", ctx?.cwd || cwd]],
|
|
100
|
-
toolCallId,
|
|
101
|
-
background,
|
|
102
|
-
signal: parentSignal,
|
|
103
|
-
onUpdate: originalUpdate,
|
|
104
|
-
run,
|
|
105
|
-
});
|
|
106
|
-
}
|
|
107
|
-
finally {
|
|
108
|
-
standalone?.close();
|
|
109
|
-
}
|
|
80
|
+
execute: (parts) => createNativeShellToolDefinition(cwd, { ...config, createOutput: parts.createOutput }, { ...options, operations: parts.operations }).execute(toolCallId, { command, timeout }, control.signal, parts.onUpdate, ctx),
|
|
81
|
+
}),
|
|
82
|
+
});
|
|
110
83
|
if (outcome.kind === "result")
|
|
111
84
|
return shellToolResult(outcome);
|
|
112
85
|
const tail = `Task ID: ${outcome.task.id}. Status: ${outcome.task.status}. Completion arrives and wakes you automatically — do not poll or wait on it; continue with other work, or end your turn and hand back to the user. If you would only wait for the result, prefer foreground next time. Use ${TASKS_TOOL_NAME} read to inspect output or ${TASKS_TOOL_NAME} kill to stop it.`;
|
|
@@ -130,7 +103,6 @@ export function createShellToolDefinition(cwd, config, options) {
|
|
|
130
103
|
},
|
|
131
104
|
};
|
|
132
105
|
},
|
|
133
|
-
...createShellRenderers(config),
|
|
134
106
|
};
|
|
135
107
|
}
|
|
136
108
|
const bashToolConfig = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shell-tool.js","sourceRoot":"","sources":["../../../src/core/tools/shell-tool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAE5C,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,eAAe,EAA+D,MAAM,mBAAmB,CAAC;AACjH,OAAO,EAGN,mBAAmB,EACnB,gBAAgB,GAEhB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,EAAE,yBAAyB,EAAE,MAAM,uBAAuB,CAAC;AAClE,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAyB,MAAM,eAAe,CAAC;AAE5F,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,CAAC;IAC9B,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,0BAA0B,EAAE,CAAC;IACjE,OAAO,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,mDAAmD,EAAE,CAAC,CAAC;IACzG,UAAU,EAAE,IAAI,CAAC,QAAQ,CACxB,IAAI,CAAC,OAAO,CAAC;QACZ,WAAW,EACV,2LAA2L;KAC5L,CAAC,CACF;CACD,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,gCAAgC,GAAG;IAC/C,OAAO,EAAE,iDAAiD;IAC1D,UAAU,EAAE,CAAC,mFAAmF,CAAC;CACxF,CAAC;AAIX,MAAM,gB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AC7C,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["import { type Static, Type } from \"typebox\";\nimport type { ExtensionContext, ToolDefinition } from \"../extensions/types.ts\";\nimport { TaskRuntime } from \"../tasks/runtime.ts\";\nimport { TASKS_TOOL_NAME, type TaskCompletion, type TaskControl, type TaskToolOutcome } from \"../tasks/types.ts\";\nimport {\n\ttype BashOperations,\n\ttype BashToolOptions,\n\tresolveSpawnContext,\n\tresolveTimeoutMs,\n\ttype ShellToolConfig,\n} from \"./bash.ts\";\nimport { createShellRenderers } from \"./renderers/bash.ts\";\nimport { runShellCommand } from \"./shell-execution.ts\";\nimport { createLocalBashOperations } from \"./shell-operations.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, type TruncationResult } from \"./truncate.ts\";\n\nconst bashSchema = Type.Object({\n\tcommand: Type.String({ description: \"Shell command to execute\" }),\n\ttimeout: Type.Optional(Type.Number({ description: \"Timeout in seconds (optional, no default timeout)\" })),\n\tbackground: Type.Optional(\n\t\tType.Boolean({\n\t\t\tdescription:\n\t\t\t\t\"true returns a managed task ID immediately and runs the command in the background, and you are notified when it completes — do not poll for its result; omit or false to block until exit\",\n\t\t}),\n\t),\n});\n\nexport const bashToolSystemPromptContribution = {\n\tsnippet: \"Execute bash commands, foreground or background\",\n\tguidelines: [\"You can inspect PI_* environment variables for current model and session details.\"],\n} as const;\n\nexport type BashToolInput = Static<typeof bashSchema>;\n\nconst bashOutputSchema = Type.Union([\n\tType.Object({\n\t\toutput: Type.String({\n\t\t\tdescription: \"Combined stdout and stderr, up to 1 MiB, keeping head and tail when truncated.\",\n\t\t}),\n\t\ttruncated: Type.Boolean(),\n\t\tfull_output_path: Type.Optional(Type.String()),\n\t\texit_code: Type.Number(),\n\t\twall_time_seconds: Type.Number(),\n\t}),\n\tType.Object({ task_id: Type.String(), status: Type.String() }),\n]);\n\nexport interface BashToolDetails {\n\ttruncation?: TruncationResult;\n\tfullOutputPath?: string;\n\t/** Settled handoff snapshot, not a command completion or exit code. */\n\tbackground?: { kind: \"background\"; taskId: string };\n}\n\nexport type BashRenderState = {\n\tdispose?: () => void;\n};\n\n/**\n * Translate terminal shell failures to the native foreground tool contract once. A task result\n * holds the command's output only; the foreground text is that output followed by the failure.\n */\nfunction shellToolResult(completion: TaskCompletion<BashToolDetails | undefined>) {\n\tconst status = completion.status;\n\tconst output = completion.result.content\n\t\t.filter((part) => part.type === \"text\")\n\t\t.map((part) => part.text)\n\t\t.join(\"\\n\");\n\tconst withError = (error: string) => (output ? `${output}\\n\\n${error}` : error);\n\tif (completion.result.structuredContent) {\n\t\tif (!completion.result.isError || !completion.error) return completion.result;\n\t\treturn { ...completion.result, content: [{ type: \"text\" as const, text: withError(completion.error) }] };\n\t}\n\tif (status === \"failed\" || status === \"timeout\" || status === \"cancelled\") {\n\t\tthrow new Error(\n\t\t\tcompletion.error ? withError(completion.error) : `${output ? `${output}\\n\\n` : \"\"}Command ${status}`,\n\t\t);\n\t}\n\treturn completion.result;\n}\n\nexport function createShellToolDefinition(\n\tcwd: string,\n\tconfig: ShellToolConfig,\n\toptions: BashToolOptions & { operations: BashOperations },\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\tconst ops = options.operations;\n\tconst commandPrefix = options?.commandPrefix;\n\tconst exposeSessionEnvironment = options?.exposeSessionEnvironment ?? true;\n\tconst spawnHook = options?.spawnHook;\n\treturn {\n\t\tname: config.name,\n\t\tlabel: config.label,\n\t\tdescription: `Execute a ${config.shellName} command in the current working directory. Returns stdout and stderr, truncated to the last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first); the full output is saved to a temp file. Optionally provide a timeout in seconds (no default). Choose the mode per call: foreground (default) blocks until the command exits — use it when your next step needs the output; background: true returns immediately with a task ID — use it for long-running work (builds, servers, watchers, big test suites) or when you have independent work to continue. A handoff is not completion: the result arrives later as an automatic completion notification; meanwhile use ${TASKS_TOOL_NAME} read to inspect output and ${TASKS_TOOL_NAME} kill to stop it. Background output is limited to 20 MiB.`,\n\t\tpromptSnippet: config.promptSnippet,\n\t\tpromptGuidelines: exposeSessionEnvironment && config.promptGuidelines ? [...config.promptGuidelines] : undefined,\n\t\tparameters: bashSchema,\n\t\toutputSchema: bashOutputSchema,\n\t\tconstrainedSampling: { type: \"json_schema\", strict: \"prefer\" },\n\t\tasync execute(\n\t\t\ttoolCallId,\n\t\t\t{ command, timeout, background }: BashToolInput,\n\t\t\tparentSignal?: AbortSignal,\n\t\t\toriginalUpdate?,\n\t\t\tctx?: ExtensionContext,\n\t\t) {\n\t\t\tconst sessionTasks = ctx?.tasks;\n\t\t\tif (sessionTasks?.closed) throw new Error(\"Task service is closed\");\n\t\t\tif (!sessionTasks && background)\n\t\t\t\tthrow new Error(\"Background execution is not available in this host. No command was started.\");\n\t\t\t// Without a session the command still runs as a task, on a throwaway runtime that never backgrounds.\n\t\t\tconst standalone = sessionTasks ? undefined : new TaskRuntime();\n\t\t\tconst run = async (\n\t\t\t\tcontrol: TaskControl<BashToolDetails | undefined>,\n\t\t\t): Promise<TaskCompletion<BashToolDetails | undefined>> => {\n\t\t\t\tif (control.signal.aborted) throw new Error(\"Command aborted\");\n\t\t\t\tresolveTimeoutMs(timeout);\n\t\t\t\tconst resolvedCommand = commandPrefix ? `${commandPrefix}\\n${command}` : command;\n\t\t\t\tconst spawnContext = resolveSpawnContext(\n\t\t\t\t\tresolvedCommand,\n\t\t\t\t\tctx?.cwd || cwd,\n\t\t\t\t\tspawnHook,\n\t\t\t\t\texposeSessionEnvironment,\n\t\t\t\t\tctx,\n\t\t\t\t);\n\t\t\t\t// A setup throw settles the task as failed, or cancelled once its signal fired.\n\t\t\t\treturn await runShellCommand({\n\t\t\t\t\toperations: ops,\n\t\t\t\t\tcontext: spawnContext,\n\t\t\t\t\ttempFilePrefix: config.tempFilePrefix,\n\t\t\t\t\ttimeout,\n\t\t\t\t\tcontrol,\n\t\t\t\t\ttaskLog: sessionTasks !== undefined,\n\t\t\t\t});\n\t\t\t};\n\t\t\tlet outcome: TaskToolOutcome<BashToolDetails | undefined>;\n\t\t\ttry {\n\t\t\t\toutcome = await (sessionTasks ?? standalone!).execute<BashToolDetails | undefined>({\n\t\t\t\t\tkind: config.name,\n\t\t\t\t\tlabel: config.shellName[0]!.toUpperCase() + config.shellName.slice(1),\n\t\t\t\t\ttitle: command,\n\t\t\t\t\tinput: { label: \"Command\", text: command, truncated: false, language: config.name },\n\t\t\t\t\tfacts: [[\"Directory\", ctx?.cwd || cwd]],\n\t\t\t\t\ttoolCallId,\n\t\t\t\t\tbackground,\n\t\t\t\t\tsignal: parentSignal,\n\t\t\t\t\tonUpdate: originalUpdate,\n\t\t\t\t\trun,\n\t\t\t\t});\n\t\t\t} finally {\n\t\t\t\tstandalone?.close();\n\t\t\t}\n\t\t\tif (outcome.kind === \"result\") return shellToolResult(outcome);\n\t\t\tconst tail = `Task ID: ${outcome.task.id}. Status: ${outcome.task.status}. Completion arrives and wakes you automatically — do not poll or wait on it; continue with other work, or end your turn and hand back to the user. If you would only wait for the result, prefer foreground next time. Use ${TASKS_TOOL_NAME} read to inspect output or ${TASKS_TOOL_NAME} kill to stop it.`;\n\t\t\t// Shell execution can become background work in two ways, and the model has to know which\n\t\t\t// one it got: a submitted background command starts from an empty log, while a detached\n\t\t\t// one already holds output and keeps its original timeout.\n\t\t\tconst handoff =\n\t\t\t\toutcome.reason === \"submitted\"\n\t\t\t\t\t? `Command handed to background. ${tail}`\n\t\t\t\t\t: `Command moved to the background while it was running, by the user. The execution continues unchanged — no restart, and a supplied timeout is still measured from command startup. Output produced so far is already in the log, so ${TASKS_TOOL_NAME} read now returns partial output, not a fresh start. ${tail}`;\n\t\t\treturn {\n\t\t\t\tstructuredContent: { task_id: outcome.task.id, status: outcome.task.status },\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: `${handoff}${outcome.task.outputPath ? `\\nFull output: ${outcome.task.outputPath}` : \"\"}`,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tdetails: {\n\t\t\t\t\tbackground: { kind: \"background\", taskId: outcome.task.id },\n\t\t\t\t\tfullOutputPath: outcome.task.outputPath,\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t\t...createShellRenderers(config),\n\t};\n}\n\nconst bashToolConfig: ShellToolConfig = {\n\tname: \"bash\",\n\tlabel: \"bash\",\n\tshellName: \"bash\",\n\tprompt: \"$\",\n\tpromptSnippet: bashToolSystemPromptContribution.snippet,\n\tpromptGuidelines: bashToolSystemPromptContribution.guidelines,\n\ttempFilePrefix: \"pi-bash\",\n};\n\nexport function createBashToolDefinition(\n\tcwd: string,\n\toptions?: BashToolOptions,\n): ReturnType<typeof createShellToolDefinition> {\n\treturn createShellToolDefinition(cwd, bashToolConfig, {\n\t\t...options,\n\t\toperations: options?.operations ?? createLocalBashOperations({ shellPath: options?.shellPath }),\n\t});\n}\n\nexport function createBashTool(cwd: string, options?: BashToolOptions) {\n\tconst definition = createBashToolDefinition(cwd, options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"shell-tool.js","sourceRoot":"","sources":["../../../src/core/tools/shell-tool.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAE5C,OAAO,EACN,yBAAyB,EACzB,eAAe,GAGf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAIN,yBAAyB,IAAI,+BAA+B,EAE5D,gBAAgB,IAAI,kBAAkB,EACtC,UAAU,IAAI,YAAY,GAE1B,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAA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AE,gCAAgC,CAAC,OAAO;IACvD,gBAAgB,EAAE,gCAAgC,CAAC,UAAU;IAC7D,cAAc,EAAE,SAAS;CACzB,CAAC;AAEF,MAAM,UAAU,wBAAwB,CACvC,GAAW,EACX,OAAyB;IAEzB,OAAO,yBAAyB,CAAC,GAAG,EAAE,cAAc,EAAE;QACrD,GAAG,OAAO;QACV,UAAU,EAAE,OAAO,EAAE,UAAU,IAAI,yBAAyB,CAAC,EAAE,SAAS,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;KAC/F,CAAC,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,GAAW,EAAE,OAAyB;IACpE,MAAM,UAAU,GAAG,wBAAwB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IAC1D,MAAM,IAAI,GAAG,kBAAkB,CAAC,UAAU,CAAC,CAAC;IAC5C,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE;QACnB,aAAa,EAAE,UAAU,CAAC,aAAa;QACvC,gBAAgB,EAAE,UAAU,CAAC,gBAAgB;KAC7C,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["/**\n * The managed shell tools: the native shell definition (`bash.ts`) plus a `background` parameter,\n * adapted to the session's Tasks. The native body stays the one owner of execution, progress,\n * output formatting and results; outside a session it runs unchanged.\n */\nimport { type Static, Type } from \"typebox\";\nimport type { ToolDefinition } from \"../extensions/types.ts\";\nimport {\n\tTASK_BACKGROUND_REJECTION,\n\tTASKS_TOOL_NAME,\n\ttype TaskCompletion,\n\ttype TaskToolOutcome,\n} from \"../tasks/types.ts\";\nimport {\n\ttype BashOperations,\n\ttype BashRenderState,\n\ttype BashToolOptions,\n\tcreateShellToolDefinition as createNativeShellToolDefinition,\n\ttype BashToolDetails as NativeBashToolDetails,\n\tbashOutputSchema as nativeOutputSchema,\n\tbashSchema as nativeSchema,\n\ttype ShellToolConfig,\n} from \"./bash.ts\";\nimport { runShellTask } from \"./shell-execution.ts\";\nimport { createLocalBashOperations } from \"./shell-operations.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nconst bashSchema = Type.Object({\n\t...nativeSchema.properties,\n\tbackground: Type.Optional(\n\t\tType.Boolean({\n\t\t\tdescription:\n\t\t\t\t\"true returns a managed task ID immediately and runs the command in the background, and you are notified when it completes — do not poll for its result; omit or false to block until exit\",\n\t\t}),\n\t),\n});\n\nexport const bashToolSystemPromptContribution = {\n\tsnippet: \"Execute bash commands, foreground or background\",\n\tguidelines: [\"You can inspect PI_* environment variables for current model and session details.\"],\n} as const;\n\nexport type BashToolInput = Static<typeof bashSchema>;\n\nconst bashOutputSchema = Type.Union([\n\tnativeOutputSchema,\n\tType.Object({ task_id: Type.String(), status: Type.String() }),\n]);\n\nexport interface BashToolDetails extends NativeBashToolDetails {\n\t/** Settled handoff snapshot, not a command completion or exit code. */\n\tbackground?: { kind: \"background\"; taskId: string };\n}\n\nconst BACKGROUND_GUIDANCE = `Choose the mode per call: foreground (default) blocks until the command exits — use it when your next step needs the output; background: true returns immediately with a task ID — use it for long-running work (builds, servers, watchers, big test suites) or when you have independent work to continue. A handoff is not completion: the result arrives later as an automatic completion notification; meanwhile use ${TASKS_TOOL_NAME} read to inspect output and ${TASKS_TOOL_NAME} kill to stop it. Background output is limited to 20 MiB.`;\n\n/**\n * Translate terminal shell failures to the native foreground tool contract once. A task result\n * holds the command's output only; the foreground text is that output followed by the failure.\n */\nfunction shellToolResult(completion: TaskCompletion<BashToolDetails | undefined>) {\n\tconst status = completion.status;\n\tconst output = completion.result.content\n\t\t.filter((part) => part.type === \"text\")\n\t\t.map((part) => part.text)\n\t\t.join(\"\\n\");\n\tconst withError = (error: string) => (output ? `${output}\\n\\n${error}` : error);\n\tif (completion.result.structuredContent) {\n\t\tif (!completion.result.isError || !completion.error) return completion.result;\n\t\treturn { ...completion.result, content: [{ type: \"text\" as const, text: withError(completion.error) }] };\n\t}\n\tif (status === \"failed\" || status === \"timeout\" || status === \"cancelled\") {\n\t\tthrow new Error(\n\t\t\tcompletion.error ? withError(completion.error) : `${output ? `${output}\\n\\n` : \"\"}Command ${status}`,\n\t\t);\n\t}\n\treturn completion.result;\n}\n\nexport function createShellToolDefinition(\n\tcwd: string,\n\tconfig: ShellToolConfig,\n\toptions: BashToolOptions & { operations: BashOperations },\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\tconst native = createNativeShellToolDefinition(cwd, config, options);\n\treturn {\n\t\t...native,\n\t\tdescription: `${native.description} ${BACKGROUND_GUIDANCE}`,\n\t\tparameters: bashSchema,\n\t\toutputSchema: bashOutputSchema,\n\t\tasync execute(toolCallId, { command, timeout, background }: BashToolInput, parentSignal, onUpdate, ctx) {\n\t\t\tconst tasks = ctx?.tasks;\n\t\t\tif (!tasks) {\n\t\t\t\tif (background) throw new Error(TASK_BACKGROUND_REJECTION);\n\t\t\t\treturn native.execute(toolCallId, { command, timeout }, parentSignal, onUpdate, ctx);\n\t\t\t}\n\t\t\tif (tasks.closed) throw new Error(\"Task service is closed\");\n\t\t\tconst outcome: TaskToolOutcome<BashToolDetails | undefined> = await tasks.execute<BashToolDetails | undefined>(\n\t\t\t\t{\n\t\t\t\t\tkind: config.name,\n\t\t\t\t\tlabel: config.shellName[0]!.toUpperCase() + config.shellName.slice(1),\n\t\t\t\t\ttitle: command,\n\t\t\t\t\tinput: { label: \"Command\", text: command, truncated: false, language: config.name },\n\t\t\t\t\tfacts: [[\"Directory\", ctx.cwd || cwd]],\n\t\t\t\t\ttoolCallId,\n\t\t\t\t\tbackground,\n\t\t\t\t\tsignal: parentSignal,\n\t\t\t\t\tonUpdate,\n\t\t\t\t\t// A setup throw settles the task as failed, or cancelled once its signal fired.\n\t\t\t\t\trun: (control) =>\n\t\t\t\t\t\trunShellTask({\n\t\t\t\t\t\t\tcontrol,\n\t\t\t\t\t\t\toperations: options.operations,\n\t\t\t\t\t\t\ttempFilePrefix: config.tempFilePrefix,\n\t\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\t\texecute: (parts) =>\n\t\t\t\t\t\t\t\tcreateNativeShellToolDefinition(\n\t\t\t\t\t\t\t\t\tcwd,\n\t\t\t\t\t\t\t\t\t{ ...config, createOutput: parts.createOutput },\n\t\t\t\t\t\t\t\t\t{ ...options, operations: parts.operations },\n\t\t\t\t\t\t\t\t).execute(toolCallId, { command, timeout }, control.signal, parts.onUpdate, ctx),\n\t\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (outcome.kind === \"result\") return shellToolResult(outcome);\n\t\t\tconst tail = `Task ID: ${outcome.task.id}. Status: ${outcome.task.status}. Completion arrives and wakes you automatically — do not poll or wait on it; continue with other work, or end your turn and hand back to the user. If you would only wait for the result, prefer foreground next time. Use ${TASKS_TOOL_NAME} read to inspect output or ${TASKS_TOOL_NAME} kill to stop it.`;\n\t\t\t// Shell execution can become background work in two ways, and the model has to know which\n\t\t\t// one it got: a submitted background command starts from an empty log, while a detached\n\t\t\t// one already holds output and keeps its original timeout.\n\t\t\tconst handoff =\n\t\t\t\toutcome.reason === \"submitted\"\n\t\t\t\t\t? `Command handed to background. ${tail}`\n\t\t\t\t\t: `Command moved to the background while it was running, by the user. The execution continues unchanged — no restart, and a supplied timeout is still measured from command startup. Output produced so far is already in the log, so ${TASKS_TOOL_NAME} read now returns partial output, not a fresh start. ${tail}`;\n\t\t\treturn {\n\t\t\t\tstructuredContent: { task_id: outcome.task.id, status: outcome.task.status },\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: `${handoff}${outcome.task.outputPath ? `\\nFull output: ${outcome.task.outputPath}` : \"\"}`,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tdetails: {\n\t\t\t\t\tbackground: { kind: \"background\", taskId: outcome.task.id },\n\t\t\t\t\tfullOutputPath: outcome.task.outputPath,\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t};\n}\n\nconst bashToolConfig: ShellToolConfig = {\n\tname: \"bash\",\n\tlabel: \"bash\",\n\tshellName: \"bash\",\n\tprompt: \"$\",\n\tpromptSnippet: bashToolSystemPromptContribution.snippet,\n\tpromptGuidelines: bashToolSystemPromptContribution.guidelines,\n\ttempFilePrefix: \"pi-bash\",\n};\n\nexport function createBashToolDefinition(\n\tcwd: string,\n\toptions?: BashToolOptions,\n): ReturnType<typeof createShellToolDefinition> {\n\treturn createShellToolDefinition(cwd, bashToolConfig, {\n\t\t...options,\n\t\toperations: options?.operations ?? createLocalBashOperations({ shellPath: options?.shellPath }),\n\t});\n}\n\nexport function createBashTool(cwd: string, options?: BashToolOptions) {\n\tconst definition = createBashToolDefinition(cwd, options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]}
|
|
@@ -1,9 +1,19 @@
|
|
|
1
|
-
import type { AgentTool } from "@earendil-works/pi-agent-core";
|
|
2
|
-
import type { TSchema } from "typebox";
|
|
1
|
+
import type { AgentTool, AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
|
|
2
|
+
import type { Static, TSchema } from "typebox";
|
|
3
3
|
import type { ExtensionToolContext, ToolDefinition } from "../extensions/types.ts";
|
|
4
|
+
/**
|
|
5
|
+
* An `AgentTool` with a TypeBox parameter schema whose `execute` and `prepareArguments` are typed by TypeBox's
|
|
6
|
+
* `Static`, as the built-in tools are (pi-agent-core types `params` through pi-schema, which maps only the common
|
|
7
|
+
* TypeBox kinds). Spreads into a `ToolDefinition` of the same schema.
|
|
8
|
+
*/
|
|
9
|
+
export type TypeBoxAgentTool<TParams extends TSchema = TSchema, TDetails = any> = Omit<AgentTool<TParams, TDetails>, "prepareArguments" | "execute"> & {
|
|
10
|
+
prepareArguments?: (args: unknown) => Static<TParams>;
|
|
11
|
+
execute: (toolCallId: string, params: Static<TParams>, signal?: AbortSignal, onUpdate?: AgentToolUpdateCallback<TDetails>) => Promise<AgentToolResult<TDetails>>;
|
|
12
|
+
};
|
|
13
|
+
/** Creates the context for one tool call. */
|
|
4
14
|
export type ToolContextFactory = (toolCallId: string, signal: AbortSignal | undefined) => ExtensionToolContext;
|
|
5
15
|
/** Wrap a ToolDefinition into an AgentTool for the core runtime. */
|
|
6
|
-
export declare function wrapToolDefinition<
|
|
16
|
+
export declare function wrapToolDefinition<TDetails = unknown>(definition: ToolDefinition<any, TDetails>, ctxFactory?: ToolContextFactory): AgentTool<any, TDetails>;
|
|
7
17
|
/** Wrap multiple ToolDefinitions into AgentTools for the core runtime. */
|
|
8
18
|
export declare function wrapToolDefinitions(definitions: ToolDefinition<any, any>[], ctxFactory?: ToolContextFactory): AgentTool<any>[];
|
|
9
19
|
/**
|
|
@@ -12,5 +22,5 @@ export declare function wrapToolDefinitions(definitions: ToolDefinition<any, any
|
|
|
12
22
|
* This keeps AgentSession's internal registry definition-first even when a caller
|
|
13
23
|
* provides plain AgentTool overrides that do not include prompt metadata or renderers.
|
|
14
24
|
*/
|
|
15
|
-
export declare function createToolDefinitionFromAgentTool
|
|
25
|
+
export declare function createToolDefinitionFromAgentTool(tool: AgentTool<any>): ToolDefinition<any, unknown>;
|
|
16
26
|
//# sourceMappingURL=tool-definition-wrapper.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-definition-wrapper.d.ts","sourceRoot":"","sources":["../../../src/core/tools/tool-definition-wrapper.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;
|
|
1
|
+
{"version":3,"file":"tool-definition-wrapper.d.ts","sourceRoot":"","sources":["../../../src/core/tools/tool-definition-wrapper.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,eAAe,EAAE,uBAAuB,EAAE,MAAM,+BAA+B,CAAC;AAEzG,OAAO,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MA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AC,CAYpG"}
|
|
@@ -15,8 +15,7 @@ function isRecord(value) {
|
|
|
15
15
|
* validator's own report says where validation failed; these hints say what
|
|
16
16
|
* the legal shape is. Union variants (`anyOf`, e.g. a nullable field) are
|
|
17
17
|
* walked through so nested shapes still get hints. Paths use the validator's
|
|
18
|
-
* dotted style
|
|
19
|
-
* (`tasks[0].prompt`). Non-null unknown fields are reported rather than
|
|
18
|
+
* dotted style (`tasks.0.prompt`). Non-null unknown fields are reported rather than
|
|
20
19
|
* silently dropped: a field like `prompt_extra` may carry briefing content
|
|
21
20
|
* the caller intended to send.
|
|
22
21
|
*/
|
|
@@ -35,7 +34,7 @@ function collectFieldHints(schema, args) {
|
|
|
35
34
|
}
|
|
36
35
|
if (node.type === "array" && Array.isArray(value)) {
|
|
37
36
|
for (let index = 0; index < value.length; index++) {
|
|
38
|
-
visit(node.items, value[index], `${path}
|
|
37
|
+
visit(node.items, value[index], `${path}.${index}`);
|
|
39
38
|
}
|
|
40
39
|
return;
|
|
41
40
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-definition-wrapper.js","sourceRoot":"","sources":["../../../src/core/tools/tool-definition-wrapper.ts"],"names":[],"mappings":"AACA,OAAO,EAAmB,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAG/E,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAI7C,MAAM,yBAAyB,GAAG,2BAA2B,CAAC;AAC9D,MAAM,WAAW,GAAG,YAAY,CAAC;AACjC,MAAM,4BAA4B,GAAG,CAAC,GAAG,IAAI,CAAC;AAC9C,MAAM,4BAA4B,GAAG,EAAE,CAAC;AACxC,MAAM,eAAe,GAAG,EAAE,CAAC;AAE3B,SAAS,QAAQ,CAAC,KAAc;IAC/B,OAAO,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC7E,CAAC;AAED;;;;;;;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,IAAI,CAAC,gBAAgB;QACvC,aAAa,EAAE,IAAI,CAAC,aAAa;QACjC,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC;KAC3G,CAAC;AACH,CAAC","sourcesContent":["import type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { type JsonObject, validateToolArguments } from \"@earendil-works/pi-ai\";\nimport type { Static, TSchema } from \"typebox\";\nimport type { ExtensionToolContext, ToolDefinition } from \"../extensions/types.ts\";\nimport { truncateHead } from \"./truncate.ts\";\n\nexport type ToolContextFactory = (toolCallId: string, signal: AbortSignal | undefined) => ExtensionToolContext;\n\nconst RECEIVED_ARGUMENTS_MARKER = \"\\n\\nReceived arguments:\\n\";\nconst HINT_MARKER = \"\\n\\nHint: \";\nconst RECEIVED_ARGUMENTS_MAX_BYTES = 2 * 1024;\nconst RECEIVED_ARGUMENTS_MAX_LINES = 40;\nconst FIELD_HINTS_MAX = 10;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/**\n * Walk schema and arguments in sync to name, at every object with\n * `additionalProperties: false`, the non-null fields the schema does not\n * declare, and at every object, the required fields the arguments lack. The\n * validator's own report says where validation failed; these hints say what\n * the legal shape is. Union variants (`anyOf`, e.g. a nullable field) are\n * walked through so nested shapes still get hints. Paths use the validator's\n * dotted style\n * (`tasks[0].prompt`). Non-null unknown fields are reported rather than\n * silently dropped: a field like `prompt_extra` may carry briefing content\n * the caller intended to send.\n */\nfunction collectFieldHints(schema: unknown, args: unknown): string[] {\n\tconst hints: string[] = [];\n\tconst visit = (node: unknown, value: unknown, path: string): void => {\n\t\tif (hints.length >= FIELD_HINTS_MAX || !isRecord(node)) return;\n\t\tif (Array.isArray(node.anyOf)) {\n\t\t\t// Only nullable single-shape unions have unambiguous field requirements.\n\t\t\t// Alternative object shapes must not contribute contradictory hints.\n\t\t\tconst variants = node.anyOf.filter((variant: unknown) => !isRecord(variant) || variant.type !== \"null\");\n\t\t\tif (value !== null && variants.length === 1) visit(variants[0], value, path);\n\t\t\treturn;\n\t\t}\n\t\tif (node.type === \"array\" && Array.isArray(value)) {\n\t\t\tfor (let index = 0; index < value.length; index++) {\n\t\t\t\tvisit(node.items, value[index], `${path}[${index}]`);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (node.type !== \"object\" || !isRecord(value)) return;\n\t\tconst properties = isRecord(node.properties) ? node.properties : {};\n\t\tconst fields = Object.keys(properties);\n\t\tconst where = path || \"root\";\n\t\tif (node.additionalProperties === false) {\n\t\t\tfor (const [key, entry] of Object.entries(value)) {\n\t\t\t\tif (entry !== null && !(key in properties) && hints.length < FIELD_HINTS_MAX) {\n\t\t\t\t\tconst subject = path ? `${path}.${key}` : key;\n\t\t\t\t\thints.push(`${subject} is not a field; fields at ${where}: ${fields.join(\", \")}`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (Array.isArray(node.required)) {\n\t\t\tfor (const key of node.required) {\n\t\t\t\tif (typeof key === \"string\" && value[key] === undefined && hints.length < FIELD_HINTS_MAX) {\n\t\t\t\t\tconst subject = path ? `${path}.${key}` : key;\n\t\t\t\t\thints.push(`${subject} is required; fields at ${where}: ${fields.join(\", \")}`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (const key of fields) {\n\t\t\tif (value[key] !== undefined && value[key] !== null) {\n\t\t\t\tvisit(properties[key], value[key], path ? `${path}.${key}` : key);\n\t\t\t}\n\t\t}\n\t};\n\tvisit(schema, args, \"\");\n\treturn hints;\n}\n\n/**\n * Rebuild pi-ai's validation error so a model can self-correct: the legal\n * fields are named next to each offending one, and the echoed arguments are\n * bounded (a 50KB tool argument must not be reflected whole into context).\n * The `Validation failed for tool \"<name>\":` prefix stays intact — the\n * question tool's renderer parses it.\n */\nfunction enrichValidationError(error: unknown, parameters: TSchema, args: unknown): Error {\n\tconst message = error instanceof Error ? error.message : String(error);\n\t// A definition synthesized from an already-wrapped tool enriches on the\n\t// inside; do not stack a second layer of hints on the same failure.\n\tif (message.includes(HINT_MARKER)) return error instanceof Error ? error : new Error(message);\n\tconst hints = collectFieldHints(parameters, args);\n\tconst markerIndex = message.indexOf(RECEIVED_ARGUMENTS_MARKER);\n\tconst head = markerIndex === -1 ? message : message.slice(0, markerIndex);\n\tconst received = markerIndex === -1 ? \"\" : message.slice(markerIndex + RECEIVED_ARGUMENTS_MARKER.length);\n\tlet enriched = hints.length > 0 ? `${head}\\n\\nHint: ${hints.join(\"\\nHint: \")}` : head;\n\tif (markerIndex !== -1) {\n\t\tconst bounded = truncateHead(received, {\n\t\t\tmaxBytes: RECEIVED_ARGUMENTS_MAX_BYTES,\n\t\t\tmaxLines: RECEIVED_ARGUMENTS_MAX_LINES,\n\t\t});\n\t\tenriched += `${RECEIVED_ARGUMENTS_MARKER}${bounded.content}`;\n\t\tif (bounded.truncated) enriched += \"\\n… (arguments truncated)\";\n\t}\n\treturn new Error(enriched);\n}\n\n/**\n * Pre-validate prepared arguments so a validation failure reaches the model\n * with field-level hints. Valid arguments pass through untouched and are\n * validated again by the agent loop as before.\n */\nfunction wrapPrepareArguments<TParams extends TSchema, TDetails>(\n\tdefinition: ToolDefinition<TParams, TDetails>,\n): (raw: unknown) => Static<TParams> {\n\tconst tool = { name: definition.name, description: definition.description, parameters: definition.parameters };\n\treturn (raw: unknown): Static<TParams> => {\n\t\tconst args = definition.prepareArguments ? definition.prepareArguments(raw) : raw;\n\t\ttry {\n\t\t\tvalidateToolArguments(tool, {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tid: \"\",\n\t\t\t\tname: definition.name,\n\t\t\t\targuments: args as JsonObject,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow enrichValidationError(error, definition.parameters, args);\n\t\t}\n\t\treturn args as Static<TParams>;\n\t};\n}\n\n/** Wrap a ToolDefinition into an AgentTool for the core runtime. */\nexport function wrapToolDefinition<TParams extends TSchema, TDetails = unknown>(\n\tdefinition: ToolDefinition<TParams, TDetails>,\n\tctxFactory?: ToolContextFactory,\n): AgentTool<TParams, TDetails> {\n\treturn {\n\t\tname: definition.name,\n\t\tlabel: definition.label,\n\t\tdescription: definition.description,\n\t\tparameters: definition.parameters,\n\t\toutputSchema: definition.outputSchema,\n\t\tconstrainedSampling: definition.constrainedSampling,\n\t\tprepareArguments: wrapPrepareArguments(definition),\n\t\texecutionMode: definition.executionMode,\n\t\texecute: (toolCallId, params, signal, onUpdate, ctx?: ExtensionToolContext) =>\n\t\t\tdefinition.execute(\n\t\t\t\ttoolCallId,\n\t\t\t\tparams,\n\t\t\t\tsignal,\n\t\t\t\tonUpdate,\n\t\t\t\tctx ?? (ctxFactory?.(toolCallId, signal) as ExtensionToolContext),\n\t\t\t),\n\t};\n}\n\n/** Wrap multiple ToolDefinitions into AgentTools for the core runtime. */\nexport function wrapToolDefinitions(\n\tdefinitions: ToolDefinition<any, any>[],\n\tctxFactory?: ToolContextFactory,\n): AgentTool<any>[] {\n\treturn definitions.map((definition) => wrapToolDefinition(definition, ctxFactory));\n}\n\n/**\n * Synthesize a minimal ToolDefinition from an AgentTool.\n *\n * This keeps AgentSession's internal registry definition-first even when a caller\n * provides plain AgentTool overrides that do not include prompt metadata or renderers.\n */\nexport function createToolDefinitionFromAgentTool<TParams extends TSchema, TDetails>(\n\ttool: AgentTool<TParams, TDetails>,\n): ToolDefinition<TParams, TDetails> {\n\treturn {\n\t\tname: tool.name,\n\t\tlabel: tool.label,\n\t\tdescription: tool.description,\n\t\tparameters: tool.parameters,\n\t\toutputSchema: tool.outputSchema,\n\t\tconstrainedSampling: tool.constrainedSampling,\n\t\tprepareArguments: tool.prepareArguments,\n\t\texecutionMode: tool.executionMode,\n\t\texecute: async (toolCallId, params, signal, onUpdate) => tool.execute(toolCallId, params, signal, onUpdate),\n\t};\n}\n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,UAAU,EAAE,CAAC,UAAU,EAAE,MAAM,CAA0B,CACjE;KACF,CAAC;AACH,CAAC;AAED,0EAA0E;AAC1E,MAAM,UAAU,mBAAmB,CAClC,WAAuC,EACvC,UAA+B;IAE/B,OAAO,WAAW,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,kBAAkB,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC;AACpF,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,iCAAiC,CAAC,IAAoB;IACrE,OAAO;QACN,IAAI,EAAE,IAAI,CAAC,IAAI;QACf,KAAK,EAAE,IAAI,CAAC,KAAK;QACjB,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,UAAU,EAAE,IAAI,CAAC,UAAiB;QAClC,YAAY,EAAE,IAAI,CAAC,YAAY;QAC/B,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;QAC7C,gBAAgB,EAAE,IAAI,CAAC,gBAAgB;QACvC,aAAa,EAAE,IAAI,CAAC,aAAa;QACjC,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC;KAC3G,CAAC;AACH,CAAC","sourcesContent":["import type { AgentTool, AgentToolResult, AgentToolUpdateCallback } from \"@earendil-works/pi-agent-core\";\nimport { type JsonObject, validateToolArguments } from \"@earendil-works/pi-ai\";\nimport type { Static, TSchema } from \"typebox\";\nimport type { ExtensionToolContext, ToolDefinition } from \"../extensions/types.ts\";\nimport { truncateHead } from \"./truncate.ts\";\n\n/**\n * An `AgentTool` with a TypeBox parameter schema whose `execute` and `prepareArguments` are typed by TypeBox's\n * `Static`, as the built-in tools are (pi-agent-core types `params` through pi-schema, which maps only the common\n * TypeBox kinds). Spreads into a `ToolDefinition` of the same schema.\n */\nexport type TypeBoxAgentTool<TParams extends TSchema = TSchema, TDetails = any> = Omit<\n\tAgentTool<TParams, TDetails>,\n\t\"prepareArguments\" | \"execute\"\n> & {\n\tprepareArguments?: (args: unknown) => Static<TParams>;\n\texecute: (\n\t\ttoolCallId: string,\n\t\tparams: Static<TParams>,\n\t\tsignal?: AbortSignal,\n\t\tonUpdate?: AgentToolUpdateCallback<TDetails>,\n\t) => Promise<AgentToolResult<TDetails>>;\n};\n\n/** Creates the context for one tool call. */\nexport type ToolContextFactory = (toolCallId: string, signal: AbortSignal | undefined) => ExtensionToolContext;\n\nconst RECEIVED_ARGUMENTS_MARKER = \"\\n\\nReceived arguments:\\n\";\nconst HINT_MARKER = \"\\n\\nHint: \";\nconst RECEIVED_ARGUMENTS_MAX_BYTES = 2 * 1024;\nconst RECEIVED_ARGUMENTS_MAX_LINES = 40;\nconst FIELD_HINTS_MAX = 10;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/**\n * Walk schema and arguments in sync to name, at every object with\n * `additionalProperties: false`, the non-null fields the schema does not\n * declare, and at every object, the required fields the arguments lack. The\n * validator's own report says where validation failed; these hints say what\n * the legal shape is. Union variants (`anyOf`, e.g. a nullable field) are\n * walked through so nested shapes still get hints. Paths use the validator's\n * dotted style (`tasks.0.prompt`). Non-null unknown fields are reported rather than\n * silently dropped: a field like `prompt_extra` may carry briefing content\n * the caller intended to send.\n */\nfunction collectFieldHints(schema: unknown, args: unknown): string[] {\n\tconst hints: string[] = [];\n\tconst visit = (node: unknown, value: unknown, path: string): void => {\n\t\tif (hints.length >= FIELD_HINTS_MAX || !isRecord(node)) return;\n\t\tif (Array.isArray(node.anyOf)) {\n\t\t\t// Only nullable single-shape unions have unambiguous field requirements.\n\t\t\t// Alternative object shapes must not contribute contradictory hints.\n\t\t\tconst variants = node.anyOf.filter((variant: unknown) => !isRecord(variant) || variant.type !== \"null\");\n\t\t\tif (value !== null && variants.length === 1) visit(variants[0], value, path);\n\t\t\treturn;\n\t\t}\n\t\tif (node.type === \"array\" && Array.isArray(value)) {\n\t\t\tfor (let index = 0; index < value.length; index++) {\n\t\t\t\tvisit(node.items, value[index], `${path}.${index}`);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (node.type !== \"object\" || !isRecord(value)) return;\n\t\tconst properties = isRecord(node.properties) ? node.properties : {};\n\t\tconst fields = Object.keys(properties);\n\t\tconst where = path || \"root\";\n\t\tif (node.additionalProperties === false) {\n\t\t\tfor (const [key, entry] of Object.entries(value)) {\n\t\t\t\tif (entry !== null && !(key in properties) && hints.length < FIELD_HINTS_MAX) {\n\t\t\t\t\tconst subject = path ? `${path}.${key}` : key;\n\t\t\t\t\thints.push(`${subject} is not a field; fields at ${where}: ${fields.join(\", \")}`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (Array.isArray(node.required)) {\n\t\t\tfor (const key of node.required) {\n\t\t\t\tif (typeof key === \"string\" && value[key] === undefined && hints.length < FIELD_HINTS_MAX) {\n\t\t\t\t\tconst subject = path ? `${path}.${key}` : key;\n\t\t\t\t\thints.push(`${subject} is required; fields at ${where}: ${fields.join(\", \")}`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (const key of fields) {\n\t\t\tif (value[key] !== undefined && value[key] !== null) {\n\t\t\t\tvisit(properties[key], value[key], path ? `${path}.${key}` : key);\n\t\t\t}\n\t\t}\n\t};\n\tvisit(schema, args, \"\");\n\treturn hints;\n}\n\n/**\n * Rebuild pi-ai's validation error so a model can self-correct: the legal\n * fields are named next to each offending one, and the echoed arguments are\n * bounded (a 50KB tool argument must not be reflected whole into context).\n * The `Validation failed for tool \"<name>\":` prefix stays intact — the\n * question tool's renderer parses it.\n */\nfunction enrichValidationError(error: unknown, parameters: TSchema, args: unknown): Error {\n\tconst message = error instanceof Error ? error.message : String(error);\n\t// A definition synthesized from an already-wrapped tool enriches on the\n\t// inside; do not stack a second layer of hints on the same failure.\n\tif (message.includes(HINT_MARKER)) return error instanceof Error ? error : new Error(message);\n\tconst hints = collectFieldHints(parameters, args);\n\tconst markerIndex = message.indexOf(RECEIVED_ARGUMENTS_MARKER);\n\tconst head = markerIndex === -1 ? message : message.slice(0, markerIndex);\n\tconst received = markerIndex === -1 ? \"\" : message.slice(markerIndex + RECEIVED_ARGUMENTS_MARKER.length);\n\tlet enriched = hints.length > 0 ? `${head}\\n\\nHint: ${hints.join(\"\\nHint: \")}` : head;\n\tif (markerIndex !== -1) {\n\t\tconst bounded = truncateHead(received, {\n\t\t\tmaxBytes: RECEIVED_ARGUMENTS_MAX_BYTES,\n\t\t\tmaxLines: RECEIVED_ARGUMENTS_MAX_LINES,\n\t\t});\n\t\tenriched += `${RECEIVED_ARGUMENTS_MARKER}${bounded.content}`;\n\t\tif (bounded.truncated) enriched += \"\\n… (arguments truncated)\";\n\t}\n\treturn new Error(enriched);\n}\n\n/**\n * Pre-validate prepared arguments so a validation failure reaches the model\n * with field-level hints. Valid arguments pass through untouched and are\n * validated again by the agent loop as before.\n */\nfunction wrapPrepareArguments(definition: ToolDefinition<any, any>): (raw: unknown) => unknown {\n\tconst tool = { name: definition.name, description: definition.description, parameters: definition.parameters };\n\treturn (raw: unknown): unknown => {\n\t\tconst args = definition.prepareArguments ? definition.prepareArguments(raw) : raw;\n\t\ttry {\n\t\t\tvalidateToolArguments(tool, {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tid: \"\",\n\t\t\t\tname: definition.name,\n\t\t\t\targuments: args as JsonObject,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow enrichValidationError(error, definition.parameters, args);\n\t\t}\n\t\treturn args;\n\t};\n}\n\n/** Wrap a ToolDefinition into an AgentTool for the core runtime. */\nexport function wrapToolDefinition<TDetails = unknown>(\n\tdefinition: ToolDefinition<any, TDetails>,\n\tctxFactory?: ToolContextFactory,\n): AgentTool<any, TDetails> {\n\treturn {\n\t\tname: definition.name,\n\t\tlabel: definition.label,\n\t\tdescription: definition.description,\n\t\tparameters: definition.parameters,\n\t\toutputSchema: definition.outputSchema,\n\t\tconstrainedSampling: definition.constrainedSampling,\n\t\tprepareArguments: wrapPrepareArguments(definition),\n\t\texecutionMode: definition.executionMode,\n\t\texecute: (toolCallId, params, signal, onUpdate, ctx?: ExtensionToolContext) =>\n\t\t\tdefinition.execute(\n\t\t\t\ttoolCallId,\n\t\t\t\tparams,\n\t\t\t\tsignal,\n\t\t\t\tonUpdate,\n\t\t\t\tctx ?? (ctxFactory?.(toolCallId, signal) as ExtensionToolContext),\n\t\t\t),\n\t};\n}\n\n/** Wrap multiple ToolDefinitions into AgentTools for the core runtime. */\nexport function wrapToolDefinitions(\n\tdefinitions: ToolDefinition<any, any>[],\n\tctxFactory?: ToolContextFactory,\n): AgentTool<any>[] {\n\treturn definitions.map((definition) => wrapToolDefinition(definition, ctxFactory));\n}\n\n/**\n * Synthesize a minimal ToolDefinition from an AgentTool.\n *\n * This keeps AgentSession's internal registry definition-first even when a caller\n * provides plain AgentTool overrides that do not include prompt metadata or renderers.\n */\nexport function createToolDefinitionFromAgentTool(tool: AgentTool<any>): ToolDefinition<any, unknown> {\n\treturn {\n\t\tname: tool.name,\n\t\tlabel: tool.label,\n\t\tdescription: tool.description,\n\t\tparameters: tool.parameters as any,\n\t\toutputSchema: tool.outputSchema,\n\t\tconstrainedSampling: tool.constrainedSampling,\n\t\tprepareArguments: tool.prepareArguments,\n\t\texecutionMode: tool.executionMode,\n\t\texecute: async (toolCallId, params, signal, onUpdate) => tool.execute(toolCallId, params, signal, onUpdate),\n\t};\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import type { AgentTool } from "@earendil-works/pi-agent-core";
|
|
2
1
|
import { type Static, Type } from "typebox";
|
|
3
2
|
import type { ToolDefinition } from "../extensions/types.ts";
|
|
3
|
+
import { type TypeBoxAgentTool } from "./tool-definition-wrapper.ts";
|
|
4
4
|
declare const writeSchema: Type.TObject<{
|
|
5
5
|
path: Type.TString;
|
|
6
6
|
content: Type.TString;
|
|
@@ -25,6 +25,6 @@ export interface WriteToolOptions {
|
|
|
25
25
|
operations?: WriteOperations;
|
|
26
26
|
}
|
|
27
27
|
export declare function createWriteToolDefinition(cwd: string, options?: WriteToolOptions): ToolDefinition<typeof writeSchema, undefined>;
|
|
28
|
-
export declare function createWriteTool(cwd: string, options?: WriteToolOptions):
|
|
28
|
+
export declare function createWriteTool(cwd: string, options?: WriteToolOptions): TypeBoxAgentTool<typeof writeSchema>;
|
|
29
29
|
export {};
|
|
30
30
|
//# sourceMappingURL=write.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"write.d.ts","sourceRoot":"","sources":["../../../src/core/tools/write.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"write.d.ts","sourceRoot":"","sources":["../../../src/core/tools/write.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,KAAK,EAAoB,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAI/E,OAAO,EAAE,KAAK,gBAAgB,EAAsB,MAAM,8BAA8B,CAAC;AAEzF,QAAA,MAAM,WAAW;;;EAGf,CAAC;AAEH,eAAO,MAAM,iCAAiC;;;CAGpC,CAAC;AAEX,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC,OAAO,WAAW,CAAC,CAAC;AAExD;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC/B,8BAA8B;IAC9B,SAAS,EAAE,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACpE,mCAAmC;IACnC,KAAK,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CACtC;AAOD,MAAM,WAAW,gBAAgB;IAChC,oEAAoE;IACpE,UAAU,CAAC,EAAE,eAAe,CAAC;CAC7B;AAED,wBAAgB,yBAAyB,CACxC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,gBAAgB,GACxB,cAAc,CAAC,OAAO,WAAW,EAAE,SAAS,CAAC,CA8C/C;AAED,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,gBAAgB,CAAC,OAAO,WAAW,CAAC,CAE7G"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"write.js","sourceRoot":"","sources":["../../../src/core/tools/write.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"write.js","sourceRoot":"","sources":["../../../src/core/tools/write.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,IAAI,OAAO,EAAE,SAAS,IAAI,WAAW,EAAE,MAAM,aAAa,CAAC;AACzE,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC/B,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAE5C,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAyB,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAEzF,MAAM,WAAW,GAAG,IAAI,CAAC,MAAM,CAAC;IAC/B,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,kDAAkD,EAAE,CAAC;IACtF,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,8BAA8B,EAAE,CAAC;CACrE,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,iCAAiC,GAAG;IAChD,OAAO,EAAE,2BAA2B;IACpC,UAAU,EAAE,CAAC,oDAAoD,CAAC;CACzD,CAAC;AAeX,MAAM,sBAAsB,GAAoB;IAC/C,SAAS,EAAE,CAAC,IAAI,EAAE,OAAO,EAAE,EAAE,CAAC,WAAW,CAA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AAE,CAAC;gBAEjB,2BAA2B;gBAC3B,MAAM,GAAG,CAAC,SAAS,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC;gBAC3C,cAAc,EAAE,CAAC;gBAEjB,OAAO;oBACN,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,yBAAyB,IAAI,EAAE,EAAE,CAAC;oBAClE,OAAO,EAAE,SAAS;iBAClB,CAAC;YACH,CAAC,CAAC,CAAC;QACJ,CAAC;QACD,GAAG,cAAc;KACjB,CAAC;AACH,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,GAAW,EAAE,OAA0B;IACtE,OAAO,kBAAkB,CAAC,yBAAyB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AACpE,CAAC","sourcesContent":["import { mkdir as fsMkdir, writeFile as fsWriteFile } from \"fs/promises\";\nimport { dirname } from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport type { ExtensionContext, ToolDefinition } from \"../extensions/types.ts\";\nimport { withFileMutationQueue } from \"./file-mutation-queue.ts\";\nimport { resolveToCwd } from \"./path-utils.ts\";\nimport { writeRenderers } from \"./renderers/write.ts\";\nimport { type TypeBoxAgentTool, wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nconst writeSchema = Type.Object({\n\tpath: Type.String({ description: \"Path to the file to write (relative or absolute)\" }),\n\tcontent: Type.String({ description: \"Content to write to the file\" }),\n});\n\nexport const writeToolSystemPromptContribution = {\n\tsnippet: \"Create or overwrite files\",\n\tguidelines: [\"Use write only for new files or complete rewrites.\"],\n} as const;\n\nexport type WriteToolInput = Static<typeof writeSchema>;\n\n/**\n * Pluggable operations for the write tool.\n * Override these to delegate file writing to remote systems (for example SSH).\n */\nexport interface WriteOperations {\n\t/** Write content to a file */\n\twriteFile: (absolutePath: string, content: string) => Promise<void>;\n\t/** Create directory recursively */\n\tmkdir: (dir: string) => Promise<void>;\n}\n\nconst defaultWriteOperations: WriteOperations = {\n\twriteFile: (path, content) => fsWriteFile(path, content, \"utf-8\"),\n\tmkdir: (dir) => fsMkdir(dir, { recursive: true }).then(() => {}),\n};\n\nexport interface WriteToolOptions {\n\t/** Custom operations for file writing. Default: local filesystem */\n\toperations?: WriteOperations;\n}\n\nexport function createWriteToolDefinition(\n\tcwd: string,\n\toptions?: WriteToolOptions,\n): ToolDefinition<typeof writeSchema, undefined> {\n\tconst ops = options?.operations ?? defaultWriteOperations;\n\treturn {\n\t\tname: \"write\",\n\t\tlabel: \"write\",\n\t\tdescription:\n\t\t\t\"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.\",\n\t\tpromptSnippet: writeToolSystemPromptContribution.snippet,\n\t\tpromptGuidelines: [...writeToolSystemPromptContribution.guidelines],\n\t\tparameters: writeSchema,\n\t\tconstrainedSampling: { type: \"json_schema\", strict: \"prefer\" },\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ path, content }: { path: string; content: string },\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\tctx?: ExtensionContext,\n\t\t) {\n\t\t\tconst absolutePath = resolveToCwd(path, ctx?.cwd || cwd);\n\t\t\tconst dir = dirname(absolutePath);\n\t\t\treturn withFileMutationQueue(absolutePath, async () => {\n\t\t\t\t// Do not reject from an abort event listener here: that would release the\n\t\t\t\t// mutation queue while an in-flight filesystem operation may still finish.\n\t\t\t\t// Checking signal.aborted after each await observes the same aborts while\n\t\t\t\t// keeping the queue locked until the current operation has settled.\n\t\t\t\tconst throwIfAborted = (): void => {\n\t\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\t};\n\n\t\t\t\tthrowIfAborted();\n\t\t\t\t// Create parent directories if needed.\n\t\t\t\tawait ops.mkdir(dir);\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\t// Write the file contents.\n\t\t\t\tawait ops.writeFile(absolutePath, content);\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: `Successfully wrote to ${path}` }],\n\t\t\t\t\tdetails: undefined,\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\t...writeRenderers,\n\t};\n}\n\nexport function createWriteTool(cwd: string, options?: WriteToolOptions): TypeBoxAgentTool<typeof writeSchema> {\n\treturn wrapToolDefinition(createWriteToolDefinition(cwd, options));\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trust-manager.d.ts","sourceRoot":"","sources":["../../src/core/trust-manager.ts"],"names":[],"mappings":"AAQA,MAAM,MAAM,oBAAoB,GAAG,OAAO,GAAG,IAAI,CAAC;AAElD,MAAM,WAAW,sBAAsB;IACtC,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,WAAW,kBAAkB;IAClC,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,oBAAoB,CAAC;CAC/B;AAED,MAAM,WAAW,kBAAkB;IAClC,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,OAAO,CAAC;IACjB,OAAO,EAAE,kBAAkB,EAAE,CAAC;IAC9B,SAAS,CAAC,EAAE,MAAM,CAAC;CACnB;
|
|
1
|
+
{"version":3,"file":"trust-manager.d.ts","sourceRoot":"","sources":["../../src/core/trust-manager.ts"],"names":[],"mappings":"AAQA,MAAM,MAAM,oBAAoB,GAAG,OAAO,GAAG,IAAI,CAAC;AAElD,MAAM,WAAW,sBAAsB;IACtC,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,WAAW,kBAAkB;IAClC,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,oBAAoB,CAAC;CAC/B;AAED,MAAM,WAAW,kBAAkB;IAClC,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,OAAO,CAAC;IACjB,OAAO,EAAE,kBAAkB,EAAE,CAAC;IAC9B,SAAS,CAAC,EAAE,MAAM,CAAC;CACnB;AAoDD,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAIzE;AAED,wBAAgB,sBAAsB,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;IAAE,kBAAkB,CAAC,EAAE,OAAO,CAAA;CAAE,GAAG,kBAAkB,EAAE,CA8BpH;AAkFD;;;;;;GAMG;AACH,wBAAgB,iCAAiC,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CA2BtE;AAED,qBAAa,iBAAiB;IAC7B,OAAO,CAAC,SAAS,CAAS;gBAEd,QAAQ,EAAE,MAAM;IAI5B,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,oBAAoB;IAItC,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,sBAAsB,GAAG,IAAI;IAOpD,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,oBAAoB,GAAG,IAAI;IAItD,OAAO,CAAC,SAAS,EAAE,kBAAkB,EAAE,GAAG,IAAI;CAe9C"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { homedir, userInfo } from "node:os";
|
|
2
3
|
import { dirname, join } from "node:path";
|
|
3
4
|
import lockfile from "proper-lockfile";
|
|
4
5
|
import { CONFIG_DIR_NAME } from "../config.js";
|
|
5
|
-
import {
|
|
6
|
-
import { canonicalizePath, resolvePath } from "../utils/paths.js";
|
|
6
|
+
import { canonicalizePath, pathsEqual, resolvePath } from "../utils/paths.js";
|
|
7
7
|
import { stripBom } from "../utils/text.js";
|
|
8
8
|
const TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES = [
|
|
9
9
|
"settings.json",
|
|
@@ -18,12 +18,28 @@ const TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES = [
|
|
|
18
18
|
function normalizeCwd(cwd) {
|
|
19
19
|
return canonicalizePath(resolvePath(cwd));
|
|
20
20
|
}
|
|
21
|
+
/** Trust file keys naming `path`. Usually one; several on Windows when saved with different casing. */
|
|
22
|
+
function findTrustFileKeys(data, path) {
|
|
23
|
+
return Object.keys(data).filter((key) => pathsEqual(key, path));
|
|
24
|
+
}
|
|
25
|
+
/** The account's home from the operating system; HOME can point elsewhere, for example under MSYS. */
|
|
26
|
+
function getAccountHomeDir() {
|
|
27
|
+
try {
|
|
28
|
+
return userInfo().homedir;
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
// Some restricted runtimes cannot query the operating-system account database.
|
|
32
|
+
return homedir();
|
|
33
|
+
}
|
|
34
|
+
}
|
|
21
35
|
function findNearestTrustEntry(data, cwd) {
|
|
22
36
|
let currentDir = normalizeCwd(cwd);
|
|
23
37
|
while (true) {
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
-
|
|
38
|
+
for (const key of findTrustFileKeys(data, currentDir)) {
|
|
39
|
+
const value = data[key];
|
|
40
|
+
if (value === true || value === false) {
|
|
41
|
+
return { path: key, decision: value };
|
|
42
|
+
}
|
|
27
43
|
}
|
|
28
44
|
const parentDir = dirname(currentDir);
|
|
29
45
|
if (parentDir === currentDir) {
|
|
@@ -149,7 +165,9 @@ function withTrustFileLock(path, fn) {
|
|
|
149
165
|
* trusted user resource and is ignored here, even when cwd is $HOME.
|
|
150
166
|
*/
|
|
151
167
|
export function hasTrustRequiringProjectResources(cwd) {
|
|
152
|
-
const
|
|
168
|
+
const homeDir = canonicalizePath(resolvePath(process.env.HOME || homedir()));
|
|
169
|
+
const userAgentsSkillsDir = join(homeDir, ".agents", "skills");
|
|
170
|
+
const accountAgentsSkillsDir = join(canonicalizePath(getAccountHomeDir()), ".agents", "skills");
|
|
153
171
|
let currentDir = canonicalizePath(resolvePath(cwd));
|
|
154
172
|
const configDir = join(currentDir, CONFIG_DIR_NAME);
|
|
155
173
|
if (TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES.some((entry) => existsSync(join(configDir, entry)))) {
|
|
@@ -157,7 +175,9 @@ export function hasTrustRequiringProjectResources(cwd) {
|
|
|
157
175
|
}
|
|
158
176
|
while (true) {
|
|
159
177
|
const agentsSkillsDir = join(currentDir, ".agents", "skills");
|
|
160
|
-
if (!
|
|
178
|
+
if (!pathsEqual(agentsSkillsDir, userAgentsSkillsDir) &&
|
|
179
|
+
!pathsEqual(agentsSkillsDir, accountAgentsSkillsDir) &&
|
|
180
|
+
existsSync(agentsSkillsDir)) {
|
|
161
181
|
return true;
|
|
162
182
|
}
|
|
163
183
|
const parentDir = dirname(currentDir);
|
|
@@ -188,13 +208,10 @@ export class ProjectTrustStore {
|
|
|
188
208
|
const data = readTrustFile(this.trustPath);
|
|
189
209
|
for (const { path, decision } of decisions) {
|
|
190
210
|
const key = normalizeCwd(path);
|
|
191
|
-
for (const
|
|
192
|
-
|
|
193
|
-
delete data[alias];
|
|
194
|
-
if (decision === null) {
|
|
195
|
-
delete data[key];
|
|
211
|
+
for (const existingKey of findTrustFileKeys(data, key)) {
|
|
212
|
+
delete data[existingKey];
|
|
196
213
|
}
|
|
197
|
-
|
|
214
|
+
if (decision !== null) {
|
|
198
215
|
data[key] = decision;
|
|
199
216
|
}
|
|
200
217
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trust-manager.js","sourceRoot":"","sources":["../../src/core/trust-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,QAAQ,MAAM,iBAAiB,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,0BAA0B,EAAE,MAAM,2BAA2B,CAAC;AACrF,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAClE,OAAO,E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EAAE,GAAG,CAAC;oBAAE,IAAI,KAAK,KAAK,GAAG;wBAAE,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC;gBACnF,IAAI,QAAQ,KAAK,IAAI,EAAE,CAAC;oBACvB,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;gBAClB,CAAC;qBAAM,CAAC;oBACP,IAAI,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC;gBACtB,CAAC;YACF,CAAC;YACD,cAAc,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;QACtC,CAAC,CAAC,CAAC;IACJ,CAAC;CACD","sourcesContent":["import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport lockfile from \"proper-lockfile\";\nimport { CONFIG_DIR_NAME } from \"../config.ts\";\nimport { findPathKeys, userAgentsSkillsDirMatcher } from \"../utils/path-identity.ts\";\nimport { canonicalizePath, resolvePath } from \"../utils/paths.ts\";\nimport { stripBom } from \"../utils/text.ts\";\n\nexport type ProjectTrustDecision = boolean | null;\n\nexport interface ProjectTrustStoreEntry {\n\tpath: string;\n\tdecision: boolean;\n}\n\nexport interface ProjectTrustUpdate {\n\tpath: string;\n\tdecision: ProjectTrustDecision;\n}\n\nexport interface ProjectTrustOption {\n\tlabel: string;\n\ttrusted: boolean;\n\tupdates: ProjectTrustUpdate[];\n\tsavedPath?: string;\n}\n\ntype TrustFile = Record<string, boolean | null | undefined>;\n\nconst TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES = [\n\t\"settings.json\",\n\t\"mcp.json\",\n\t\"extensions\",\n\t\"skills\",\n\t\"prompts\",\n\t\"themes\",\n\t\"SYSTEM.md\",\n\t\"APPEND_SYSTEM.md\",\n] as const;\n\nfunction normalizeCwd(cwd: string): string {\n\treturn canonicalizePath(resolvePath(cwd));\n}\n\nfunction findNearestTrustEntry(data: TrustFile, cwd: string): ProjectTrustStoreEntry | null {\n\tlet currentDir = normalizeCwd(cwd);\n\twhile (true) {\n\t\tconst value = data[findPathKeys(data, currentDir)[0] ?? currentDir];\n\t\tif (value === true || value === false) {\n\t\t\treturn { path: currentDir, decision: value };\n\t\t}\n\n\t\tconst parentDir = dirname(currentDir);\n\t\tif (parentDir === currentDir) {\n\t\t\treturn null;\n\t\t}\n\t\tcurrentDir = parentDir;\n\t}\n}\n\nexport function getProjectTrustParentPath(cwd: string): string | undefined {\n\tconst trustPath = normalizeCwd(cwd);\n\tconst parentDir = dirname(trustPath);\n\treturn parentDir === trustPath ? undefined : parentDir;\n}\n\nexport function getProjectTrustOptions(cwd: string, options?: { includeSessionOnly?: boolean }): ProjectTrustOption[] {\n\tconst trustPath = normalizeCwd(cwd);\n\tconst trustOptions: ProjectTrustOption[] = [\n\t\t{ label: \"Trust\", trusted: true, updates: [{ path: trustPath, decision: true }], savedPath: trustPath },\n\t];\n\tconst parentPath = getProjectTrustParentPath(cwd);\n\tif (parentPath !== undefined) {\n\t\ttrustOptions.push({\n\t\t\tlabel: `Trust parent folder (${parentPath})`,\n\t\t\ttrusted: true,\n\t\t\tupdates: [\n\t\t\t\t{ path: parentPath, decision: true },\n\t\t\t\t{ path: trustPath, decision: null },\n\t\t\t],\n\t\t\tsavedPath: parentPath,\n\t\t});\n\t}\n\tif (options?.includeSessionOnly) {\n\t\ttrustOptions.push({ label: \"Trust (this session only)\", trusted: true, updates: [] });\n\t}\n\ttrustOptions.push({\n\t\tlabel: \"Do not trust\",\n\t\ttrusted: false,\n\t\tupdates: [{ path: trustPath, decision: false }],\n\t\tsavedPath: trustPath,\n\t});\n\tif (options?.includeSessionOnly) {\n\t\ttrustOptions.push({ label: \"Do not trust (this session only)\", trusted: false, updates: [] });\n\t}\n\treturn trustOptions;\n}\n\nfunction readTrustFile(path: string): TrustFile {\n\tif (!existsSync(path)) {\n\t\treturn {};\n\t}\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(stripBom(readFileSync(path, \"utf-8\")));\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthrow new Error(`Failed to read trust store ${path}: ${message}`);\n\t}\n\n\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n\t\tthrow new Error(`Invalid trust store ${path}: expected an object`);\n\t}\n\n\tconst data: TrustFile = {};\n\tfor (const [key, value] of Object.entries(parsed)) {\n\t\tif (value !== true && value !== false && value !== null) {\n\t\t\tthrow new Error(`Invalid trust store ${path}: value for ${JSON.stringify(key)} must be true, false, or null`);\n\t\t}\n\t\tdata[key] = value;\n\t}\n\treturn data;\n}\n\nfunction writeTrustFile(path: string, data: TrustFile): void {\n\tconst sorted: TrustFile = {};\n\tfor (const key of Object.keys(data).sort()) {\n\t\tconst value = data[key];\n\t\tif (value === true || value === false || value === null) {\n\t\t\tsorted[key] = value;\n\t\t}\n\t}\n\tmkdirSync(dirname(path), { recursive: true });\n\twriteFileSync(path, `${JSON.stringify(sorted, null, 2)}\\n`, \"utf-8\");\n}\n\nfunction acquireTrustLockSync(path: string): () => void {\n\tconst trustDir = dirname(path);\n\tmkdirSync(trustDir, { recursive: true });\n\tconst maxAttempts = 10;\n\tconst delayMs = 20;\n\tlet lastError: unknown;\n\n\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\ttry {\n\t\t\treturn lockfile.lockSync(trustDir, { realpath: false, lockfilePath: `${path}.lock` });\n\t\t} catch (error) {\n\t\t\tconst code =\n\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t: undefined;\n\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tlastError = error;\n\t\t\tconst start = Date.now();\n\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\t// Sleep synchronously to avoid changing trust store callers to async.\n\t\t\t}\n\t\t}\n\t}\n\n\tif (lastError instanceof Error) {\n\t\tthrow lastError;\n\t}\n\tthrow new Error(\"Failed to acquire trust store lock\");\n}\n\nfunction withTrustFileLock<T>(path: string, fn: () => T): T {\n\tconst release = acquireTrustLockSync(path);\n\ttry {\n\t\treturn fn();\n\t} finally {\n\t\trelease();\n\t}\n}\n\n/**\n * Returns true when cwd has project-local resources that must be gated by\n * project trust: trust-requiring entries under cwd/.pi, or .agents/skills in\n * cwd or one of its ancestors. Returns false when no such project resources\n * exist. The user/global ~/.agents/skills directory is always treated as a\n * trusted user resource and is ignored here, even when cwd is $HOME.\n */\nexport function hasTrustRequiringProjectResources(cwd: string): boolean {\n\tconst isUserAgentsSkillsDir = userAgentsSkillsDirMatcher();\n\tlet currentDir = canonicalizePath(resolvePath(cwd));\n\n\tconst configDir = join(currentDir, CONFIG_DIR_NAME);\n\tif (TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES.some((entry) => existsSync(join(configDir, entry)))) {\n\t\treturn true;\n\t}\n\n\twhile (true) {\n\t\tconst agentsSkillsDir = join(currentDir, \".agents\", \"skills\");\n\t\tif (!isUserAgentsSkillsDir(agentsSkillsDir) && existsSync(agentsSkillsDir)) {\n\t\t\treturn true;\n\t\t}\n\n\t\tconst parentDir = dirname(currentDir);\n\t\tif (parentDir === currentDir) {\n\t\t\treturn false;\n\t\t}\n\t\tcurrentDir = parentDir;\n\t}\n}\n\nexport class ProjectTrustStore {\n\tprivate trustPath: string;\n\n\tconstructor(agentDir: string) {\n\t\tthis.trustPath = join(resolvePath(agentDir), \"trust.json\");\n\t}\n\n\tget(cwd: string): ProjectTrustDecision {\n\t\treturn this.getEntry(cwd)?.decision ?? null;\n\t}\n\n\tgetEntry(cwd: string): ProjectTrustStoreEntry | null {\n\t\treturn withTrustFileLock(this.trustPath, () => {\n\t\t\tconst data = readTrustFile(this.trustPath);\n\t\t\treturn findNearestTrustEntry(data, cwd);\n\t\t});\n\t}\n\n\tset(cwd: string, decision: ProjectTrustDecision): void {\n\t\tthis.setMany([{ path: cwd, decision }]);\n\t}\n\n\tsetMany(decisions: ProjectTrustUpdate[]): void {\n\t\twithTrustFileLock(this.trustPath, () => {\n\t\t\tconst data = readTrustFile(this.trustPath);\n\t\t\tfor (const { path, decision } of decisions) {\n\t\t\t\tconst key = normalizeCwd(path);\n\t\t\t\tfor (const alias of findPathKeys(data, key)) if (alias !== key) delete data[alias];\n\t\t\t\tif (decision === null) {\n\t\t\t\t\tdelete data[key];\n\t\t\t\t} else {\n\t\t\t\t\tdata[key] = decision;\n\t\t\t\t}\n\t\t\t}\n\t\t\twriteTrustFile(this.trustPath, data);\n\t\t});\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"trust-manager.js","sourceRoot":"","sources":["../../src/core/trust-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,QAAQ,MAAM,iBAAiB,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAC9E,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAuB5C,MAAM,wCAAwC,GAAG;IAChD,eAAe;IACf,UAAU;IACV,YAAY;IACZ,QAAQ;IACR,SAAS;IACT,QAAQ;IACR,WAAW;IACX,kBAAkB;CACT,CAAC;AAEX,SAAS,YAAY,CAAC,GAAW;IAChC,OAAO,gBAAgB,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC;AAC3C,CAAC;AAED,uGAAuG;AACvG,SAAS,iBAAiB,CAAC,IAAe,EAAE,IAAY;IACvD,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,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C,CAAC,CAAC;IACzC,CAAC;IAED,OAAO,CAAC,SAA+B;QACtC,iBAAiB,CAAC,IAAI,CAAC,SAAS,EAAE,GAAG,EAAE;YACtC,MAAM,IAAI,GAAG,aAAa,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;YAC3C,KAAK,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,SAAS,EAAE,CAAC;gBAC5C,MAAM,GAAG,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC;gBAC/B,KAAK,MAAM,WAAW,IAAI,iBAAiB,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;oBACxD,OAAO,IAAI,CAAC,WAAW,CAAC,CAAC;gBAC1B,CAAC;gBACD,IAAI,QAAQ,KAAK,IAAI,EAAE,CAAC;oBACvB,IAAI,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC;gBACtB,CAAC;YACF,CAAC;YACD,cAAc,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;QACtC,CAAC,CAAC,CAAC;IACJ,CAAC;CACD","sourcesContent":["import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir, userInfo } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport lockfile from \"proper-lockfile\";\nimport { CONFIG_DIR_NAME } from \"../config.ts\";\nimport { canonicalizePath, pathsEqual, resolvePath } from \"../utils/paths.ts\";\nimport { stripBom } from \"../utils/text.ts\";\n\nexport type ProjectTrustDecision = boolean | null;\n\nexport interface ProjectTrustStoreEntry {\n\tpath: string;\n\tdecision: boolean;\n}\n\nexport interface ProjectTrustUpdate {\n\tpath: string;\n\tdecision: ProjectTrustDecision;\n}\n\nexport interface ProjectTrustOption {\n\tlabel: string;\n\ttrusted: boolean;\n\tupdates: ProjectTrustUpdate[];\n\tsavedPath?: string;\n}\n\ntype TrustFile = Record<string, boolean | null | undefined>;\n\nconst TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES = [\n\t\"settings.json\",\n\t\"mcp.json\",\n\t\"extensions\",\n\t\"skills\",\n\t\"prompts\",\n\t\"themes\",\n\t\"SYSTEM.md\",\n\t\"APPEND_SYSTEM.md\",\n] as const;\n\nfunction normalizeCwd(cwd: string): string {\n\treturn canonicalizePath(resolvePath(cwd));\n}\n\n/** Trust file keys naming `path`. Usually one; several on Windows when saved with different casing. */\nfunction findTrustFileKeys(data: TrustFile, path: string): string[] {\n\treturn Object.keys(data).filter((key) => pathsEqual(key, path));\n}\n\n/** The account's home from the operating system; HOME can point elsewhere, for example under MSYS. */\nfunction getAccountHomeDir(): string {\n\ttry {\n\t\treturn userInfo().homedir;\n\t} catch {\n\t\t// Some restricted runtimes cannot query the operating-system account database.\n\t\treturn homedir();\n\t}\n}\n\nfunction findNearestTrustEntry(data: TrustFile, cwd: string): ProjectTrustStoreEntry | null {\n\tlet currentDir = normalizeCwd(cwd);\n\twhile (true) {\n\t\tfor (const key of findTrustFileKeys(data, currentDir)) {\n\t\t\tconst value = data[key];\n\t\t\tif (value === true || value === false) {\n\t\t\t\treturn { path: key, decision: value };\n\t\t\t}\n\t\t}\n\n\t\tconst parentDir = dirname(currentDir);\n\t\tif (parentDir === currentDir) {\n\t\t\treturn null;\n\t\t}\n\t\tcurrentDir = parentDir;\n\t}\n}\n\nexport function getProjectTrustParentPath(cwd: string): string | undefined {\n\tconst trustPath = normalizeCwd(cwd);\n\tconst parentDir = dirname(trustPath);\n\treturn parentDir === trustPath ? undefined : parentDir;\n}\n\nexport function getProjectTrustOptions(cwd: string, options?: { includeSessionOnly?: boolean }): ProjectTrustOption[] {\n\tconst trustPath = normalizeCwd(cwd);\n\tconst trustOptions: ProjectTrustOption[] = [\n\t\t{ label: \"Trust\", trusted: true, updates: [{ path: trustPath, decision: true }], savedPath: trustPath },\n\t];\n\tconst parentPath = getProjectTrustParentPath(cwd);\n\tif (parentPath !== undefined) {\n\t\ttrustOptions.push({\n\t\t\tlabel: `Trust parent folder (${parentPath})`,\n\t\t\ttrusted: true,\n\t\t\tupdates: [\n\t\t\t\t{ path: parentPath, decision: true },\n\t\t\t\t{ path: trustPath, decision: null },\n\t\t\t],\n\t\t\tsavedPath: parentPath,\n\t\t});\n\t}\n\tif (options?.includeSessionOnly) {\n\t\ttrustOptions.push({ label: \"Trust (this session only)\", trusted: true, updates: [] });\n\t}\n\ttrustOptions.push({\n\t\tlabel: \"Do not trust\",\n\t\ttrusted: false,\n\t\tupdates: [{ path: trustPath, decision: false }],\n\t\tsavedPath: trustPath,\n\t});\n\tif (options?.includeSessionOnly) {\n\t\ttrustOptions.push({ label: \"Do not trust (this session only)\", trusted: false, updates: [] });\n\t}\n\treturn trustOptions;\n}\n\nfunction readTrustFile(path: string): TrustFile {\n\tif (!existsSync(path)) {\n\t\treturn {};\n\t}\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(stripBom(readFileSync(path, \"utf-8\")));\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthrow new Error(`Failed to read trust store ${path}: ${message}`);\n\t}\n\n\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n\t\tthrow new Error(`Invalid trust store ${path}: expected an object`);\n\t}\n\n\tconst data: TrustFile = {};\n\tfor (const [key, value] of Object.entries(parsed)) {\n\t\tif (value !== true && value !== false && value !== null) {\n\t\t\tthrow new Error(`Invalid trust store ${path}: value for ${JSON.stringify(key)} must be true, false, or null`);\n\t\t}\n\t\tdata[key] = value;\n\t}\n\treturn data;\n}\n\nfunction writeTrustFile(path: string, data: TrustFile): void {\n\tconst sorted: TrustFile = {};\n\tfor (const key of Object.keys(data).sort()) {\n\t\tconst value = data[key];\n\t\tif (value === true || value === false || value === null) {\n\t\t\tsorted[key] = value;\n\t\t}\n\t}\n\tmkdirSync(dirname(path), { recursive: true });\n\twriteFileSync(path, `${JSON.stringify(sorted, null, 2)}\\n`, \"utf-8\");\n}\n\nfunction acquireTrustLockSync(path: string): () => void {\n\tconst trustDir = dirname(path);\n\tmkdirSync(trustDir, { recursive: true });\n\tconst maxAttempts = 10;\n\tconst delayMs = 20;\n\tlet lastError: unknown;\n\n\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\ttry {\n\t\t\treturn lockfile.lockSync(trustDir, { realpath: false, lockfilePath: `${path}.lock` });\n\t\t} catch (error) {\n\t\t\tconst code =\n\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t: undefined;\n\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tlastError = error;\n\t\t\tconst start = Date.now();\n\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\t// Sleep synchronously to avoid changing trust store callers to async.\n\t\t\t}\n\t\t}\n\t}\n\n\tif (lastError instanceof Error) {\n\t\tthrow lastError;\n\t}\n\tthrow new Error(\"Failed to acquire trust store lock\");\n}\n\nfunction withTrustFileLock<T>(path: string, fn: () => T): T {\n\tconst release = acquireTrustLockSync(path);\n\ttry {\n\t\treturn fn();\n\t} finally {\n\t\trelease();\n\t}\n}\n\n/**\n * Returns true when cwd has project-local resources that must be gated by\n * project trust: trust-requiring entries under cwd/.pi, or .agents/skills in\n * cwd or one of its ancestors. Returns false when no such project resources\n * exist. The user/global ~/.agents/skills directory is always treated as a\n * trusted user resource and is ignored here, even when cwd is $HOME.\n */\nexport function hasTrustRequiringProjectResources(cwd: string): boolean {\n\tconst homeDir = canonicalizePath(resolvePath(process.env.HOME || homedir()));\n\tconst userAgentsSkillsDir = join(homeDir, \".agents\", \"skills\");\n\tconst accountAgentsSkillsDir = join(canonicalizePath(getAccountHomeDir()), \".agents\", \"skills\");\n\tlet currentDir = canonicalizePath(resolvePath(cwd));\n\n\tconst configDir = join(currentDir, CONFIG_DIR_NAME);\n\tif (TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES.some((entry) => existsSync(join(configDir, entry)))) {\n\t\treturn true;\n\t}\n\n\twhile (true) {\n\t\tconst agentsSkillsDir = join(currentDir, \".agents\", \"skills\");\n\t\tif (\n\t\t\t!pathsEqual(agentsSkillsDir, userAgentsSkillsDir) &&\n\t\t\t!pathsEqual(agentsSkillsDir, accountAgentsSkillsDir) &&\n\t\t\texistsSync(agentsSkillsDir)\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\n\t\tconst parentDir = dirname(currentDir);\n\t\tif (parentDir === currentDir) {\n\t\t\treturn false;\n\t\t}\n\t\tcurrentDir = parentDir;\n\t}\n}\n\nexport class ProjectTrustStore {\n\tprivate trustPath: string;\n\n\tconstructor(agentDir: string) {\n\t\tthis.trustPath = join(resolvePath(agentDir), \"trust.json\");\n\t}\n\n\tget(cwd: string): ProjectTrustDecision {\n\t\treturn this.getEntry(cwd)?.decision ?? null;\n\t}\n\n\tgetEntry(cwd: string): ProjectTrustStoreEntry | null {\n\t\treturn withTrustFileLock(this.trustPath, () => {\n\t\t\tconst data = readTrustFile(this.trustPath);\n\t\t\treturn findNearestTrustEntry(data, cwd);\n\t\t});\n\t}\n\n\tset(cwd: string, decision: ProjectTrustDecision): void {\n\t\tthis.setMany([{ path: cwd, decision }]);\n\t}\n\n\tsetMany(decisions: ProjectTrustUpdate[]): void {\n\t\twithTrustFileLock(this.trustPath, () => {\n\t\t\tconst data = readTrustFile(this.trustPath);\n\t\t\tfor (const { path, decision } of decisions) {\n\t\t\t\tconst key = normalizeCwd(path);\n\t\t\t\tfor (const existingKey of findTrustFileKeys(data, key)) {\n\t\t\t\t\tdelete data[existingKey];\n\t\t\t\t}\n\t\t\t\tif (decision !== null) {\n\t\t\t\t\tdata[key] = decision;\n\t\t\t\t}\n\t\t\t}\n\t\t\twriteTrustFile(this.trustPath, data);\n\t\t});\n\t}\n}\n"]}
|