dal-code 1.0.25 → 1.0.27
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 +37 -0
- package/NOTICE +7 -0
- package/dal-docs/README.md +13 -0
- package/dal-docs/settings.md +18 -2
- package/dist/cli/args.d.ts +3 -0
- package/dist/cli/args.js +14 -14
- package/dist/core/agent-session-services.d.ts +2 -0
- package/dist/core/agent-session-services.js +1 -1
- package/dist/core/agent-session.d.ts +27 -1
- package/dist/core/agent-session.js +9 -8
- package/dist/core/background-processes.d.ts +73 -0
- package/dist/core/background-processes.js +7 -0
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/loader.js +1 -1
- package/dist/core/extensions/permission-surface.js +1 -1
- package/dist/core/extensions/runner.js +1 -1
- package/dist/core/extensions/types.d.ts +6 -0
- package/dist/core/host-capabilities.d.ts +50 -0
- package/dist/core/host-capabilities.js +2 -0
- package/dist/core/permissions/rules.d.ts +45 -0
- package/dist/core/permissions/rules.js +1 -0
- package/dist/core/permissions/shell-words.js +2 -0
- package/dist/core/permissions/tool-policy.d.ts +46 -0
- package/dist/core/permissions/tool-policy.js +1 -0
- package/dist/core/sandbox/availability.d.ts +14 -0
- package/dist/core/sandbox/availability.js +1 -0
- package/dist/core/sandbox/denial.d.ts +25 -0
- package/dist/core/sandbox/denial.js +3 -0
- package/dist/core/sandbox/index.d.ts +5 -0
- package/dist/core/sandbox/index.js +1 -0
- package/dist/core/sandbox/policy.d.ts +66 -0
- package/dist/core/sandbox/policy.js +1 -0
- package/dist/core/sandbox/runtime.d.ts +41 -0
- package/dist/core/sandbox/runtime.js +1 -0
- package/dist/core/sandbox/shell-sandbox.d.ts +125 -0
- package/dist/core/sandbox/shell-sandbox.js +5 -0
- package/dist/core/sandbox/windows.d.ts +122 -0
- package/dist/core/sandbox/windows.js +5 -0
- package/dist/core/sdk.d.ts +3 -0
- package/dist/core/sdk.js +1 -1
- package/dist/core/settings-manager.d.ts +20 -0
- package/dist/core/settings-manager.js +1 -1
- package/dist/core/tools/bash.d.ts +16 -1
- package/dist/core/tools/bash.js +16 -14
- package/dist/core/tools/find.js +11 -11
- package/dist/core/tools/grep.js +10 -10
- package/dist/core/tools/index.d.ts +1 -0
- package/dist/core/tools/index.js +1 -1
- package/dist/core/tools/ls.js +6 -6
- package/dist/core/tools/powershell.d.ts +1 -1
- package/dist/core/tools/powershell.js +2 -2
- package/dist/core/tools/process.d.ts +26 -0
- package/dist/core/tools/process.js +22 -0
- package/dist/core/tools/read.js +15 -15
- package/dist/dal/builtins.js +2 -2
- package/dist/dal/child-env.js +1 -1
- package/dist/dal/manifest.d.ts +32 -0
- package/dist/dal/manifest.js +1 -0
- package/dist/index.d.ts +8 -3
- package/dist/index.js +1 -1
- package/dist/main.js +4 -4
- package/dist/modes/index.d.ts +2 -2
- package/dist/modes/print-mode.js +6 -4
- package/dist/modes/rpc/environment-update.js +1 -0
- package/dist/modes/rpc/rpc-client.d.ts +38 -1
- package/dist/modes/rpc/rpc-client.js +4 -1
- package/dist/modes/rpc/rpc-mode.d.ts +1 -0
- package/dist/modes/rpc/rpc-mode.js +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +95 -0
- package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-bridge/src/index.js +1 -1
- package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-interactive/LICENSE +21 -0
- package/dist/node_modules/@dalcode/dal-interactive/package.json +33 -0
- package/dist/node_modules/@dalcode/dal-interactive/src/handoff.js +28 -0
- package/dist/node_modules/@dalcode/dal-interactive/src/index.js +1 -0
- package/dist/node_modules/@dalcode/dal-interactive/src/interactive-shell.js +1 -0
- package/dist/node_modules/@dalcode/dal-interactive/src/questionnaire.js +3 -0
- package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
- package/dist/node_modules/@dalcode/dal-mcp/src/add-wizard.js +1 -1
- package/dist/node_modules/@dalcode/dal-mcp/src/config.d.ts +1 -1
- package/dist/node_modules/@dalcode/dal-mcp/src/config.js +1 -1
- package/dist/node_modules/@dalcode/dal-mcp/src/index.js +18 -18
- package/dist/node_modules/@dalcode/dal-mcp/src/proxy.js +6 -6
- package/dist/node_modules/@dalcode/dal-mcp/src/report.js +1 -1
- package/dist/node_modules/@dalcode/dal-mcp/src/types.d.ts +1 -1
- package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +2 -2
- package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +2 -2
- package/dist/node_modules/@dalcode/dal-plugins/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-review/LICENSE +21 -0
- package/dist/node_modules/@dalcode/dal-review/package.json +34 -0
- package/dist/node_modules/@dalcode/dal-review/src/args.d.ts +13 -0
- package/dist/node_modules/@dalcode/dal-review/src/args.js +1 -0
- package/dist/node_modules/@dalcode/dal-review/src/core.d.ts +6 -0
- package/dist/node_modules/@dalcode/dal-review/src/core.js +1 -0
- package/dist/node_modules/@dalcode/dal-review/src/findings.d.ts +23 -0
- package/dist/node_modules/@dalcode/dal-review/src/findings.js +4 -0
- package/dist/node_modules/@dalcode/dal-review/src/index.js +1 -0
- package/dist/node_modules/@dalcode/dal-review/src/prompt.d.ts +3 -0
- package/dist/node_modules/@dalcode/dal-review/src/prompt.js +29 -0
- package/dist/node_modules/@dalcode/dal-review/src/runner.d.ts +91 -0
- package/dist/node_modules/@dalcode/dal-review/src/runner.js +2 -0
- package/dist/node_modules/@dalcode/dal-review/src/targets.d.ts +33 -0
- package/dist/node_modules/@dalcode/dal-review/src/targets.js +17 -0
- package/dist/node_modules/@dalcode/dal-review/src/types.d.ts +94 -0
- package/dist/node_modules/@dalcode/dal-review/src/types.js +1 -0
- package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-router/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
- package/dist/node_modules/@dalcode/dal-subagent/src/agents.js +2 -2
- package/dist/node_modules/@dalcode/dal-subagent/src/index.js +12 -12
- package/dist/node_modules/@dalcode/dal-subagent/src/process-runner.js +3 -3
- package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-terminal/LICENSE +21 -0
- package/dist/node_modules/@dalcode/dal-terminal/package.json +33 -0
- package/dist/node_modules/@dalcode/dal-terminal/src/contract.d.ts +60 -0
- package/dist/node_modules/@dalcode/dal-terminal/src/contract.js +7 -0
- package/dist/node_modules/@dalcode/dal-terminal/src/index.js +6 -0
- package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-web/src/config.js +2 -2
- package/dist/node_modules/@dalcode/dal-web/src/index.js +4 -4
- package/dist/node_modules/@dalcode/dal-web/src/search.js +4 -4
- package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-workflow/src/index.js +4 -4
- package/dist/node_modules/@dalcode/dal-workflow/src/plan-mode.js +13 -13
- package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
- package/dist/node_modules/@earendil-works/chord/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.d.ts +4 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.js +1 -1
- package/dist/node_modules/@earendil-works/pi-agent-core/package.json +4 -4
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/amazon-bedrock.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/anthropic.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-workers-ai.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/mistral.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/radius.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/together.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-client/package.json +3 -3
- package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-server/package.json +5 -5
- package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/package.json +3 -3
- package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
- package/dist/sdk/index.d.ts +6 -2
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/review.d.ts +1 -0
- package/dist/sdk/review.js +1 -0
- package/dist/sdk/subagents.d.ts +8 -0
- package/dist/sdk/subagents.js +1 -0
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/index.ts +6 -0
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +83 -5
- package/package.json +14 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var s=Object.defineProperty;var i=(e,a)=>s(e,"name",{value:a,configurable:!0});import{createRequire as m}from"node:module";import{getLanguage as t,translate as o}from"@dalcode/dal-pi-kit";const n=[{package:"@dalcode/dal-plugins",label:"\u63D2\u4EF6\u517C\u5BB9",description:"\u8BA9\u793E\u533A\u63D2\u4EF6\u5728 DAL \u4E2D\u53EF\u7528\uFF0C\u5E76\u63D0\u4F9B\u63D2\u4EF6\u641C\u7D22",activation:"always"},{package:"@dalcode/deepailab",label:"DeepAILab \u8D26\u53F7",description:"DeepAILab \u767B\u5F55\u3001\u5957\u9910\u4E0E\u6A21\u578B\u63D0\u4F9B\u65B9\uFF08/login\u3001/account\uFF09",activation:"always"},{package:"@dalcode/dal-gateway",label:"DAL \u7F51\u5173",description:"\u7ECF DAL \u7F51\u5173\u8C03\u7528\u6A21\u578B",activation:"always"},{package:"@dalcode/dal-guard",label:"\u547D\u4EE4\u5BA1\u6279",description:"\u9AD8\u98CE\u9669\u547D\u4EE4\u6267\u884C\u524D\u8BF7\u4F60\u786E\u8BA4\uFF08/guard\uFF09",activation:"always",safetyCritical:!0},{package:"@dalcode/dal-lsp",label:"\u8BED\u8A00\u670D\u52A1\u5668",description:"\u67E5\u7C7B\u578B\u9519\u8BEF\u3001\u5B9A\u4E49\u4E0E\u5F15\u7528",activation:"always"},{package:"@dalcode/dal-subagent",label:"\u5B50\u52A9\u624B",description:"\u6D3E\u51FA\u5B50\u52A9\u624B\u5E76\u884C\u5904\u7406\u4EFB\u52A1",activation:"always"},{package:"@dalcode/dal-router",label:"\u667A\u80FD\u8DEF\u7531",description:"\u6309\u4EFB\u52A1\u81EA\u52A8\u6311\u9009\u6A21\u578B\uFF08/factory\uFF09",activation:"always"},{package:"@dalcode/dal-mcp",label:"MCP",description:"\u8FDE\u63A5 MCP \u670D\u52A1\u5668\u5E76\u4F7F\u7528\u5176\u5DE5\u5177\uFF08/mcp\uFF09",activation:"always"},{package:"@dalcode/dal-skills",label:"\u6280\u80FD",description:"\u641C\u7D22\u548C\u52A0\u8F7D\u672C\u5730\u4E0E\u4E91\u7AEF\u6280\u80FD\uFF08/skills\uFF09",activation:"always"},{package:"@dalcode/dal-office",label:"\u529E\u516C\u6587\u6863",description:"\u751F\u6210\u3001\u8BFB\u53D6\u548C\u4FEE\u6539 PPT\u3001Word\u3001Excel\u3001\u56FE\u8868",activation:"always"},{package:"@dalcode/dal-web",label:"\u8054\u7F51",description:"\u7F51\u9875\u641C\u7D22\u4E0E\u7F51\u9875\u8BFB\u53D6\uFF08/web\uFF09",activation:"always"},{package:"@dalcode/dal-workflow",label:"\u8BA1\u5212\u4E0E\u5F85\u529E",description:"\u8BA1\u5212\u6A21\u5F0F\u3001\u5F85\u529E\u6E05\u5355\u548C\u5B8C\u6210\u63D0\u9192\uFF08/plan\u3001/todos\uFF09",activation:"always"},{package:"@dalcode/dal-tool-catalog",label:"\u5DE5\u5177\u76EE\u5F55",description:"\u529E\u516C\u3001\u8054\u7F51\u7B49\u5DE5\u5177\u6309\u9700\u52A0\u8F7D\uFF0C\u8282\u7701\u4E0A\u4E0B\u6587",activation:"always"},{package:"@dalcode/dal-halo",label:"Halo",description:"\u5728 Halo \u7075\u52A8\u5C9B\u4E0A\u663E\u793A\u8FDB\u5EA6\u548C\u5BA1\u6279",activation:"halo-app"},{package:"@dalcode/dal-lang",label:"\u754C\u9762\u8BED\u8A00",description:"\u5207\u6362\u4E2D\u6587\u6216\u82F1\u6587\u754C\u9762\uFF08/lang\uFF09",activation:"always"},{package:"@dalcode/dal-bridge",label:"DAL Code \u6865\u63A5",description:"\u5728 DAL Code \u4E2D\u628A\u5BA1\u6279\u3001\u8BA1\u5212\u548C\u63D0\u95EE\u4EA4\u7ED9\u7F16\u8F91\u5668",activation:"dal-code"},{package:"@dalcode/dal-telemetry",label:"\u4F7F\u7528\u7EDF\u8BA1",description:"\u533F\u540D\u4F7F\u7528\u7EDF\u8BA1\uFF08/telemetry\uFF09",activation:"always"},{package:"@dalcode/dal-rewind",label:"\u68C0\u67E5\u70B9",description:"\u6BCF\u8F6E\u6539\u52A8\u81EA\u52A8\u7559\u68C0\u67E5\u70B9\uFF0C\u53EF\u56DE\u9000\uFF08/rewind\uFF09",activation:"always"},{package:"@dalcode/dal-review",label:"\u4EE3\u7801\u8BC4\u5BA1",description:"\u53EA\u8BFB\u8BC4\u5BA1\u6539\u52A8\uFF0C\u6309\u4E25\u91CD\u7A0B\u5EA6\u5217\u51FA\u95EE\u9898\uFF08/review\uFF09",activation:"always"},{package:"@dalcode/dal-interactive",label:"\u7EC8\u7AEF\u4EA4\u4E92",description:"\u95EE\u5377\u63D0\u95EE\u3001/handoff \u4EA4\u63A5\u5230\u65B0\u4F1A\u8BDD\u3001!vim \u7B49\u4EA4\u4E92\u5F0F\u547D\u4EE4\uFF08\u4EC5\u7EC8\u7AEF\u754C\u9762\uFF09",activation:"tui"},{package:"@dalcode/dal-terminal",label:"\u7EC8\u7AEF\u4E0A\u4E0B\u6587",description:"\u5BBF\u4E3B\u7A0B\u5E8F\u63D0\u4F9B\u7EC8\u7AEF\u65F6\uFF0C\u52A9\u624B\u53EF\u8BFB\u53D6\u7EC8\u7AEF\u8F93\u51FA\uFF08@terminal\uFF09",activation:"host-capability"},{package:"cc-safety-net",label:"\u5371\u9669\u547D\u4EE4\u62E6\u622A",description:"\u6267\u884C\u524D\u62E6\u4E0B rm -rf\u3001\u5F3A\u5236\u63A8\u9001\u7B49\u7834\u574F\u6027\u547D\u4EE4",activation:"always",safetyCritical:!0}],p=n.map(e=>e.package),v=new Set(n.filter(e=>e.safetyCritical).map(e=>e.package));function u(e){try{const l=m(import.meta.url)(`${e}/package.json`);return{version:l.version??"",extensions:[...l.pi?.extensions??[]]}}catch{return}}i(u,"installedManifest");function g(e=t()){return n.map(a=>{const l=u(a.package);return{name:a.package,label:o(a.label,e),description:o(a.description,e),enabledByDefault:!0,canDisable:!1,safetyCritical:a.safetyCritical===!0,activation:a.activation,installed:l!==void 0,version:l?.version??"",extensions:l?.extensions??[]}})}i(g,"listBundledExtensions");const d=[{name:"read",label:"\u8BFB\u53D6\u6587\u4EF6",summary:"\u8BFB\u53D6\u6587\u4EF6\u5185\u5BB9\uFF0C\u4E5F\u80FD\u770B\u56FE\u7247",source:"core",readOnly:!0,availability:"default"},{name:"bash",label:"\u8FD0\u884C\u547D\u4EE4",summary:"\u5728\u7EC8\u7AEF\u91CC\u8FD0\u884C\u547D\u4EE4",source:"core",readOnly:!1,availability:"default"},{name:"edit",label:"\u7F16\u8F91\u6587\u4EF6",summary:"\u6309\u539F\u6587\u66FF\u6362\u4FEE\u6539\u6587\u4EF6",source:"core",readOnly:!1,availability:"default"},{name:"write",label:"\u5199\u5165\u6587\u4EF6",summary:"\u65B0\u5EFA\u6216\u8986\u76D6\u6587\u4EF6",source:"core",readOnly:!1,availability:"default"},{name:"grep",label:"\u641C\u7D22\u5185\u5BB9",summary:"\u5728\u6587\u4EF6\u91CC\u641C\u7D22\u6587\u672C",source:"core",readOnly:!0,availability:"opt-in"},{name:"find",label:"\u67E5\u627E\u6587\u4EF6",summary:"\u6309\u540D\u79F0\u67E5\u627E\u6587\u4EF6",source:"core",readOnly:!0,availability:"opt-in"},{name:"ls",label:"\u5217\u51FA\u76EE\u5F55",summary:"\u5217\u51FA\u76EE\u5F55\u5185\u5BB9",source:"core",readOnly:!0,availability:"opt-in"},{name:"powershell",label:"\u8FD0\u884C PowerShell",summary:"\u5728 Windows \u4E0A\u7528 PowerShell \u8FD0\u884C\u547D\u4EE4",source:"core",readOnly:!1,availability:"opt-in"},{name:"process",label:"\u540E\u53F0\u8FDB\u7A0B",summary:"\u5728\u540E\u53F0\u8FD0\u884C\u5F00\u53D1\u670D\u52A1\u5668\u7B49\u957F\u65F6\u95F4\u547D\u4EE4\uFF0C\u968F\u65F6\u67E5\u770B\u8F93\u51FA",source:"core",readOnly:!1,availability:"default"},{name:"plugin_search",label:"\u641C\u7D22\u63D2\u4EF6",summary:"\u641C\u7D22\u53EF\u5B89\u88C5\u7684\u63D2\u4EF6",source:"@dalcode/dal-plugins",readOnly:!0,availability:"default"},{name:"lsp",label:"\u8BED\u8A00\u670D\u52A1\u5668",summary:"\u67E5\u7C7B\u578B\u9519\u8BEF\u3001\u7B26\u53F7\u3001\u5B9A\u4E49\u4E0E\u5F15\u7528",source:"@dalcode/dal-lsp",readOnly:!0,availability:"on-demand"},{name:"task",label:"\u5B50\u52A9\u624B",summary:"\u6D3E\u51FA\u5B50\u52A9\u624B\u5904\u7406\u4E00\u9879\u5B50\u4EFB\u52A1",source:"@dalcode/dal-subagent",readOnly:!1,availability:"default"},{name:"mcp",label:"MCP \u5DE5\u5177",summary:"\u8C03\u7528\u5DF2\u8FDE\u63A5 MCP \u670D\u52A1\u5668\u7684\u5DE5\u5177",source:"@dalcode/dal-mcp",readOnly:!1,availability:"mcp"},{name:"skill",label:"\u6280\u80FD",summary:"\u641C\u7D22\u5E76\u52A0\u8F7D\u4E13\u9879\u4EFB\u52A1\u6307\u5F15",source:"@dalcode/dal-skills",readOnly:!0,availability:"default"},{name:"office_ppt_plan",label:"\u89C4\u5212 PPT",summary:"\u5148\u5217\u51FA PPT \u7684\u9875\u9762\u5927\u7EB2",source:"@dalcode/dal-office",readOnly:!0,availability:"on-demand"},{name:"office_ppt_generate",label:"\u751F\u6210 PPT",summary:"\u751F\u6210 PowerPoint \u6F14\u793A\u6587\u7A3F",source:"@dalcode/dal-office",readOnly:!1,availability:"on-demand"},{name:"office_doc_generate",label:"\u751F\u6210 Word",summary:"\u751F\u6210 Word \u6587\u6863",source:"@dalcode/dal-office",readOnly:!1,availability:"on-demand"},{name:"office_md_generate",label:"\u751F\u6210 Markdown",summary:"\u751F\u6210 Markdown \u6587\u6863",source:"@dalcode/dal-office",readOnly:!1,availability:"on-demand"},{name:"office_sheet_generate",label:"\u751F\u6210\u8868\u683C",summary:"\u751F\u6210 Excel \u8868\u683C",source:"@dalcode/dal-office",readOnly:!1,availability:"on-demand"},{name:"office_chart_generate",label:"\u751F\u6210\u56FE\u8868",summary:"\u751F\u6210 ECharts \u56FE\u8868",source:"@dalcode/dal-office",readOnly:!1,availability:"on-demand"},{name:"office_drawio_generate",label:"\u751F\u6210\u6D41\u7A0B\u56FE",summary:"\u751F\u6210 draw.io \u56FE",source:"@dalcode/dal-office",readOnly:!1,availability:"on-demand"},{name:"office_read_file",label:"\u8BFB\u53D6\u6587\u6863",summary:"\u8BFB\u53D6 Word\u3001PPT\u3001Excel\u3001PDF\u3001CSV",source:"@dalcode/dal-office",readOnly:!0,availability:"on-demand"},{name:"office_docx_edit",label:"\u4FEE\u6539 Word",summary:"\u6309\u4F4D\u7F6E\u4FEE\u6539\u5DF2\u6709\u7684 Word \u6587\u6863",source:"@dalcode/dal-office",readOnly:!1,availability:"on-demand"},{name:"office_pptx_edit",label:"\u4FEE\u6539 PPT",summary:"\u6309\u4F4D\u7F6E\u4FEE\u6539\u5DF2\u6709\u7684 PPT",source:"@dalcode/dal-office",readOnly:!1,availability:"on-demand"},{name:"office_xlsx_edit",label:"\u4FEE\u6539\u8868\u683C",summary:"\u6309\u4F4D\u7F6E\u4FEE\u6539\u5DF2\u6709\u7684 Excel",source:"@dalcode/dal-office",readOnly:!1,availability:"on-demand"},{name:"web_search",label:"\u7F51\u9875\u641C\u7D22",summary:"\u8054\u7F51\u641C\u7D22\u6700\u65B0\u4FE1\u606F",source:"@dalcode/dal-web",readOnly:!0,availability:"on-demand"},{name:"web_fetch",label:"\u8BFB\u53D6\u7F51\u9875",summary:"\u8BFB\u53D6\u7F51\u9875\u6B63\u6587",source:"@dalcode/dal-web",readOnly:!0,availability:"on-demand"},{name:"todo",label:"\u5F85\u529E\u6E05\u5355",summary:"\u7EF4\u62A4\u672C\u6B21\u4EFB\u52A1\u7684\u5F85\u529E\u6E05\u5355",source:"@dalcode/dal-workflow",readOnly:!0,availability:"default"},{name:"tool_catalog",label:"\u5DE5\u5177\u76EE\u5F55",summary:"\u67E5\u770B\u5E76\u542F\u7528\u6309\u9700\u52A0\u8F7D\u7684\u5DE5\u5177\u5206\u7EC4",source:"@dalcode/dal-tool-catalog",readOnly:!0,availability:"default"},{name:"submit_plan",label:"\u63D0\u4EA4\u8BA1\u5212",summary:"\u628A\u8BA1\u5212\u4EA4\u7ED9\u4F60\u5BA1\u6279",source:"@dalcode/dal-bridge",readOnly:!0,availability:"dal-code"},{name:"ask_user",label:"\u8BE2\u95EE\u4F60",summary:"\u5F00\u5DE5\u524D\u7528\u5361\u7247\u786E\u8BA4\u5173\u952E\u51B3\u5B9A",source:"@dalcode/dal-bridge",readOnly:!0,availability:"dal-code"},{name:"review_report",label:"\u63D0\u4EA4\u8BC4\u5BA1\u7ED3\u679C",summary:"\u8BC4\u5BA1\u52A9\u624B\u63D0\u4EA4\u53D1\u73B0\u7684\u95EE\u9898",source:"@dalcode/dal-review",readOnly:!0,availability:"reviewer"},{name:"questionnaire",label:"\u95EE\u5377",summary:"\u7528\u9009\u62E9\u9898\u5411\u4F60\u786E\u8BA4\u9700\u6C42\u6216\u504F\u597D",source:"@dalcode/dal-interactive",readOnly:!0,availability:"tui"},{name:"terminal_read",label:"\u8BFB\u53D6\u7EC8\u7AEF",summary:"\u8BFB\u53D6\u7EC8\u7AEF\u6700\u8FD1\u7684\u8F93\u51FA",source:"@dalcode/dal-terminal",readOnly:!0,availability:"host"}],w=(()=>{const e={};for(const a of d){if(a.source==="core")continue;const l=e[a.source]??[];l.push(a.name),e[a.source]=l}return{builtin:d.filter(a=>a.source==="core").map(a=>a.name),extensions:e}})();function O(e=t()){return d.map(a=>({name:a.name,label:o(a.label,e),summary:o(a.summary,e),source:a.source,readOnly:a.readOnly,availability:a.availability}))}i(O,"listToolCatalog");function _(e,a=t()){const l=d.find(c=>c.name===e);if(l)return o(l.label,a);const r=e.match(/^mcp__(.+?)__(.+)$/);return r?`${r[1]} \xB7 ${r[2]}`:e}i(_,"toolDisplayLabel");export{p as BUNDLED_EXTENSION_PACKAGES,w as DAL_TOOL_NAMES,v as SAFETY_CRITICAL_PACKAGES,g as listBundledExtensions,O as listToolCatalog,_ as toolDisplayLabel};
|
package/dist/index.d.ts
CHANGED
|
@@ -2,33 +2,38 @@ export { type Args, parseArgs } from "./cli/args.ts";
|
|
|
2
2
|
export { CONFIG_DIR_NAME, getAgentDir, getDocsPath, getExamplesPath, getPackageDir, getReadmePath, SHARED_SKILL_CONFIG_DIRS, VERSION, } from "./config.ts";
|
|
3
3
|
export { AgentSession, type AgentSessionConfig, type AgentSessionEvent, type AgentSessionEventListener, type ModelCycleResult, type ParsedSkillBlock, type PromptOptions, parseSkillBlock, type SessionStats, } from "./core/agent-session.ts";
|
|
4
4
|
export { readStoredCredential } from "./core/auth-storage.ts";
|
|
5
|
+
export { type BackgroundProcessEvent, type BackgroundProcessInfo, BackgroundProcessManager, type BackgroundProcessState, MAX_BACKGROUND_PROCESSES, } from "./core/background-processes.ts";
|
|
5
6
|
export type { CacheWarmingDecision, CacheWarmingStatus } from "./core/cache-warmer.ts";
|
|
6
7
|
export { type BranchPreparation, type BranchSummaryResult, type CollectEntriesResult, type CompactionResult, type CutPointResult, calculateContextTokens, collectEntriesForBranchSummary, compact, DEFAULT_COMPACTION_SETTINGS, estimateTokens, type FileOperations, findCutPoint, findTurnStartIndex, type GenerateBranchSummaryOptions, generateBranchSummary, generateSummary, generateSummaryWithUsage, getLastAssistantUsage, prepareBranchEntries, serializeConversation, shouldCompact, } from "./core/compaction/index.ts";
|
|
7
8
|
export { createEventBus, type EventBus, type EventBusController } from "./core/event-bus.ts";
|
|
8
9
|
export type { AfterProviderResponseEvent, AgentActivityOutcome, AgentBeforeSettleEvent, AgentBeforeSettleEventResult, AgentEndEvent, AgentSettledEvent, AgentStartEvent, AgentToolResult, AgentToolUpdateCallback, AppKeybinding, AutocompleteProviderFactory, BashToolCallEvent, BeforeAgentStartEvent, BeforeAgentStartEventResult, BeforeProviderHeadersEvent, BeforeProviderRequestEvent, BeforeProviderRequestEventResult, BoundaryContextPreview, BoundaryResult, BoundaryState, BuildSystemPromptOptions, CacheWarmingDecisionEvent, CacheWarmingDecisionEventResult, CompactionEntryDraft, CompactOptions, ContextEditEntryDraft, ContextEvent, ContextEventResult, ContextUsage, ContextWithSystemEvent, CustomEntryDraft, CustomMessageEntryDraft, CustomToolCallEvent, EditToolCallEvent, EntryRenderer, EntryRenderOptions, ExecOptions, ExecResult, Extension, ExtensionActions, ExtensionAPI, ExtensionCommandContext, ExtensionCommandContextActions, ExtensionContext, ExtensionContextActions, ExtensionError, ExtensionEvent, ExtensionFactory, ExtensionFlag, ExtensionHandler, ExtensionRuntime, ExtensionShortcut, ExtensionUIContext, ExtensionUIDialogOptions, ExtensionWidgetOptions, FindToolCallEvent, GrepToolCallEvent, InlineExtension, InputEvent, InputEventResult, InputSource, KeybindingsManager, LoadExtensionsResult, LsToolCallEvent, MarkdownTransformContext, MarkdownTransformer, MessageEndEvent, MessageEndEventResult, MessageRenderer, MessageRenderOptions, MessageStartEvent, MessageUpdateEvent, ModelPickerEntry, ModelPickerEntryState, ModelSelectEvent, ModelSelectSource, NormalizedBuildSystemPromptOptions, PowerShellToolCallEvent, ProjectTrustContext, ProjectTrustEvent, ProjectTrustEventDecision, ProjectTrustEventResult, ProjectTrustHandler, ProviderConfig, ProviderModelConfig, ReadToolCallEvent, RegisteredCommand, RegisteredModelPickerEntry, RegisteredTool, ResolvedCommand, ResourcesDiscoverEvent, ResourcesDiscoverResult, SessionBeforeCompactEvent, SessionBeforeCompactResult, SessionBeforeForkEvent, SessionBeforeForkResult, SessionBeforeSwitchEvent, SessionBeforeSwitchResult, SessionBeforeTreeEvent, SessionBeforeTreeResult, SessionBoundaryDraft, SessionCompactEvent, SessionCompactFailedEvent, SessionInfoChangedEvent, SessionShutdownEvent, SessionStartEvent, SessionTreeEvent, SlashCommandInfo, SlashCommandSource, SourceInfo, TerminalInputHandler, ThinkingLevelSelectEvent, ToolCallEvent, ToolCallEventResult, ToolDefinition, ToolExecutionEndEvent, ToolExecutionMode, ToolExecutionStartEvent, ToolExecutionUpdateEvent, ToolInfo, ToolRenderResultOptions, ToolResultEvent, ToolResultEventResult, TurnEndEvent, TurnEndEventResult, TurnStartEvent, UIPromptEndEvent, UIPromptKind, UIPromptStartEvent, UserBashEvent, UserBashEventResult, WidgetPlacement, WorkingIndicatorOptions, WriteToolCallEvent, } from "./core/extensions/index.ts";
|
|
9
10
|
export { createExtensionRuntime, defineTool, discoverAndLoadExtensions, ExtensionRunner, isBashToolResult, isEditToolResult, isFindToolResult, isGrepToolResult, isLsToolResult, isPowerShellToolResult, isReadToolResult, isToolCallEventType, isWriteToolResult, wrapRegisteredTool, wrapRegisteredTools, } from "./core/extensions/index.ts";
|
|
10
11
|
export type { ReadonlyFooterDataProvider } from "./core/footer-data-provider.ts";
|
|
12
|
+
export { getHostCapabilities, HOST_CAPABILITIES_ENV, HOST_TOKEN_ENV, HOST_TOKEN_HEADER, HOST_URL_ENV, HostCallError, type HostCallErrorCode, type HostCallOptions, type HostCallRequest, HostCapabilities, type HostCapabilitiesListener, type HostCapability, type HostCapabilitySource, type HostTransport, parseHostCapabilities, } from "./core/host-capabilities.ts";
|
|
11
13
|
export { convertToLlm } from "./core/messages.ts";
|
|
12
14
|
export { ModelRegistry } from "./core/model-registry.ts";
|
|
13
15
|
export { type ModelScopeDiagnostic, type ResolveCliModelResult, type ResolveModelScopeResult, resolveCliModel, resolveModelScopeWithDiagnostics, type ScopedModel, } from "./core/model-resolver.ts";
|
|
14
16
|
export { type CreateModelRuntimeOptions, CredentialSynchronizationError, type CredentialSynchronizationOperation, ModelRuntime, type ModelRuntimeAuthOverrides, } from "./core/model-runtime.ts";
|
|
15
17
|
export type { PackageManager, PathMetadata, ProgressCallback, ProgressEvent, ResolvedPaths, ResolvedResource, } from "./core/package-manager.ts";
|
|
16
18
|
export { DefaultPackageManager } from "./core/package-manager.ts";
|
|
19
|
+
export { buildRuleSet, matchPermissionRules, type PermissionBehavior, type PermissionRule, type PermissionRuleSet, type PermissionRuleSource, parsePermissionRule, type RuleCall, type RuleVerdict, } from "./core/permissions/rules.ts";
|
|
20
|
+
export { evaluateToolPolicy, type PermissionAskHandler, type PermissionAskRequest, readAccessDenial, registerPermissionAskHandler, type ToolPolicyDecision, } from "./core/permissions/tool-policy.ts";
|
|
17
21
|
export { buildProjectMap, formatProjectMapPrompt, type ProjectMap, type ProjectMapOptions, } from "./core/project-map.ts";
|
|
18
22
|
export type { ResourceCollision, ResourceDiagnostic, ResourceLoader } from "./core/resource-loader.ts";
|
|
19
23
|
export { DefaultResourceLoader, loadProjectContextFiles } from "./core/resource-loader.ts";
|
|
24
|
+
export { detectSandboxAvailability, type ResolvedSandboxPolicy, registerSandboxEscalationHandler, resolveSandboxPolicy, SANDBOX_ENV, type SandboxAvailability, type SandboxBlockedAccess, type SandboxDenial, type SandboxEscalationDecision, type SandboxEscalationHandler, type SandboxEscalationInput, type SandboxEscalationRequest, type SandboxEvent, type SandboxLevel, type SandboxOptions, type SandboxRunDetails, type SandboxSettings, type SandboxStatus, ShellSandbox, } from "./core/sandbox/index.ts";
|
|
20
25
|
export { AgentSessionRuntime, type AgentSessionRuntimeDiagnostic, type AgentSessionServices, type CreateAgentSessionFromServicesOptions, type CreateAgentSessionOptions, type CreateAgentSessionResult, type CreateAgentSessionRuntimeFactory, type CreateAgentSessionRuntimeResult, type CreateAgentSessionServicesOptions, createAgentSession, createAgentSessionFromServices, createAgentSessionRuntime, createAgentSessionServices, createBashTool, createCodingTools, createEditTool, createFindTool, createGrepTool, createLsTool, createPowerShellTool, createReadOnlyTools, createReadTool, createWriteTool, type PromptTemplate, } from "./core/sdk.ts";
|
|
21
26
|
export { type BranchSummaryEntry, buildContextEntries, buildSessionContext, buildSessionProjection, type CompactionEntry, type ContextEditableContent, type ContextEditEntry, CURRENT_SESSION_VERSION, type CustomEntry, type CustomMessageEntry, type FileEntry, getLatestCompactionEntry, type ModelChangeEntry, migrateSessionEntries, type NewSessionOptions, type ProjectedSessionEntry, parseSessionEntries, type SessionContext, type SessionEntry, type SessionEntryBase, type SessionHeader, type SessionInfo, type SessionInfoEntry, SessionManager, type SessionMessageEntry, type SessionProjection, type SessionTreeNode, sessionEntryToContextMessages, type ThinkingLevelChangeEntry, } from "./core/session-manager.ts";
|
|
22
27
|
export { type CacheWarmingMode, type CompactionModelOverride, type CompactionSettings, type DefaultProjectTrust, type FullscreenExitOutput, type ImageSettings, type PackageSource, type RetrySettings, SettingsManager, type SettingsManagerCreateOptions, type TuiMode, } from "./core/settings-manager.ts";
|
|
23
28
|
export { formatSkillsForPrompt, type LoadSkillsFromDirOptions, type LoadSkillsResult, loadSkills, loadSkillsFromDir, type Skill, type SkillFrontmatter, } from "./core/skills.ts";
|
|
24
29
|
export { createSyntheticSourceInfo } from "./core/source-info.ts";
|
|
25
30
|
export { type EditDiffResult, generateDiffString, generateUnifiedPatch } from "./core/tools/edit-diff.ts";
|
|
26
|
-
export { type BashOperations, type BashSpawnContext, type BashSpawnHook, type BashToolDetails, type BashToolInput, type BashToolOptions, createBashToolDefinition, createEditToolDefinition, createFindToolDefinition, createGrepToolDefinition, createLocalBashOperations, createLocalPowerShellOperations, createLsToolDefinition, createPowerShellToolDefinition, createReadToolDefinition, createWriteToolDefinition, DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, type EditOperations, type EditToolDetails, type EditToolInput, type EditToolOptions, type FindOperations, type FindToolDetails, type FindToolInput, type FindToolOptions, formatSize, type GrepOperations, type GrepToolDetails, type GrepToolInput, type GrepToolOptions, type LsOperations, type LsToolDetails, type LsToolInput, type LsToolOptions, type PowerShellOperations, type PowerShellSpawnContext, type PowerShellSpawnHook, type PowerShellToolDetails, type PowerShellToolInput, type PowerShellToolOptions, type ReadOperations, type ReadToolDetails, type ReadToolInput, type ReadToolOptions, registerShellExecutionGuard, type ShellExecutionGuard, type ShellExecutionRequest, type ToolsOptions, type TruncationOptions, type TruncationResult, truncateHead, truncateLine, truncateTail, type WriteOperations, type WriteToolInput, type WriteToolOptions, withFileMutationQueue, } from "./core/tools/index.ts";
|
|
31
|
+
export { type BashOperations, type BashSpawnContext, type BashSpawnHook, type BashToolDetails, type BashToolInput, type BashToolOptions, createBashToolDefinition, createEditToolDefinition, createFindToolDefinition, createGrepToolDefinition, createLocalBashOperations, createLocalPowerShellOperations, createLsToolDefinition, createPowerShellToolDefinition, createProcessToolDefinition, createReadToolDefinition, createWriteToolDefinition, DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, type EditOperations, type EditToolDetails, type EditToolInput, type EditToolOptions, type FindOperations, type FindToolDetails, type FindToolInput, type FindToolOptions, formatSize, type GrepOperations, type GrepToolDetails, type GrepToolInput, type GrepToolOptions, type LsOperations, type LsToolDetails, type LsToolInput, type LsToolOptions, type PowerShellOperations, type PowerShellSpawnContext, type PowerShellSpawnHook, type PowerShellToolDetails, type PowerShellToolInput, type PowerShellToolOptions, type ProcessToolDetails, type ProcessToolInput, type ReadOperations, type ReadToolDetails, type ReadToolInput, type ReadToolOptions, registerShellExecutionGuard, type ShellExecutionGuard, type ShellExecutionRequest, type ToolsOptions, type TruncationOptions, type TruncationResult, truncateHead, truncateLine, truncateTail, type WriteOperations, type WriteToolInput, type WriteToolOptions, withFileMutationQueue, } from "./core/tools/index.ts";
|
|
27
32
|
export { hasTrustRequiringProjectResources, type ProjectTrustDecision, ProjectTrustStore, type ProjectTrustStoreEntry, type ProjectTrustUpdate, } from "./core/trust-manager.ts";
|
|
28
33
|
export { applyShellEnvironmentPolicy, DEFAULT_SHELL_ENV_EXCLUDES, isDalCodeCredentialName, type ShellEnvironmentPolicy, withoutDalCodeCredentials, } from "./dal/child-env.ts";
|
|
29
34
|
export * from "./dal/hooks/index.ts";
|
|
30
35
|
export { type MainOptions, main } from "./main.ts";
|
|
31
|
-
export { InteractiveMode, type InteractiveModeOptions, type JsonAgentSessionEvent, type ModelInfo, type PrintModeOptions, RpcClient, type RpcClientOptions, type RpcCommand, type RpcEventListener, type RpcExtensionUIRequest, type RpcExtensionUIResponse, type RpcResponse, type RpcSessionState, runPrintMode, runRpcMode, } from "./modes/index.ts";
|
|
36
|
+
export { InteractiveMode, type InteractiveModeOptions, type JsonAgentSessionEvent, type ModelInfo, type PrintModeOptions, RpcClient, type RpcClientOptions, type RpcCommand, type RpcEventListener, type RpcExitListener, type RpcExtensionUIRequest, type RpcExtensionUIResponse, type RpcHostRequest, type RpcHostRequestHandler, type RpcHostResponse, type RpcProcessExit, type RpcResponse, type RpcSessionState, runPrintMode, runRpcMode, } from "./modes/index.ts";
|
|
32
37
|
export { ArminComponent, AssistantMessageComponent, BashExecutionComponent, BorderedLoader, BranchSummaryMessageComponent, CompactionSummaryMessageComponent, CustomEditor, type CustomEditorOptions, CustomMessageComponent, DynamicBorder, ExtensionEditorComponent, ExtensionInputComponent, ExtensionSelectorComponent, FooterComponent, keyHint, keyText, LoginDialogComponent, ModelSelectorComponent, OAuthSelectorComponent, type RenderDiffOptions, rawKeyHint, renderDiff, SessionSelectorComponent, type SettingsCallbacks, type SettingsConfig, SettingsSelectorComponent, ShowImagesSelectorComponent, SkillInvocationMessageComponent, ThemeSelectorComponent, ThinkingSelectorComponent, ToolExecutionComponent, type ToolExecutionOptions, TreeSelectorComponent, truncateToVisualLines, UserMessageComponent, UserMessageSelectorComponent, type VisualTruncateResult, } from "./modes/interactive/components/index.ts";
|
|
33
38
|
export { getLanguageFromPath, getMarkdownTheme, getSelectListTheme, getSettingsListTheme, highlightCode, initTheme, Theme, type ThemeColor, } from "./modes/interactive/theme/theme.ts";
|
|
34
39
|
export { copyToClipboard } from "./utils/clipboard.ts";
|
|
@@ -36,4 +41,4 @@ export { parseFrontmatter, stripFrontmatter } from "./utils/frontmatter.ts";
|
|
|
36
41
|
export { convertToPng } from "./utils/image-convert.ts";
|
|
37
42
|
export { formatDimensionNote, type ResizedImage, resizeImage } from "./utils/image-resize.ts";
|
|
38
43
|
export { detectSupportedImageMimeTypeFromFile } from "./utils/mime.ts";
|
|
39
|
-
export { getPowerShellConfig, getShellConfig } from "./utils/shell.ts";
|
|
44
|
+
export { getPowerShellConfig, getShellConfig, getShellEnv } from "./utils/shell.ts";
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{parseArgs as t}from"./cli/args.js";import{CONFIG_DIR_NAME as n,getAgentDir as i,getDocsPath as a,getExamplesPath as s,getPackageDir as l,getReadmePath as m,SHARED_SKILL_CONFIG_DIRS as p,VERSION as c}from"./config.js";import{AgentSession as g,parseSkillBlock as T}from"./core/agent-session.js";import{readStoredCredential as f}from"./core/auth-storage.js";import{calculateContextTokens as C,collectEntriesForBranchSummary as x,compact as E,DEFAULT_COMPACTION_SETTINGS as h,estimateTokens as R,findCutPoint as D,findTurnStartIndex as M,generateBranchSummary as L,generateSummary as P,generateSummaryWithUsage as A,getLastAssistantUsage as y,prepareBranchEntries as F,serializeConversation as I,shouldCompact as _}from"./core/compaction/index.js";import{createEventBus as B}from"./core/event-bus.js";import{createExtensionRuntime as N,defineTool as w,discoverAndLoadExtensions as O,ExtensionRunner as U,isBashToolResult as G,isEditToolResult as j,isFindToolResult as b,isGrepToolResult as H,isLsToolResult as W,isPowerShellToolResult as z,isReadToolResult as V,isToolCallEventType as X,isWriteToolResult as K,wrapRegisteredTool as q,wrapRegisteredTools as Q}from"./core/extensions/index.js";import{convertToLlm as J}from"./core/messages.js";import{ModelRegistry as $}from"./core/model-registry.js";import{resolveCliModel as oe,resolveModelScopeWithDiagnostics as te}from"./core/model-resolver.js";import{CredentialSynchronizationError as ne,ModelRuntime as ie}from"./core/model-runtime.js";import{DefaultPackageManager as se}from"./core/package-manager.js";import{buildProjectMap as me,formatProjectMapPrompt as pe}from"./core/project-map.js";import{DefaultResourceLoader as Se,loadProjectContextFiles as ge}from"./core/resource-loader.js";import{AgentSessionRuntime as de,createAgentSession as fe,createAgentSessionFromServices as ue,createAgentSessionRuntime as Ce,createAgentSessionServices as xe,createBashTool as Ee,createCodingTools as he,createEditTool as Re,createFindTool as De,createGrepTool as Me,createLsTool as Le,createPowerShellTool as Pe,createReadOnlyTools as Ae,createReadTool as ye,createWriteTool as Fe}from"./core/sdk.js";import{buildContextEntries as _e,buildSessionContext as ke,buildSessionProjection as Be,CURRENT_SESSION_VERSION as ve,getLatestCompactionEntry as Ne,migrateSessionEntries as we,parseSessionEntries as Oe,SessionManager as Ue,sessionEntryToContextMessages as Ge}from"./core/session-manager.js";import{SettingsManager as be}from"./core/settings-manager.js";import{formatSkillsForPrompt as We,loadSkills as ze,loadSkillsFromDir as Ve}from"./core/skills.js";import{createSyntheticSourceInfo as Ke}from"./core/source-info.js";import{generateDiffString as Qe,generateUnifiedPatch as Ye}from"./core/tools/edit-diff.js";import{createBashToolDefinition as Ze,createEditToolDefinition as $e,createFindToolDefinition as eo,createGrepToolDefinition as oo,createLocalBashOperations as to,createLocalPowerShellOperations as ro,createLsToolDefinition as no,createPowerShellToolDefinition as io,createReadToolDefinition as ao,createWriteToolDefinition as so,DEFAULT_MAX_BYTES as lo,DEFAULT_MAX_LINES as mo,formatSize as po,registerShellExecutionGuard as co,truncateHead as So,truncateLine as go,truncateTail as To,withFileMutationQueue as fo}from"./core/tools/index.js";import{hasTrustRequiringProjectResources as Co,ProjectTrustStore as xo}from"./core/trust-manager.js";import{applyShellEnvironmentPolicy as ho,DEFAULT_SHELL_ENV_EXCLUDES as Ro,isDalCodeCredentialName as Do,withoutDalCodeCredentials as Mo}from"./dal/child-env.js";export*from"./dal/hooks/index.js";import{main as Ao}from"./main.js";import{InteractiveMode as Fo,RpcClient as Io,runPrintMode as _o,runRpcMode as ko}from"./modes/index.js";import{ArminComponent as vo,AssistantMessageComponent as No,BashExecutionComponent as wo,BorderedLoader as Oo,BranchSummaryMessageComponent as Uo,CompactionSummaryMessageComponent as Go,CustomEditor as jo,CustomMessageComponent as bo,DynamicBorder as Ho,ExtensionEditorComponent as Wo,ExtensionInputComponent as zo,ExtensionSelectorComponent as Vo,FooterComponent as Xo,keyHint as Ko,keyText as qo,LoginDialogComponent as Qo,ModelSelectorComponent as Yo,OAuthSelectorComponent as Jo,rawKeyHint as Zo,renderDiff as $o,SessionSelectorComponent as et,SettingsSelectorComponent as ot,ShowImagesSelectorComponent as tt,SkillInvocationMessageComponent as rt,ThemeSelectorComponent as nt,ThinkingSelectorComponent as it,ToolExecutionComponent as at,TreeSelectorComponent as st,truncateToVisualLines as lt,UserMessageComponent as mt,UserMessageSelectorComponent as pt}from"./modes/interactive/components/index.js";import{getLanguageFromPath as St,getMarkdownTheme as gt,getSelectListTheme as Tt,getSettingsListTheme as dt,highlightCode as ft,initTheme as ut,Theme as Ct}from"./modes/interactive/theme/theme.js";import{copyToClipboard as Et}from"./utils/clipboard.js";import{parseFrontmatter as Rt,stripFrontmatter as Dt}from"./utils/frontmatter.js";import{convertToPng as Lt}from"./utils/image-convert.js";import{formatDimensionNote as At,resizeImage as yt}from"./utils/image-resize.js";import{detectSupportedImageMimeTypeFromFile as It}from"./utils/mime.js";import{getPowerShellConfig as kt,getShellConfig as Bt}from"./utils/shell.js";export{g as AgentSession,de as AgentSessionRuntime,vo as ArminComponent,No as AssistantMessageComponent,wo as BashExecutionComponent,Oo as BorderedLoader,Uo as BranchSummaryMessageComponent,n as CONFIG_DIR_NAME,ve as CURRENT_SESSION_VERSION,Go as CompactionSummaryMessageComponent,ne as CredentialSynchronizationError,jo as CustomEditor,bo as CustomMessageComponent,h as DEFAULT_COMPACTION_SETTINGS,lo as DEFAULT_MAX_BYTES,mo as DEFAULT_MAX_LINES,Ro as DEFAULT_SHELL_ENV_EXCLUDES,se as DefaultPackageManager,Se as DefaultResourceLoader,Ho as DynamicBorder,Wo as ExtensionEditorComponent,zo as ExtensionInputComponent,U as ExtensionRunner,Vo as ExtensionSelectorComponent,Xo as FooterComponent,Fo as InteractiveMode,Qo as LoginDialogComponent,$ as ModelRegistry,ie as ModelRuntime,Yo as ModelSelectorComponent,Jo as OAuthSelectorComponent,xo as ProjectTrustStore,Io as RpcClient,p as SHARED_SKILL_CONFIG_DIRS,Ue as SessionManager,et as SessionSelectorComponent,be as SettingsManager,ot as SettingsSelectorComponent,tt as ShowImagesSelectorComponent,rt as SkillInvocationMessageComponent,Ct as Theme,nt as ThemeSelectorComponent,it as ThinkingSelectorComponent,at as ToolExecutionComponent,st as TreeSelectorComponent,mt as UserMessageComponent,pt as UserMessageSelectorComponent,c as VERSION,ho as applyShellEnvironmentPolicy,_e as buildContextEntries,me as buildProjectMap,ke as buildSessionContext,Be as buildSessionProjection,C as calculateContextTokens,x as collectEntriesForBranchSummary,E as compact,J as convertToLlm,Lt as convertToPng,Et as copyToClipboard,fe as createAgentSession,ue as createAgentSessionFromServices,Ce as createAgentSessionRuntime,xe as createAgentSessionServices,Ee as createBashTool,Ze as createBashToolDefinition,he as createCodingTools,Re as createEditTool,$e as createEditToolDefinition,B as createEventBus,N as createExtensionRuntime,De as createFindTool,eo as createFindToolDefinition,Me as createGrepTool,oo as createGrepToolDefinition,to as createLocalBashOperations,ro as createLocalPowerShellOperations,Le as createLsTool,no as createLsToolDefinition,Pe as createPowerShellTool,io as createPowerShellToolDefinition,Ae as createReadOnlyTools,ye as createReadTool,ao as createReadToolDefinition,Ke as createSyntheticSourceInfo,Fe as createWriteTool,so as createWriteToolDefinition,w as defineTool,It as detectSupportedImageMimeTypeFromFile,O as discoverAndLoadExtensions,R as estimateTokens,D as findCutPoint,M as findTurnStartIndex,At as formatDimensionNote,pe as formatProjectMapPrompt,po as formatSize,We as formatSkillsForPrompt,L as generateBranchSummary,Qe as generateDiffString,P as generateSummary,A as generateSummaryWithUsage,Ye as generateUnifiedPatch,i as getAgentDir,a as getDocsPath,s as getExamplesPath,St as getLanguageFromPath,y as getLastAssistantUsage,Ne as getLatestCompactionEntry,gt as getMarkdownTheme,l as getPackageDir,kt as getPowerShellConfig,m as getReadmePath,Tt as getSelectListTheme,dt as getSettingsListTheme,Bt as getShellConfig,Co as hasTrustRequiringProjectResources,ft as highlightCode,ut as initTheme,G as isBashToolResult,Do as isDalCodeCredentialName,j as isEditToolResult,b as isFindToolResult,H as isGrepToolResult,W as isLsToolResult,z as isPowerShellToolResult,V as isReadToolResult,X as isToolCallEventType,K as isWriteToolResult,Ko as keyHint,qo as keyText,ge as loadProjectContextFiles,ze as loadSkills,Ve as loadSkillsFromDir,Ao as main,we as migrateSessionEntries,t as parseArgs,Rt as parseFrontmatter,Oe as parseSessionEntries,T as parseSkillBlock,F as prepareBranchEntries,Zo as rawKeyHint,f as readStoredCredential,co as registerShellExecutionGuard,$o as renderDiff,yt as resizeImage,oe as resolveCliModel,te as resolveModelScopeWithDiagnostics,_o as runPrintMode,ko as runRpcMode,I as serializeConversation,Ge as sessionEntryToContextMessages,_ as shouldCompact,Dt as stripFrontmatter,So as truncateHead,go as truncateLine,To as truncateTail,lt as truncateToVisualLines,fo as withFileMutationQueue,Mo as withoutDalCodeCredentials,q as wrapRegisteredTool,Q as wrapRegisteredTools};
|
|
1
|
+
import{parseArgs as t}from"./cli/args.js";import{CONFIG_DIR_NAME as n,getAgentDir as i,getDocsPath as a,getExamplesPath as s,getPackageDir as l,getReadmePath as m,SHARED_SKILL_CONFIG_DIRS as c,VERSION as p}from"./config.js";import{AgentSession as g,parseSkillBlock as d}from"./core/agent-session.js";import{readStoredCredential as f}from"./core/auth-storage.js";import{BackgroundProcessManager as C,MAX_BACKGROUND_PROCESSES as x}from"./core/background-processes.js";import{calculateContextTokens as h,collectEntriesForBranchSummary as R,compact as D,DEFAULT_COMPACTION_SETTINGS as P,estimateTokens as A,findCutPoint as M,findTurnStartIndex as L,generateBranchSummary as _,generateSummary as y,generateSummaryWithUsage as I,getLastAssistantUsage as F,prepareBranchEntries as N,serializeConversation as O,shouldCompact as B}from"./core/compaction/index.js";import{createEventBus as k}from"./core/event-bus.js";import{createExtensionRuntime as b,defineTool as U,discoverAndLoadExtensions as w,ExtensionRunner as G,isBashToolResult as V,isEditToolResult as j,isFindToolResult as K,isGrepToolResult as W,isLsToolResult as X,isPowerShellToolResult as z,isReadToolResult as q,isToolCallEventType as Q,isWriteToolResult as Y,wrapRegisteredTool as J,wrapRegisteredTools as Z}from"./core/extensions/index.js";import{getHostCapabilities as ee,HOST_CAPABILITIES_ENV as oe,HOST_TOKEN_ENV as te,HOST_TOKEN_HEADER as re,HOST_URL_ENV as ne,HostCallError as ie,HostCapabilities as ae,parseHostCapabilities as se}from"./core/host-capabilities.js";import{convertToLlm as me}from"./core/messages.js";import{ModelRegistry as pe}from"./core/model-registry.js";import{resolveCliModel as ge,resolveModelScopeWithDiagnostics as de}from"./core/model-resolver.js";import{CredentialSynchronizationError as fe,ModelRuntime as ue}from"./core/model-runtime.js";import{DefaultPackageManager as xe}from"./core/package-manager.js";import{buildRuleSet as he,matchPermissionRules as Re,parsePermissionRule as De}from"./core/permissions/rules.js";import{evaluateToolPolicy as Ae,readAccessDenial as Me,registerPermissionAskHandler as Le}from"./core/permissions/tool-policy.js";import{buildProjectMap as ye,formatProjectMapPrompt as Ie}from"./core/project-map.js";import{DefaultResourceLoader as Ne,loadProjectContextFiles as Oe}from"./core/resource-loader.js";import{detectSandboxAvailability as ve,registerSandboxEscalationHandler as ke,resolveSandboxPolicy as He,SANDBOX_ENV as be,ShellSandbox as Ue}from"./core/sandbox/index.js";import{AgentSessionRuntime as Ge,createAgentSession as Ve,createAgentSessionFromServices as je,createAgentSessionRuntime as Ke,createAgentSessionServices as We,createBashTool as Xe,createCodingTools as ze,createEditTool as qe,createFindTool as Qe,createGrepTool as Ye,createLsTool as Je,createPowerShellTool as Ze,createReadOnlyTools as $e,createReadTool as eo,createWriteTool as oo}from"./core/sdk.js";import{buildContextEntries as ro,buildSessionContext as no,buildSessionProjection as io,CURRENT_SESSION_VERSION as ao,getLatestCompactionEntry as so,migrateSessionEntries as lo,parseSessionEntries as mo,SessionManager as co,sessionEntryToContextMessages as po}from"./core/session-manager.js";import{SettingsManager as go}from"./core/settings-manager.js";import{formatSkillsForPrompt as fo,loadSkills as uo,loadSkillsFromDir as Co}from"./core/skills.js";import{createSyntheticSourceInfo as Eo}from"./core/source-info.js";import{generateDiffString as Ro,generateUnifiedPatch as Do}from"./core/tools/edit-diff.js";import{createBashToolDefinition as Ao,createEditToolDefinition as Mo,createFindToolDefinition as Lo,createGrepToolDefinition as _o,createLocalBashOperations as yo,createLocalPowerShellOperations as Io,createLsToolDefinition as Fo,createPowerShellToolDefinition as No,createProcessToolDefinition as Oo,createReadToolDefinition as Bo,createWriteToolDefinition as vo,DEFAULT_MAX_BYTES as ko,DEFAULT_MAX_LINES as Ho,formatSize as bo,registerShellExecutionGuard as Uo,truncateHead as wo,truncateLine as Go,truncateTail as Vo,withFileMutationQueue as jo}from"./core/tools/index.js";import{hasTrustRequiringProjectResources as Wo,ProjectTrustStore as Xo}from"./core/trust-manager.js";import{applyShellEnvironmentPolicy as qo,DEFAULT_SHELL_ENV_EXCLUDES as Qo,isDalCodeCredentialName as Yo,withoutDalCodeCredentials as Jo}from"./dal/child-env.js";export*from"./dal/hooks/index.js";import{main as et}from"./main.js";import{InteractiveMode as tt,RpcClient as rt,runPrintMode as nt,runRpcMode as it}from"./modes/index.js";import{ArminComponent as st,AssistantMessageComponent as lt,BashExecutionComponent as mt,BorderedLoader as ct,BranchSummaryMessageComponent as pt,CompactionSummaryMessageComponent as St,CustomEditor as gt,CustomMessageComponent as dt,DynamicBorder as Tt,ExtensionEditorComponent as ft,ExtensionInputComponent as ut,ExtensionSelectorComponent as Ct,FooterComponent as xt,keyHint as Et,keyText as ht,LoginDialogComponent as Rt,ModelSelectorComponent as Dt,OAuthSelectorComponent as Pt,rawKeyHint as At,renderDiff as Mt,SessionSelectorComponent as Lt,SettingsSelectorComponent as _t,ShowImagesSelectorComponent as yt,SkillInvocationMessageComponent as It,ThemeSelectorComponent as Ft,ThinkingSelectorComponent as Nt,ToolExecutionComponent as Ot,TreeSelectorComponent as Bt,truncateToVisualLines as vt,UserMessageComponent as kt,UserMessageSelectorComponent as Ht}from"./modes/interactive/components/index.js";import{getLanguageFromPath as Ut,getMarkdownTheme as wt,getSelectListTheme as Gt,getSettingsListTheme as Vt,highlightCode as jt,initTheme as Kt,Theme as Wt}from"./modes/interactive/theme/theme.js";import{copyToClipboard as zt}from"./utils/clipboard.js";import{parseFrontmatter as Qt,stripFrontmatter as Yt}from"./utils/frontmatter.js";import{convertToPng as Zt}from"./utils/image-convert.js";import{formatDimensionNote as er,resizeImage as or}from"./utils/image-resize.js";import{detectSupportedImageMimeTypeFromFile as rr}from"./utils/mime.js";import{getPowerShellConfig as ir,getShellConfig as ar,getShellEnv as sr}from"./utils/shell.js";export{g as AgentSession,Ge as AgentSessionRuntime,st as ArminComponent,lt as AssistantMessageComponent,C as BackgroundProcessManager,mt as BashExecutionComponent,ct as BorderedLoader,pt as BranchSummaryMessageComponent,n as CONFIG_DIR_NAME,ao as CURRENT_SESSION_VERSION,St as CompactionSummaryMessageComponent,fe as CredentialSynchronizationError,gt as CustomEditor,dt as CustomMessageComponent,P as DEFAULT_COMPACTION_SETTINGS,ko as DEFAULT_MAX_BYTES,Ho as DEFAULT_MAX_LINES,Qo as DEFAULT_SHELL_ENV_EXCLUDES,xe as DefaultPackageManager,Ne as DefaultResourceLoader,Tt as DynamicBorder,ft as ExtensionEditorComponent,ut as ExtensionInputComponent,G as ExtensionRunner,Ct as ExtensionSelectorComponent,xt as FooterComponent,oe as HOST_CAPABILITIES_ENV,te as HOST_TOKEN_ENV,re as HOST_TOKEN_HEADER,ne as HOST_URL_ENV,ie as HostCallError,ae as HostCapabilities,tt as InteractiveMode,Rt as LoginDialogComponent,x as MAX_BACKGROUND_PROCESSES,pe as ModelRegistry,ue as ModelRuntime,Dt as ModelSelectorComponent,Pt as OAuthSelectorComponent,Xo as ProjectTrustStore,rt as RpcClient,be as SANDBOX_ENV,c as SHARED_SKILL_CONFIG_DIRS,co as SessionManager,Lt as SessionSelectorComponent,go as SettingsManager,_t as SettingsSelectorComponent,Ue as ShellSandbox,yt as ShowImagesSelectorComponent,It as SkillInvocationMessageComponent,Wt as Theme,Ft as ThemeSelectorComponent,Nt as ThinkingSelectorComponent,Ot as ToolExecutionComponent,Bt as TreeSelectorComponent,kt as UserMessageComponent,Ht as UserMessageSelectorComponent,p as VERSION,qo as applyShellEnvironmentPolicy,ro as buildContextEntries,ye as buildProjectMap,he as buildRuleSet,no as buildSessionContext,io as buildSessionProjection,h as calculateContextTokens,R as collectEntriesForBranchSummary,D as compact,me as convertToLlm,Zt as convertToPng,zt as copyToClipboard,Ve as createAgentSession,je as createAgentSessionFromServices,Ke as createAgentSessionRuntime,We as createAgentSessionServices,Xe as createBashTool,Ao as createBashToolDefinition,ze as createCodingTools,qe as createEditTool,Mo as createEditToolDefinition,k as createEventBus,b as createExtensionRuntime,Qe as createFindTool,Lo as createFindToolDefinition,Ye as createGrepTool,_o as createGrepToolDefinition,yo as createLocalBashOperations,Io as createLocalPowerShellOperations,Je as createLsTool,Fo as createLsToolDefinition,Ze as createPowerShellTool,No as createPowerShellToolDefinition,Oo as createProcessToolDefinition,$e as createReadOnlyTools,eo as createReadTool,Bo as createReadToolDefinition,Eo as createSyntheticSourceInfo,oo as createWriteTool,vo as createWriteToolDefinition,U as defineTool,ve as detectSandboxAvailability,rr as detectSupportedImageMimeTypeFromFile,w as discoverAndLoadExtensions,A as estimateTokens,Ae as evaluateToolPolicy,M as findCutPoint,L as findTurnStartIndex,er as formatDimensionNote,Ie as formatProjectMapPrompt,bo as formatSize,fo as formatSkillsForPrompt,_ as generateBranchSummary,Ro as generateDiffString,y as generateSummary,I as generateSummaryWithUsage,Do as generateUnifiedPatch,i as getAgentDir,a as getDocsPath,s as getExamplesPath,ee as getHostCapabilities,Ut as getLanguageFromPath,F as getLastAssistantUsage,so as getLatestCompactionEntry,wt as getMarkdownTheme,l as getPackageDir,ir as getPowerShellConfig,m as getReadmePath,Gt as getSelectListTheme,Vt as getSettingsListTheme,ar as getShellConfig,sr as getShellEnv,Wo as hasTrustRequiringProjectResources,jt as highlightCode,Kt as initTheme,V as isBashToolResult,Yo as isDalCodeCredentialName,j as isEditToolResult,K as isFindToolResult,W as isGrepToolResult,X as isLsToolResult,z as isPowerShellToolResult,q as isReadToolResult,Q as isToolCallEventType,Y as isWriteToolResult,Et as keyHint,ht as keyText,Oe as loadProjectContextFiles,uo as loadSkills,Co as loadSkillsFromDir,et as main,Re as matchPermissionRules,lo as migrateSessionEntries,t as parseArgs,Qt as parseFrontmatter,se as parseHostCapabilities,De as parsePermissionRule,mo as parseSessionEntries,d as parseSkillBlock,N as prepareBranchEntries,At as rawKeyHint,Me as readAccessDenial,f as readStoredCredential,Le as registerPermissionAskHandler,ke as registerSandboxEscalationHandler,Uo as registerShellExecutionGuard,Mt as renderDiff,or as resizeImage,ge as resolveCliModel,de as resolveModelScopeWithDiagnostics,He as resolveSandboxPolicy,nt as runPrintMode,it as runRpcMode,O as serializeConversation,po as sessionEntryToContextMessages,B as shouldCompact,Yt as stripFrontmatter,wo as truncateHead,Go as truncateLine,Vo as truncateTail,vt as truncateToVisualLines,jo as withFileMutationQueue,Jo as withoutDalCodeCredentials,J as wrapRegisteredTool,Z as wrapRegisteredTools};
|
package/dist/main.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
2
|
-
`));if(t.kind!=="check"){const o=AbortSignal.timeout(15e3),i=await
|
|
3
|
-
`),!0}const
|
|
4
|
-
`),process.exitCode=n.status==="ready"?0:n.status==="not_ready"?1:2}catch(a){const n=a instanceof H?a.message:c("\u65E0\u6CD5\u83B7\u53D6\u51ED\u636E");console.error(d.red(u(c("\u9519\u8BEF\uFF1A{message}"),{message:n}))),process.exitCode=t.kind==="check"?2:1}return!0}m(eo,"runAuthCommand");async function to(e,t){if(e.fileArgs.length===0)return ce({parsed:e,stdinContent:t});const{text:s,images:a}=await et(e.fileArgs,{autoResizeImages:!1});return ce({parsed:e,fileText:s,fileImages:a,stdinContent:t})}m(to,"prepareInitialMessage");function U(e,t,s){const a=g.findById(t,e,s);return a?{type:"local",path:a}:void 0}m(U,"findLocalSessionByExactId");async function Se(e,t,s){if(e.includes("/")||e.includes("\\")||e.endsWith(".jsonl"))return{type:"path",path:ve(e,t)};const a=U(e,t,s);if(a)return a;const l=(await g.list(t,s)).find(i=>i.id.startsWith(e));if(l)return{type:"local",path:l.path};const p=await g.listAll(s),o=p.find(i=>i.id===e)??p.find(i=>i.id.startsWith(e));return o?{type:"global",path:o.path,cwd:o.cwd}:{type:"not_found",arg:e}}m(Se,"resolveSessionPath");async function oo(e){return new Promise(t=>{const s=Be({input:process.stdin,output:process.stdout});s.question(`${e} [y/N] `,a=>{s.close(),t(a.toLowerCase()==="y"||a.toLowerCase()==="yes")})})}m(oo,"promptConfirm");function so(e){if(!e.fork)return;const t=[e.session?"--session":void 0,e.continue?"--continue":void 0,e.resume?"--resume":void 0,e.noSession?"--no-session":void 0].filter(s=>s!==void 0);t.length>0&&(console.error(d.red(u(c("\u9519\u8BEF\uFF1A--fork \u4E0D\u80FD\u548C {flags} \u540C\u65F6\u4F7F\u7528"),{flags:t.join(", ")}))),process.exit(1))}m(so,"validateForkFlags");function no(e){if(e.sessionId===void 0)return;const t=[e.session?"--session":void 0,e.continue?"--continue":void 0,e.resume?"--resume":void 0].filter(s=>s!==void 0);t.length>0&&(console.error(d.red(u(c("\u9519\u8BEF\uFF1A--session-id \u4E0D\u80FD\u548C {flags} \u540C\u65F6\u4F7F\u7528"),{flags:t.join(", ")}))),process.exit(1));try{At(e.sessionId)}catch(s){const a=s instanceof Error?s.message:String(s);console.error(d.red(u(c("\u9519\u8BEF\uFF1A{message}"),{message:a}))),process.exit(1)}}m(no,"validateSessionIdFlags");function io(e,t){try{return g.open(e,t)}catch(s){const a=s instanceof Error?s.message:String(s);console.error(d.red(u(c("\u9519\u8BEF\uFF1A{message}"),{message:a}))),process.exit(1)}}m(io,"openSessionOrExit");function xe(e,t,s,a){try{return g.forkFrom(e,t,s,{id:a})}catch(n){const l=n instanceof Error?n.message:String(n);console.error(d.red(u(c("\u9519\u8BEF\uFF1A{message}"),{message:l}))),process.exit(1)}}m(xe,"forkSessionOrExit");async function ro(e,t,s,a){if(e.noSession||e.help||e.listModels!==void 0)return g.inMemory(t,e.sessionId!==void 0?{id:e.sessionId}:void 0);if(e.fork){e.sessionId&&U(e.sessionId,t,s)&&(console.error(d.red(u(c("ID \u4E3A\u300C{id}\u300D\u7684\u4F1A\u8BDD\u5DF2\u7ECF\u5B58\u5728"),{id:e.sessionId}))),process.exit(1));const n=await Se(e.fork,t,s);switch(n.type){case"path":case"local":case"global":return xe(n.path,t,s,e.sessionId);case"not_found":console.error(d.red(u(c("\u6CA1\u6709\u627E\u5230\u5339\u914D\u300C{session}\u300D\u7684\u4F1A\u8BDD"),{session:n.arg}))),process.exit(1)}}if(e.session){const n=await Se(e.session,t,s);switch(n.type){case"path":case"local":return io(n.path,s);case"global":return console.log(d.yellow(u(c("\u5728\u53E6\u4E00\u4E2A\u9879\u76EE\u91CC\u627E\u5230\u4E86\u8FD9\u4E2A\u4F1A\u8BDD\uFF1A{cwd}"),{cwd:n.cwd}))),await oo(c("\u8981\u628A\u8FD9\u4E2A\u4F1A\u8BDD\u5206\u53C9\u5230\u5F53\u524D\u76EE\u5F55\u5417\uFF1F"))||(console.log(d.dim(c("\u5DF2\u53D6\u6D88\u3002"))),process.exit(0)),xe(n.path,t,s);case"not_found":console.error(d.red(u(c("\u6CA1\u6709\u627E\u5230\u5339\u914D\u300C{session}\u300D\u7684\u4F1A\u8BDD"),{session:n.arg}))),process.exit(1)}}if(e.resume)try{const n=await st((l,p)=>g.list(t,s,l,p),(l,p)=>g.listAll(s,l,p),a);return n||(console.log(d.dim(c("\u6CA1\u6709\u9009\u62E9\u4F1A\u8BDD"))),process.exit(0)),g.open(n,s)}finally{K()}if(e.continue)return g.continueRecent(t,s);if(e.sessionId){const n=U(e.sessionId,t,s);if(n)return g.open(n.path,s);console.error(d.yellow(u(c("\u8B66\u544A\uFF1A\u5F53\u524D\u9879\u76EE\u91CC\u6CA1\u6709 ID \u4E3A\u300C{id}\u300D\u7684\u4F1A\u8BDD\uFF0C\u5C06\u7528\u8FD9\u4E2A ID \u65B0\u5EFA\u4E00\u4E2A\u4F1A\u8BDD\u3002"),{id:e.sessionId})))}return g.create(t,s,{id:e.sessionId})}m(ro,"createSessionManager");function ao(e,t,s,a,n){const l={},p=[];let o=!1;if(e.model){const i=xt({cliProvider:e.provider,cliModel:e.model,cliThinking:e.thinking,modelRuntime:a});i.warning&&p.push({type:"warning",message:i.warning}),i.error&&p.push({type:"error",message:i.error}),i.model&&(l.model=i.model,!e.thinking&&i.thinkingLevel&&(l.thinkingLevel=i.thinkingLevel,o=!0))}if(!l.model&&t.length>0&&!s){const i=n.getDefaultProvider(),T=n.getDefaultModel(),M=i&&T?a.getModel(i,T):void 0,y=M?t.find(v=>Ke(v.model,M)):void 0;y?(l.model=y.model,!e.thinking&&y.thinkingLevel&&(l.thinkingLevel=y.thinkingLevel)):(l.model=t[0].model,!e.thinking&&t[0].thinkingLevel&&(l.thinkingLevel=t[0].thinkingLevel))}return e.thinking&&(l.thinkingLevel=e.thinking),t.length>0&&(l.scopedModels=t.map(i=>({model:i.model,thinkingLevel:i.thinkingLevel}))),e.noTools?l.noTools="all":e.noBuiltinTools&&(l.noTools="builtin"),e.tools&&(l.tools=[...e.tools]),e.excludeTools&&(l.excludeTools=[...e.excludeTools]),{options:l,cliThinkingFromModel:o,diagnostics:p}}m(ao,"buildSessionOptions");function R(e,t){return t?.map(s=>$t(s)?ve(s,e):s)}m(R,"resolveCliPaths");async function lo(e,t){return rt(t,kt(e),[{label:"Continue",value:e.fallbackCwd},{label:"Cancel",value:void 0}])}m(lo,"promptForMissingSessionCwd");async function Xo(e,t){Ft();const s=[...Ot,...t?.extensionFactories??[]],a=e.includes("--offline")||he(process.env.PI_OFFLINE);if(a&&(process.env.PI_OFFLINE="1",process.env.PI_SKIP_VERSION_CHECK="1"),await eo(e))return;process.platform==="win32"&&Yt(dt()),Ut();const n=process.cwd(),l=ct(),p=B.create(n,l,{projectTrusted:!1});if(me(p.getGlobalSettings().httpProxy),bt(),Et(),jt(),ue(),await Vt(e,{extensionFactories:s})){const r=process.exitCode??0;if(process.platform==="win32"&&r===0&&e[0]==="update")return;process.exit(r);return}if(await qt(e,{extensionFactories:s}))return;const o=le(e);if(o.diagnostics.length>0){for(const r of o.diagnostics){const f=r.type==="error"?d.red:d.yellow;console.error(f(u(r.type==="error"?c("\u9519\u8BEF\uFF1A{message}"):c("\u8B66\u544A\uFF1A{message}"),{message:r.message})))}o.diagnostics.some(r=>r.type==="error")&&process.exit(1)}if(h("parseArgs"),o.version&&(console.log(mt),process.exit(0)),o.export){let r;try{const f=o.messages.length>0?o.messages[0]:void 0;r=await St(o.export,f)}catch(f){const C=f instanceof Error?f.message:c("\u5BFC\u51FA\u4F1A\u8BDD\u5931\u8D25");console.error(d.red(u(c("\u9519\u8BEF\uFF1A{message}"),{message:C}))),process.exit(1)}console.log(u(c("\u5DF2\u5BFC\u51FA\u5230\uFF1A{path}"),{path:r})),process.exit(0)}let i=Qt(o,process.stdin.isTTY,process.stdout.isTTY);i!=="interactive"&&!Zt(o)&&Pt(),(o.mode==="rpc"||o.mode==="acp")&&o.fileArgs.length>0&&(console.error(d.red(u(c("\u9519\u8BEF\uFF1A{mode} \u6A21\u5F0F\u4E0D\u652F\u6301 @\u6587\u4EF6 \u53C2\u6570"),{mode:o.mode.toUpperCase()}))),process.exit(1)),so(o),no(o);const{migratedAuthProviders:M,deprecationWarnings:y}=_t(n);h("runMigrations");const v=B.create(n,l),E=fe(v);i==="interactive"&&!o.help&&o.listModels===void 0&&nt()&&(await it(v),h("firstTimeSetup")),i==="interactive"&&o.useTheme!==void 0&&v.applyOverrides({theme:o.useTheme});const q=process.env[at],V=(o.sessionDir?zt(o.sessionDir):void 0)??(q?lt(q):void 0)??v.getSessionDir();let w=await ro(o,n,V,v);const k=Ct(w,n);if(k)if(i==="interactive"){const r=await lo(k,v);r||process.exit(0),w=g.open(k.sessionFile,V,r)}else console.error(d.red(new It(k).message)),process.exit(1);if(o.name!==void 0){const r=We(o.name);r===void 0&&(console.error(d.red(c("\u9519\u8BEF\uFF1A--name \u7684\u503C\u4E0D\u80FD\u4E3A\u7A7A"))),process.exit(1)),w.appendSessionInfo(r)}h("createSessionManager");const $=new Rt(l),z=w.getCwd(),ye=o.projectTrustOverride===void 0&&!ge(z)?z:void 0,Y=o.help||o.listModels!==void 0?"print":i,G=new Map,we=[...Lt(),...R(n,o.extensions)??[]],Te=R(n,o.skills),Pe=R(n,o.promptTemplates),Me=R(n,o.themes),ke=m(async({cwd:r,agentDir:f,sessionManager:C,sessionStartEvent:oe,projectTrustContext:Re})=>{const se=oe===void 0,ne=[],ie=G.get(r),re=ge(r),ae=o.projectTrustOverride===void 0&&ie===void 0&&re,Ee=ae?!1:ie??o.projectTrustOverride??(!re||$.get(r)===!0),be=B.create(r,f,{projectTrusted:Ee}),I=await pt({cwd:r,agentDir:f,settingsManager:be,modelRuntimeSignal:AbortSignal.timeout(15e3),extensionFlagValues:o.unknownFlags,resourceLoaderReloadOptions:ae?{resolveProjectTrust:m(async({extensionsResult:D})=>{const F=await Mt({cwd:r,trustStore:$,trustOverride:o.projectTrustOverride,defaultProjectTrust:v.getDefaultProjectTrust(),extensionsResult:D,projectTrustContext:Re??ot({cwd:r,mode:se?Y:i,settingsManager:v,hasUI:se&&Y==="interactive"}),onExtensionError:m(De=>ne.push({type:"warning",message:De}),"onExtensionError")});return G.set(r,F),F},"resolveProjectTrust")}:void 0,resourceLoaderOptions:{additionalExtensionPaths:we,additionalSkillPaths:Te,additionalPromptTemplatePaths:Pe,additionalThemePaths:Me,noExtensions:o.noExtensions,noSkills:o.noSkills,noPromptTemplates:o.noPromptTemplates,noThemes:o.noThemes,noContextFiles:o.noContextFiles,systemPrompt:o.systemPrompt,appendSystemPrompt:o.appendSystemPrompt,extensionFactories:s}}),{settingsManager:j,modelRuntime:O,resourceLoader:Le}=I,_=[...ne,...I.diagnostics,...fe(j),...Le.getExtensions().errors.map(({path:D,error:F})=>({type:"error",message:`Failed to load extension "${D}": ${F}`}))],N=o.models??j.getEnabledModels(),je=N&&N.length>0?await yt(N,O,{signal:AbortSignal.timeout(15e3)}):[],{options:x,cliThinkingFromModel:Oe,diagnostics:_e}=ao(o,je,C.buildSessionContext().messages.length>0,O,j);_.push(..._e),o.apiKey&&(x.model?await O.setRuntimeApiKey(x.model.provider,o.apiKey):_.push({type:"error",message:c("\u4F7F\u7528 --api-key \u65F6\u9700\u8981\u901A\u8FC7 --model\u3001--provider/--model \u6216 --models \u6307\u5B9A\u6A21\u578B")}));const A=await ft({services:I,sessionManager:C,sessionStartEvent:oe,model:x.model,thinkingLevel:x.thinkingLevel,scopedModels:x.scopedModels,tools:x.tools,excludeTools:x.excludeTools,noTools:x.noTools,customTools:x.customTools}),Ne=o.thinking!==void 0||Oe;return A.session.model&&Ne&&A.session.setThinkingLevel(A.session.thinkingLevel),{...A,services:I,diagnostics:_}},"createRuntime");h("createRuntime");const S=await ut(ke,{cwd:w.getCwd(),agentDir:l,sessionManager:w});h("createAgentSessionRuntime");const{services:Ce,session:Ie,modelFallbackMessage:Ae}=S,{settingsManager:b,modelRuntime:J,resourceLoader:Fe}=Ce;if(me(b.getGlobalSettings().httpProxy),ue(b.getHttpIdleTimeoutMs()),o.help){W(E);const r=Fe.getExtensions().extensions.flatMap(f=>Array.from(f.flags.values()));Ue(r),process.exit(0)}if(o.listModels!==void 0){W(pe([...E,...S.diagnostics]));const r=typeof o.listModels=="string"?o.listModels:void 0;await tt(J,r,AbortSignal.timeout(15e3)),process.exit(0)}let L;i!=="rpc"&&i!=="acp"&&(L=await Jt(),L!==void 0&&i==="interactive"&&(i="print")),h("readPipedStdin");const{initialMessage:Q,initialImages:X}=await to(o,L);h("prepareInitialMessage"),Wt(b.getTheme(),i==="interactive"),h("initTheme"),i==="interactive"&&y.length>0&&await Nt(y),h("resolveModelScope");const Z=pe([...E,...S.diagnostics]),ee=S.diagnostics.some(r=>r.type==="error");(i!=="interactive"||ee)&&W(Z),ee&&(S.diagnostics.some(r=>r.message.includes("Failed to load extension"))&&console.error(d.yellow(Gt())),process.exit(1)),h("createAgentSession"),i!=="interactive"&&!Ie.model&&(console.error(d.red(gt())),process.exit(1));const te=he(process.env.PI_STARTUP_BENCHMARK);if(te&&i!=="interactive"&&(console.error(d.red(c("\u9519\u8BEF\uFF1API_STARTUP_BENCHMARK \u53EA\u652F\u6301\u4EA4\u4E92\u6A21\u5F0F"))),process.exit(1)),!a&&(i==="rpc"||i==="acp")){const r=new AbortController,f=setTimeout(()=>r.abort(),15e3);J.refresh({signal:r.signal}).catch(()=>{}).finally(()=>clearTimeout(f))}if(i==="rpc")P(),await Kt(S);else if(i==="acp")P(),await Ht(S);else if(i==="interactive"){const r=new Dt(S,{migratedProviders:M,startupDiagnostics:Z,modelFallbackMessage:Ae,autoTrustOnReloadCwd:ye,initialMessage:Q,initialImages:X,initialMessages:o.messages,verbose:o.verbose,tuiMode:o.tuiMode,initialThemeSetting:o.useTheme});if(te){await r.init(),h("interactiveMode.init"),await new Promise(f=>setTimeout(f,150)),r.stop(),K(),P(),process.stdout.writableLength>0&&await new Promise(f=>process.stdout.once("drain",f)),process.stderr.writableLength>0&&await new Promise(f=>process.stderr.once("drain",f));return}P(),await r.run()}else{P();const r=await Bt(S,{mode:Xt(i),messages:o.messages,initialMessage:Q,initialImages:X});K(),Tt(),r!==0&&(process.exitCode=r);return}}m(Xo,"main");export{ro as createSessionManager,Xo as main};
|
|
1
|
+
var Be=Object.defineProperty;var m=(e,t)=>Be(e,"name",{value:t,configurable:!0});import{createInterface as Ke}from"node:readline";import{modelsAreEqual as We}from"@earendil-works/pi-ai";import d from"chalk";import{normalizeSessionName as Ue,parseArgs as ce,printHelp as qe}from"./cli/args.js";import{checkProviderAuth as Ve,createAuthCheckModelRuntime as $e,getProviderCredential as ze}from"./cli/auth-check.js";import{AuthCommandError as B,getAuthCommandName as Ye,getAuthCommandUsage as Ge,isAuthCommandHelp as Je,parseAuthCommand as Qe,printAuthCommandHelp as Xe,validateAuthCommandArgs as Ze}from"./cli/auth-command.js";import{resolveCredentialForPrint as et}from"./cli/credential-print.js";import{processFileArguments as tt}from"./cli/file-processor.js";import{buildInitialMessage as de}from"./cli/initial-message.js";import{listModels as ot}from"./cli/list-models.js";import{createProjectTrustContext as st}from"./cli/project-trust.js";import{selectSession as nt}from"./cli/session-picker.js";import{shouldRunFirstTimeSetup as it,showFirstTimeSetup as rt,showStartupSelector as at}from"./cli/startup-ui.js";import{APP_NAME as me,ENV_SESSION_DIR as lt,expandTildePath as ct,getAgentDir as dt,getPackageDir as mt,VERSION as ut}from"./config.js";import{createAgentSessionRuntime as ft}from"./core/agent-session-runtime.js";import{createAgentSessionFromServices as pt,createAgentSessionServices as gt}from"./core/agent-session-services.js";import{formatNoModelsAvailableMessage as ht}from"./core/auth-guidance.js";import{AuthStorage as vt,ReadOnlyAuthStorage as xt}from"./core/auth-storage.js";import{exportFromFile as St}from"./core/export-html/index.js";import{applyHttpProxySettings as ue,configureHttpDispatcher as fe}from"./core/http-dispatcher.js";import{resolveCliModel as wt,resolveModelScope as yt}from"./core/model-resolver.js";import{ModelRuntime as Tt}from"./core/model-runtime.js";import{restoreStdout as Pt,takeOverStdout as Mt}from"./core/output-guard.js";import{resolveProjectTrusted as kt}from"./core/project-trust.js";import{formatMissingSessionCwdPrompt as Ct,getMissingSessionCwdIssue as It,MissingSessionCwdError as At}from"./core/session-cwd.js";import{assertValidSessionId as bt,SessionManager as g}from"./core/session-manager.js";import{collectSettingsDiagnostics as pe,deduplicateDiagnostics as ge}from"./core/settings-diagnostics.js";import{SettingsManager as K}from"./core/settings-manager.js";import{printTimings as k,resetTimings as Ft,time as h}from"./core/timings.js";import{hasTrustRequiringProjectResources as he,ProjectTrustStore as Rt}from"./core/trust-manager.js";import{applyDalEnvApiKeyPolicy as Et,applyDalSystemProxyFallback as Lt,dalBuiltinExtensionPaths as jt}from"./dal/builtins.js";import{fill as u,t as c}from"./dal/i18n.js";import{installDalShellSafetyNet as Ot}from"./dal/safety-net.js";import{builtInExtensions as _t}from"./extensions/index.js";import{runMigrations as Nt,showDeprecationWarnings as Dt}from"./migrations.js";import{InteractiveMode as Ht,runAcpMode as Bt,runPrintMode as Kt,runRpcMode as Wt}from"./modes/index.js";import{initTheme as Ut,stopThemeWatcher as W}from"./modes/interactive/theme/theme.js";import{cleanupManagedInstall as qt,handleConfigCommand as Vt,handlePackageCommand as $t}from"./package-manager-cli.js";import{isTruthyEnvFlag as ve}from"./utils/offline.js";import{isLocalPath as zt,normalizePath as Yt,resolvePath as xe}from"./utils/paths.js";import{cleanupWindowsSelfUpdateQuarantine as Gt}from"./utils/windows-self-update.js";const Jt=m(()=>u(c("\u63D0\u793A\uFF1A\u53EF\u4EE5\u7528\u300C{app} -ne\u300D\u5728\u4E0D\u52A0\u8F7D\u6269\u5C55\u7684\u60C5\u51B5\u4E0B\u542F\u52A8\u3002"),{app:me}),"extensionLoadFailureHint");async function Qt(){if(!process.stdin.isTTY)return new Promise(e=>{let t="";process.stdin.setEncoding("utf8"),process.stdin.on("data",s=>{t+=s}),process.stdin.on("end",()=>{e(t.trim()||void 0)}),process.stdin.resume()})}m(Qt,"readPipedStdin");function U(e){for(const t of e){const s=t.type==="error"?d.red:t.type==="warning"?d.yellow:d.dim,l=t.type==="error"?u(c("\u9519\u8BEF\uFF1A{message}"),{message:t.message}):t.type==="warning"?u(c("\u8B66\u544A\uFF1A{message}"),{message:t.message}):t.message;console.error(s(l))}}m(U,"reportDiagnostics");function Xt(e,t,s){return e.mode==="rpc"?"rpc":e.mode==="acp"?"acp":e.mode==="json"?"json":e.print||!t||!s?"print":"interactive"}m(Xt,"resolveAppMode");function Zt(e){return e==="json"?"json":"text"}m(Zt,"toPrintOutputMode");function eo(e){return!e.print&&e.mode===void 0&&(e.help===!0||e.listModels!==void 0)}m(eo,"isPlainRuntimeMetadataCommand");async function to(e){if(Je(e))return Xe(),!0;let t;try{t=Qe(e)}catch(l){const n=l instanceof B?l.message:c("\u65E0\u6CD5\u89E3\u6790 auth \u547D\u4EE4");return console.error(d.red(u(c("\u9519\u8BEF\uFF1A{message}"),{message:n}))),process.exitCode=1,!0}if(!t)return!1;const s=ce(t.args);if(s.unknownFlags.size>0){const l=s.unknownFlags.keys().next().value;return console.error(d.red(u(c("\u300C{command}\u300D\u4E0D\u652F\u6301\u9009\u9879 --{option}\u3002"),{option:String(l),command:Ye(t.kind)}))),console.error(d.dim(u(c("\u8BF7\u67E5\u770B\u300C{app} --help\u300D\u6216\u300C{usage}\u300D\u3002"),{app:me,usage:Ge(t.kind)}))),process.exitCode=1,!0}try{if(s.diagnostics.length>0)throw new B(s.diagnostics.map(o=>o.message).join(`
|
|
2
|
+
`));if(t.kind!=="check"){const o=AbortSignal.timeout(15e3),i=await Tt.create({allowModelNetwork:!1,signal:o}),T=await et(s,i,t.kind,t.minExpiryMs,o);return process.stdout.write(`${T}
|
|
3
|
+
`),!0}const l=Ze(s,t.kind);let n,a;try{const o=t.noRefresh?new xt:vt.create(),i=await $e(o);n=await Ve(s,i,{refresh:!t.noRefresh}),t.credentials&&n.status==="ready"&&(a=await ze(n.provider,i,o,{refresh:!t.noRefresh}),a||(n={status:"not_ready",provider:n.provider,reason:"credential_not_available"}))}catch{n={status:"invalid",provider:l.provider??l.model,reason:"invalid_state"}}const p=t.json?JSON.stringify({...n,...a?{credentials:a}:{}}):a??n.status;process.stdout.write(`${p}
|
|
4
|
+
`),process.exitCode=n.status==="ready"?0:n.status==="not_ready"?1:2}catch(l){const n=l instanceof B?l.message:c("\u65E0\u6CD5\u83B7\u53D6\u51ED\u636E");console.error(d.red(u(c("\u9519\u8BEF\uFF1A{message}"),{message:n}))),process.exitCode=t.kind==="check"?2:1}return!0}m(to,"runAuthCommand");async function oo(e,t){if(e.fileArgs.length===0)return de({parsed:e,stdinContent:t});const{text:s,images:l}=await tt(e.fileArgs,{autoResizeImages:!1});return de({parsed:e,fileText:s,fileImages:l,stdinContent:t})}m(oo,"prepareInitialMessage");function q(e,t,s){const l=g.findById(t,e,s);return l?{type:"local",path:l}:void 0}m(q,"findLocalSessionByExactId");async function Se(e,t,s){if(e.includes("/")||e.includes("\\")||e.endsWith(".jsonl"))return{type:"path",path:xe(e,t)};const l=q(e,t,s);if(l)return l;const a=(await g.list(t,s)).find(i=>i.id.startsWith(e));if(a)return{type:"local",path:a.path};const p=await g.listAll(s),o=p.find(i=>i.id===e)??p.find(i=>i.id.startsWith(e));return o?{type:"global",path:o.path,cwd:o.cwd}:{type:"not_found",arg:e}}m(Se,"resolveSessionPath");async function so(e){return new Promise(t=>{const s=Ke({input:process.stdin,output:process.stdout});s.question(`${e} [y/N] `,l=>{s.close(),t(l.toLowerCase()==="y"||l.toLowerCase()==="yes")})})}m(so,"promptConfirm");function no(e){if(!e.fork)return;const t=[e.session?"--session":void 0,e.continue?"--continue":void 0,e.resume?"--resume":void 0,e.noSession?"--no-session":void 0].filter(s=>s!==void 0);t.length>0&&(console.error(d.red(u(c("\u9519\u8BEF\uFF1A--fork \u4E0D\u80FD\u548C {flags} \u540C\u65F6\u4F7F\u7528"),{flags:t.join(", ")}))),process.exit(1))}m(no,"validateForkFlags");function io(e){if(e.sessionId===void 0)return;const t=[e.session?"--session":void 0,e.continue?"--continue":void 0,e.resume?"--resume":void 0].filter(s=>s!==void 0);t.length>0&&(console.error(d.red(u(c("\u9519\u8BEF\uFF1A--session-id \u4E0D\u80FD\u548C {flags} \u540C\u65F6\u4F7F\u7528"),{flags:t.join(", ")}))),process.exit(1));try{bt(e.sessionId)}catch(s){const l=s instanceof Error?s.message:String(s);console.error(d.red(u(c("\u9519\u8BEF\uFF1A{message}"),{message:l}))),process.exit(1)}}m(io,"validateSessionIdFlags");function ro(e,t){try{return g.open(e,t)}catch(s){const l=s instanceof Error?s.message:String(s);console.error(d.red(u(c("\u9519\u8BEF\uFF1A{message}"),{message:l}))),process.exit(1)}}m(ro,"openSessionOrExit");function we(e,t,s,l){try{return g.forkFrom(e,t,s,{id:l})}catch(n){const a=n instanceof Error?n.message:String(n);console.error(d.red(u(c("\u9519\u8BEF\uFF1A{message}"),{message:a}))),process.exit(1)}}m(we,"forkSessionOrExit");async function ao(e,t,s,l){if(e.noSession||e.help||e.listModels!==void 0)return g.inMemory(t,e.sessionId!==void 0?{id:e.sessionId}:void 0);if(e.fork){e.sessionId&&q(e.sessionId,t,s)&&(console.error(d.red(u(c("ID \u4E3A\u300C{id}\u300D\u7684\u4F1A\u8BDD\u5DF2\u7ECF\u5B58\u5728"),{id:e.sessionId}))),process.exit(1));const n=await Se(e.fork,t,s);switch(n.type){case"path":case"local":case"global":return we(n.path,t,s,e.sessionId);case"not_found":console.error(d.red(u(c("\u6CA1\u6709\u627E\u5230\u5339\u914D\u300C{session}\u300D\u7684\u4F1A\u8BDD"),{session:n.arg}))),process.exit(1)}}if(e.session){const n=await Se(e.session,t,s);switch(n.type){case"path":case"local":return ro(n.path,s);case"global":return console.log(d.yellow(u(c("\u5728\u53E6\u4E00\u4E2A\u9879\u76EE\u91CC\u627E\u5230\u4E86\u8FD9\u4E2A\u4F1A\u8BDD\uFF1A{cwd}"),{cwd:n.cwd}))),await so(c("\u8981\u628A\u8FD9\u4E2A\u4F1A\u8BDD\u5206\u53C9\u5230\u5F53\u524D\u76EE\u5F55\u5417\uFF1F"))||(console.log(d.dim(c("\u5DF2\u53D6\u6D88\u3002"))),process.exit(0)),we(n.path,t,s);case"not_found":console.error(d.red(u(c("\u6CA1\u6709\u627E\u5230\u5339\u914D\u300C{session}\u300D\u7684\u4F1A\u8BDD"),{session:n.arg}))),process.exit(1)}}if(e.resume)try{const n=await nt((a,p)=>g.list(t,s,a,p),(a,p)=>g.listAll(s,a,p),l);return n||(console.log(d.dim(c("\u6CA1\u6709\u9009\u62E9\u4F1A\u8BDD"))),process.exit(0)),g.open(n,s)}finally{W()}if(e.continue)return g.continueRecent(t,s);if(e.sessionId){const n=q(e.sessionId,t,s);if(n)return g.open(n.path,s);console.error(d.yellow(u(c("\u8B66\u544A\uFF1A\u5F53\u524D\u9879\u76EE\u91CC\u6CA1\u6709 ID \u4E3A\u300C{id}\u300D\u7684\u4F1A\u8BDD\uFF0C\u5C06\u7528\u8FD9\u4E2A ID \u65B0\u5EFA\u4E00\u4E2A\u4F1A\u8BDD\u3002"),{id:e.sessionId})))}return g.create(t,s,{id:e.sessionId})}m(ao,"createSessionManager");function lo(e,t,s,l,n){const a={},p=[];let o=!1;if(e.model){const i=wt({cliProvider:e.provider,cliModel:e.model,cliThinking:e.thinking,modelRuntime:l});i.warning&&p.push({type:"warning",message:i.warning}),i.error&&p.push({type:"error",message:i.error}),i.model&&(a.model=i.model,!e.thinking&&i.thinkingLevel&&(a.thinkingLevel=i.thinkingLevel,o=!0))}if(!a.model&&t.length>0&&!s){const i=n.getDefaultProvider(),T=n.getDefaultModel(),C=i&&T?l.getModel(i,T):void 0,w=C?t.find(x=>We(x.model,C)):void 0;w?(a.model=w.model,!e.thinking&&w.thinkingLevel&&(a.thinkingLevel=w.thinkingLevel)):(a.model=t[0].model,!e.thinking&&t[0].thinkingLevel&&(a.thinkingLevel=t[0].thinkingLevel))}return e.thinking&&(a.thinkingLevel=e.thinking),t.length>0&&(a.scopedModels=t.map(i=>({model:i.model,thinkingLevel:i.thinkingLevel}))),e.noTools?a.noTools="all":e.noBuiltinTools&&(a.noTools="builtin"),e.tools&&(a.tools=[...e.tools]),e.excludeTools&&(a.excludeTools=[...e.excludeTools]),a.sandbox={defaultLevel:"workspace-write",...e.sandbox?{level:e.sandbox}:{},...e.sandboxAllowDomains?{allowedDomains:[...e.sandboxAllowDomains]}:{}},a.defaultActiveTools=["read","bash","edit","write","process"],{options:a,cliThinkingFromModel:o,diagnostics:p}}m(lo,"buildSessionOptions");function E(e,t){return t?.map(s=>zt(s)?xe(s,e):s)}m(E,"resolveCliPaths");async function co(e,t){return at(t,Ct(e),[{label:"Continue",value:e.fallbackCwd},{label:"Cancel",value:void 0}])}m(co,"promptForMissingSessionCwd");async function Zo(e,t){Ft();const s=[..._t,...t?.extensionFactories??[]],l=e.includes("--offline")||ve(process.env.PI_OFFLINE);if(l&&(process.env.PI_OFFLINE="1",process.env.PI_SKIP_VERSION_CHECK="1"),await to(e))return;process.platform==="win32"&&Gt(mt()),qt();const n=process.cwd(),a=dt(),p=K.create(n,a,{projectTrusted:!1});if(ue(p.getGlobalSettings().httpProxy),Lt(),Et(),Ot(),fe(),await $t(e,{extensionFactories:s})){const r=process.exitCode??0;if(process.platform==="win32"&&r===0&&e[0]==="update")return;process.exit(r);return}if(await Vt(e,{extensionFactories:s}))return;const o=ce(e);if(o.diagnostics.length>0){for(const r of o.diagnostics){const f=r.type==="error"?d.red:d.yellow;console.error(f(u(r.type==="error"?c("\u9519\u8BEF\uFF1A{message}"):c("\u8B66\u544A\uFF1A{message}"),{message:r.message})))}o.diagnostics.some(r=>r.type==="error")&&process.exit(1)}if(h("parseArgs"),o.version&&(console.log(ut),process.exit(0)),o.export){let r;try{const f=o.messages.length>0?o.messages[0]:void 0;r=await St(o.export,f)}catch(f){const A=f instanceof Error?f.message:c("\u5BFC\u51FA\u4F1A\u8BDD\u5931\u8D25");console.error(d.red(u(c("\u9519\u8BEF\uFF1A{message}"),{message:A}))),process.exit(1)}console.log(u(c("\u5DF2\u5BFC\u51FA\u5230\uFF1A{path}"),{path:r})),process.exit(0)}let i=Xt(o,process.stdin.isTTY,process.stdout.isTTY);i!=="interactive"&&!eo(o)&&Mt(),(o.mode==="rpc"||o.mode==="acp")&&o.fileArgs.length>0&&(console.error(d.red(u(c("\u9519\u8BEF\uFF1A{mode} \u6A21\u5F0F\u4E0D\u652F\u6301 @\u6587\u4EF6 \u53C2\u6570"),{mode:o.mode.toUpperCase()}))),process.exit(1)),no(o),io(o);const{migratedAuthProviders:C,deprecationWarnings:w}=Nt(n);h("runMigrations");const x=K.create(n,a),L=pe(x);i==="interactive"&&!o.help&&o.listModels===void 0&&it()&&(await rt(x),h("firstTimeSetup")),i==="interactive"&&o.useTheme!==void 0&&x.applyOverrides({theme:o.useTheme});const V=process.env[lt],$=(o.sessionDir?Yt(o.sessionDir):void 0)??(V?ct(V):void 0)??x.getSessionDir();let y=await ao(o,n,$,x);const I=It(y,n);if(I)if(i==="interactive"){const r=await co(I,x);r||process.exit(0),y=g.open(I.sessionFile,$,r)}else console.error(d.red(new At(I).message)),process.exit(1);if(o.name!==void 0){const r=Ue(o.name);r===void 0&&(console.error(d.red(c("\u9519\u8BEF\uFF1A--name \u7684\u503C\u4E0D\u80FD\u4E3A\u7A7A"))),process.exit(1)),y.appendSessionInfo(r)}h("createSessionManager");const z=new Rt(a),Y=y.getCwd(),ye=o.projectTrustOverride===void 0&&!he(Y)?Y:void 0,G=o.help||o.listModels!==void 0?"print":i,J=new Map,Te=[...jt(),...E(n,o.extensions)??[]],Pe=E(n,o.skills),Me=E(n,o.promptTemplates),ke=E(n,o.themes),Ce=m(async({cwd:r,agentDir:f,sessionManager:A,sessionStartEvent:se,projectTrustContext:Re})=>{const ne=se===void 0,ie=[],re=J.get(r),ae=he(r),le=o.projectTrustOverride===void 0&&re===void 0&&ae,Ee=le?!1:re??o.projectTrustOverride??(!ae||z.get(r)===!0),Le=K.create(r,f,{projectTrusted:Ee}),b=await gt({cwd:r,agentDir:f,settingsManager:Le,modelRuntimeSignal:AbortSignal.timeout(15e3),extensionFlagValues:o.unknownFlags,resourceLoaderReloadOptions:le?{resolveProjectTrust:m(async({extensionsResult:H})=>{const R=await kt({cwd:r,trustStore:z,trustOverride:o.projectTrustOverride,defaultProjectTrust:x.getDefaultProjectTrust(),extensionsResult:H,projectTrustContext:Re??st({cwd:r,mode:ne?G:i,settingsManager:x,hasUI:ne&&G==="interactive"}),onExtensionError:m(He=>ie.push({type:"warning",message:He}),"onExtensionError")});return J.set(r,R),R},"resolveProjectTrust")}:void 0,resourceLoaderOptions:{additionalExtensionPaths:Te,additionalSkillPaths:Pe,additionalPromptTemplatePaths:Me,additionalThemePaths:ke,noExtensions:o.noExtensions,noSkills:o.noSkills,noPromptTemplates:o.noPromptTemplates,noThemes:o.noThemes,noContextFiles:o.noContextFiles,systemPrompt:o.systemPrompt,appendSystemPrompt:o.appendSystemPrompt,extensionFactories:s}}),{settingsManager:_,modelRuntime:N,resourceLoader:je}=b,F=[...ie,...b.diagnostics,...pe(_),...je.getExtensions().errors.map(({path:H,error:R})=>({type:"error",message:`Failed to load extension "${H}": ${R}`}))],D=o.models??_.getEnabledModels(),Oe=D&&D.length>0?await yt(D,N,{signal:AbortSignal.timeout(15e3)}):[],{options:v,cliThinkingFromModel:_e,diagnostics:Ne}=lo(o,Oe,A.buildSessionContext().messages.length>0,N,_);F.push(...Ne),o.apiKey&&(v.model?await N.setRuntimeApiKey(v.model.provider,o.apiKey):F.push({type:"error",message:c("\u4F7F\u7528 --api-key \u65F6\u9700\u8981\u901A\u8FC7 --model\u3001--provider/--model \u6216 --models \u6307\u5B9A\u6A21\u578B")}));const P=await pt({services:b,sessionManager:A,sessionStartEvent:se,model:v.model,thinkingLevel:v.thinkingLevel,scopedModels:v.scopedModels,tools:v.tools,excludeTools:v.excludeTools,noTools:v.noTools,customTools:v.customTools,sandbox:v.sandbox,defaultActiveTools:v.defaultActiveTools}),De=o.thinking!==void 0||_e;P.session.model&&De&&P.session.setThinkingLevel(P.session.thinkingLevel);const M=P.session.getSandboxStatus();return M&&M.level!=="off"&&!M.enforced&&F.push({type:"warning",message:u(c("\u547D\u4EE4\u6C99\u7BB1\u4E0D\u53EF\u7528\uFF08{level}\uFF09\uFF1A{reason} shell \u547D\u4EE4\u4F1A\u88AB\u62D2\u7EDD\uFF1B\u786E\u5B9A\u4E0D\u8981\u6C99\u7BB1\u8BF7\u7528 --sandbox off\u3002"),{level:M.level,reason:M.unavailableReason??""})}),{...P,services:b,diagnostics:F}},"createRuntime");h("createRuntime");const S=await ft(Ce,{cwd:y.getCwd(),agentDir:a,sessionManager:y});h("createAgentSessionRuntime");const{services:Ie,session:Ae,modelFallbackMessage:be}=S,{settingsManager:j,modelRuntime:Q,resourceLoader:Fe}=Ie;if(ue(j.getGlobalSettings().httpProxy),fe(j.getHttpIdleTimeoutMs()),o.help){U(L);const r=Fe.getExtensions().extensions.flatMap(f=>Array.from(f.flags.values()));qe(r),process.exit(0)}if(o.listModels!==void 0){U(ge([...L,...S.diagnostics]));const r=typeof o.listModels=="string"?o.listModels:void 0;await ot(Q,r,AbortSignal.timeout(15e3)),process.exit(0)}let O;i!=="rpc"&&i!=="acp"&&(O=await Qt(),O!==void 0&&i==="interactive"&&(i="print")),h("readPipedStdin");const{initialMessage:X,initialImages:Z}=await oo(o,O);h("prepareInitialMessage"),Ut(j.getTheme(),i==="interactive"),h("initTheme"),i==="interactive"&&w.length>0&&await Dt(w),h("resolveModelScope");const ee=ge([...L,...S.diagnostics]),te=S.diagnostics.some(r=>r.type==="error");(i!=="interactive"||te)&&U(ee),te&&(S.diagnostics.some(r=>r.message.includes("Failed to load extension"))&&console.error(d.yellow(Jt())),process.exit(1)),h("createAgentSession"),i!=="interactive"&&!Ae.model&&(console.error(d.red(ht())),process.exit(1));const oe=ve(process.env.PI_STARTUP_BENCHMARK);if(oe&&i!=="interactive"&&(console.error(d.red(c("\u9519\u8BEF\uFF1API_STARTUP_BENCHMARK \u53EA\u652F\u6301\u4EA4\u4E92\u6A21\u5F0F"))),process.exit(1)),!l&&(i==="rpc"||i==="acp")){const r=new AbortController,f=setTimeout(()=>r.abort(),15e3);Q.refresh({signal:r.signal}).catch(()=>{}).finally(()=>clearTimeout(f))}if(i==="rpc")k(),await Wt(S);else if(i==="acp")k(),await Bt(S);else if(i==="interactive"){const r=new Ht(S,{migratedProviders:C,startupDiagnostics:ee,modelFallbackMessage:be,autoTrustOnReloadCwd:ye,initialMessage:X,initialImages:Z,initialMessages:o.messages,verbose:o.verbose,tuiMode:o.tuiMode,initialThemeSetting:o.useTheme});if(oe){await r.init(),h("interactiveMode.init"),await new Promise(f=>setTimeout(f,150)),r.stop(),W(),k(),process.stdout.writableLength>0&&await new Promise(f=>process.stdout.once("drain",f)),process.stderr.writableLength>0&&await new Promise(f=>process.stderr.once("drain",f));return}k(),await r.run()}else{k();const r=await Kt(S,{mode:Zt(i),messages:o.messages,initialMessage:X,initialImages:Z});W(),Pt(),r!==0&&(process.exitCode=r);return}}m(Zo,"main");export{ao as createSessionManager,Zo as main};
|
package/dist/modes/index.d.ts
CHANGED
|
@@ -2,6 +2,6 @@ export { runAcpMode } from "./acp/acp-mode.ts";
|
|
|
2
2
|
export { InteractiveMode, type InteractiveModeOptions } from "./interactive/interactive-mode.ts";
|
|
3
3
|
export type { JsonAgentSessionEvent } from "./json-event.ts";
|
|
4
4
|
export { type PrintModeOptions, runPrintMode } from "./print-mode.ts";
|
|
5
|
-
export { type ModelInfo, RpcClient, type RpcClientOptions, type RpcEventListener } from "./rpc/rpc-client.ts";
|
|
5
|
+
export { type ModelInfo, RpcClient, type RpcClientOptions, type RpcEventListener, type RpcExitListener, type RpcHostRequestHandler, type RpcProcessExit, } from "./rpc/rpc-client.ts";
|
|
6
6
|
export { runRpcMode } from "./rpc/rpc-mode.ts";
|
|
7
|
-
export type { RpcCommand, RpcExtensionUIRequest, RpcExtensionUIResponse, RpcResponse, RpcSessionState, } from "./rpc/rpc-types.ts";
|
|
7
|
+
export type { RpcCommand, RpcExtensionUIRequest, RpcExtensionUIResponse, RpcHostRequest, RpcHostResponse, RpcResponse, RpcSessionState, } from "./rpc/rpc-types.ts";
|
package/dist/modes/print-mode.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)}),
|
|
3
|
-
`)}await S(),
|
|
4
|
-
`)
|
|
1
|
+
var x=Object.defineProperty;var n=(r,l)=>x(r,"name",{value:l,configurable:!0});import{flushRawStdout as I,waitForRawStdoutBackpressure as R,writeRawStdout as c}from"../core/output-guard.js";import{fill as M,t as u}from"../dal/i18n.js";import{killTrackedDetachedChildren as j}from"../utils/shell.js";import{toJsonEvent as k}from"./json-event.js";async function G(r,l){const{mode:i,messages:b=[],initialMessage:p,initialImages:h}=l;let g=0,o=r.session,f,d,m=!1;const w=[],y=n(async()=>{m||(m=!0,f?.(),d?.(),await r.dispose())},"disposeRuntime");n(()=>{const e=["SIGTERM"];process.platform!=="win32"&&e.push("SIGHUP");for(const s of e){const t=n(()=>{j(),y().finally(()=>{process.exit(s==="SIGHUP"?129:143)})},"handler");process.on(s,t),w.push(()=>process.off(s,t))}},"registerSignalHandlers")(),r.setRebindSession(async()=>{await S()});const S=n(async()=>{o=r.session,await o.bindExtensions({mode:i==="json"?"json":"print",commandContextActions:{waitForIdle:n(()=>o.waitForIdle(),"waitForIdle"),newSession:n(async e=>r.newSession(e),"newSession"),fork:n(async(e,s)=>({cancelled:(await r.fork(e,s)).cancelled}),"fork"),navigateTree:n(async(e,s)=>({cancelled:(await o.navigateTree(e,{summarize:s?.summarize,customInstructions:s?.customInstructions,replaceInstructions:s?.replaceInstructions,label:s?.label})).cancelled}),"navigateTree"),switchSession:n(async(e,s)=>r.switchSession(e,s),"switchSession"),reload:n(async()=>{await o.reload()},"reload")},onError:n(e=>{console.error(M(u("\u6269\u5C55\u51FA\u9519\uFF08{path}\uFF09\uFF1A{error}"),{path:e.extensionPath,error:String(e.error)}))},"onError")}),f?.(),d?.(),f=o.subscribe(e=>{i==="json"&&c(`${JSON.stringify(k(e))}
|
|
2
|
+
`)}),d=i==="json"?o.agent.subscribe(async()=>{await R()}):void 0},"rebindSession");try{if(i==="json"){const e=o.sessionManager.getHeader();e&&c(`${JSON.stringify(e)}
|
|
3
|
+
`)}await S(),p&&await o.prompt(p,{images:h});for(const e of b)await o.prompt(e);if(i==="text"){const e=o.state,s=e.messages[e.messages.length-1];if(s?.role==="custom"&&s.display){const t=typeof s.content=="string"?s.content:s.content.filter(a=>a.type==="text").map(a=>a.text).join(`
|
|
4
|
+
`);t&&c(`${t}
|
|
5
|
+
`)}else if(s?.role==="assistant"){const t=s;if(t.stopReason==="error"||t.stopReason==="aborted")console.error(t.errorMessage||(t.stopReason==="aborted"?u("\u8BF7\u6C42\u5DF2\u4E2D\u6B62"):u("\u8BF7\u6C42\u51FA\u9519"))),g=1;else for(const a of t.content)a.type==="text"&&c(`${a.text}
|
|
6
|
+
`)}}return g}catch(e){return console.error(e instanceof Error?e.message:String(e)),1}finally{for(const e of w)e();await y(),await I()}}n(G,"runPrintMode");export{G as runPrintMode};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var f=Object.defineProperty;var i=(t,r)=>f(t,"name",{value:r,configurable:!0});const a=/^[A-Za-z_][A-Za-z0-9_]*$/;function v(t,r=process.env){const n=t.set??{},o=t.unset??[];if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("set_environment: `set` must be an object of name \u2192 string value");if(!Array.isArray(o))throw new Error("set_environment: `unset` must be an array of names");for(const[e,s]of Object.entries(n)){if(!a.test(e))throw new Error(`set_environment: invalid variable name ${JSON.stringify(e)}`);if(typeof s!="string")throw new Error(`set_environment: the value of ${e} must be a string`)}for(const e of o){if(typeof e!="string"||!a.test(e))throw new Error(`set_environment: invalid variable name ${JSON.stringify(e)}`);if(e in n)throw new Error(`set_environment: ${e} is both set and unset`)}for(const[e,s]of Object.entries(n))r[e]=s;for(const e of o)delete r[e];return[...Object.keys(n),...o]}i(v,"applyEnvironmentUpdate");export{v as applyEnvironmentUpdate};
|
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import type { AgentMessage, ThinkingLevel } from "@earendil-works/pi-agent-core";
|
|
2
2
|
import type { ImageContent } from "@earendil-works/pi-ai";
|
|
3
3
|
import type { SessionStats } from "../../core/agent-session.ts";
|
|
4
|
+
import type { BackgroundProcessInfo } from "../../core/background-processes.ts";
|
|
4
5
|
import type { BashResult } from "../../core/bash-executor.ts";
|
|
5
6
|
import type { CompactionResult } from "../../core/compaction/index.ts";
|
|
7
|
+
import type { HostCapability } from "../../core/host-capabilities.ts";
|
|
8
|
+
import type { SandboxStatus } from "../../core/sandbox/shell-sandbox.ts";
|
|
6
9
|
import type { SessionEntry, SessionTreeNode } from "../../core/session-manager.ts";
|
|
7
10
|
import type { JsonAgentSessionEvent } from "../json-event.ts";
|
|
8
|
-
import type { RpcExtensionUIRequest, RpcExtensionUIResponse, RpcSessionState, RpcSlashCommand } from "./rpc-types.ts";
|
|
11
|
+
import type { RpcExtensionUIRequest, RpcExtensionUIResponse, RpcHostRequest, RpcSessionState, RpcSlashCommand } from "./rpc-types.ts";
|
|
9
12
|
export interface RpcClientOptions {
|
|
10
13
|
cliPath?: string;
|
|
11
14
|
cwd?: string;
|
|
@@ -22,7 +25,18 @@ export interface ModelInfo {
|
|
|
22
25
|
reasoning: boolean;
|
|
23
26
|
}
|
|
24
27
|
export type RpcEventListener = (event: JsonAgentSessionEvent) => void;
|
|
28
|
+
export interface RpcProcessExit {
|
|
29
|
+
code: number | null;
|
|
30
|
+
signal: NodeJS.Signals | null;
|
|
31
|
+
stderrTail: string;
|
|
32
|
+
expected: boolean;
|
|
33
|
+
turnInFlight: boolean;
|
|
34
|
+
error?: string;
|
|
35
|
+
}
|
|
36
|
+
export type RpcExitListener = (exit: RpcProcessExit) => void;
|
|
37
|
+
export declare function rpcStderrTail(stderr: string): string;
|
|
25
38
|
export type RpcExtensionUIHandler = (request: RpcExtensionUIRequest) => Promise<RpcExtensionUIResponse | undefined> | RpcExtensionUIResponse | undefined;
|
|
39
|
+
export type RpcHostRequestHandler = (request: RpcHostRequest) => Promise<unknown> | unknown;
|
|
26
40
|
export declare class RpcClient {
|
|
27
41
|
private process;
|
|
28
42
|
private stopReadingStdout;
|
|
@@ -30,12 +44,19 @@ export declare class RpcClient {
|
|
|
30
44
|
private pendingRequests;
|
|
31
45
|
private requestId;
|
|
32
46
|
private extensionUIHandler;
|
|
47
|
+
private hostRequestHandler;
|
|
33
48
|
private stderr;
|
|
34
49
|
private exitError;
|
|
35
50
|
private options;
|
|
51
|
+
private exitListeners;
|
|
52
|
+
private exitInfo;
|
|
53
|
+
private stopping;
|
|
54
|
+
private turnInFlight;
|
|
36
55
|
constructor(options?: RpcClientOptions);
|
|
37
56
|
start(): Promise<void>;
|
|
38
57
|
stop(): Promise<void>;
|
|
58
|
+
onExit(listener: RpcExitListener): () => void;
|
|
59
|
+
getExit(): RpcProcessExit | undefined;
|
|
39
60
|
onEvent(listener: RpcEventListener): () => void;
|
|
40
61
|
setExtensionUIHandler(handler: RpcExtensionUIHandler | null): void;
|
|
41
62
|
getStderr(): string;
|
|
@@ -77,6 +98,18 @@ export declare class RpcClient {
|
|
|
77
98
|
abortRetry(): Promise<void>;
|
|
78
99
|
bash(command: string): Promise<BashResult>;
|
|
79
100
|
abortBash(): Promise<void>;
|
|
101
|
+
getSandboxStatus(): Promise<SandboxStatus | null>;
|
|
102
|
+
listBackgroundProcesses(): Promise<BackgroundProcessInfo[]>;
|
|
103
|
+
readBackgroundProcess(processId: string, tail?: number): Promise<{
|
|
104
|
+
text: string;
|
|
105
|
+
truncated: boolean;
|
|
106
|
+
process: BackgroundProcessInfo;
|
|
107
|
+
}>;
|
|
108
|
+
stopBackgroundProcess(processId: string): Promise<BackgroundProcessInfo>;
|
|
109
|
+
setEnvironment(update: {
|
|
110
|
+
set?: Record<string, string>;
|
|
111
|
+
unset?: string[];
|
|
112
|
+
}): Promise<string[]>;
|
|
80
113
|
getSessionStats(): Promise<SessionStats>;
|
|
81
114
|
exportHtml(outputPath?: string): Promise<{
|
|
82
115
|
path: string;
|
|
@@ -107,11 +140,15 @@ export declare class RpcClient {
|
|
|
107
140
|
setSessionName(name: string): Promise<void>;
|
|
108
141
|
getMessages(): Promise<AgentMessage[]>;
|
|
109
142
|
getCommands(): Promise<RpcSlashCommand[]>;
|
|
143
|
+
setHostCapabilities(capabilities: HostCapability[], handler: RpcHostRequestHandler | null): Promise<HostCapability[]>;
|
|
110
144
|
waitForIdle(timeout?: number): Promise<void>;
|
|
111
145
|
collectEvents(timeout?: number): Promise<JsonAgentSessionEvent[]>;
|
|
112
146
|
promptAndWait(message: string, images?: ImageContent[], timeout?: number): Promise<JsonAgentSessionEvent[]>;
|
|
113
147
|
private handleLine;
|
|
114
148
|
private answerExtensionUIRequest;
|
|
149
|
+
private answerHostRequest;
|
|
150
|
+
private reportExit;
|
|
151
|
+
private createExitWhileWaitingError;
|
|
115
152
|
private createProcessExitError;
|
|
116
153
|
private rejectPendingRequests;
|
|
117
154
|
private send;
|
|
@@ -1 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var y=Object.defineProperty;var h=(d,t)=>y(d,"name",{value:t,configurable:!0});import{spawn as w}from"node:child_process";import{attachJsonlLineReader as _,serializeJsonLine as p}from"./jsonl.js";const f=20,l=2e3;function m(d){const e=d.split(/\r?\n/u).filter(s=>s.trim().length>0).slice(-f).join(`
|
|
2
|
+
`);return e.length>l?e.slice(-l):e}h(m,"rpcStderrTail");const E=new Set(["select","confirm","input","editor","requestInput","requestChoice"]);class S{static{h(this,"RpcClient")}process=null;stopReadingStdout=null;eventListeners=[];pendingRequests=new Map;requestId=0;extensionUIHandler=null;hostRequestHandler=null;stderr="";exitError=null;options;exitListeners=new Set;exitInfo;stopping=!1;turnInFlight=!1;constructor(t={}){this.options=t}async start(){if(this.process)throw new Error("Client already started");this.exitError=null,this.exitInfo=void 0,this.stopping=!1,this.turnInFlight=!1;const t=this.options.cliPath??"dist/cli.js",e=["--mode","rpc"];this.options.provider&&e.push("--provider",this.options.provider),this.options.model&&e.push("--model",this.options.model),this.options.args&&e.push(...this.options.args);const s=w(process.execPath,[t,...e],{cwd:this.options.cwd,env:{...this.options.inheritEnv===!1?{}:process.env,...this.options.env},stdio:["pipe","pipe","pipe"]});if(this.process=s,s.stderr?.on("data",r=>{this.stderr+=r.toString(),process.stderr.write(r)}),s.once("exit",(r,n)=>{if(this.process!==s)return;this.reportExit({code:r,signal:n});const i=this.createProcessExitError(r,n);this.exitError=i,this.rejectPendingRequests(i)}),s.once("error",r=>{if(this.process!==s)return;const n=new Error(`Agent process error: ${r.message}. Stderr: ${this.stderr}`);s.exitCode===null&&s.signalCode===null&&this.reportExit({code:null,signal:null,error:r.message}),this.exitError=n,this.rejectPendingRequests(n)}),s.stdin?.on("error",r=>{if(this.process!==s)return;const n=this.exitError??new Error(`Agent process stdin error: ${r.message}. Stderr: ${this.stderr}`);this.exitError=n,this.rejectPendingRequests(n)}),this.stopReadingStdout=_(s.stdout,r=>{this.handleLine(r)}),await new Promise(r=>setTimeout(r,100)),this.process.exitCode!==null){const r=this.exitError??this.createProcessExitError(this.process.exitCode,this.process.signalCode);throw this.exitError=r,r}}async stop(){this.process&&(this.stopReadingStdout?.(),this.stopReadingStdout=null,this.stopping=!0,this.process.kill("SIGTERM"),await new Promise(t=>{const e=setTimeout(()=>{this.process?.kill("SIGKILL"),t()},1e3);this.process?.on("exit",()=>{clearTimeout(e),t()})}),this.process=null,this.pendingRequests.clear())}onExit(t){const e=this.exitInfo;return e?(queueMicrotask(()=>t(e)),()=>{}):(this.exitListeners.add(t),()=>{this.exitListeners.delete(t)})}getExit(){return this.exitInfo}onEvent(t){return this.eventListeners.push(t),()=>{const e=this.eventListeners.indexOf(t);e!==-1&&this.eventListeners.splice(e,1)}}setExtensionUIHandler(t){this.extensionUIHandler=t}getStderr(){return this.stderr}async prompt(t,e){(await this.send({type:"prompt",message:t,images:e})).success&&(this.turnInFlight=!0)}async steer(t,e){await this.send({type:"steer",message:t,images:e})}async followUp(t,e){await this.send({type:"follow_up",message:t,images:e})}async abort(){await this.send({type:"abort"})}async clearQueue(){const t=await this.send({type:"clear_queue"});return this.getData(t)}async newSession(t){const e=await this.send({type:"new_session",parentSession:t});return this.getData(e)}async getState(){const t=await this.send({type:"get_state"});return this.getData(t)}async setModel(t,e){const s=await this.send({type:"set_model",provider:t,modelId:e});return this.getData(s)}async cycleModel(){const t=await this.send({type:"cycle_model"});return this.getData(t)}async getAvailableModels(){const t=await this.send({type:"get_available_models"});return this.getData(t).models}async setThinkingLevel(t){await this.send({type:"set_thinking_level",level:t})}async cycleThinkingLevel(){const t=await this.send({type:"cycle_thinking_level"});return this.getData(t)}async getAvailableThinkingLevels(){const t=await this.send({type:"get_available_thinking_levels"});return this.getData(t).levels}async setSteeringMode(t){await this.send({type:"set_steering_mode",mode:t})}async setFollowUpMode(t){await this.send({type:"set_follow_up_mode",mode:t})}async compact(t){const e=await this.send({type:"compact",customInstructions:t});return this.getData(e)}async setAutoCompaction(t){await this.send({type:"set_auto_compaction",enabled:t})}async setAutoRetry(t){await this.send({type:"set_auto_retry",enabled:t})}async abortRetry(){await this.send({type:"abort_retry"})}async bash(t){const e=await this.send({type:"bash",command:t});return this.getData(e)}async abortBash(){await this.send({type:"abort_bash"})}async getSandboxStatus(){const t=await this.send({type:"get_sandbox_status"});return this.getData(t)}async listBackgroundProcesses(){const t=await this.send({type:"list_background_processes"});return this.getData(t).processes}async readBackgroundProcess(t,e){const s=await this.send({type:"read_background_process",processId:t,...e!==void 0?{tail:e}:{}});return this.getData(s)}async stopBackgroundProcess(t){const e=await this.send({type:"stop_background_process",processId:t});return this.getData(e).process}async setEnvironment(t){const e=await this.send({type:"set_environment",...t});return this.getData(e).changed}async getSessionStats(){const t=await this.send({type:"get_session_stats"});return this.getData(t)}async exportHtml(t){const e=await this.send({type:"export_html",outputPath:t});return this.getData(e)}async switchSession(t){const e=await this.send({type:"switch_session",sessionPath:t});return this.getData(e)}async fork(t){const e=await this.send({type:"fork",entryId:t});return this.getData(e)}async clone(){const t=await this.send({type:"clone"});return this.getData(t)}async getForkMessages(){const t=await this.send({type:"get_fork_messages"});return this.getData(t).messages}async getEntries(t){const e=await this.send({type:"get_entries",since:t});return this.getData(e)}async getTree(){const t=await this.send({type:"get_tree"});return this.getData(t)}async getLastAssistantText(){const t=await this.send({type:"get_last_assistant_text"});return this.getData(t).text}async setSessionName(t){await this.send({type:"set_session_name",name:t})}async getMessages(){const t=await this.send({type:"get_messages"});return this.getData(t).messages}async getCommands(){const t=await this.send({type:"get_commands"});return this.getData(t).commands}async setHostCapabilities(t,e){this.hostRequestHandler=e;const s=await this.send({type:"set_host_capabilities",capabilities:t});return this.getData(s).capabilities}waitForIdle(t=6e4){return new Promise((e,s)=>{const r=setTimeout(()=>{n(),i(),s(new Error(`Timeout waiting for agent to become idle. Stderr: ${this.stderr}`))},t),n=this.onEvent(o=>{o.type==="agent_settled"&&(clearTimeout(r),n(),i(),e())}),i=this.onExit(o=>{clearTimeout(r),n(),s(this.createExitWhileWaitingError(o))})})}collectEvents(t=6e4){return new Promise((e,s)=>{const r=[],n=setTimeout(()=>{i(),o(),s(new Error(`Timeout collecting events. Stderr: ${this.stderr}`))},t),i=this.onEvent(a=>{r.push(a),a.type==="agent_settled"&&(clearTimeout(n),i(),o(),e(r))}),o=this.onExit(a=>{clearTimeout(n),i(),s(this.createExitWhileWaitingError(a))})})}async promptAndWait(t,e,s=6e4){const r=this.collectEvents(s);return await this.prompt(t,e),r}handleLine(t){try{const e=JSON.parse(t);if(e.type==="agent_start"?this.turnInFlight=!0:e.type==="agent_settled"&&(this.turnInFlight=!1),e.type==="response"&&e.id&&this.pendingRequests.has(e.id)){const s=this.pendingRequests.get(e.id);this.pendingRequests.delete(e.id),s.resolve(e);return}if(e.type==="extension_ui_request"&&E.has(e.method)&&this.answerExtensionUIRequest(e),e.type==="host_request"){this.answerHostRequest(e);return}for(const s of this.eventListeners)s(e)}catch{}}async answerExtensionUIRequest(t){const e={type:"extension_ui_response",id:t.id,cancelled:!0};let s=e;if(this.extensionUIHandler)try{s=await this.extensionUIHandler(t)??e}catch{s=e}const r=this.process?.stdin;if(!(!r||r.destroyed||!r.writable))try{r.write(p({...s,id:t.id}))}catch{}}async answerHostRequest(t){let e;if(!this.hostRequestHandler)e={type:"host_response",id:t.id,error:"host has no handler for host requests"};else try{const r=await this.hostRequestHandler(t);e={type:"host_response",id:t.id,result:r??null}}catch(r){e={type:"host_response",id:t.id,error:r instanceof Error?r.message:String(r)}}const s=this.process?.stdin;if(!(!s||s.destroyed||!s.writable))try{s.write(p(e))}catch{}}reportExit(t){if(this.exitInfo)return;const e={code:t.code,signal:t.signal,stderrTail:m(this.stderr),expected:this.stopping,turnInFlight:this.turnInFlight,...t.error?{error:t.error}:{}};this.exitInfo=e,this.turnInFlight=!1;const s=[...this.exitListeners];this.exitListeners.clear();for(const r of s)try{r(e)}catch{}}createExitWhileWaitingError(t){const e=t.signal?`signal ${t.signal}`:`code ${t.code??"unknown"}`,s=t.stderrTail?`
|
|
3
|
+
Last stderr output:
|
|
4
|
+
${t.stderrTail}`:"";return new Error(`Agent process exited (${e}) before the turn finished.${s}`)}createProcessExitError(t,e){return new Error(`Agent process exited (code=${t} signal=${e}). Stderr: ${this.stderr}`)}rejectPendingRequests(t){for(const e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}async send(t){const e=this.process,s=e?.stdin;if(!e||!s)throw new Error("Client not started");if(this.exitError)throw this.exitError;if(e.exitCode!==null){const i=this.createProcessExitError(e.exitCode,e.signalCode);throw this.exitError=i,i}if(s.destroyed||!s.writable){const i=new Error(`Agent process stdin is not writable. Stderr: ${this.stderr}`);throw this.exitError=i,i}const r=`req_${++this.requestId}`,n={...t,id:r};return new Promise((i,o)=>{const a=setTimeout(()=>{this.pendingRequests.delete(r),o(new Error(`Timeout waiting for response to ${t.type}. Stderr: ${this.stderr}`))},3e4);this.pendingRequests.set(r,{resolve:h(c=>{clearTimeout(a),i(c)},"resolve"),reject:h(c=>{clearTimeout(a),o(c)},"reject")});try{s.write(p(n))}catch(c){const u=c instanceof Error?c:new Error(String(c)),g=this.pendingRequests.get(r);this.pendingRequests.delete(r),g?.reject(u)}})}getData(t){if(!t.success){const s=t;throw new Error(s.error)}return t.data}}export{S as RpcClient,m as rpcStderrTail};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
import type { AgentSessionRuntime } from "../../core/agent-session-runtime.ts";
|
|
2
2
|
export type { RpcCommand, RpcExtensionUIRequest, RpcExtensionUIResponse, RpcResponse, RpcSessionState, } from "./rpc-types.ts";
|
|
3
|
+
export declare const PROMPT_ABORTED_BEFORE_START = "Prompt aborted before it started";
|
|
3
4
|
export declare function runRpcMode(runtimeHost: AgentSessionRuntime): Promise<never>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var P=Object.defineProperty;var i=(l,o)=>P(l,"name",{value:o,configurable:!0});import*as p from"node:crypto";import{resolveExtensionNotify as A}from"../../core/extensions/index.js";import{flushRawStdout as D,takeOverStdout as B,waitForRawStdoutBackpressure as _,writeRawStdout as N}from"../../core/output-guard.js";import{killTrackedDetachedChildren as $}from"../../utils/shell.js";import{theme as J}from"../interactive/theme/theme.js";import{toJsonEvent as W}from"../json-event.js";import{attachJsonlLineReader as G,serializeJsonLine as z}from"./jsonl.js";async function V(l){B();let o=l.session,h,w;const a=i(e=>{N(z(e))},"output"),r=i((e,t,s)=>s===void 0?{id:e,type:"response",command:t,success:!0}:{id:e,type:"response",command:t,success:!0,data:s},"success"),d=i((e,t,s)=>({id:e,type:"response",command:t,success:!1,error:s}),"error"),m=new Map;let b=!1,I=!1;const k=[];function g(e,t,s,n){if(e?.signal?.aborted)return Promise.resolve(t);const c=p.randomUUID();return new Promise((u,L)=>{let x;const v=i(()=>{x&&clearTimeout(x),e?.signal?.removeEventListener("abort",C),m.delete(c)},"cleanup"),C=i(()=>{v(),u(t)},"onAbort");e?.signal?.addEventListener("abort",C,{once:!0}),e?.timeout&&(x=setTimeout(()=>{v(),u(t)},e.timeout)),m.set(c,{resolve:i(F=>{v(),u(n(F))},"resolve"),reject:L}),a({type:"extension_ui_request",id:c,...s})})}i(g,"createDialogPromise");const U=i(()=>({select:i((e,t,s)=>g(s,void 0,{method:"select",title:e,options:t,timeout:s?.timeout},n=>"cancelled"in n&&n.cancelled?void 0:"value"in n?n.value:void 0),"select"),confirm:i((e,t,s)=>g(s,!1,{method:"confirm",title:e,message:t,timeout:s?.timeout},n=>"cancelled"in n&&n.cancelled?!1:"confirmed"in n?n.confirmed:!1),"confirm"),input:i((e,t,s)=>g(s,void 0,{method:"input",title:e,placeholder:t,timeout:s?.timeout},n=>"cancelled"in n&&n.cancelled?void 0:"value"in n?n.value:void 0),"input"),notify(e,t){const s=A(e,t);a({type:"extension_ui_request",id:p.randomUUID(),method:"notify",message:s.message,notifyType:s.type})},setPanel(e,t){a({type:"extension_ui_request",id:p.randomUUID(),method:"setPanel",panelId:e,panel:t})},requestInput:i(e=>g(e,void 0,{method:"requestInput",title:e.title,placeholder:e.placeholder,timeout:e.timeout},t=>"cancelled"in t&&t.cancelled?void 0:"value"in t?t.value:void 0),"requestInput"),requestChoice:i(e=>g(e,void 0,{method:"requestChoice",title:e.title,items:e.items,timeout:e.timeout},t=>"cancelled"in t&&t.cancelled?void 0:"value"in t?t.value:void 0),"requestChoice"),onTerminalInput(){return()=>{}},setStatus(e,t){a({type:"extension_ui_request",id:p.randomUUID(),method:"setStatus",statusKey:e,statusText:t})},setWorkingMessage(e){},setWorkingVisible(e){},setWorkingIndicator(e){},setHiddenThinkingLabel(e){},setWidget(e,t,s){(t===void 0||Array.isArray(t))&&a({type:"extension_ui_request",id:p.randomUUID(),method:"setWidget",widgetKey:e,widgetLines:t,widgetPlacement:s?.placement})},setFooter(e){},setHeader(e){},setTitle(e){a({type:"extension_ui_request",id:p.randomUUID(),method:"setTitle",title:e})},async custom(){},pasteToEditor(e){this.setEditorText(e)},setEditorText(e){a({type:"extension_ui_request",id:p.randomUUID(),method:"set_editor_text",text:e})},getEditorText(){return""},async editor(e,t){const s=p.randomUUID();return new Promise((n,c)=>{m.set(s,{resolve:i(u=>{"cancelled"in u&&u.cancelled?n(void 0):"value"in u?n(u.value):n(void 0)},"resolve"),reject:c}),a({type:"extension_ui_request",id:s,method:"editor",title:e,prefill:t})})},addAutocompleteProvider(){},setEditorComponent(){},getEditorComponent(){},get theme(){return J},getAllThemes(){return[]},getTheme(e){},setTheme(e){return{success:!1,error:"Theme switching not supported in RPC mode"}},getToolsExpanded(){return!1},setToolsExpanded(e){}}),"createExtensionUIContext");l.setRebindSession(async()=>{await f()});const f=i(async()=>{o=l.session,await o.bindExtensions({uiContext:U(),mode:"rpc",commandContextActions:{waitForIdle:i(()=>o.waitForIdle(),"waitForIdle"),newSession:i(async e=>l.newSession(e),"newSession"),fork:i(async(e,t)=>({cancelled:(await l.fork(e,t)).cancelled}),"fork"),navigateTree:i(async(e,t)=>({cancelled:(await o.navigateTree(e,{summarize:t?.summarize,customInstructions:t?.customInstructions,replaceInstructions:t?.replaceInstructions,label:t?.label})).cancelled}),"navigateTree"),switchSession:i(async(e,t)=>l.switchSession(e,t),"switchSession"),reload:i(async()=>{await o.reload()},"reload")},shutdownHandler:i(()=>{b=!0},"shutdownHandler"),onError:i(e=>{a({type:"extension_error",extensionPath:e.extensionPath,event:e.event,error:e.error})},"onError")}),h?.(),w?.(),h=o.subscribe(e=>{a(W(e)),e.type==="agent_settled"&&T()}),w=o.agent.subscribe(async()=>{await _()})},"rebindSession"),M=i(()=>{const e=["SIGTERM"];process.platform!=="win32"&&e.push("SIGHUP");for(const t of e){const s=i(()=>{$(),y(t==="SIGHUP"?129:143,t)},"handler");process.on(t,s),k.push(()=>process.off(t,s))}},"registerSignalHandlers");await f(),M();const R=i(async e=>{const t=e.id;switch(e.type){case"prompt":{let s=!1;o.prompt(e.message,{images:e.images,streamingBehavior:e.streamingBehavior,source:"rpc",preflightResult:i(n=>{n&&(s=!0,a(r(t,"prompt")))},"preflightResult")}).catch(n=>{s||a(d(t,"prompt",n.message))});return}case"steer":return await o.steer(e.message,e.images,{source:"rpc"}),r(t,"steer");case"follow_up":return await o.followUp(e.message,e.images,{source:"rpc"}),r(t,"follow_up");case"abort":return await o.abort(),r(t,"abort");case"clear_queue":return r(t,"clear_queue",o.clearQueue());case"new_session":{const s=e.parentSession?{parentSession:e.parentSession}:void 0,n=await l.newSession(s);return n.cancelled||await f(),r(t,"new_session",n)}case"get_state":{const s={model:o.model,thinkingLevel:o.thinkingLevel,isStreaming:o.isStreaming,isCompacting:o.isCompacting,steeringMode:o.steeringMode,followUpMode:o.followUpMode,sessionFile:o.sessionFile,sessionId:o.sessionId,sessionName:o.sessionName,autoCompactionEnabled:o.autoCompactionEnabled,messageCount:o.messages.length,pendingMessageCount:o.pendingMessageCount};return r(t,"get_state",s)}case"set_model":{const n=o.modelRuntime.getAvailableSnapshot().find(c=>c.provider===e.provider&&c.id===e.modelId);return n?(await o.setModel(n),r(t,"set_model",n)):d(t,"set_model",`Model not found: ${e.provider}/${e.modelId}`)}case"cycle_model":{const s=await o.cycleModel();return s?r(t,"cycle_model",s):r(t,"cycle_model",null)}case"get_available_models":{const s=o.modelRuntime.getAvailableSnapshot();return r(t,"get_available_models",{models:s})}case"set_thinking_level":return o.setThinkingLevel(e.level),r(t,"set_thinking_level");case"cycle_thinking_level":{const s=o.cycleThinkingLevel();return s?r(t,"cycle_thinking_level",{level:s}):r(t,"cycle_thinking_level",null)}case"get_available_thinking_levels":{const s=o.getAvailableThinkingLevels();return r(t,"get_available_thinking_levels",{levels:s})}case"set_steering_mode":return o.setSteeringMode(e.mode),r(t,"set_steering_mode");case"set_follow_up_mode":return o.setFollowUpMode(e.mode),r(t,"set_follow_up_mode");case"compact":{const s=await o.compact(e.customInstructions);return r(t,"compact",s)}case"set_auto_compaction":return o.setAutoCompactionEnabled(e.enabled),r(t,"set_auto_compaction");case"set_auto_retry":return o.setAutoRetryEnabled(e.enabled),r(t,"set_auto_retry");case"abort_retry":return o.abortRetry(),r(t,"abort_retry");case"bash":{const s=await o.extensionRunner.emitUserBash({type:"user_bash",command:e.command,excludeFromContext:e.excludeFromContext??!1,cwd:o.sessionManager.getCwd()});if(s?.result)return o.recordBashResult(e.command,s.result,{excludeFromContext:e.excludeFromContext}),r(t,"bash",s.result);const n=await o.executeBash(e.command,void 0,{excludeFromContext:e.excludeFromContext,id:t,operations:s?.operations});return r(t,"bash",n)}case"abort_bash":return o.abortBash(),r(t,"abort_bash");case"get_session_stats":{const s=o.getSessionStats();return r(t,"get_session_stats",s)}case"export_html":{const s=await o.exportToHtml(e.outputPath);return r(t,"export_html",{path:s})}case"switch_session":{const s=await l.switchSession(e.sessionPath);return s.cancelled||await f(),r(t,"switch_session",s)}case"fork":{const s=await l.fork(e.entryId);return s.cancelled||await f(),r(t,"fork",{text:s.selectedText,cancelled:s.cancelled})}case"clone":{const s=o.sessionManager.getLeafId();if(!s)return d(t,"clone","Cannot clone session: no current entry selected");const n=await l.fork(s,{position:"at"});return n.cancelled||await f(),r(t,"clone",{cancelled:n.cancelled})}case"get_fork_messages":{const s=o.getUserMessagesForForking();return r(t,"get_fork_messages",{messages:s})}case"get_entries":{const s=o.sessionManager;let n=s.getEntries();if(e.since!==void 0){const c=n.findIndex(u=>u.id===e.since);if(c===-1)return d(t,"get_entries",`Entry not found: ${e.since}`);n=n.slice(c+1)}return r(t,"get_entries",{entries:n,leafId:s.getLeafId()})}case"get_tree":{const s=o.sessionManager;return r(t,"get_tree",{tree:s.getTree(),leafId:s.getLeafId()})}case"get_last_assistant_text":{const s=o.getLastAssistantText();return r(t,"get_last_assistant_text",{text:s})}case"set_session_name":{const s=e.name.trim();return s?(o.setSessionName(s),r(t,"set_session_name")):d(t,"set_session_name","Session name cannot be empty")}case"get_messages":return r(t,"get_messages",{messages:o.messages});case"get_commands":{const s=[];for(const n of o.extensionRunner.getRegisteredCommands())s.push({name:n.invocationName,description:n.description,source:"extension",sourceInfo:n.sourceInfo});for(const n of o.promptTemplates)s.push({name:n.name,description:n.description,source:"prompt",sourceInfo:n.sourceInfo});for(const n of o.resourceLoader.getSkills().skills)s.push({name:`skill:${n.name}`,description:n.description,source:"skill",sourceInfo:n.sourceInfo});return r(t,"get_commands",{commands:s})}default:{const s=e;return d(t,s.type,`Unknown command: ${s.type}`)}}},"handleCommand");let S=i(()=>{},"detachInput");async function y(e=0,t){I&&process.exit(e),I=!0;for(const s of k)s();h?.(),w?.(),await l.dispose(),S(),process.stdin.pause(),t!=="SIGTERM"&&await D(),process.exit(e)}i(y,"shutdown");async function T(){b&&await y()}i(T,"checkShutdownRequested");const q=i(async e=>{let t;try{t=JSON.parse(e)}catch(n){a(d(void 0,"parse",`Failed to parse command: ${n instanceof Error?n.message:String(n)}`)),await _();return}if(typeof t=="object"&&t!==null&&"type"in t&&t.type==="extension_ui_response"){const n=t,c=m.get(n.id);c&&(m.delete(n.id),c.resolve(n));return}const s=t;try{const n=await R(s);n&&(a(n),await _()),await T()}catch(n){a(d(s.id,s.type,n instanceof Error?n.message:String(n))),await _()}},"handleInputLine"),E=i(()=>{y()},"onInputEnd");return process.stdin.on("end",E),S=(()=>{const e=G(process.stdin,t=>{q(t)});return()=>{e(),process.stdin.off("end",E)}})(),new Promise(()=>{})}i(V,"runRpcMode");export{V as runRpcMode};
|
|
1
|
+
var O=Object.defineProperty;var i=(u,r)=>O(u,"name",{value:r,configurable:!0});import*as p from"node:crypto";import{resolveExtensionNotify as N}from"../../core/extensions/index.js";import{DEFAULT_HOST_CALL_TIMEOUT_MS as $,getHostCapabilities as L,HostCallError as x,parseHostCapabilities as J}from"../../core/host-capabilities.js";import{flushRawStdout as W,takeOverStdout as j,waitForRawStdoutBackpressure as I,writeRawStdout as G}from"../../core/output-guard.js";import{killTrackedDetachedChildren as H}from"../../utils/shell.js";import{theme as z}from"../interactive/theme/theme.js";import{toJsonEvent as K}from"../json-event.js";import{applyEnvironmentUpdate as Q}from"./environment-update.js";import{attachJsonlLineReader as X,serializeJsonLine as Y}from"./jsonl.js";const Z="Prompt aborted before it started";async function ce(u){j();let r=u.session,k,S;const c=i(e=>{G(Y(e))},"output"),o=i((e,t,s)=>s===void 0?{id:e,type:"response",command:t,success:!0}:{id:e,type:"response",command:t,success:!0,data:s},"success"),d=i((e,t,s)=>({id:e,type:"response",command:t,success:!1,error:s}),"error"),m=new Map,b=new Map,q=i((e,t)=>{const s=p.randomUUID();return new Promise((n,a)=>{const l=i(()=>{clearTimeout(w),t.signal?.removeEventListener("abort",f),b.delete(s)},"cleanup"),y=i(g=>{l(),c({type:"host_request_cancelled",id:s}),a(g)},"giveUp"),f=i(()=>y(new x("aborted","host call aborted")),"onAbort"),w=setTimeout(()=>y(new x("timeout","host did not answer in time")),t.timeoutMs??$);t.signal?.addEventListener("abort",f,{once:!0}),b.set(s,{resolve:i(g=>{l(),n(g)},"resolve"),reject:i(g=>{l(),a(g)},"reject")});const v={type:"host_request",id:s,capability:e.capability,method:e.method,params:e.params};c(v)})},"rpcHostTransport");let E=!1,C=!1;const U=[];function h(e,t,s,n){if(e?.signal?.aborted)return Promise.resolve(t);const a=p.randomUUID();return new Promise((l,y)=>{let f;const w=i(()=>{f&&clearTimeout(f),e?.signal?.removeEventListener("abort",v),m.delete(a)},"cleanup"),v=i(()=>{w(),l(t)},"onAbort");e?.signal?.addEventListener("abort",v,{once:!0}),e?.timeout&&(f=setTimeout(()=>{w(),l(t)},e.timeout)),m.set(a,{resolve:i(g=>{w(),l(n(g))},"resolve"),reject:y}),c({type:"extension_ui_request",id:a,...s})})}i(h,"createDialogPromise");const F=i(()=>({select:i((e,t,s)=>h(s,void 0,{method:"select",title:e,options:t,timeout:s?.timeout},n=>"cancelled"in n&&n.cancelled?void 0:"value"in n?n.value:void 0),"select"),confirm:i((e,t,s)=>h(s,!1,{method:"confirm",title:e,message:t,timeout:s?.timeout},n=>"cancelled"in n&&n.cancelled?!1:"confirmed"in n?n.confirmed:!1),"confirm"),input:i((e,t,s)=>h(s,void 0,{method:"input",title:e,placeholder:t,timeout:s?.timeout},n=>"cancelled"in n&&n.cancelled?void 0:"value"in n?n.value:void 0),"input"),notify(e,t){const s=N(e,t);c({type:"extension_ui_request",id:p.randomUUID(),method:"notify",message:s.message,notifyType:s.type})},setPanel(e,t){c({type:"extension_ui_request",id:p.randomUUID(),method:"setPanel",panelId:e,panel:t})},requestInput:i(e=>h(e,void 0,{method:"requestInput",title:e.title,placeholder:e.placeholder,timeout:e.timeout},t=>"cancelled"in t&&t.cancelled?void 0:"value"in t?t.value:void 0),"requestInput"),requestChoice:i(e=>h(e,void 0,{method:"requestChoice",title:e.title,items:e.items,timeout:e.timeout},t=>"cancelled"in t&&t.cancelled?void 0:"value"in t?t.value:void 0),"requestChoice"),onTerminalInput(){return()=>{}},setStatus(e,t){c({type:"extension_ui_request",id:p.randomUUID(),method:"setStatus",statusKey:e,statusText:t})},setWorkingMessage(e){},setWorkingVisible(e){},setWorkingIndicator(e){},setHiddenThinkingLabel(e){},setWidget(e,t,s){(t===void 0||Array.isArray(t))&&c({type:"extension_ui_request",id:p.randomUUID(),method:"setWidget",widgetKey:e,widgetLines:t,widgetPlacement:s?.placement})},setFooter(e){},setHeader(e){},setTitle(e){c({type:"extension_ui_request",id:p.randomUUID(),method:"setTitle",title:e})},async custom(){},pasteToEditor(e){this.setEditorText(e)},setEditorText(e){c({type:"extension_ui_request",id:p.randomUUID(),method:"set_editor_text",text:e})},getEditorText(){return""},async editor(e,t){const s=p.randomUUID();return new Promise((n,a)=>{m.set(s,{resolve:i(l=>{"cancelled"in l&&l.cancelled?n(void 0):"value"in l?n(l.value):n(void 0)},"resolve"),reject:a}),c({type:"extension_ui_request",id:s,method:"editor",title:e,prefill:t})})},addAutocompleteProvider(){},setEditorComponent(){},getEditorComponent(){},get theme(){return z},getAllThemes(){return[]},getTheme(e){},setTheme(e){return{success:!1,error:"Theme switching not supported in RPC mode"}},getToolsExpanded(){return!1},setToolsExpanded(e){}}),"createExtensionUIContext");u.setRebindSession(async()=>{await _()});const _=i(async()=>{r=u.session,k?.(),S?.(),k=r.subscribe(e=>{c(K(e)),e.type==="agent_settled"&&R()}),S=r.agent.subscribe(async()=>{await I()}),await r.bindExtensions({uiContext:F(),mode:"rpc",commandContextActions:{waitForIdle:i(()=>r.waitForIdle(),"waitForIdle"),newSession:i(async e=>u.newSession(e),"newSession"),fork:i(async(e,t)=>({cancelled:(await u.fork(e,t)).cancelled}),"fork"),navigateTree:i(async(e,t)=>({cancelled:(await r.navigateTree(e,{summarize:t?.summarize,customInstructions:t?.customInstructions,replaceInstructions:t?.replaceInstructions,label:t?.label})).cancelled}),"navigateTree"),switchSession:i(async(e,t)=>u.switchSession(e,t),"switchSession"),reload:i(async()=>{await r.reload()},"reload")},shutdownHandler:i(()=>{E=!0},"shutdownHandler"),onError:i(e=>{c({type:"extension_error",extensionPath:e.extensionPath,event:e.event,error:e.error})},"onError")})},"rebindSession"),A=i(()=>{const e=["SIGTERM"];process.platform!=="win32"&&e.push("SIGHUP");for(const t of e){const s=i(()=>{H(),T(t==="SIGHUP"?129:143,t)},"handler");process.on(t,s),U.push(()=>process.off(t,s))}},"registerSignalHandlers");await _(),A();const D=i(async e=>{const t=e.id;switch(e.type){case"prompt":{let s=!1,n=!1;r.prompt(e.message,{images:e.images,streamingBehavior:e.streamingBehavior,source:"rpc",preflightResult:i(a=>{a?(s=!0,c(o(t,"prompt"))):n=!0},"preflightResult")}).then(()=>{n&&!s&&c(d(t,"prompt",Z))},a=>{s||c(d(t,"prompt",a.message))});return}case"steer":return await r.steer(e.message,e.images,{source:"rpc"}),o(t,"steer");case"follow_up":return await r.followUp(e.message,e.images,{source:"rpc"}),o(t,"follow_up");case"abort":return await r.abort(),o(t,"abort");case"clear_queue":return o(t,"clear_queue",r.clearQueue());case"new_session":{const s=e.parentSession?{parentSession:e.parentSession}:void 0,n=await u.newSession(s);return n.cancelled||await _(),o(t,"new_session",n)}case"get_state":{const s={model:r.model,thinkingLevel:r.thinkingLevel,isStreaming:r.isStreaming,isCompacting:r.isCompacting,steeringMode:r.steeringMode,followUpMode:r.followUpMode,sessionFile:r.sessionFile,sessionId:r.sessionId,sessionName:r.sessionName,autoCompactionEnabled:r.autoCompactionEnabled,messageCount:r.messages.length,pendingMessageCount:r.pendingMessageCount};return o(t,"get_state",s)}case"set_model":{const n=r.modelRuntime.getAvailableSnapshot().find(a=>a.provider===e.provider&&a.id===e.modelId);return n?(await r.setModel(n),o(t,"set_model",n)):d(t,"set_model",`Model not found: ${e.provider}/${e.modelId}`)}case"cycle_model":{const s=await r.cycleModel();return s?o(t,"cycle_model",s):o(t,"cycle_model",null)}case"get_available_models":{const s=r.modelRuntime.getAvailableSnapshot();return o(t,"get_available_models",{models:s})}case"set_thinking_level":return r.setThinkingLevel(e.level),o(t,"set_thinking_level");case"cycle_thinking_level":{const s=r.cycleThinkingLevel();return s?o(t,"cycle_thinking_level",{level:s}):o(t,"cycle_thinking_level",null)}case"get_available_thinking_levels":{const s=r.getAvailableThinkingLevels();return o(t,"get_available_thinking_levels",{levels:s})}case"set_steering_mode":return r.setSteeringMode(e.mode),o(t,"set_steering_mode");case"set_follow_up_mode":return r.setFollowUpMode(e.mode),o(t,"set_follow_up_mode");case"compact":{const s=await r.compact(e.customInstructions);return o(t,"compact",s)}case"set_auto_compaction":return r.setAutoCompactionEnabled(e.enabled),o(t,"set_auto_compaction");case"set_auto_retry":return r.setAutoRetryEnabled(e.enabled),o(t,"set_auto_retry");case"abort_retry":return r.abortRetry(),o(t,"abort_retry");case"bash":{const s=await r.extensionRunner.emitUserBash({type:"user_bash",command:e.command,excludeFromContext:e.excludeFromContext??!1,cwd:r.sessionManager.getCwd()});if(s?.result)return r.recordBashResult(e.command,s.result,{excludeFromContext:e.excludeFromContext}),o(t,"bash",s.result);const n=await r.executeBash(e.command,void 0,{excludeFromContext:e.excludeFromContext,id:t,operations:s?.operations});return o(t,"bash",n)}case"abort_bash":return r.abortBash(),o(t,"abort_bash");case"get_sandbox_status":return o(t,"get_sandbox_status",r.getSandboxStatus()??null);case"list_background_processes":return o(t,"list_background_processes",{processes:r.backgroundProcesses.list()});case"read_background_process":{const{text:s,truncated:n,info:a}=r.backgroundProcesses.read(e.processId,e.tail!==void 0?{tail:e.tail}:{tail:200});return o(t,"read_background_process",{text:s,truncated:n,process:a})}case"stop_background_process":{const s=await r.backgroundProcesses.stop(e.processId);return o(t,"stop_background_process",{process:s})}case"get_session_stats":{const s=r.getSessionStats();return o(t,"get_session_stats",s)}case"export_html":{const s=await r.exportToHtml(e.outputPath);return o(t,"export_html",{path:s})}case"switch_session":{const s=await u.switchSession(e.sessionPath);return s.cancelled||await _(),o(t,"switch_session",s)}case"fork":{const s=await u.fork(e.entryId);return s.cancelled||await _(),o(t,"fork",{text:s.selectedText,cancelled:s.cancelled})}case"clone":{const s=r.sessionManager.getLeafId();if(!s)return d(t,"clone","Cannot clone session: no current entry selected");const n=await u.fork(s,{position:"at"});return n.cancelled||await _(),o(t,"clone",{cancelled:n.cancelled})}case"get_fork_messages":{const s=r.getUserMessagesForForking();return o(t,"get_fork_messages",{messages:s})}case"get_entries":{const s=r.sessionManager;let n=s.getEntries();if(e.since!==void 0){const a=n.findIndex(l=>l.id===e.since);if(a===-1)return d(t,"get_entries",`Entry not found: ${e.since}`);n=n.slice(a+1)}return o(t,"get_entries",{entries:n,leafId:s.getLeafId()})}case"get_tree":{const s=r.sessionManager;return o(t,"get_tree",{tree:s.getTree(),leafId:s.getLeafId()})}case"get_last_assistant_text":{const s=r.getLastAssistantText();return o(t,"get_last_assistant_text",{text:s})}case"set_session_name":{const s=e.name.trim();return s?(r.setSessionName(s),o(t,"set_session_name")):d(t,"set_session_name","Session name cannot be empty")}case"get_messages":return o(t,"get_messages",{messages:r.messages});case"get_commands":{const s=[];for(const n of r.extensionRunner.getRegisteredCommands())s.push({name:n.invocationName,description:n.description,source:"extension",sourceInfo:n.sourceInfo});for(const n of r.promptTemplates)s.push({name:n.name,description:n.description,source:"prompt",sourceInfo:n.sourceInfo});for(const n of r.resourceLoader.getSkills().skills)s.push({name:`skill:${n.name}`,description:n.description,source:"skill",sourceInfo:n.sourceInfo});return o(t,"get_commands",{commands:s})}case"set_host_capabilities":{const s=L();return s.set("rpc",J(e.capabilities),q),o(t,"set_host_capabilities",{capabilities:s.list()})}case"set_environment":{const s=Q({set:e.set,unset:e.unset});return o(t,"set_environment",{changed:s})}default:{const s=e;return d(t,s.type,`Unknown command: ${s.type}`)}}},"handleCommand");let M=i(()=>{},"detachInput");async function T(e=0,t){C&&process.exit(e),C=!0;for(const s of U)s();k?.(),S?.(),L().clear("rpc");for(const s of b.values())s.reject(new x("unavailable","RPC host disconnected"));await u.dispose(),M(),process.stdin.pause(),t!=="SIGTERM"&&await W(),process.exit(e)}i(T,"shutdown");async function R(){E&&await T()}i(R,"checkShutdownRequested");const B=i(async e=>{let t;try{t=JSON.parse(e)}catch(n){c(d(void 0,"parse",`Failed to parse command: ${n instanceof Error?n.message:String(n)}`)),await I();return}if(typeof t=="object"&&t!==null&&"type"in t&&t.type==="extension_ui_response"){const n=t,a=m.get(n.id);a&&(m.delete(n.id),a.resolve(n));return}if(typeof t=="object"&&t!==null&&"type"in t&&t.type==="host_response"){const n=t,a=b.get(n.id);a&&("error"in n?a.reject(new x("host_error",String(n.error))):a.resolve(n.result));return}const s=t;try{const n=await D(s);n&&(c(n),await I()),await R()}catch(n){c(d(s.id,s.type,n instanceof Error?n.message:String(n))),await I()}},"handleInputLine"),P=i(()=>{T()},"onInputEnd");return process.stdin.on("end",P),M=(()=>{const e=X(process.stdin,t=>{B(t)});return()=>{e(),process.stdin.off("end",P)}})(),new Promise(()=>{})}i(ce,"runRpcMode");export{Z as PROMPT_ABORTED_BEFORE_START,ce as runRpcMode};
|