dal-code 1.0.31 → 1.0.32
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 +8 -0
- package/dal-docs/settings.md +11 -0
- package/dist/core/sandbox/index.d.ts +2 -1
- package/dist/core/sandbox/index.js +1 -1
- package/dist/core/sandbox/package-managers.d.ts +19 -0
- package/dist/core/sandbox/package-managers.js +1 -0
- package/dist/core/sandbox/policy.d.ts +1 -0
- package/dist/core/sandbox/policy.js +1 -1
- package/dist/core/sandbox/shell-sandbox.d.ts +14 -0
- package/dist/core/sandbox/shell-sandbox.js +5 -5
- package/dist/dal/host-extensions.d.ts +2 -0
- package/dist/dal/host-extensions.js +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -1
- package/dist/main.js +4 -4
- 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/package.json +2 -2
- 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/config.d.ts +2 -0
- package/dist/node_modules/@dalcode/dal-mcp/src/config.js +1 -1
- package/dist/node_modules/@dalcode/dal-mcp/src/index.js +17 -17
- package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +1 -1
- package/dist/node_modules/@dalcode/dal-plugins/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-rewind/src/commands.js +2 -2
- package/dist/node_modules/@dalcode/dal-rewind/src/core.d.ts +20 -2
- package/dist/node_modules/@dalcode/dal-rewind/src/core.js +3 -4
- package/dist/node_modules/@dalcode/dal-rewind/src/index.js +1 -1
- 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-telemetry/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
- 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-workflow/package.json +2 -2
- package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
- package/dist/node_modules/@dalcode/deepailab/src/index.js +3 -3
- package/dist/node_modules/@earendil-works/chord/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-agent-core/package.json +2 -2
- 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/nvidia.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/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-codemode/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-mcp/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 +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/rewind.d.ts +1 -1
- package/dist/sdk/rewind.js +1 -1
- 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/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 +2 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -8,6 +8,14 @@ DAL Code 的发布说明。这里只写用户看得见的变化。
|
|
|
8
8
|
|
|
9
9
|
## [Unreleased]
|
|
10
10
|
|
|
11
|
+
## [1.0.32] - 2026-10-15
|
|
12
|
+
|
|
13
|
+
- 沙箱里装依赖(npm、pnpm、yarn、pip、uv、cargo、go 等)现在执行前只问一次是否允许联网,同意后直接装好;会自动使用你配置的镜像源。
|
|
14
|
+
- 不允许联网时,安装命令几秒内就会提示被拦截,不会再卡一分钟以上。
|
|
15
|
+
- 对话回退点不再保存 .env、私钥、证书、云凭据这类敏感文件,也不会保存超大文件;回退时不会删除这些文件。
|
|
16
|
+
- 对话中途安装的连接器(MCP),在同一次回复里就能使用。
|
|
17
|
+
- 模型的服务通道暂时不可用时,会如实提示你换个模型或稍后再试,不会再误导你重新登录。
|
|
18
|
+
|
|
11
19
|
## [1.0.31] - 2026-10-14
|
|
12
20
|
|
|
13
21
|
- 助手现在能看到所有可用技能的名称和适用场景(本机技能与云端技能合并为一份清单),任务符合某个技能时会先加载它再动手;你点名某个技能时一定会使用它。
|
package/dal-docs/settings.md
CHANGED
|
@@ -80,6 +80,17 @@ each server as connecting, connected or failed (with the reason), and hosts
|
|
|
80
80
|
receive the same as `mcp_status` events (see the RPC event docs, "Host
|
|
81
81
|
events").
|
|
82
82
|
|
|
83
|
+
Servers added during a session are picked up without starting a new one: a
|
|
84
|
+
server written to either mcp.json (for example a connector DAL Code installs
|
|
85
|
+
from the market) or registered by an extension with `registerMcpServer()`.
|
|
86
|
+
Before the model's next request, in the same reply or at the next message,
|
|
87
|
+
the session connects the new server and waits for it (up to the connect
|
|
88
|
+
timeout), so that request already offers its tools. A changed entry is
|
|
89
|
+
reconnected; a removed one is disconnected. Only mcp.json and the product's
|
|
90
|
+
own or host-provided extensions (passed with `--extension`, or an SDK host's
|
|
91
|
+
inline extensions) can add servers this way. A server registered by any other
|
|
92
|
+
extension is ignored with a warning. Such a server belongs in mcp.json.
|
|
93
|
+
|
|
83
94
|
## Custom models — models.json
|
|
84
95
|
|
|
85
96
|
Models normally come from the DeepAILab gateway after `/login`.
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export { detectSandboxAvailability, type SandboxAvailability, setSandboxAvailabilityForTesting, } from "./availability.ts";
|
|
2
2
|
export { collectBlockedAccesses, describeDenialForModel, parseOutput, parseViolationLine, type SandboxBlockedAccess, type SandboxDenial, } from "./denial.ts";
|
|
3
|
+
export { detectNetworkCommand, FAIL_FAST_NETWORK_ENV, type NetworkCommand, networkDomainsFor, PACKAGE_MANAGERS, type PackageEcosystem, type PackageManager, packageCacheDirs, } from "./package-managers.ts";
|
|
3
4
|
export { domainMatches, filesystemRules, isAlwaysBlockedHost, isSandboxLevel, PROTECTED_HOME_READS, PROTECTED_HOME_WRITES, PROTECTED_WRITE_NAMES, type ResolvedSandboxPolicy, readSandboxEnvironment, resolveSandboxPolicy, SANDBOX_ENV, SANDBOX_LEVELS, type SandboxLevel, type SandboxOverride, type SandboxSettings, type SandboxSettingsSources, sandboxEnvironmentValue, stricterLevel, } from "./policy.ts";
|
|
4
5
|
export { decideNetworkRequest, type NetworkGrant, registerNetworkGrant, resetSandboxRuntime } from "./runtime.ts";
|
|
5
|
-
export { getProcessShellSandbox, type PreparedCommand, registerSandboxEscalationHandler, type SandboxEscalationDecision, type SandboxEscalationHandler, type SandboxEscalationInput, type SandboxEscalationRequest, type SandboxEvent, type SandboxOptions, type SandboxRunDetails, type SandboxStatus, ShellSandbox, type ShellSandboxOptions, setProcessShellSandbox, } from "./shell-sandbox.ts";
|
|
6
|
+
export { getProcessShellSandbox, type PlannedNetworkEscalation, type PreparedCommand, registerSandboxEscalationHandler, type SandboxEscalationDecision, type SandboxEscalationHandler, type SandboxEscalationInput, type SandboxEscalationRequest, type SandboxEvent, type SandboxOptions, type SandboxRunDetails, type SandboxStatus, ShellSandbox, type ShellSandboxOptions, setProcessShellSandbox, } from "./shell-sandbox.ts";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{detectSandboxAvailability as
|
|
1
|
+
import{detectSandboxAvailability as r,setSandboxAvailabilityForTesting as t}from"./availability.js";import{collectBlockedAccesses as s,describeDenialForModel as n,parseOutput as i,parseViolationLine as l}from"./denial.js";import{detectNetworkCommand as E,FAIL_FAST_NETWORK_ENV as S,networkDomainsFor as c,PACKAGE_MANAGERS as x,packageCacheDirs as b}from"./package-managers.js";import{domainMatches as A,filesystemRules as _,isAlwaysBlockedHost as R,isSandboxLevel as T,PROTECTED_HOME_READS as p,PROTECTED_HOME_WRITES as N,PROTECTED_WRITE_NAMES as D,readSandboxEnvironment as O,resolveSandboxPolicy as f,SANDBOX_ENV as k,SANDBOX_LEVELS as v,sandboxEnvironmentValue as P,stricterLevel as u}from"./policy.js";import{decideNetworkRequest as L,registerNetworkGrant as M,resetSandboxRuntime as g}from"./runtime.js";import{getProcessShellSandbox as w,registerSandboxEscalationHandler as y,ShellSandbox as F,setProcessShellSandbox as V}from"./shell-sandbox.js";export{S as FAIL_FAST_NETWORK_ENV,x as PACKAGE_MANAGERS,p as PROTECTED_HOME_READS,N as PROTECTED_HOME_WRITES,D as PROTECTED_WRITE_NAMES,k as SANDBOX_ENV,v as SANDBOX_LEVELS,F as ShellSandbox,s as collectBlockedAccesses,L as decideNetworkRequest,n as describeDenialForModel,E as detectNetworkCommand,r as detectSandboxAvailability,A as domainMatches,_ as filesystemRules,w as getProcessShellSandbox,R as isAlwaysBlockedHost,T as isSandboxLevel,c as networkDomainsFor,b as packageCacheDirs,i as parseOutput,l as parseViolationLine,O as readSandboxEnvironment,M as registerNetworkGrant,y as registerSandboxEscalationHandler,g as resetSandboxRuntime,f as resolveSandboxPolicy,P as sandboxEnvironmentValue,V as setProcessShellSandbox,t as setSandboxAvailabilityForTesting,u as stricterLevel};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export type PackageEcosystem = "node" | "python" | "rust" | "go" | "ruby" | "php";
|
|
2
|
+
export interface NetworkCommand {
|
|
3
|
+
ecosystems: PackageEcosystem[];
|
|
4
|
+
managers: PackageManager[];
|
|
5
|
+
urlHosts: string[];
|
|
6
|
+
yarn: boolean;
|
|
7
|
+
}
|
|
8
|
+
interface PlatformContext {
|
|
9
|
+
platform?: NodeJS.Platform;
|
|
10
|
+
env?: NodeJS.ProcessEnv;
|
|
11
|
+
home?: string;
|
|
12
|
+
}
|
|
13
|
+
export type PackageManager = "npm" | "pnpm" | "yarn" | "bun" | "pip" | "uv" | "poetry" | "cargo" | "go" | "bundler" | "composer";
|
|
14
|
+
export declare const PACKAGE_MANAGERS: readonly PackageManager[];
|
|
15
|
+
export declare function packageCacheDirs(managers?: readonly PackageManager[], options?: PlatformContext): string[];
|
|
16
|
+
export declare function detectNetworkCommand(command: string): NetworkCommand | undefined;
|
|
17
|
+
export declare function networkDomainsFor(detected: NetworkCommand, cwd: string, options?: PlatformContext): string[];
|
|
18
|
+
export declare const FAIL_FAST_NETWORK_ENV: Readonly<Record<string, string>>;
|
|
19
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var I=Object.defineProperty;var l=(o,r)=>I(o,"name",{value:r,configurable:!0});import{existsSync as L,readFileSync as w}from"node:fs";import{homedir as P}from"node:os";import{dirname as T,isAbsolute as C,join as d,relative as D,resolve as k,win32 as b}from"node:path";import{isAlwaysBlockedHost as G}from"./policy.js";function E(o){return{platform:o.platform??process.platform,env:o.env??process.env,home:o.home??P()}}l(E,"context");function u(o){const r=o?.trim();return r||void 0}l(u,"nonEmpty");const M=["npm","pnpm","yarn","bun","pip","uv","poetry","cargo","go","bundler","composer"];function ut(o=M,r={}){const{platform:a,env:n,home:i}=E(r),p=a==="win32",e=p?b.join:d,s=u(n.LOCALAPPDATA)??e(i,"AppData","Local"),t=u(n.XDG_CACHE_HOME)??e(i,".cache"),c=a==="darwin"?e(i,"Library","Caches"):p?s:t,m={npm:l(()=>{const f=u(n.npm_config_cache)??u(n.NPM_CONFIG_CACHE)??(p?e(s,"npm-cache"):e(i,".npm"));return[e(f,"_cacache"),e(f,"_logs"),e(f,"_npx")]},"npm"),pnpm:l(()=>{const f=u(n.npm_config_store_dir)??u(n.PNPM_STORE_DIR);if(a==="darwin")return[f,e(i,"Library","pnpm","store"),e(c,"pnpm")];if(p)return[f,e(s,"pnpm","store"),e(s,"pnpm-cache")];const y=u(n.XDG_DATA_HOME)??e(i,".local","share");return[f,e(y,"pnpm","store"),e(t,"pnpm")]},"pnpm"),yarn:l(()=>[u(n.YARN_CACHE_FOLDER),p?e(s,"Yarn","Berry","cache"):e(i,".yarn","berry","cache"),a==="darwin"?e(c,"Yarn"):p?e(s,"Yarn","Cache"):e(t,"yarn")],"yarn"),bun:l(()=>[e(u(n.BUN_INSTALL)??e(i,".bun"),"install","cache")],"bun"),pip:l(()=>[u(n.PIP_CACHE_DIR),p?e(s,"pip","Cache"):e(c,"pip")],"pip"),uv:l(()=>[u(n.UV_CACHE_DIR),p?e(s,"uv","cache"):e(t,"uv")],"uv"),poetry:l(()=>[p?e(s,"pypoetry","Cache"):e(c,"pypoetry")],"poetry"),cargo:l(()=>{const f=u(n.CARGO_HOME)??e(i,".cargo");return[e(f,"registry"),e(f,"git")]},"cargo"),go:l(()=>{const f=u(n.GOPATH)?.split(p?";":":")[0]??e(i,"go");return[u(n.GOMODCACHE)??e(f,"pkg","mod"),u(n.GOCACHE)??e(p?s:c,"go-build")]},"go"),bundler:l(()=>[e(i,".bundle","cache"),e(i,".gem","specs")],"bundler"),composer:l(()=>[u(n.COMPOSER_CACHE_DIR),a==="darwin"?e(c,"composer"):p?e(s,"Composer"):e(t,"composer")],"composer")},h=p?b.isAbsolute:C,N=p?b.relative:D,O=l(f=>{const y=N(f,i);return y===""||!(y.startsWith("..")||h(y))||f.split(/[\\/]/).filter(Boolean).length<2},"tooBroad"),x=o.flatMap(f=>m[f]());return[...new Set(x.filter(f=>!!f&&h(f)&&!O(f)))]}l(ut,"packageCacheDirs");const H=new Set(["install","i","in","ins","inst","insta","instal","isnt","isnta","isntal","isntall","add","ci","clean-install","ic","install-clean","isntall-clean","install-test","it","install-ci-test","cit","update","up","upgrade","udpate","create"]),U=new Set(["install","i","add","update","up","upgrade","fetch","dlx","create"]),F=new Set(["install","add","up","upgrade","dlx","create","global"]),Y=new Set(["install","i","add","a","update","create"]),A=new Set(["install","download","wheel"]),X=new Set(["sync","add","lock"]),v=new Set(["install","add","update","lock"]),V=new Set(["install","sync","update","lock"]),B=new Set(["fetch","install","add","update","generate-lockfile","binstall"]),$=new Set(["install","update","fetch"]),W=new Set(["install","update","add","lock"]),j=new Set(["install","require","update","create-project"]),z={npm:"npm",npx:"npm",pnpm:"pnpm",pnpx:"pnpm",yarn:"yarn",bun:"bun",bunx:"bun",uv:"uv",uvx:"uv",poetry:"poetry",cargo:"cargo",go:"go",gem:"bundler",bundle:"bundler",bundler:"bundler",composer:"composer"},K=new Set(["sudo","env","time","command","exec","nohup","nice","builtin"]);function Z(o){const r=[];for(const a of o.split(/&&|\|\||[;|&\n]|\$\(|`|\(|\)/)){const n=[...a.matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g)].map(i=>i[1]??i[2]??i[3]??"");for(;n.length>0&&(/^[A-Za-z_][A-Za-z0-9_]*=/.test(n[0])||K.has(n[0]));)n.shift();n.length>0&&r.push(n)}return r}l(Z,"simpleCommands");function q(o){return(o.split(/[\\/]/).pop()??o).replace(/\.(?:cmd|exe|bat|ps1)$/i,"").toLowerCase()}l(q,"programName");function _(o){return o.find(r=>!r.startsWith("-"))}l(_,"firstArgument");function S(o){if(o.some(a=>a==="-y"||a==="--yes"||a==="-p"||a.startsWith("--package")))return!0;const r=_(o);return r?/^(?:@[^/]+\/)?create-/.test(r)||/^(?:@[^/]+\/)?[^@/]+@/.test(r):!1}l(S,"npxDownloads");function J(o){const r=[];for(const a of o)for(const n of a.matchAll(/\b(?:https?|git\+https?):\/\/[^\s'"]+/gi)){const i=g(n[0].replace(/^git\+/i,""));i&&r.push(i)}return r}l(J,"urlHostsIn");function g(o){try{const r=new URL(o).hostname.toLowerCase();return r&&!G(r)?r:void 0}catch{return}}l(g,"hostOf");function ft(o){const r=new Set,a=new Set,n=[];let i=!1;for(const p of Z(o)){const e=q(p[0]),s=p.slice(1),t=_(s);let c,m=!1;switch(e){case"npm":(t&&(H.has(t)||(t==="exec"||t==="x")&&S(s.slice(1)))||t==="init"&&s.slice(s.indexOf(t)+1).some(h=>!h.startsWith("-")))&&(c="node");break;case"npx":case"bunx":S(s)&&(c="node");break;case"pnpm":t&&U.has(t)&&(c="node");break;case"pnpx":c="node";break;case"yarn":(t===void 0||F.has(t))&&(c="node",i=!0);break;case"bun":t&&Y.has(t)&&(c="node");break;case"pip":case"pip3":t&&A.has(t)&&(c="python");break;case"uv":t==="pip"?(A.has(_(s.slice(s.indexOf(t)+1))??"")||_(s.slice(s.indexOf(t)+1))==="sync")&&(c="python"):t==="tool"?_(s.slice(s.indexOf(t)+1))==="install"&&(c="python"):t&&X.has(t)&&(c="python");break;case"uvx":case"pipx":(e==="uvx"||t==="install"||t==="run")&&(c="python");break;case"poetry":t&&v.has(t)&&(c="python");break;case"pipenv":t&&V.has(t)&&(c="python");break;case"cargo":t&&B.has(t)&&(c="rust");break;case"go":if(t==="get"||t==="install")c="go";else if(t==="mod"){const h=_(s.slice(s.indexOf(t)+1));(h==="download"||h==="tidy")&&(c="go")}break;case"gem":t&&$.has(t)&&(c="ruby");break;case"bundle":case"bundler":(t===void 0||W.has(t))&&(c="ruby");break;case"composer":t&&j.has(t)&&(c="php");break;case"curl":case"wget":m=!0;break;case"git":m=t==="clone";break;default:if(/^python(?:\d+(?:\.\d+)*)?$|^py$/.test(e)){const h=s.indexOf("-m");h>=0&&s[h+1]==="pip"&&A.has(_(s.slice(h+2))??"")&&(c="python")}else/^pip\d+(?:\.\d+)*$/.test(e)&&t&&A.has(t)&&(c="python")}c&&(r.add(c),a.add(z[e]??"pip")),(c||m)&&n.push(...J(s))}if(!(r.size===0&&n.length===0))return{ecosystems:[...r],managers:[...a],urlHosts:[...new Set(n)],yarn:i}}l(ft,"detectNetworkCommand");const Q={rust:["crates.io","index.crates.io","static.crates.io"],ruby:["rubygems.org","index.rubygems.org"],php:["repo.packagist.org","packagist.org","api.github.com","codeload.github.com"]};function R(o){try{return L(o)?w(o,"utf8"):void 0}catch{return}}l(R,"readText");function tt(o,r){const a=[];let n=k(o);for(;a.push(n),n!==r;){const i=T(n);if(i===n)break;n=i}return a}l(tt,"ancestors");function et(o){let r;const a=[];for(const n of o.split(/\r?\n/)){const i=/^\s*(@[^:\s]+:)?registry\s*=\s*(\S+)\s*$/.exec(n);if(!i||i[2].includes("${"))continue;const p=g(i[2].replace(/^["']|["']$/g,""));p&&(i[1]?a.push(p):r??=p)}return{...r?{defaultRegistry:r}:{},scoped:a}}l(et,"npmrcRegistries");function nt(o,r,a,n){const i=[];let p=g(u(a.npm_config_registry)??u(a.NPM_CONFIG_REGISTRY)??"")??(r?g(u(a.YARN_NPM_REGISTRY_SERVER)??u(a.YARN_REGISTRY)??""):void 0);const e=[];for(const s of tt(o,n))e.push(d(s,".npmrc")),r&&e.push(d(s,".yarnrc.yml"),d(s,".yarnrc"));e.push(d(n,".npmrc"));for(const s of e){const t=R(s);if(t)if(s.endsWith(".npmrc")){const c=et(t);p??=c.defaultRegistry,i.push(...c.scoped)}else for(const c of t.matchAll(/^\s*(npmRegistryServer\s*:|registry\s+)\s*["']?([^"'\s#]+)/gm)){const m=g(c[2]);m&&(/^\S/.test(c[0])||c[1].startsWith("registry")?p??=m:i.push(m))}}return p?i.unshift(p):i.unshift(...r?["registry.yarnpkg.com","registry.npmjs.org"]:["registry.npmjs.org"]),i}l(nt,"nodeDomains");function st(o,r,a){const n=[];let i=!1;for(const s of["PIP_INDEX_URL","UV_INDEX_URL","UV_DEFAULT_INDEX"]){const t=g(u(o[s])??"");t&&(n.push(t),i=!0)}for(const s of["PIP_EXTRA_INDEX_URL","UV_EXTRA_INDEX_URL","UV_INDEX"])for(const t of(o[s]??"").split(/\s+/)){const c=g(t);c&&n.push(c)}const p=a==="win32"?[d(u(o.APPDATA)??d(r,"AppData","Roaming"),"pip","pip.ini"),d(r,"pip","pip.ini")]:[d(r,".pip","pip.conf"),d(u(o.XDG_CONFIG_HOME)??d(r,".config"),"pip","pip.conf"),d(r,"Library","Application Support","pip","pip.conf"),"/etc/pip.conf"],e=u(o.PIP_CONFIG_FILE);e&&p.unshift(e);for(const s of p){const t=R(s);if(t)for(const c of t.matchAll(/^\s*(index-url|extra-index-url)\s*[=:]\s*(.+)$/gm))for(const m of c[2].split(/\s+/)){const h=g(m);h&&(n.push(h),c[1]==="index-url"&&(i=!0))}}return i?n:["pypi.org","files.pythonhosted.org",...n]}l(st,"pythonDomains");function ot(o,r,a){const n=u(o.GOENV);return n||(a==="darwin"?d(r,"Library","Application Support","go","env"):a==="win32"?d(u(o.APPDATA)??d(r,"AppData","Roaming"),"go","env"):d(u(o.XDG_CONFIG_HOME)??d(r,".config"),"go","env"))}l(ot,"goEnvFile");function rt(o,r,a){const n={};for(const s of(R(ot(o,r,a))??"").split(/\r?\n/)){const t=/^\s*(GOPROXY|GOSUMDB)\s*=\s*(.*)$/.exec(s);t&&(n[t[1]]=t[2].trim())}const i=u(o.GOPROXY)??n.GOPROXY??"https://proxy.golang.org,direct",p=u(o.GOSUMDB)??n.GOSUMDB??"sum.golang.org",e=[];for(const s of i.split(/[,|]/)){const t=g(s.trim());t&&e.push(t)}if(p!=="off")for(const s of p.split(/\s+/)){const t=s.includes("://")?g(s):g(`https://${s.split("+")[0]}`);t&&e.push(t)}return e}l(rt,"goDomains");function dt(o,r,a={}){const{platform:n,env:i,home:p}=E(a),e=[];for(const s of o.ecosystems)s==="node"?e.push(...nt(r,o.yarn,i,p)):s==="python"?e.push(...st(i,p,n)):s==="go"?e.push(...rt(i,p,n)):e.push(...Q[s]);return e.push(...o.urlHosts),[...new Set(e)]}l(dt,"networkDomainsFor");const ht={npm_config_fetch_retries:"0",npm_config_fetch_retry_mintimeout:"1000",npm_config_fetch_retry_maxtimeout:"2000",YARN_HTTP_RETRY:"0",PIP_RETRIES:"0",PIP_TIMEOUT:"5",UV_HTTP_RETRIES:"0",CARGO_NET_RETRY:"0",BUNDLE_RETRY:"0"};export{ht as FAIL_FAST_NETWORK_ENV,M as PACKAGE_MANAGERS,ft as detectNetworkCommand,dt as networkDomainsFor,ut as packageCacheDirs};
|
|
@@ -61,6 +61,7 @@ export declare function filesystemRules(policy: ResolvedSandboxPolicy, cwd: stri
|
|
|
61
61
|
gitDirs?: string[];
|
|
62
62
|
extraWrite?: string[];
|
|
63
63
|
scratchDir?: string;
|
|
64
|
+
packageCaches?: string[];
|
|
64
65
|
}): CommandFilesystemRules;
|
|
65
66
|
export declare function domainMatches(host: string, pattern: string): boolean;
|
|
66
67
|
export declare function isAlwaysBlockedHost(host: string): boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var A=Object.defineProperty;var i=(e,r)=>A(e,"name",{value:r,configurable:!0});import{existsSync as O,readdirSync as C,realpathSync as N}from"node:fs";import{homedir as h}from"node:os";import{isAbsolute as W,join as u,relative as T,resolve as _}from"node:path";import{packageCacheDirs as j}from"./package-managers.js";const B=["read-only","workspace-write","off"],g="DAL_SANDBOX",D={off:0,"workspace-write":1,"read-only":2};function v(e){return typeof e=="string"&&B.includes(e)}i(v,"isSandboxLevel");function I(e,r){return D[r]>D[e]?r:e}i(I,"stricterLevel");function a(e){return Array.isArray(e)?e.filter(r=>typeof r=="string"&&r.length>0):[]}i(a,"strings");function f(e){return[...new Set(e)]}i(f,"unique");const P=process.env[g];function z(e={[g]:P}){const r=e[g];if(r)try{const t=JSON.parse(r);return v(t.level)?{level:t.level,allowedDomains:a(t.allowedDomains)}:void 0}catch{return}}i(z,"readSandboxEnvironment");function $(e){return JSON.stringify({level:e.level,allowedDomains:e.network.allowedDomains})}i($,"sandboxEnvironmentValue");function Q(e){const r=e.settings?.global??{},t=e.settings?.project??{},s=z(e.env),l=e.override??{};let o,c;return l.level?(o=l.level,c="override"):s?.level?(o=s.level,c="environment"):v(r.level)?(o=r.level,c="settings"):(o=e.defaultLevel,c="default"),!l.level&&v(t.level)&&I(o,t.level)!==o&&(o=t.level,c="project"),{level:o,levelSource:c,network:{allowedDomains:f([...a(r.network?.allowedDomains),...a(s?.allowedDomains),...a(l.allowedDomains)]),deniedDomains:f([...a(r.network?.deniedDomains),...a(t.network?.deniedDomains)]),allowLocalBinding:r.network?.allowLocalBinding===!0},filesystem:{allowWrite:a(r.filesystem?.allowWrite),denyRead:f([...a(r.filesystem?.denyRead),...a(t.filesystem?.denyRead)]),denyWrite:f([...a(r.filesystem?.denyWrite),...a(t.filesystem?.denyWrite)]),allowRead:a(r.filesystem?.allowRead)}}}i(Q,"resolveSandboxPolicy");const H=[".git/hooks",".git/config",".gitmodules",".dal",".claude",".agents",".mcp.json",".cursor",".vscode",".idea",".env"],M=[".gitconfig",".bashrc",".bash_profile",".zshrc",".zprofile",".profile",".config/fish",".dal"],V=[".ssh",".gnupg",".aws",".config/gcloud",".azure",".kube",".docker/config.json",".netrc",".npmrc",".pypirc",".git-credentials",".config/gh","Library/Keychains","Library/Application Support/Google/Chrome","Library/Application Support/Firefox","Library/Safari",".mozilla",".config/google-chrome",".config/chromium",".dal/agent/auth.json"];function m(e,r){return e==="~"?h():e.startsWith("~/")?u(h(),e.slice(2)):W(e)?e:_(r,e)}i(m,"expandPath");function w(e){try{return N(e)}catch{return e}}i(w,"realpathOrSelf");function x(e,r){const t=T(r,e);return t===""||!t.startsWith("..")&&!W(t)}i(x,"isWithin");function U(e,r,t={}){const s=h(),l=e.level==="workspace-write"?f([r,w(r),...e.filesystem.allowWrite.map(n=>m(n,r))]):[],o=e.level==="workspace-write"?t.gitDirs??[]:[],c=(t.extraWrite??[]).map(n=>m(n,r)),k=t.scratchDir?[t.scratchDir,w(t.scratchDir)]:[],E=e.level==="workspace-write"?t.packageCaches??j():[],R=f([...l,...o,...c,...k,...E]),d=[];if(e.level==="read-only"){const n=f([r,w(r)]);c.some(y=>n.some(S=>x(y,S)||x(S,y)))||d.push(...n)}for(const n of[...l,...c]){for(const p of H)d.push(u(n,p));d.push(u(n,".env.*"));for(const p of X(n))d.push(u(n,p))}for(const n of o)d.push(u(n,"hooks"),u(n,"config"));for(const n of M)d.push(u(s,n));d.push(...e.filesystem.denyWrite.map(n=>m(n,r)));const b=new Set(e.filesystem.allowRead.map(n=>m(n,r))),L=[...V.map(n=>u(s,n)).filter(n=>!b.has(n)),...e.filesystem.denyRead.map(n=>m(n,r))];return{allowWrite:R,denyWrite:f(d),denyRead:f(L)}}i(U,"filesystemRules");function X(e){if(!O(e))return[];try{return C(e).filter(r=>r.startsWith(".env."))}catch{return[]}}i(X,"listEnvFiles");function Y(e,r){const t=e.toLowerCase(),s=r.toLowerCase();return s.startsWith("*.")?t.endsWith(s.slice(1)):t===s}i(Y,"domainMatches");function Z(e){const r=e.toLowerCase().replace(/^\[|\]$/g,"");if(r==="localhost"||r.endsWith(".localhost")||r==="::1"||r==="0.0.0.0")return!0;if(r.startsWith("fe80:")||r.startsWith("fc")||r.startsWith("fd"))return r.includes(":");const t=r.split(".").map(o=>Number(o));if(t.length!==4||t.some(o=>!Number.isInteger(o)||o<0||o>255))return!1;const[s,l]=t;return s===127||s===10||s===172&&l>=16&&l<=31||s===192&&l===168||s===169&&l===254}i(Z,"isAlwaysBlockedHost");export{V as PROTECTED_HOME_READS,M as PROTECTED_HOME_WRITES,H as PROTECTED_WRITE_NAMES,g as SANDBOX_ENV,B as SANDBOX_LEVELS,Y as domainMatches,m as expandPath,U as filesystemRules,Z as isAlwaysBlockedHost,v as isSandboxLevel,z as readSandboxEnvironment,Q as resolveSandboxPolicy,$ as sandboxEnvironmentValue,I as stricterLevel};
|
|
@@ -9,6 +9,11 @@ export interface SandboxEscalationInput {
|
|
|
9
9
|
allow_domains?: string[];
|
|
10
10
|
allow_write?: string[];
|
|
11
11
|
}
|
|
12
|
+
export interface PlannedNetworkEscalation extends SandboxEscalationInput {
|
|
13
|
+
mode: "allow";
|
|
14
|
+
allow_domains: string[];
|
|
15
|
+
trigger: NonNullable<SandboxEscalationRequest["trigger"]>;
|
|
16
|
+
}
|
|
12
17
|
export interface SandboxEscalationRequest {
|
|
13
18
|
toolCallId: string;
|
|
14
19
|
toolName: string;
|
|
@@ -20,11 +25,16 @@ export interface SandboxEscalationRequest {
|
|
|
20
25
|
allowDomains: string[];
|
|
21
26
|
allowWrite: string[];
|
|
22
27
|
background: boolean;
|
|
28
|
+
trigger?: "package-install" | "download";
|
|
23
29
|
}
|
|
24
30
|
export interface SandboxEscalationDecision {
|
|
25
31
|
approved: boolean;
|
|
26
32
|
scope?: "once" | "session";
|
|
27
33
|
message?: string;
|
|
34
|
+
grant?: {
|
|
35
|
+
allowDomains?: string[];
|
|
36
|
+
allowWrite?: string[];
|
|
37
|
+
};
|
|
28
38
|
}
|
|
29
39
|
export type SandboxEscalationHandler = (request: SandboxEscalationRequest, ctx: ExtensionContext | undefined) => Promise<SandboxEscalationDecision | undefined> | SandboxEscalationDecision | undefined;
|
|
30
40
|
export type SandboxEvent = {
|
|
@@ -107,6 +117,10 @@ export declare class ShellSandbox {
|
|
|
107
117
|
status(): SandboxStatus;
|
|
108
118
|
describeForModel(): string | undefined;
|
|
109
119
|
unavailableRefusal(): string | undefined;
|
|
120
|
+
planNetworkEscalation(call: {
|
|
121
|
+
command: string;
|
|
122
|
+
cwd: string;
|
|
123
|
+
}): PlannedNetworkEscalation | undefined;
|
|
110
124
|
prepare(request: {
|
|
111
125
|
command: string;
|
|
112
126
|
cwd: string;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)){const
|
|
3
|
-
`)}async prepare(e){const o=this.policy.level;if(o==="off")return
|
|
4
|
-
${e.command}`,
|
|
5
|
-
`),
|
|
1
|
+
var G=Object.defineProperty;var m=(n,e)=>G(n,"name",{value:e,configurable:!0});import{spawnSync as Q}from"node:child_process";import{mkdirSync as V,mkdtempSync as z,rmSync as J}from"node:fs";import{tmpdir as Z}from"node:os";import{isAbsolute as P,join as q,relative as ee,resolve as oe}from"node:path";import{fill as y,t as h}from"../../dal/i18n.js";import{detectSandboxAvailability as ne}from"./availability.js";import{collectBlockedAccesses as O}from"./denial.js";import{detectNetworkCommand as T,FAIL_FAST_NETWORK_ENV as L,networkDomainsFor as te,packageCacheDirs as ie}from"./package-managers.js";import{domainMatches as U,expandPath as B,filesystemRules as ae}from"./policy.js";import{acquireSandboxRuntime as se,ensureFilteringProxy as re,proxyUnavailableReason as M,registerNetworkGrant as le,releaseSandboxRuntime as de,violationsForCommand as ce,wrapCommand as me}from"./runtime.js";import{prepareWindowsCommand as he}from"./windows.js";const R=Symbol.for("dal.sandbox.escalationHandlers"),k=globalThis;k[R]instanceof Set||(k[R]=new Set);const j=k[R];function je(n){return j.add(n),()=>{j.delete(n)}}m(je,"registerSandboxEscalationHandler");const F=Symbol.for("dal.sandbox.processSandbox");function Ae(n){k[F]=n}m(Ae,"setProcessShellSandbox");function Ne(){return k[F]}m(Ne,"getProcessShellSandbox");const K=new Map;function fe(n){const e=K.get(n);if(e)return e;const o=Q("git",["rev-parse","--absolute-git-dir","--git-common-dir"],{cwd:n,encoding:"utf8",timeout:3e3}),r=[];if(o.status===0)for(const s of o.stdout.split(`
|
|
2
|
+
`)){const i=s.trim();if(!i)continue;const t=P(i)?i:oe(n,i),a=ee(n,t);(a.startsWith("..")||P(a))&&r.push(t)}const l=[...new Set(r)];return K.set(n,l),l}m(fe,"gitDirsOutside");function S(n){return Array.isArray(n)?n.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}m(S,"cleanList");let ue=0;class Ie{static{m(this,"ShellSandbox")}policy;onEscalation;onEvent;availabilityOverride;sessionDomains=new Set;sessionWritable=new Set;holdsRuntime=!1;sharedScratch;ownScratch;constructor(e){this.policy=e.policy,this.onEscalation=e.onEscalation,this.onEvent=e.onEvent,this.availabilityOverride=e.availability,this.sharedScratch=e.scratchDir,this.active&&(se(),this.holdsRuntime=!0)}scratchDir(){return this.sharedScratch?this.sharedScratch():(this.ownScratch??=we(),this.ownScratch)}async dispose(){this.ownScratch&&(J(this.ownScratch,{recursive:!0,force:!0}),this.ownScratch=void 0),this.holdsRuntime&&(this.holdsRuntime=!1,await de())}get level(){return this.policy.level}get active(){return this.policy.level!=="off"}availability(){return this.availabilityOverride??ne()}status(){const e=this.availability(),o=M();return{level:this.policy.level,levelSource:this.policy.levelSource,enforced:this.active&&e.available,platform:e.platform,...e.mechanism?{mechanism:e.mechanism}:{},...this.active&&!e.available&&e.reason?{unavailableReason:e.reason}:{},...e.isolationTier?{isolationTier:e.isolationTier}:{},...e.limitations?.length?{limitations:[...e.limitations]}:{},network:{allowedDomains:[...this.policy.network.allowedDomains],deniedDomains:[...this.policy.network.deniedDomains],...o?{proxyError:o}:{}},sessionAllowances:{domains:[...this.sessionDomains],writablePaths:[...this.sessionWritable]}}}describeForModel(){if(!this.active)return;const e=this.policy.level==="read-only"?"nothing may be written except $TMPDIR (a scratch directory for this session)":"writes are limited to the working directory, $TMPDIR (a scratch directory for this session) and package-manager caches (agent/editor config, git hooks and .env files stay read-only)",o=this.policy.network.allowedDomains,r=(o.length>0?`network is off except ${o.join(", ")}`:"network is off")+(this.policy.level==="workspace-write"?" (package installs such as npm/pnpm/yarn/pip/uv/cargo/go and curl/wget/git clone of a URL ask the user for their registry's hosts automatically before running; run them plainly, without sandbox_escalation)":"");return`Commands run inside an OS sandbox (${this.policy.level}): ${e}; ${r}; credential files such as ~/.ssh cannot be read. When the sandbox blocks something the result says what; only then, and only if the task needs it, retry with sandbox_escalation.`}unavailableRefusal(){if(!this.active)return;const e=this.availability();if(!e.available)return[`Command refused: the sandbox level is "${this.policy.level}", but ${e.reason??"the OS sandbox is unavailable."}`,"Commands are not run without the sandbox unless the user says so explicitly.",'The user can fix the sandbox, or opt out explicitly with `dal --sandbox off` or "sandbox": { "level": "off" } in ~/.dal/agent/settings.json.','A single command can still run if the user approves it: retry with sandbox_escalation {"mode":"unsandboxed","justification":"..."}.'].join(`
|
|
3
|
+
`)}planNetworkEscalation(e){if(this.policy.level!=="workspace-write"||!this.availability().available)return;const o=T(e.command);if(!o)return;const r=[...this.policy.network.allowedDomains,...this.sessionDomains],l=this.policy.network.deniedDomains,s=te(o,e.cwd).filter(t=>!r.some(a=>U(t,a))&&!l.some(a=>U(t,a)));if(s.length===0)return;const i=o.ecosystems.length>0?"package-install":"download";return{mode:"allow",allow_domains:s,trigger:i,justification:i==="package-install"?h("\u8FD9\u6761\u547D\u4EE4\u8981\u5B89\u88C5\u4F9D\u8D56\uFF0C\u9700\u8981\u4ECE\u8F6F\u4EF6\u6E90\u4E0B\u8F7D\u3002"):h("\u8FD9\u6761\u547D\u4EE4\u8981\u4ECE\u7F51\u4E0A\u4E0B\u8F7D\u6587\u4EF6\u3002")}}async prepare(e){const o=this.policy.level;if(o==="off")return H(e.command,{level:o,sandboxed:!1});const r=this.unavailableRefusal();if(r&&e.escalation?.mode!=="unsandboxed")throw new Error(r);let l=[],s=[],i;const t=e.escalation||r?void 0:this.planNetworkEscalation(e),a=t?await this.approveEscalation(e,t,t.trigger):void 0;if(t&&a&&a.decidedBy!=="none"){const f={request:a.request,decision:a.decision};if(i=f,!f.decision.approved)throw new Error(`The user did not allow network access for this command${f.decision.message?` (${f.decision.message})`:""}: it needs ${t.allow_domains.join(", ")}. Do not retry it with sandbox_escalation; continue without it or ask the user.`);l=a.allowDomains,s=a.allowWrite}else if(e.escalation){const{decidedBy:f,allowDomains:x,allowWrite:C,...w}=await this.approveEscalation(e,e.escalation);if(i=w,!w.decision.approved)throw new Error(`Sandbox escalation refused${w.decision.message?`: ${w.decision.message}`:"."} Do not retry the same escalation; continue without it or ask the user.`);if(w.request.mode==="unsandboxed")return H(e.command,{level:o,sandboxed:!1,escalation:i});l=x,s=C}const d=this.availability(),b=e.shellKind??"bash";if(b!=="bash"&&d.mechanism!=="mxc")throw new Error(`Command refused: ${b} commands cannot run inside the ${d.mechanism??"OS"} sandbox, and the sandbox level is "${o}". Use the bash tool, or the user can opt out with \`dal --sandbox off\`.`);const u=this.scratchDir();o==="workspace-write"&&pe(T(e.command)?.managers);const p=ae(this.policy,e.cwd,{gitDirs:this.policy.level==="workspace-write"?fe(e.cwd):[],extraWrite:[...this.sessionWritable,...s],scratchDir:u}),c={allowedDomains:[...this.policy.network.allowedDomains,...this.sessionDomains,...l],deniedDomains:this.policy.network.deniedDomains,refusals:[]},D=`${process.pid}-${++ue}`,g=c.allowedDomains.length===0;if(d.mechanism==="mxc"&&d.mxc){const f=g?{...e.env??process.env,...L}:e.env;return this.prepareWindows({...e,...f?{env:f}:{}},{level:o,shellKind:b,scratch:u,rules:p,grant:c,runId:D,escalation:i,availability:d})}const v=be(u),E=g?Object.entries(L).map(([f,x])=>` ${f}=${x}`).join(""):"",A=`export DAL_SANDBOX_RUN=${D} TMPDIR=${v} TMP=${v} TEMP=${v}${E}
|
|
4
|
+
${e.command}`,X=Date.now(),W=await me({command:A,shell:e.shell,allowWrite:p.allowWrite,denyWrite:p.denyWrite,denyRead:p.denyRead,allowLocalBinding:e.background===!0||this.policy.network.allowLocalBinding,...d.ripgrep?{ripgrep:d.ripgrep}:{}},c),$={level:o,sandboxed:!0,...i?{escalation:i}:{}};let N=!1;return{command:W.command,sandboxed:!0,details:$,finish:m(async(f,x)=>{if(N)return $.denial;if(N=!0,W.release(),f===0)return;const C=d.platform==="darwin"?await ce(A,X,400):[],w=O({refusals:c.refusals,violations:C,output:x});if(!w)return;const I=W.proxied?void 0:M(),_={level:o,platform:d.platform,command:e.command,cwd:e.cwd,blocked:w,...I&&w.some(Y=>Y.kind==="network")?{networkProxyError:I}:{}};return $.denial=_,this.onEvent?.({type:"sandbox_denied",toolCallId:e.toolCallId,toolName:e.toolName,denial:_}),_},"finish")}}async prepareWindows(e,o){const{level:r,grant:l,availability:s}=o,i=s.mxc;if(!i)throw new Error("Command refused: the Windows sandbox (mxc) is not loaded.");let t,a;if(l.allowedDomains.length>0){const c=await re();"port"in c?t=c.port:a=c.error}const d=he({runtime:i,kind:o.shellKind,shellPath:e.shell,command:e.command,cwd:e.cwd,level:r,rules:o.rules,env:e.env??process.env,scratchDir:o.scratch,runId:o.runId,...t!==void 0?{proxyPort:t}:{},allowLocalNetwork:e.background===!0||this.policy.network.allowLocalBinding}),b=le(l),u={level:r,sandboxed:!0,...o.escalation?{escalation:o.escalation}:{}};let p=!1;return{command:d.command,sandboxed:!0,details:u,finish:m(async(c,D)=>{if(p)return u.denial;if(p=!0,b(),d.cleanup(),c===0)return;const g=O({refusals:l.refusals,violations:[],output:D});if(!g)return;const v={level:r,platform:s.platform,command:e.command,cwd:e.cwd,blocked:g,...a&&g.some(E=>E.kind==="network")?{networkProxyError:a}:{}};return u.denial=v,this.onEvent?.({type:"sandbox_denied",toolCallId:e.toolCallId,toolName:e.toolName,denial:v}),v},"finish")}}uiApprovals=Promise.resolve();queueUiApproval(e){const o=this.uiApprovals.then(e,e);return this.uiApprovals=o.catch(()=>{}),o}async approveEscalation(e,o,r){const l=o.mode==="unsandboxed"?"unsandboxed":"allow",s={toolCallId:e.toolCallId,toolName:e.toolName,command:e.command,cwd:e.cwd,level:this.policy.level,mode:l,justification:typeof o.justification=="string"?o.justification.trim():"",allowDomains:l==="allow"?S(o.allow_domains):[],allowWrite:l==="allow"?S(o.allow_write).map(t=>B(t,e.cwd)):[],background:e.background===!0,...r?{trigger:r}:{}},i=m((t,a)=>{const d=t.approved&&t.scope==="session"&&l==="unsandboxed"?{...t,scope:"once"}:t,b=d.approved&&l==="allow"?d.grant:void 0,u=[...new Set([...s.allowDomains,...S(b?.allowDomains)])],p=[...new Set([...s.allowWrite,...S(b?.allowWrite).map(c=>B(c,e.cwd))])];if(d.approved&&d.scope==="session"){for(const c of u)this.sessionDomains.add(c);for(const c of p)this.sessionWritable.add(c)}return r&&a==="none"||this.onEvent?.({type:"sandbox_escalation",toolCallId:e.toolCallId,toolName:e.toolName,request:s,decision:d,decidedBy:a}),{request:s,decision:d,decidedBy:a,allowDomains:u,allowWrite:p}},"finish");if(!s.justification)return i({approved:!1,message:"an escalation needs a justification"},"none");if(l==="allow"&&s.allowDomains.length===0&&s.allowWrite.length===0)return i({approved:!1,message:'mode "allow" needs allow_domains or allow_write'},"none");if(this.onEscalation){const t=await this.onEscalation(s,e.ctx);if(t)return i(t,"sdk")}for(const t of j){const a=await t(s,e.ctx);if(a)return i(a,"handler")}if(e.ctx?.hasUI){const t=e.ctx;return i(await this.queueUiApproval(()=>ve(s,t,e.signal)),"ui")}return i({approved:!1,message:"nobody is available to approve it (no interactive UI and no approver configured)"},"none")}}function H(n,e){return{command:n,sandboxed:!1,details:e,finish:m(async()=>{},"finish")}}m(H,"passthrough");function pe(n){if(!(!n||n.length===0))for(const e of ie(n))try{V(e,{recursive:!0,mode:448})}catch{}}m(pe,"ensurePackageCaches");function we(){return z(q(Z(),"dal-sandbox-"))}m(we,"createScratchDir");function be(n){return`'${n.replace(/'/g,"'\\''")}'`}m(be,"shellQuote");async function ve(n,e,o){if(o?.aborted)return{approved:!1,message:"the turn was interrupted before the user answered"};const r=h("\u4EC5\u672C\u6B21\u5141\u8BB8"),l=h("\u672C\u4F1A\u8BDD\u5185\u90FD\u5141\u8BB8"),s=h("\u62D2\u7EDD"),i=n.mode==="unsandboxed"?h("\u5728\u6C99\u7BB1\u4E4B\u5916\u8FD0\u884C\u547D\u4EE4\uFF08\u53EF\u8BBF\u95EE\u4F60\u7684\u5168\u90E8\u6587\u4EF6\u548C\u7F51\u7EDC\uFF09"):[n.allowDomains.length>0?y(h("\u8BBF\u95EE {domains}"),{domains:n.allowDomains.join(", ")}):"",n.allowWrite.length>0?y(h("\u5199\u5165 {paths}"),{paths:n.allowWrite.join(", ")}):""].filter(Boolean).join(h("\uFF0C\u5E76")),t=[y(h("\u52A9\u624B\u60F3\u8981{what}\u3002"),{what:i}),y(h("\u547D\u4EE4\uFF1A{command}"),{command:n.command}),y(h("\u76EE\u5F55\uFF1A{cwd}"),{cwd:n.cwd}),n.trigger?y(h("\u539F\u56E0\uFF1A{reason}"),{reason:n.justification}):y(h("\u52A9\u624B\u7ED9\u7684\u7406\u7531\uFF08\u672A\u7ECF\u6838\u5B9E\uFF09\uFF1A{reason}"),{reason:n.justification})].join(`
|
|
5
|
+
`),a=n.mode==="unsandboxed"?[r,s]:[r,l,s],d=await e.ui.select(t,a,o?{signal:o}:void 0);return o?.aborted?{approved:!1,message:"the turn was interrupted before the user answered"}:d===r?{approved:!0,scope:"once"}:d===l?{approved:!0,scope:"session"}:{approved:!1,message:"the user declined"}}m(ve,"askThroughUi");export{Ie as ShellSandbox,we as createScratchDir,Ne as getProcessShellSandbox,je as registerSandboxEscalationHandler,Ae as setProcessShellSandbox};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var f=Object.defineProperty;var s=(t,o)=>f(t,"name",{value:o,configurable:!0});import{resolve as r}from"node:path";import{dalBuiltinExtensionPaths as u}from"./builtins.js";const e=Symbol.for("dal.hostExtensionPaths");function i(){const t=globalThis;return t[e]instanceof Set||(t[e]=new Set),t[e]}s(i,"hostPaths");let a;function m(t){const o=i();for(const n of t)o.add(r(n))}s(m,"markHostExtensionPaths");function d(t){if(t.startsWith("<inline"))return!0;if(t.startsWith("<"))return!1;const o=r(t);return i().has(o)?!0:(a??=new Set(u().map(n=>r(n))),a.has(o))}s(d,"isHostExtensionPath");export{d as isHostExtensionPath,m as markHostExtensionPaths};
|
package/dist/index.d.ts
CHANGED
|
@@ -22,7 +22,7 @@ export { evaluateToolPolicy, type PermissionAskHandler, type PermissionAskReques
|
|
|
22
22
|
export { buildProjectMap, formatProjectMapPrompt, type ProjectMap, type ProjectMapOptions, } from "./core/project-map.ts";
|
|
23
23
|
export type { ResourceCollision, ResourceDiagnostic, ResourceLoader } from "./core/resource-loader.ts";
|
|
24
24
|
export { DefaultResourceLoader, loadProjectContextFiles } from "./core/resource-loader.ts";
|
|
25
|
-
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";
|
|
25
|
+
export { detectSandboxAvailability, getProcessShellSandbox, type PlannedNetworkEscalation, 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";
|
|
26
26
|
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";
|
|
27
27
|
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";
|
|
28
28
|
export { type CacheWarmingMode, type CompactionModelOverride, type CompactionSettings, type DefaultProjectTrust, type FullscreenExitOutput, type ImageSettings, type PackageSource, type QuietStartup, type RetrySettings, SettingsManager, type SettingsManagerCreateOptions, type TuiMode, } from "./core/settings-manager.ts";
|
|
@@ -34,6 +34,7 @@ export { hasTrustRequiringProjectResources, type ProjectTrustDecision, ProjectTr
|
|
|
34
34
|
export { type ModelRoute, type ModelRouteReason, type ModelRouteRequest, VIRTUAL_MODEL_STATE_ENTRY, type VirtualModelDefinition, type VirtualModelStateData, } from "./core/virtual-models.ts";
|
|
35
35
|
export { applyShellEnvironmentPolicy, DEFAULT_SHELL_ENV_EXCLUDES, isDalCodeCredentialName, type ShellEnvironmentPolicy, withoutDalCodeCredentials, } from "./dal/child-env.ts";
|
|
36
36
|
export * from "./dal/hooks/index.ts";
|
|
37
|
+
export { isHostExtensionPath, markHostExtensionPaths } from "./dal/host-extensions.ts";
|
|
37
38
|
export { type CodemodeExtensionOptions, createCodemodeExtension } from "./extensions/codemode/index.ts";
|
|
38
39
|
export type { CodemodeStoreEntryData, CodemodeToolDetails } from "./extensions/codemode/tool.ts";
|
|
39
40
|
export type { LoadedMcpConfig, McpExposure, McpServerConfig, McpServerEntry } from "./extensions/mcp/config.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 c,VERSION as p}from"./config.js";import{AgentSession as T,parseSkillBlock as d}from"./core/agent-session.js";import{readStoredCredential as f}from"./core/auth-storage.js";import{BackgroundProcessManager as u,MAX_BACKGROUND_PROCESSES as C}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 N,prepareBranchEntries as F,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 V,isBashToolResult as G,isEditToolResult as j,isFindToolResult as K,isGrepToolResult as W,isLsToolResult as X,isPowerShellToolResult as z,isReadToolResult as Y,isToolCallEventType as q,isWriteToolResult as Q,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 Te,resolveModelScopeWithDiagnostics as de}from"./core/model-resolver.js";import{CredentialSynchronizationError as fe,ModelRuntime as xe}from"./core/model-runtime.js";import{DefaultPackageManager as Ce}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 Fe,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 Ve,createAgentSession as Ge,createAgentSessionFromServices as je,createAgentSessionRuntime as Ke,createAgentSessionServices as We,createBashTool as Xe,createCodingTools as ze,createEditTool as Ye,createFindTool as qe,createGrepTool as Qe,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 To}from"./core/settings-manager.js";import{formatSkillsForPrompt as fo,loadSkills as xo,loadSkillsFromDir as uo}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 No,createPowerShellToolDefinition as Fo,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 Vo,truncateTail as Go,withFileMutationQueue as jo}from"./core/tools/index.js";import{hasTrustRequiringProjectResources as Wo,ProjectTrustStore as Xo}from"./core/trust-manager.js";import{VIRTUAL_MODEL_STATE_ENTRY as Yo}from"./core/virtual-models.js";import{applyShellEnvironmentPolicy as Qo,DEFAULT_SHELL_ENV_EXCLUDES as Jo,isDalCodeCredentialName as Zo,withoutDalCodeCredentials as $o}from"./dal/child-env.js";export*from"./dal/hooks/index.js";import{createCodemodeExtension as tt}from"./extensions/codemode/index.js";import{createMcpExtension as nt}from"./extensions/mcp/index.js";import{createToolSearchExtension as at}from"./extensions/tool-search/index.js";import{main as lt}from"./main.js";import{InteractiveMode as ct,RpcClient as pt,runPrintMode as St,runRpcMode as Tt}from"./modes/index.js";import{ArminComponent as gt,AssistantMessageComponent as ft,BashExecutionComponent as xt,BorderedLoader as ut,BranchSummaryMessageComponent as Ct,CompactionSummaryMessageComponent as Et,CustomEditor as ht,CustomMessageComponent as Rt,DynamicBorder as Dt,ExtensionEditorComponent as Pt,ExtensionInputComponent as At,ExtensionSelectorComponent as Mt,FooterComponent as Lt,keyHint as _t,keyText as yt,LoginDialogComponent as It,ModelSelectorComponent as Nt,OAuthSelectorComponent as Ft,rawKeyHint as Ot,renderDiff as Bt,SessionSelectorComponent as vt,SettingsSelectorComponent as kt,ShowImagesSelectorComponent as Ht,SkillInvocationMessageComponent as bt,ThemeSelectorComponent as Ut,ThinkingSelectorComponent as wt,ToolExecutionComponent as Vt,TreeSelectorComponent as Gt,truncateToVisualLines as jt,UserMessageComponent as Kt,UserMessageSelectorComponent as Wt}from"./modes/interactive/components/index.js";import{getLanguageFromPath as zt,getMarkdownTheme as Yt,getSelectListTheme as qt,getSettingsListTheme as Qt,highlightCode as Jt,initTheme as Zt,Theme as $t}from"./modes/interactive/theme/theme.js";import{copyToClipboard as or}from"./utils/clipboard.js";import{parseFrontmatter as rr,stripFrontmatter as nr}from"./utils/frontmatter.js";import{convertToPng as ar}from"./utils/image-convert.js";import{formatDimensionNote as lr,resizeImage as mr}from"./utils/image-resize.js";import{detectSupportedImageMimeTypeFromFile as pr}from"./utils/mime.js";import{getPowerShellConfig as Tr,getShellConfig as dr,getShellEnv as gr}from"./utils/shell.js";export{T as AgentSession,Ve as AgentSessionRuntime,gt as ArminComponent,ft as AssistantMessageComponent,u as BackgroundProcessManager,xt as BashExecutionComponent,ut as BorderedLoader,Ct as BranchSummaryMessageComponent,n as CONFIG_DIR_NAME,ao as CURRENT_SESSION_VERSION,Et as CompactionSummaryMessageComponent,fe as CredentialSynchronizationError,ht as CustomEditor,Rt as CustomMessageComponent,P as DEFAULT_COMPACTION_SETTINGS,ko as DEFAULT_MAX_BYTES,Ho as DEFAULT_MAX_LINES,Jo as DEFAULT_SHELL_ENV_EXCLUDES,Ce as DefaultPackageManager,Fe as DefaultResourceLoader,Dt as DynamicBorder,Pt as ExtensionEditorComponent,At as ExtensionInputComponent,V as ExtensionRunner,Mt as ExtensionSelectorComponent,Lt 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,ct as InteractiveMode,It as LoginDialogComponent,C as MAX_BACKGROUND_PROCESSES,pe as ModelRegistry,xe as ModelRuntime,Nt as ModelSelectorComponent,Ft as OAuthSelectorComponent,Xo as ProjectTrustStore,pt as RpcClient,be as SANDBOX_ENV,c as SHARED_SKILL_CONFIG_DIRS,co as SessionManager,vt as SessionSelectorComponent,To as SettingsManager,kt as SettingsSelectorComponent,Ue as ShellSandbox,Ht as ShowImagesSelectorComponent,bt as SkillInvocationMessageComponent,$t as Theme,Ut as ThemeSelectorComponent,wt as ThinkingSelectorComponent,Vt as ToolExecutionComponent,Gt as TreeSelectorComponent,Kt as UserMessageComponent,Wt as UserMessageSelectorComponent,p as VERSION,Yo as VIRTUAL_MODEL_STATE_ENTRY,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,ar as convertToPng,or as copyToClipboard,Ge as createAgentSession,je as createAgentSessionFromServices,Ke as createAgentSessionRuntime,We as createAgentSessionServices,Xe as createBashTool,Ao as createBashToolDefinition,tt as createCodemodeExtension,ze as createCodingTools,Ye as createEditTool,Mo as createEditToolDefinition,k as createEventBus,b as createExtensionRuntime,qe as createFindTool,Lo as createFindToolDefinition,Qe as createGrepTool,_o as createGrepToolDefinition,yo as createLocalBashOperations,Io as createLocalPowerShellOperations,Je as createLsTool,No as createLsToolDefinition,nt as createMcpExtension,Ze as createPowerShellTool,Fo as createPowerShellToolDefinition,Oo as createProcessToolDefinition,$e as createReadOnlyTools,eo as createReadTool,Bo as createReadToolDefinition,Eo as createSyntheticSourceInfo,at as createToolSearchExtension,oo as createWriteTool,vo as createWriteToolDefinition,U as defineTool,ve as detectSandboxAvailability,pr as detectSupportedImageMimeTypeFromFile,w as discoverAndLoadExtensions,A as estimateTokens,Ae as evaluateToolPolicy,M as findCutPoint,L as findTurnStartIndex,lr 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,zt as getLanguageFromPath,N as getLastAssistantUsage,so as getLatestCompactionEntry,Yt as getMarkdownTheme,l as getPackageDir,Tr as getPowerShellConfig,m as getReadmePath,qt as getSelectListTheme,Qt as getSettingsListTheme,dr as getShellConfig,gr as getShellEnv,Wo as hasTrustRequiringProjectResources,Jt as highlightCode,Zt as initTheme,G as isBashToolResult,Zo as isDalCodeCredentialName,j as isEditToolResult,K as isFindToolResult,W as isGrepToolResult,X as isLsToolResult,z as isPowerShellToolResult,Y as isReadToolResult,q as isToolCallEventType,Q as isWriteToolResult,_t as keyHint,yt as keyText,Oe as loadProjectContextFiles,xo as loadSkills,uo as loadSkillsFromDir,lt as main,Re as matchPermissionRules,lo as migrateSessionEntries,t as parseArgs,rr as parseFrontmatter,se as parseHostCapabilities,De as parsePermissionRule,mo as parseSessionEntries,d as parseSkillBlock,F as prepareBranchEntries,Ot as rawKeyHint,Me as readAccessDenial,f as readStoredCredential,Le as registerPermissionAskHandler,ke as registerSandboxEscalationHandler,Uo as registerShellExecutionGuard,Bt as renderDiff,mr as resizeImage,Te as resolveCliModel,de as resolveModelScopeWithDiagnostics,He as resolveSandboxPolicy,St as runPrintMode,Tt as runRpcMode,O as serializeConversation,po as sessionEntryToContextMessages,B as shouldCompact,nr as stripFrontmatter,wo as truncateHead,Vo as truncateLine,Go as truncateTail,jt as truncateToVisualLines,jo as withFileMutationQueue,$o as withoutDalCodeCredentials,J as wrapRegisteredTool,Z 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 T,parseSkillBlock as d}from"./core/agent-session.js";import{readStoredCredential as x}from"./core/auth-storage.js";import{BackgroundProcessManager as E,MAX_BACKGROUND_PROCESSES as u}from"./core/background-processes.js";import{calculateContextTokens as h,collectEntriesForBranchSummary as R,compact as P,DEFAULT_COMPACTION_SETTINGS as D,estimateTokens as A,findCutPoint as M,findTurnStartIndex as L,generateBranchSummary as _,generateSummary as y,generateSummaryWithUsage as I,getLastAssistantUsage as N,prepareBranchEntries as F,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 V,isBashToolResult as G,isEditToolResult as j,isFindToolResult as K,isGrepToolResult as W,isLsToolResult as X,isPowerShellToolResult as z,isReadToolResult as Y,isToolCallEventType as q,isWriteToolResult as Q,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 Te,resolveModelScopeWithDiagnostics as de}from"./core/model-resolver.js";import{CredentialSynchronizationError as xe,ModelRuntime as fe}from"./core/model-runtime.js";import{DefaultPackageManager as ue}from"./core/package-manager.js";import{buildRuleSet as he,matchPermissionRules as Re,parsePermissionRule as Pe}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 Fe,loadProjectContextFiles as Oe}from"./core/resource-loader.js";import{detectSandboxAvailability as He,getProcessShellSandbox as ke,registerSandboxEscalationHandler as ve,resolveSandboxPolicy as be,SANDBOX_ENV as Ue,ShellSandbox as we}from"./core/sandbox/index.js";import{AgentSessionRuntime as Ge,createAgentSession as je,createAgentSessionFromServices as Ke,createAgentSessionRuntime as We,createAgentSessionServices as Xe,createBashTool as ze,createCodingTools as Ye,createEditTool as qe,createFindTool as Qe,createGrepTool as Je,createLsTool as Ze,createPowerShellTool as $e,createReadOnlyTools as eo,createReadTool as oo,createWriteTool as to}from"./core/sdk.js";import{buildContextEntries as no,buildSessionContext as io,buildSessionProjection as ao,CURRENT_SESSION_VERSION as so,getLatestCompactionEntry as lo,migrateSessionEntries as mo,parseSessionEntries as co,SessionManager as po,sessionEntryToContextMessages as So}from"./core/session-manager.js";import{SettingsManager as go}from"./core/settings-manager.js";import{formatSkillsForPrompt as fo,loadSkills as Eo,loadSkillsFromDir as uo}from"./core/skills.js";import{createSyntheticSourceInfo as ho}from"./core/source-info.js";import{generateDiffString as Po,generateUnifiedPatch as Do}from"./core/tools/edit-diff.js";import{createBashToolDefinition as Mo,createEditToolDefinition as Lo,createFindToolDefinition as _o,createGrepToolDefinition as yo,createLocalBashOperations as Io,createLocalPowerShellOperations as No,createLsToolDefinition as Fo,createPowerShellToolDefinition as Oo,createProcessToolDefinition as Bo,createReadToolDefinition as Ho,createWriteToolDefinition as ko,DEFAULT_MAX_BYTES as vo,DEFAULT_MAX_LINES as bo,formatSize as Uo,registerShellExecutionGuard as wo,truncateHead as Vo,truncateLine as Go,truncateTail as jo,withFileMutationQueue as Ko}from"./core/tools/index.js";import{hasTrustRequiringProjectResources as Xo,ProjectTrustStore as zo}from"./core/trust-manager.js";import{VIRTUAL_MODEL_STATE_ENTRY as qo}from"./core/virtual-models.js";import{applyShellEnvironmentPolicy as Jo,DEFAULT_SHELL_ENV_EXCLUDES as Zo,isDalCodeCredentialName as $o,withoutDalCodeCredentials as et}from"./dal/child-env.js";export*from"./dal/hooks/index.js";import{isHostExtensionPath as rt,markHostExtensionPaths as nt}from"./dal/host-extensions.js";import{createCodemodeExtension as at}from"./extensions/codemode/index.js";import{createMcpExtension as lt}from"./extensions/mcp/index.js";import{createToolSearchExtension as ct}from"./extensions/tool-search/index.js";import{main as St}from"./main.js";import{InteractiveMode as dt,RpcClient as gt,runPrintMode as xt,runRpcMode as ft}from"./modes/index.js";import{ArminComponent as ut,AssistantMessageComponent as Ct,BashExecutionComponent as ht,BorderedLoader as Rt,BranchSummaryMessageComponent as Pt,CompactionSummaryMessageComponent as Dt,CustomEditor as At,CustomMessageComponent as Mt,DynamicBorder as Lt,ExtensionEditorComponent as _t,ExtensionInputComponent as yt,ExtensionSelectorComponent as It,FooterComponent as Nt,keyHint as Ft,keyText as Ot,LoginDialogComponent as Bt,ModelSelectorComponent as Ht,OAuthSelectorComponent as kt,rawKeyHint as vt,renderDiff as bt,SessionSelectorComponent as Ut,SettingsSelectorComponent as wt,ShowImagesSelectorComponent as Vt,SkillInvocationMessageComponent as Gt,ThemeSelectorComponent as jt,ThinkingSelectorComponent as Kt,ToolExecutionComponent as Wt,TreeSelectorComponent as Xt,truncateToVisualLines as zt,UserMessageComponent as Yt,UserMessageSelectorComponent as qt}from"./modes/interactive/components/index.js";import{getLanguageFromPath as Jt,getMarkdownTheme as Zt,getSelectListTheme as $t,getSettingsListTheme as er,highlightCode as or,initTheme as tr,Theme as rr}from"./modes/interactive/theme/theme.js";import{copyToClipboard as ir}from"./utils/clipboard.js";import{parseFrontmatter as sr,stripFrontmatter as lr}from"./utils/frontmatter.js";import{convertToPng as cr}from"./utils/image-convert.js";import{formatDimensionNote as Sr,resizeImage as Tr}from"./utils/image-resize.js";import{detectSupportedImageMimeTypeFromFile as gr}from"./utils/mime.js";import{getPowerShellConfig as fr,getShellConfig as Er,getShellEnv as ur}from"./utils/shell.js";export{T as AgentSession,Ge as AgentSessionRuntime,ut as ArminComponent,Ct as AssistantMessageComponent,E as BackgroundProcessManager,ht as BashExecutionComponent,Rt as BorderedLoader,Pt as BranchSummaryMessageComponent,n as CONFIG_DIR_NAME,so as CURRENT_SESSION_VERSION,Dt as CompactionSummaryMessageComponent,xe as CredentialSynchronizationError,At as CustomEditor,Mt as CustomMessageComponent,D as DEFAULT_COMPACTION_SETTINGS,vo as DEFAULT_MAX_BYTES,bo as DEFAULT_MAX_LINES,Zo as DEFAULT_SHELL_ENV_EXCLUDES,ue as DefaultPackageManager,Fe as DefaultResourceLoader,Lt as DynamicBorder,_t as ExtensionEditorComponent,yt as ExtensionInputComponent,V as ExtensionRunner,It as ExtensionSelectorComponent,Nt 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,dt as InteractiveMode,Bt as LoginDialogComponent,u as MAX_BACKGROUND_PROCESSES,pe as ModelRegistry,fe as ModelRuntime,Ht as ModelSelectorComponent,kt as OAuthSelectorComponent,zo as ProjectTrustStore,gt as RpcClient,Ue as SANDBOX_ENV,c as SHARED_SKILL_CONFIG_DIRS,po as SessionManager,Ut as SessionSelectorComponent,go as SettingsManager,wt as SettingsSelectorComponent,we as ShellSandbox,Vt as ShowImagesSelectorComponent,Gt as SkillInvocationMessageComponent,rr as Theme,jt as ThemeSelectorComponent,Kt as ThinkingSelectorComponent,Wt as ToolExecutionComponent,Xt as TreeSelectorComponent,Yt as UserMessageComponent,qt as UserMessageSelectorComponent,p as VERSION,qo as VIRTUAL_MODEL_STATE_ENTRY,Jo as applyShellEnvironmentPolicy,no as buildContextEntries,ye as buildProjectMap,he as buildRuleSet,io as buildSessionContext,ao as buildSessionProjection,h as calculateContextTokens,R as collectEntriesForBranchSummary,P as compact,me as convertToLlm,cr as convertToPng,ir as copyToClipboard,je as createAgentSession,Ke as createAgentSessionFromServices,We as createAgentSessionRuntime,Xe as createAgentSessionServices,ze as createBashTool,Mo as createBashToolDefinition,at as createCodemodeExtension,Ye as createCodingTools,qe as createEditTool,Lo as createEditToolDefinition,k as createEventBus,b as createExtensionRuntime,Qe as createFindTool,_o as createFindToolDefinition,Je as createGrepTool,yo as createGrepToolDefinition,Io as createLocalBashOperations,No as createLocalPowerShellOperations,Ze as createLsTool,Fo as createLsToolDefinition,lt as createMcpExtension,$e as createPowerShellTool,Oo as createPowerShellToolDefinition,Bo as createProcessToolDefinition,eo as createReadOnlyTools,oo as createReadTool,Ho as createReadToolDefinition,ho as createSyntheticSourceInfo,ct as createToolSearchExtension,to as createWriteTool,ko as createWriteToolDefinition,U as defineTool,He as detectSandboxAvailability,gr as detectSupportedImageMimeTypeFromFile,w as discoverAndLoadExtensions,A as estimateTokens,Ae as evaluateToolPolicy,M as findCutPoint,L as findTurnStartIndex,Sr as formatDimensionNote,Ie as formatProjectMapPrompt,Uo as formatSize,fo as formatSkillsForPrompt,_ as generateBranchSummary,Po as generateDiffString,y as generateSummary,I as generateSummaryWithUsage,Do as generateUnifiedPatch,i as getAgentDir,a as getDocsPath,s as getExamplesPath,ee as getHostCapabilities,Jt as getLanguageFromPath,N as getLastAssistantUsage,lo as getLatestCompactionEntry,Zt as getMarkdownTheme,l as getPackageDir,fr as getPowerShellConfig,ke as getProcessShellSandbox,m as getReadmePath,$t as getSelectListTheme,er as getSettingsListTheme,Er as getShellConfig,ur as getShellEnv,Xo as hasTrustRequiringProjectResources,or as highlightCode,tr as initTheme,G as isBashToolResult,$o as isDalCodeCredentialName,j as isEditToolResult,K as isFindToolResult,W as isGrepToolResult,rt as isHostExtensionPath,X as isLsToolResult,z as isPowerShellToolResult,Y as isReadToolResult,q as isToolCallEventType,Q as isWriteToolResult,Ft as keyHint,Ot as keyText,Oe as loadProjectContextFiles,Eo as loadSkills,uo as loadSkillsFromDir,St as main,nt as markHostExtensionPaths,Re as matchPermissionRules,mo as migrateSessionEntries,t as parseArgs,sr as parseFrontmatter,se as parseHostCapabilities,Pe as parsePermissionRule,co as parseSessionEntries,d as parseSkillBlock,F as prepareBranchEntries,vt as rawKeyHint,Me as readAccessDenial,x as readStoredCredential,Le as registerPermissionAskHandler,ve as registerSandboxEscalationHandler,wo as registerShellExecutionGuard,bt as renderDiff,Tr as resizeImage,Te as resolveCliModel,de as resolveModelScopeWithDiagnostics,be as resolveSandboxPolicy,xt as runPrintMode,ft as runRpcMode,O as serializeConversation,So as sessionEntryToContextMessages,B as shouldCompact,lr as stripFrontmatter,Vo as truncateHead,Go as truncateLine,jo as truncateTail,zt as truncateToVisualLines,Ko as withFileMutationQueue,et 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 l=
|
|
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(oo,"runAuthCommand");async function so(e,t){if(e.fileArgs.length===0)return me({parsed:e,stdinContent:t});const{text:s,images:l}=await tt(e.fileArgs,{autoResizeImages:!1});return me({parsed:e,fileText:s,fileImages:l,stdinContent:t})}m(so,"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:we(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 no(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(no,"promptConfirm");function io(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(io,"validateForkFlags");function ro(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(ro,"validateSessionIdFlags");function ao(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(ao,"openSessionOrExit");function ye(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(ye,"forkSessionOrExit");async function lo(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 ye(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 ao(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 no(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)),ye(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{$()}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(lo,"createSessionManager");function co(e,t,s,l,n){const a={},p=[];let o=!1;if(e.provider&&!e.model&&p.push({type:"error",message:`--provider requires --model (for example: --provider ${e.provider} --model <pattern>)`}),e.model){const i=St({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(),M=n.getDefaultModel(),A=i&&M?l.getModel(i,M):void 0,S=A?t.find(x=>$e(x.model,A)):void 0;S?(a.model=S.model,!e.thinking&&S.thinkingLevel&&(a.thinkingLevel=S.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(co,"buildSessionOptions");function L(e,t){return t?.map(s=>Yt(s)?we(s,e):s)}m(L,"resolveCliPaths");async function mo(e,t){return at(t,Ct(e),[{label:"Continue",value:e.fallbackCwd},{label:"Cancel",value:void 0}])}m(mo,"promptForMissingSessionCwd");async function ts(e,t){Et();const s=[..._t,...t?.extensionFactories??[]],l=e.includes("--offline")||xe(process.env.PI_OFFLINE);if(l&&(process.env.PI_OFFLINE="1",process.env.PI_SKIP_VERSION_CHECK="1"),await oo(e))return;process.platform==="win32"&&Jt(mt()),Ut();const n=process.cwd(),a=dt(),p=K.create(n,a,{projectTrusted:!1});if(fe(p.getGlobalSettings().httpProxy),Lt(),Rt(),Ot(),pe(),await zt(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;if(e[0]==="mcp"){const{runMcpCommand:r}=await Nt();process.exitCode=await r(e.slice(1),{cwd:n,agentDir:a});return}const o=de(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 wt(o.export,f)}catch(f){const E=f instanceof Error?f.message:c("\u5BFC\u51FA\u4F1A\u8BDD\u5931\u8D25");console.error(d.red(u(c("\u9519\u8BEF\uFF1A{message}"),{message:E}))),process.exit(1)}console.log(u(c("\u5DF2\u5BFC\u51FA\u5230\uFF1A{path}"),{path:r})),process.exit(0)}let i=Zt(o,process.stdin.isTTY,process.stdout.isTTY);i!=="interactive"&&!to(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)),io(o),ro(o);const{migratedAuthProviders:A,deprecationWarnings:S}=Dt(n);h("runMigrations");const x=K.create(n,a),j=ge(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 U=process.env[lt],V=(o.sessionDir?Gt(o.sessionDir):void 0)??(U?ct(U):void 0)??x.getSessionDir();let y=await lo(o,n,V,x);const b=It(y,n);if(b)if(i==="interactive"){const r=await mo(b,x);r||process.exit(0),y=g.open(b.sessionFile,V,r)}else console.error(d.red(new At(b).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)),y.appendSessionInfo(r)}h("createSessionManager");const z=new Ft(a),Y=y.getCwd(),Te=o.projectTrustOverride===void 0&&!ve(Y)?Y:void 0,G=o.help||o.listModels!==void 0?"print":i,J=new Map,Me=[...jt(),...L(n,o.extensions)??[]],Pe=L(n,o.skills),ke=L(n,o.promptTemplates),Ce=L(n,o.themes),Ie=m(async({cwd:r,agentDir:f,sessionManager:E,sessionStartEvent:se,projectTrustContext:Re})=>{const ne=se===void 0,ie=[],re=J.get(r),ae=ve(r),le=o.projectTrustOverride===void 0&&re===void 0&&ae,Le=le?!1:re??o.projectTrustOverride??(!ae||z.get(r)===!0),je=K.create(r,f,{projectTrusted:Le}),F=await gt({cwd:r,agentDir:f,settingsManager:je,modelRuntimeSignal:AbortSignal.timeout(15e3),extensionFlagValues:o.unknownFlags,resourceLoaderReloadOptions:le?{resolveProjectTrust:m(async({extensionsResult:C})=>{const T=await kt({cwd:r,trustStore:z,trustOverride:o.projectTrustOverride,defaultProjectTrust:x.getDefaultProjectTrust(),extensionsResult:C,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,T),T},"resolveProjectTrust")}:void 0,resourceLoaderOptions:{additionalExtensionPaths:Me,additionalSkillPaths:Pe,additionalPromptTemplatePaths:ke,additionalThemePaths:Ce,noExtensions:o.noExtensions,disabledBuiltinExtensions:o.noMcp?["mcp"]:void 0,noSkills:o.noSkills,noPromptTemplates:o.noPromptTemplates,noThemes:o.noThemes,noContextFiles:o.noContextFiles,systemPrompt:o.systemPrompt,appendSystemPrompt:o.appendSystemPrompt,extensionFactories:s}}),{settingsManager:N,modelRuntime:D,resourceLoader:ce}=F,R=[...ie,...F.diagnostics,...ge(N),...ce.getExtensions().errors.map(({path:C,error:T})=>({type:"error",message:`Failed to load extension "${C}": ${T}`})),...(ce.getExtensions().warnings??[]).map(({path:C,warning:T})=>({type:"warning",message:`Extension package "${C}": ${T}`}))],H=o.models??N.getEnabledModels(),Oe=H&&H.length>0?await yt(H,D,{signal:AbortSignal.timeout(15e3)}):[],{options:v,cliThinkingFromModel:_e,diagnostics:Ne}=co(o,Oe,E.buildSessionContext().messages.length>0,D,N);R.push(...Ne),o.apiKey&&(v.model?await D.setRuntimeApiKey(v.model.provider,o.apiKey):R.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:F,sessionManager:E,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 k=P.session.getSandboxStatus();return k&&k.level!=="off"&&!k.enforced&&R.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:k.level,reason:k.unavailableReason??""})}),{...P,services:F,diagnostics:R}},"createRuntime");h("createRuntime");const w=await ft(Ie,{cwd:y.getCwd(),agentDir:a,sessionManager:y});h("createAgentSessionRuntime");const{services:Ae,session:be,modelFallbackMessage:Ee}=w,{settingsManager:O,modelRuntime:Q,resourceLoader:Fe}=Ae;if(fe(O.getGlobalSettings().httpProxy),pe(O.getHttpIdleTimeoutMs()),o.help){W(j);const r=Fe.getExtensions().extensions.flatMap(f=>Array.from(f.flags.values()));qe(r),process.exit(0)}if(o.listModels!==void 0){W(he([...j,...w.diagnostics]));const r=typeof o.listModels=="string"?o.listModels:void 0;await ot(Q,r,AbortSignal.timeout(15e3)),process.exit(0)}let _;i!=="rpc"&&i!=="acp"&&(_=await Xt(),_!==void 0&&i==="interactive"&&(i="print")),h("readPipedStdin");const{initialMessage:X,initialImages:Z}=await so(o,_);h("prepareInitialMessage"),qt(O.getTheme(),i==="interactive"),h("initTheme"),i==="interactive"&&S.length>0&&await Ht(S),h("resolveModelScope");const ee=he([...j,...w.diagnostics]),te=w.diagnostics.some(r=>r.type==="error");(i!=="interactive"||te)&&W(ee),te&&(w.diagnostics.some(r=>r.message.includes("Failed to load extension"))&&console.error(d.yellow(Qt())),process.exit(1)),h("createAgentSession"),i!=="interactive"&&!be.model&&(console.error(d.red(ht())),process.exit(1));const oe=xe(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")I(),await Wt(w);else if(i==="acp")I(),await Kt(w);else if(i==="interactive"){const r=new Bt(w,{migratedProviders:A,startupDiagnostics:ee,modelFallbackMessage:Ee,autoTrustOnReloadCwd:Te,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(),$(),I(),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}I(),await r.run()}else{I();const r=await $t(w,{mode:eo(i),messages:o.messages,initialMessage:X,initialImages:Z});$(),Mt(),r!==0&&(process.exitCode=r);return}}m(ts,"main");export{lo as createSessionManager,ts as main};
|
|
1
|
+
var Ke=Object.defineProperty;var m=(e,t)=>Ke(e,"name",{value:t,configurable:!0});import{createInterface as $e}from"node:readline";import{modelsAreEqual as We}from"@earendil-works/pi-ai";import d from"chalk";import{normalizeSessionName as qe,parseArgs as me,printHelp as Ue}from"./cli/args.js";import{checkProviderAuth as Ve,createAuthCheckModelRuntime as ze,getProviderCredential as Ye}from"./cli/auth-check.js";import{AuthCommandError as B,getAuthCommandName as Ge,getAuthCommandUsage as Je,isAuthCommandHelp as Qe,parseAuthCommand as Xe,printAuthCommandHelp as Ze,validateAuthCommandArgs as et}from"./cli/auth-command.js";import{resolveCredentialForPrint as tt}from"./cli/credential-print.js";import{processFileArguments as ot}from"./cli/file-processor.js";import{buildInitialMessage as ue}from"./cli/initial-message.js";import{listModels as st}from"./cli/list-models.js";import{createProjectTrustContext as nt}from"./cli/project-trust.js";import{selectSession as it}from"./cli/session-picker.js";import{shouldRunFirstTimeSetup as rt,showFirstTimeSetup as at,showStartupSelector as lt}from"./cli/startup-ui.js";import{APP_NAME as fe,ENV_SESSION_DIR as ct,expandTildePath as dt,getAgentDir as mt,getPackageDir as ut,VERSION as ft}from"./config.js";import{createAgentSessionRuntime as pt}from"./core/agent-session-runtime.js";import{createAgentSessionFromServices as gt,createAgentSessionServices as ht}from"./core/agent-session-services.js";import{formatNoModelsAvailableMessage as vt}from"./core/auth-guidance.js";import{AuthStorage as xt,ReadOnlyAuthStorage as wt}from"./core/auth-storage.js";import{exportFromFile as St}from"./core/export-html/index.js";import{applyHttpProxySettings as pe,configureHttpDispatcher as ge}from"./core/http-dispatcher.js";import{resolveCliModel as yt,resolveModelScope as Tt}from"./core/model-resolver.js";import{ModelRuntime as Pt}from"./core/model-runtime.js";import{restoreStdout as Mt,takeOverStdout as kt}from"./core/output-guard.js";import{resolveProjectTrusted as Ct}from"./core/project-trust.js";import{formatMissingSessionCwdPrompt as It,getMissingSessionCwdIssue as At,MissingSessionCwdError as bt}from"./core/session-cwd.js";import{assertValidSessionId as Et,SessionManager as g}from"./core/session-manager.js";import{collectSettingsDiagnostics as he,deduplicateDiagnostics as ve}from"./core/settings-diagnostics.js";import{SettingsManager as K}from"./core/settings-manager.js";import{printTimings as I,resetTimings as Ft,time as h}from"./core/timings.js";import{hasTrustRequiringProjectResources as xe,ProjectTrustStore as Rt}from"./core/trust-manager.js";import{applyDalEnvApiKeyPolicy as Lt,applyDalSystemProxyFallback as jt,dalBuiltinExtensionPaths as Ot}from"./dal/builtins.js";import{markHostExtensionPaths as _t}from"./dal/host-extensions.js";import{fill as u,t as c}from"./dal/i18n.js";import{installDalShellSafetyNet as Nt}from"./dal/safety-net.js";import{builtInExtensions as Dt}from"./extensions/index.js";import{loadMcpCommand as Ht}from"./extensions/mcp/cli.lazy.js";import{runMigrations as Bt,showDeprecationWarnings as Kt}from"./migrations.js";import{InteractiveMode as $t,runAcpMode as Wt,runPrintMode as qt,runRpcMode as Ut}from"./modes/index.js";import{initTheme as Vt,stopThemeWatcher as $}from"./modes/interactive/theme/theme.js";import{cleanupManagedInstall as zt,handleConfigCommand as Yt,handlePackageCommand as Gt}from"./package-manager-cli.js";import{isTruthyEnvFlag as we}from"./utils/offline.js";import{isLocalPath as Jt,normalizePath as Qt,resolvePath as Se}from"./utils/paths.js";import{cleanupWindowsSelfUpdateQuarantine as Xt}from"./utils/windows-self-update.js";const Zt=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:fe}),"extensionLoadFailureHint");async function eo(){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(eo,"readPipedStdin");function W(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(W,"reportDiagnostics");function to(e,t,s){return e.mode==="rpc"?"rpc":e.mode==="acp"?"acp":e.mode==="json"?"json":e.print||!t||!s?"print":"interactive"}m(to,"resolveAppMode");function oo(e){return e==="json"?"json":"text"}m(oo,"toPrintOutputMode");function so(e){return!e.print&&e.mode===void 0&&(e.help===!0||e.listModels!==void 0)}m(so,"isPlainRuntimeMetadataCommand");async function no(e){if(Qe(e))return Ze(),!0;let t;try{t=Xe(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=me(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:Ge(t.kind)}))),console.error(d.dim(u(c("\u8BF7\u67E5\u770B\u300C{app} --help\u300D\u6216\u300C{usage}\u300D\u3002"),{app:fe,usage:Je(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 Pt.create({allowModelNetwork:!1,signal:o}),P=await tt(s,i,t.kind,t.minExpiryMs,o);return process.stdout.write(`${P}
|
|
3
|
+
`),!0}const l=et(s,t.kind);let n,a;try{const o=t.noRefresh?new wt:xt.create(),i=await ze(o);n=await Ve(s,i,{refresh:!t.noRefresh}),t.credentials&&n.status==="ready"&&(a=await Ye(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(no,"runAuthCommand");async function io(e,t){if(e.fileArgs.length===0)return ue({parsed:e,stdinContent:t});const{text:s,images:l}=await ot(e.fileArgs,{autoResizeImages:!1});return ue({parsed:e,fileText:s,fileImages:l,stdinContent:t})}m(io,"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 ye(e,t,s){if(e.includes("/")||e.includes("\\")||e.endsWith(".jsonl"))return{type:"path",path:Se(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(ye,"resolveSessionPath");async function ro(e){return new Promise(t=>{const s=$e({input:process.stdin,output:process.stdout});s.question(`${e} [y/N] `,l=>{s.close(),t(l.toLowerCase()==="y"||l.toLowerCase()==="yes")})})}m(ro,"promptConfirm");function ao(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(ao,"validateForkFlags");function lo(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{Et(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(lo,"validateSessionIdFlags");function co(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(co,"openSessionOrExit");function Te(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(Te,"forkSessionOrExit");async function mo(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 ye(e.fork,t,s);switch(n.type){case"path":case"local":case"global":return Te(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 ye(e.session,t,s);switch(n.type){case"path":case"local":return co(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 ro(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)),Te(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 it((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{$()}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(mo,"createSessionManager");function uo(e,t,s,l,n){const a={},p=[];let o=!1;if(e.provider&&!e.model&&p.push({type:"error",message:`--provider requires --model (for example: --provider ${e.provider} --model <pattern>)`}),e.model){const i=yt({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(),P=n.getDefaultModel(),A=i&&P?l.getModel(i,P):void 0,S=A?t.find(x=>We(x.model,A)):void 0;S?(a.model=S.model,!e.thinking&&S.thinkingLevel&&(a.thinkingLevel=S.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(uo,"buildSessionOptions");function L(e,t){return t?.map(s=>Jt(s)?Se(s,e):s)}m(L,"resolveCliPaths");async function fo(e,t){return lt(t,It(e),[{label:"Continue",value:e.fallbackCwd},{label:"Cancel",value:void 0}])}m(fo,"promptForMissingSessionCwd");async function ns(e,t){Ft();const s=[...Dt,...t?.extensionFactories??[]],l=e.includes("--offline")||we(process.env.PI_OFFLINE);if(l&&(process.env.PI_OFFLINE="1",process.env.PI_SKIP_VERSION_CHECK="1"),await no(e))return;process.platform==="win32"&&Xt(ut()),zt();const n=process.cwd(),a=mt(),p=K.create(n,a,{projectTrusted:!1});if(pe(p.getGlobalSettings().httpProxy),jt(),Lt(),Nt(),ge(),await Gt(e,{extensionFactories:s})){const r=process.exitCode??0;if(process.platform==="win32"&&r===0&&e[0]==="update")return;process.exit(r);return}if(await Yt(e,{extensionFactories:s}))return;if(e[0]==="mcp"){const{runMcpCommand:r}=await Ht();process.exitCode=await r(e.slice(1),{cwd:n,agentDir:a});return}const o=me(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(ft),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 E=f instanceof Error?f.message:c("\u5BFC\u51FA\u4F1A\u8BDD\u5931\u8D25");console.error(d.red(u(c("\u9519\u8BEF\uFF1A{message}"),{message:E}))),process.exit(1)}console.log(u(c("\u5DF2\u5BFC\u51FA\u5230\uFF1A{path}"),{path:r})),process.exit(0)}let i=to(o,process.stdin.isTTY,process.stdout.isTTY);i!=="interactive"&&!so(o)&&kt(),(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)),ao(o),lo(o);const{migratedAuthProviders:A,deprecationWarnings:S}=Bt(n);h("runMigrations");const x=K.create(n,a),j=he(x);i==="interactive"&&!o.help&&o.listModels===void 0&&rt()&&(await at(x),h("firstTimeSetup")),i==="interactive"&&o.useTheme!==void 0&&x.applyOverrides({theme:o.useTheme});const U=process.env[ct],V=(o.sessionDir?Qt(o.sessionDir):void 0)??(U?dt(U):void 0)??x.getSessionDir();let y=await mo(o,n,V,x);const b=At(y,n);if(b)if(i==="interactive"){const r=await fo(b,x);r||process.exit(0),y=g.open(b.sessionFile,V,r)}else console.error(d.red(new bt(b).message)),process.exit(1);if(o.name!==void 0){const r=qe(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(),Pe=o.projectTrustOverride===void 0&&!xe(Y)?Y:void 0,G=o.help||o.listModels!==void 0?"print":i,J=new Map,Q=L(n,o.extensions)??[];_t(Q);const Me=[...Ot(),...Q],ke=L(n,o.skills),Ce=L(n,o.promptTemplates),Ie=L(n,o.themes),Ae=m(async({cwd:r,agentDir:f,sessionManager:E,sessionStartEvent:ne,projectTrustContext:Le})=>{const ie=ne===void 0,re=[],ae=J.get(r),le=xe(r),ce=o.projectTrustOverride===void 0&&ae===void 0&&le,je=ce?!1:ae??o.projectTrustOverride??(!le||z.get(r)===!0),Oe=K.create(r,f,{projectTrusted:je}),F=await ht({cwd:r,agentDir:f,settingsManager:Oe,modelRuntimeSignal:AbortSignal.timeout(15e3),extensionFlagValues:o.unknownFlags,resourceLoaderReloadOptions:ce?{resolveProjectTrust:m(async({extensionsResult:C})=>{const T=await Ct({cwd:r,trustStore:z,trustOverride:o.projectTrustOverride,defaultProjectTrust:x.getDefaultProjectTrust(),extensionsResult:C,projectTrustContext:Le??nt({cwd:r,mode:ie?G:i,settingsManager:x,hasUI:ie&&G==="interactive"}),onExtensionError:m(Be=>re.push({type:"warning",message:Be}),"onExtensionError")});return J.set(r,T),T},"resolveProjectTrust")}:void 0,resourceLoaderOptions:{additionalExtensionPaths:Me,additionalSkillPaths:ke,additionalPromptTemplatePaths:Ce,additionalThemePaths:Ie,noExtensions:o.noExtensions,disabledBuiltinExtensions:o.noMcp?["mcp"]:void 0,noSkills:o.noSkills,noPromptTemplates:o.noPromptTemplates,noThemes:o.noThemes,noContextFiles:o.noContextFiles,systemPrompt:o.systemPrompt,appendSystemPrompt:o.appendSystemPrompt,extensionFactories:s}}),{settingsManager:N,modelRuntime:D,resourceLoader:de}=F,R=[...re,...F.diagnostics,...he(N),...de.getExtensions().errors.map(({path:C,error:T})=>({type:"error",message:`Failed to load extension "${C}": ${T}`})),...(de.getExtensions().warnings??[]).map(({path:C,warning:T})=>({type:"warning",message:`Extension package "${C}": ${T}`}))],H=o.models??N.getEnabledModels(),_e=H&&H.length>0?await Tt(H,D,{signal:AbortSignal.timeout(15e3)}):[],{options:v,cliThinkingFromModel:Ne,diagnostics:De}=uo(o,_e,E.buildSessionContext().messages.length>0,D,N);R.push(...De),o.apiKey&&(v.model?await D.setRuntimeApiKey(v.model.provider,o.apiKey):R.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 M=await gt({services:F,sessionManager:E,sessionStartEvent:ne,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}),He=o.thinking!==void 0||Ne;M.session.model&&He&&M.session.setThinkingLevel(M.session.thinkingLevel);const k=M.session.getSandboxStatus();return k&&k.level!=="off"&&!k.enforced&&R.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:k.level,reason:k.unavailableReason??""})}),{...M,services:F,diagnostics:R}},"createRuntime");h("createRuntime");const w=await pt(Ae,{cwd:y.getCwd(),agentDir:a,sessionManager:y});h("createAgentSessionRuntime");const{services:be,session:Ee,modelFallbackMessage:Fe}=w,{settingsManager:O,modelRuntime:X,resourceLoader:Re}=be;if(pe(O.getGlobalSettings().httpProxy),ge(O.getHttpIdleTimeoutMs()),o.help){W(j);const r=Re.getExtensions().extensions.flatMap(f=>Array.from(f.flags.values()));Ue(r),process.exit(0)}if(o.listModels!==void 0){W(ve([...j,...w.diagnostics]));const r=typeof o.listModels=="string"?o.listModels:void 0;await st(X,r,AbortSignal.timeout(15e3)),process.exit(0)}let _;i!=="rpc"&&i!=="acp"&&(_=await eo(),_!==void 0&&i==="interactive"&&(i="print")),h("readPipedStdin");const{initialMessage:Z,initialImages:ee}=await io(o,_);h("prepareInitialMessage"),Vt(O.getTheme(),i==="interactive"),h("initTheme"),i==="interactive"&&S.length>0&&await Kt(S),h("resolveModelScope");const te=ve([...j,...w.diagnostics]),oe=w.diagnostics.some(r=>r.type==="error");(i!=="interactive"||oe)&&W(te),oe&&(w.diagnostics.some(r=>r.message.includes("Failed to load extension"))&&console.error(d.yellow(Zt())),process.exit(1)),h("createAgentSession"),i!=="interactive"&&!Ee.model&&(console.error(d.red(vt())),process.exit(1));const se=we(process.env.PI_STARTUP_BENCHMARK);if(se&&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);X.refresh({signal:r.signal}).catch(()=>{}).finally(()=>clearTimeout(f))}if(i==="rpc")I(),await Ut(w);else if(i==="acp")I(),await Wt(w);else if(i==="interactive"){const r=new $t(w,{migratedProviders:A,startupDiagnostics:te,modelFallbackMessage:Fe,autoTrustOnReloadCwd:Pe,initialMessage:Z,initialImages:ee,initialMessages:o.messages,verbose:o.verbose,tuiMode:o.tuiMode,initialThemeSetting:o.useTheme});if(se){await r.init(),h("interactiveMode.init"),await new Promise(f=>setTimeout(f,150)),r.stop(),$(),I(),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}I(),await r.run()}else{I();const r=await qt(w,{mode:oo(i),messages:o.messages,initialMessage:Z,initialImages:ee});$(),Mt(),r!==0&&(process.exitCode=r);return}}m(ns,"main");export{mo as createSessionManager,ns as main};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dalcode/dal-bridge",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.32",
|
|
4
4
|
"private": true,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
]
|
|
19
19
|
},
|
|
20
20
|
"dependencies": {
|
|
21
|
-
"@dalcode/dal-pi-kit": "1.0.
|
|
21
|
+
"@dalcode/dal-pi-kit": "1.0.32",
|
|
22
22
|
"typebox": "1.3.7"
|
|
23
23
|
},
|
|
24
24
|
"peerDependencies": {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var j=Object.defineProperty;var A=(o,F)=>j(o,"name",{value:F,configurable:!0});var H=Object.defineProperty,d=A((o,F)=>H(o,"name",{value:F,configurable:!0}),"d");import{t}from"@dalcode/dal-pi-kit";import{getProcessShellSandbox as R,registerPermissionAskHandler as q,registerSandboxEscalationHandler as V}from"@earendil-works/pi-coding-agent";import{Type as m}from"typebox";import{AskUserInputError as W,askUserSchema as G,buildAskUserRequest as z,describeAnswers as J,THUMBNAIL_CHANNEL as K}from"./ask-user.js";import{askUserTimeoutMs as Q,BridgeClient as X,planTimeoutMs as Y,readBridgeConfig as Z,readSubagentAttribution as uu}from"./client.js";const eu=m.Object({goal:m.String({description:t("\u8FD9\u4E2A\u8BA1\u5212\u8981\u8FBE\u6210\u4EC0\u4E48\uFF0C\u4E00\u53E5\u8BDD\u8BF4\u660E")}),reasoning:m.Optional(m.String({description:t("\u4E3A\u4EC0\u4E48\u9009\u8FD9\u4E2A\u65B9\u6848")})),steps:m.Array(m.Object({title:m.String({description:t("\u8FD9\u4E00\u6B65\u505A\u4EC0\u4E48")}),description:m.Optional(m.String({description:t("\u8FD9\u4E00\u6B65\u7684\u7EC6\u8282")}))}),{description:t("\u6309\u987A\u5E8F\u6392\u5217\u7684\u6267\u884C\u6B65\u9AA4")})}),tu=new Set(["read","grep","ripgrep","find","fd","ls","glob","todo_read","todo","lsp","terminal_read","review_report"]),ou=new Set(["read","grep","ripgrep","find","fd","ls","glob","lsp"]),S="DALCODE_BRIDGE_EVALUATE_READ_TOOLS",ru="submit_plan",I="ask_user";function x(o){return o.scope==="session"?"session":"once"}A(x,"ee"),d(x,"escalationScope");function k(o){const F=o.grant,p=d(l=>Array.isArray(l)?l.filter(E=>typeof E=="string"&&E.length>0):[],"list"),n=p(F?.allowDomains),s=p(F?.allowWrite);return{approved:!0,scope:x(o),...n.length>0||s.length>0?{grant:{allowDomains:n,allowWrite:s}}:{}}}A(k,"h"),d(k,"escalationApproval");function _(o){const F=o.input;for(const p of["command","file_path","path","filePath"]){const n=F[p];if(typeof n=="string"&&n.length>0)return n}}A(_,"R"),d(_,"ruleContentFor");function N(o,F){const p=o.input,n=o.toolName==="process";if(o.toolName!=="bash"&&!(n&&p.action==="start")||typeof p.command!="string"||p.command.length===0)return;const s=R(),l=s?.planNetworkEscalation({command:p.command,cwd:F.cwd});if(!(!s||!l))return{toolCallId:o.toolCallId,toolName:o.toolName,command:p.command,cwd:F.cwd,level:s.level,mode:"allow",justification:l.justification,allowDomains:l.allow_domains,allowWrite:[],background:n,trigger:l.trigger}}A(N,"ne"),d(N,"plannedNetworkEscalation");let g,T=!1,B,P=!1;function L(o,F){const p=Z();if(!p)return;const n=new X(p,F),s=uu();function l(u){const e=u.sessionManager.getSessionId();return s?{sessionId:s.parentSessionId,subagent:{id:s.subagentId,sessionId:e,...s.parentTaskId?{parentTaskId:s.parentTaskId}:{},...s.parentSubagentId?{parentSubagentId:s.parentSubagentId}:{},...s.label?{label:s.label}:{}}}:{sessionId:e}}A(l,"c"),d(l,"caller");let E,b=0;function f(u){const e=u.model;return{provider:e?.provider??"unknown",model:e?.id??e?.name??"unknown"}}A(f,"_"),d(f,"describeModel");const w=new Map,C=new Set,O=process.env[S]==="1";o.on("tool_call",async(u,e)=>{const r=ou.has(u.toolName);if((r?!O:tu.has(u.toolName))||u.toolName===ru||u.toolName===I)return;const i=u.input.sandbox_escalation,c=i?void 0:N(u,e),a=await n.post("/api/internal/pi-bridge/permission",{...l(e),toolName:u.toolName,toolInput:u.input,ruleContent:_(u),...i||c?{category:"sandbox_escalation"}:{},...c?{sandboxEscalation:c}:{},...r?{readOnly:!0}:{}});if(!a)return{block:!0,reason:t("dal-bridge\uFF1A\u65E0\u6CD5\u8054\u7CFB DAL Code \u53D6\u5F97\u6388\u6743\uFF0C\u5DF2\u62D2\u7EDD\u6267\u884C\u3002")};if(a.decision==="deny")return{block:!0,reason:a.message??t("dal-bridge\uFF1A\u7528\u6237\u5DF2\u62D2\u7EDD\u8BE5\u64CD\u4F5C\u3002")};(i||c)&&w.set(u.toolCallId,k(a)),C.add(u.toolCallId),C.size>1e3&&C.delete(C.values().next().value)});const y=d(async(u,e)=>{if(C.delete(u.toolCallId))return{approved:!0};const r=await n.post("/api/internal/pi-bridge/permission",{...l(e),toolName:u.toolName,toolInput:u.input,ruleContent:_({input:u.input}),category:"permission_rule",rule:u.rule,ruleSource:u.source});return r?r.decision==="allow"?{approved:!0}:{approved:!1,message:r.message??t("dal-bridge\uFF1A\u7528\u6237\u5DF2\u62D2\u7EDD\u8BE5\u64CD\u4F5C\u3002")}:{approved:!1,message:t("dal-bridge\uFF1A\u65E0\u6CD5\u8054\u7CFB DAL Code \u53D6\u5F97\u6388\u6743\uFF0C\u5DF2\u62D2\u7EDD\u6267\u884C\u3002")}},"approveRule");B=y,P||(q((u,e)=>B?.(u,e)),P=!0);const h=d(async(u,e)=>{const r=w.get(u.toolCallId);if(r)return w.delete(u.toolCallId),r;if(!e)return;const i=await n.post("/api/internal/pi-bridge/permission",{...l(e),toolName:u.toolName,toolInput:{command:u.command},ruleContent:u.command,category:"sandbox_escalation",sandboxEscalation:u});return i?i.decision==="allow"?k(i):{approved:!1,message:i.message??t("dal-bridge\uFF1A\u7528\u6237\u5DF2\u62D2\u7EDD\u8BE5\u64CD\u4F5C\u3002")}:{approved:!1,message:t("dal-bridge\uFF1A\u65E0\u6CD5\u8054\u7CFB DAL Code \u53D6\u5F97\u6388\u6743\uFF0C\u5DF2\u62D2\u7EDD\u6267\u884C\u3002")}},"approveEscalation");g=h,T||(V((u,e)=>g?.(u,e)),T=!0),o.on("session_shutdown",()=>{g===h&&(g=void 0),B===y&&(B=void 0)}),o.on("after_provider_response",(u,e)=>{u.status>=400?E={...f(e),reason:`HTTP ${u.status}`}:(E=void 0,b=0)}),o.on("before_provider_request",async(u,e)=>{if(!E)return;const r=f(e);if(r.provider===E.provider&&r.model===E.model)return;b+=1;const i={provider:E.provider,model:E.model},c=E.reason;E=void 0,await n.post("/api/internal/pi-bridge/provider-fallback",{...l(e),from:i,to:r,reason:c,attempt:b,blocked:!0});const a=new Error(t("dal-bridge\uFF1A\u8BF7\u6C42\u5931\u8D25\u540E\u4E0D\u5141\u8BB8\u81EA\u52A8\u6362\u6A21\u578B\u3002")+` ${i.provider}/${i.model} \u2192 ${r.provider}/${r.model} (${c})`);throw a.name="ProviderSwapAborted",a}),o.registerTool({name:"submit_plan",label:t("\u63D0\u4EA4\u8BA1\u5212\u5F85\u5BA1\u6279"),description:t(t("\u5728\u52A8\u624B\u6539\u52A8\u4E4B\u524D\uFF0C\u628A\u8BA1\u5212\u63D0\u4EA4\u7ED9\u7528\u6237\u5BA1\u6279\u3002\u8FD4\u56DE\u662F\u5426\u7EE7\u7EED\u6267\u884C\uFF0C\u4EE5\u53CA\u7528\u6237\u7ED9\u51FA\u7684\u53CD\u9988\u3002")+t("\u5F53\u4EFB\u52A1\u662F\u591A\u6B65\u9AA4\u7684\u3001\u6216\u4F1A\u6539\u52A8\u591A\u4E2A\u6587\u4EF6\u65F6\u4F7F\u7528\u3002")),promptSnippet:t("submit_plan - \u591A\u6B65\u9AA4\u4EFB\u52A1\u52A8\u624B\u524D\u5148\u63D0\u4EA4\u8BA1\u5212\u5F85\u7528\u6237\u5BA1\u6279"),parameters:eu,execute:d(async(u,e,r,i,c)=>{const a=await n.post("/api/internal/pi-bridge/plan",{...l(c),goal:e.goal,reasoning:e.reasoning,steps:e.steps},{timeoutMs:Y()});return!a||a.decision==="cancel"?{content:[{type:"text",text:a?.feedback?`Plan not approved. User feedback: ${a.feedback}`:"Plan not approved. Stop and wait for further instructions."}],details:{approved:!1,...a?.feedback?{feedback:a.feedback}:{}}}:{content:[{type:"text",text:"Plan approved. Proceed with the steps."}],details:{approved:!0}}},"execute")});const U=d((u,e)=>{let r;return o.events.emit(K,{ref:u,...e!==void 0?{title:e}:{},reply:d(i=>{r=i},"reply")}),r},"resolveThumbnail");o.registerTool({name:I,label:t("\u8BE2\u95EE\u7528\u6237"),description:t("\u52A8\u624B\u505A PPT\u3001\u6587\u6863\u3001\u8868\u683C\u3001\u9875\u9762\u4E4B\u524D\uFF0C\u7528\u4E00\u5F20\u5361\u7247\u5411\u7528\u6237\u786E\u8BA4\u4F1A\u6539\u53D8\u4EA7\u51FA\u7684\u5173\u952E\u51B3\u5B9A\uFF08\u6700\u591A 3 \u9898\uFF09\u3002\u9898\u578B\uFF1Achoice \u9009\u9879\uFF08\u53EF\u5E26\u7F29\u7565\u56FE\uFF09\u3001swatch \u914D\u8272\u3001outline \u53EF\u6392\u5E8F\u5927\u7EB2\u3001slider \u6570\u503C\u3001text \u81EA\u7531\u6587\u672C\u3002\u6BCF\u9898\u90FD\u8981\u6709\u63A8\u8350\u9879\u3002"),promptSnippet:t("ask_user - \u5F00\u5DE5\u524D\u7528\u4E00\u5F20\u5361\u7247\u786E\u8BA4\u5173\u952E\u51B3\u5B9A\uFF08\u6700\u591A 3 \u9898\uFF0C\u6BCF\u9898\u6709\u63A8\u8350\u9879\uFF09"),promptGuidelines:[t("ask_user \u53EA\u5728\u5F00\u5DE5\u524D\u95EE\u4E00\u6B21\uFF0C\u4E00\u8F6E\u6700\u591A 3 \u9898\uFF1B\u540C\u4E00\u4EFB\u52A1\u4E4B\u540E\u4E0D\u518D\u8FFD\u95EE\uFF0C\u9664\u975E\u7528\u6237\u4E3B\u52A8\u8981\u6C42\u3002"),t("\u53EA\u95EE\u4F1A\u6539\u53D8\u4EA7\u51FA\u7684\u51B3\u5B9A\uFF08\u53D7\u4F17/\u7528\u9014\u3001\u98CE\u683C\u6216\u4E3B\u9898\u3001\u7BC7\u5E45\u3001\u5927\u7EB2\u987A\u5E8F\uFF09\uFF1B\u80FD\u4ECE\u7528\u6237\u539F\u8BDD\u3001\u9644\u4EF6\u6216\u9879\u76EE\u6587\u4EF6\u63A8\u65AD\u51FA\u7684\u4E0D\u95EE\u3002"),t("\u7528\u6237\u8BF4\u4E86\u300C\u76F4\u63A5\u505A / \u4F60\u51B3\u5B9A / \u5FEB\u901F\u51FA\u4E00\u7248\u300D\uFF0C\u6216\u662F\u5728\u4FEE\u6539\u5DF2\u6709\u6587\u4EF6\uFF08\u5E26\u5B9A\u4F4D\u3001\u300C\u628A\u7B2C 3 \u9875\u6539\u6210\u2026\u300D\uFF09\u65F6\uFF0C\u4E0D\u8981\u8C03\u7528 ask_user\u3002"),t("\u6BCF\u9898\u90FD\u6807\u51FA\u63A8\u8350\u9879\uFF08recommended\uFF09\uFF1B\u98CE\u683C\u9898\u4F18\u5148\u7528 thumbnail \u7F29\u7565\u56FE\uFF08theme:\u2026 / page:\u2026 / doc:\u2026\uFF09\uFF0C\u914D\u8272\u7528 swatch\u3002"),t("\u7528\u6237\u8DF3\u8FC7\u65F6\u6309\u63A8\u8350\u9879\u7EE7\u7EED\uFF0C\u5E76\u5728\u56DE\u590D\u91CC\u7528\u4E00\u53E5\u8BDD\u8BF4\u660E\u7528\u4E86\u54EA\u4E9B\u63A8\u8350\u9879\u3002")],parameters:G,execute:d(async(u,e,r,i,c)=>{let a;try{a=z(e,c.cwd,U)}catch(v){throw v instanceof W?new Error(`ask_user: ${v.message}`):v}const D=await n.post("/api/internal/pi-bridge/ask-user",{...l(c),...a},{timeoutMs:Q()});if(!D||D.cancelled)return{content:[{type:"text",text:"User did not answer. Stop and wait for further instructions."}],details:{answered:!1,request:a}};const{text:M,skipped:$}=J(a,D);return{content:[{type:"text",text:M}],details:{answered:!0,answers:D.answers??{},...D.structured?{structured:D.structured}:{},...D.summary?{summary:D.summary}:{},skipped:$,request:a}}},"execute")})}A(L,"te"),d(L,"default");export{S as EVALUATE_READS_ENV,L as default};
|