dal-code 1.0.38 → 1.0.39

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.
Files changed (81) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dal-docs/settings.md +1 -1
  3. package/dist/core/agent-session.js +4 -4
  4. package/dist/core/compaction/compaction.js +31 -13
  5. package/dist/core/permissions/tool-policy.js +1 -1
  6. package/dist/core/project-facts.d.ts +16 -0
  7. package/dist/core/project-facts.js +2 -0
  8. package/dist/core/sandbox/policy.js +1 -1
  9. package/dist/core/sandbox/windows.js +1 -1
  10. package/dist/core/system-prompt.d.ts +1 -0
  11. package/dist/core/system-prompt.js +12 -12
  12. package/dist/core/workspace-lock.d.ts +29 -0
  13. package/dist/core/workspace-lock.js +3 -0
  14. package/dist/index.d.ts +2 -0
  15. package/dist/index.js +1 -1
  16. package/dist/main.js +3 -3
  17. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  18. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  19. package/dist/node_modules/@dalcode/dal-goal/package.json +2 -2
  20. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  21. package/dist/node_modules/@dalcode/dal-guard/src/attribution.js +1 -0
  22. package/dist/node_modules/@dalcode/dal-guard/src/credentials.js +1 -1
  23. package/dist/node_modules/@dalcode/dal-guard/src/index.js +1 -1
  24. package/dist/node_modules/@dalcode/dal-guard/src/package-manager.js +1 -0
  25. package/dist/node_modules/@dalcode/dal-guard/src/workspace.js +2 -0
  26. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  27. package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
  28. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  29. package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
  30. package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
  31. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  32. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +4 -2
  33. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  34. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +4 -2
  35. package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -4
  36. package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
  37. package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
  38. package/dist/node_modules/@dalcode/dal-router/package.json +5 -4
  39. package/dist/node_modules/@dalcode/dal-router/src/commands.js +7 -7
  40. package/dist/node_modules/@dalcode/dal-router/src/config.d.ts +2 -0
  41. package/dist/node_modules/@dalcode/dal-router/src/config.js +2 -2
  42. package/dist/node_modules/@dalcode/dal-router/src/index.js +4 -4
  43. package/dist/node_modules/@dalcode/dal-router/src/subagent.js +1 -1
  44. package/dist/node_modules/@dalcode/dal-router/src/suggest.js +2 -0
  45. package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
  46. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  47. package/dist/node_modules/@dalcode/dal-subagent/src/index.js +12 -12
  48. package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
  49. package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
  50. package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
  51. package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
  52. package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
  53. package/dist/node_modules/@dalcode/dal-workflow/src/completion-check.js +4 -0
  54. package/dist/node_modules/@dalcode/dal-workflow/src/index.js +4 -4
  55. package/dist/node_modules/@dalcode/dal-workflow/src/ledger.js +3 -0
  56. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  57. package/dist/node_modules/@earendil-works/chord/package.json +1 -1
  58. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +2 -2
  59. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  60. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  61. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  62. package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
  63. package/dist/node_modules/@earendil-works/pi-client/package.json +3 -3
  64. package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
  65. package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
  66. package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
  67. package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
  68. package/dist/node_modules/@earendil-works/pi-server/package.json +3 -3
  69. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  70. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  71. package/dist/utils/version-check.d.ts +1 -0
  72. package/dist/utils/version-check.js +2 -2
  73. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  74. package/examples/extensions/gondolin/package-lock.json +2 -2
  75. package/examples/extensions/gondolin/package.json +1 -1
  76. package/examples/extensions/sandbox/package-lock.json +2 -2
  77. package/examples/extensions/sandbox/package.json +1 -1
  78. package/examples/extensions/with-deps/package-lock.json +2 -2
  79. package/examples/extensions/with-deps/package.json +1 -1
  80. package/npm-shrinkwrap.json +2 -2
  81. package/package.json +1 -1
@@ -1 +1 @@
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};
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 _,sep as j}from"node:path";import{packageCacheDirs as B}from"./package-managers.js";const I=["read-only","workspace-write","off"],g="DAL_SANDBOX",D={off:0,"workspace-write":1,"read-only":2};function v(e){return typeof e=="string"&&I.includes(e)}i(v,"isSandboxLevel");function P(e,r){return D[r]>D[e]?r:e}i(P,"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 z=process.env[g];function H(e={[g]:z}){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(H,"readSandboxEnvironment");function Q(e){return JSON.stringify({level:e.level,allowedDomains:e.network.allowedDomains})}i(Q,"sandboxEnvironmentValue");function U(e){const r=e.settings?.global??{},t=e.settings?.project??{},s=H(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)&&P(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(U,"resolveSandboxPolicy");const M=[".git/hooks",".git/config",".gitmodules",".dal",".claude",".agents",".mcp.json",".cursor",".vscode",".idea",".env"],V=[".gitconfig",".bashrc",".bash_profile",".zshrc",".zprofile",".profile",".config/fish",".dal"],X=[".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!==".."&&!t.startsWith(`..${j}`)&&!W(t)}i(x,"isWithin");function Y(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??B():[],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 M)d.push(u(n,p));d.push(u(n,".env.*"));for(const p of F(n))d.push(u(n,p))}for(const n of o)d.push(u(n,"hooks"),u(n,"config"));for(const n of V)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=[...X.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(Y,"filesystemRules");function F(e){if(!O(e))return[];try{return C(e).filter(r=>r.startsWith(".env."))}catch{return[]}}i(F,"listEnvFiles");function Z(e,r){const t=e.toLowerCase(),s=r.toLowerCase();return s.startsWith("*.")?t.endsWith(s.slice(1)):t===s}i(Z,"domainMatches");function ee(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(ee,"isAlwaysBlockedHost");export{X as PROTECTED_HOME_READS,V as PROTECTED_HOME_WRITES,M as PROTECTED_WRITE_NAMES,g as SANDBOX_ENV,I as SANDBOX_LEVELS,Z as domainMatches,m as expandPath,Y as filesystemRules,ee as isAlwaysBlockedHost,v as isSandboxLevel,H as readSandboxEnvironment,U as resolveSandboxPolicy,Q as sandboxEnvironmentValue,P as stricterLevel};
@@ -1,4 +1,4 @@
1
- var S=Object.defineProperty;var c=(e,r)=>S(e,"name",{value:r,configurable:!0});import{spawnSync as D}from"node:child_process";import{existsSync as u,mkdtempSync as I,readFileSync as v,rmSync as w,writeFileSync as p}from"node:fs";import{createRequire as y}from"node:module";import{tmpdir as L}from"node:os";import{join as d,win32 as m}from"node:path";const x="DAL_MXC_SDK_DIR",P="0.6.0-alpha",O=/^0\.6\.\d+$/,H=["Allowlisted domains are reached through dal's filtering proxy, handed to mxc as its network proxy; mxc does not enforce per-host allow or block lists on Windows.","A background process that may listen locally gets mxc's local-network access, which also reaches other machines on the private network, not only localhost.","Protected names inside a writable folder (.env, .git/hooks, .vscode, .dal, \u2026) are protected only if they already exist when the command starts; creating a missing one is not blocked.","Protected credential files (~/.ssh, cloud credentials, \u2026) are denied only if they exist when the command starts."];let h;function V(e){h=e}c(V,"setMxcRuntimeForTesting");function E(e){const r=e[x]?.trim();if(r)return u(d(r,"package.json"))?{dir:r}:{error:`${x} is set to ${r}, but there is no package there.`};try{const o=y(import.meta.url);return{dir:d(o.resolve("@microsoft/mxc-sdk/package.json"),"..")}}catch{return{error:`Microsoft eXecution Containers (mxc) is not installed. Install it with \`npm install -g @microsoft/mxc-sdk@0.6.0\`, or set ${x} to an @microsoft/mxc-sdk 0.6 package directory.`}}}c(E,"sdkDirectory");function B(e={}){if(h)return h;const r=e.env??process.env,o=E(r);if("error"in o)return o;let t;try{t=JSON.parse(v(d(o.dir,"package.json"),"utf8")).version??""}catch(n){return{error:`cannot read the mxc SDK at ${o.dir}: ${n instanceof Error?n.message:n}`}}if(!O.test(t))return{error:`dal supports @microsoft/mxc-sdk 0.6.x, but ${o.dir} is version ${t||"(unknown)"}. Install @microsoft/mxc-sdk@0.6.0.`};const a=(e.arch??process.arch)==="arm64"?"arm64":"x64",s=d(o.dir,"bin",a,"wxc-exec.exe");if(!u(s))return{error:`the mxc SDK at ${o.dir} has no ${a} wxc-exec.exe.`};let i;try{i=y(import.meta.url)(d(o.dir,"dist","index.js"))}catch(n){return{error:`cannot load the mxc SDK at ${o.dir}: ${n instanceof Error?n.message:n}`}}return{sdkDir:o.dir,sdkVersion:t,wxcExec:s,api:i}}c(B,"loadMxcRuntime");function l(e){return e.replace(/\//g,"\\")}c(l,"toWindowsPath");function f(e){return e.length>0&&!/[\s"]/.test(e)?e:`"${e.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\+)$/,"$1$1")}"`}c(f,"quoteWindowsArgument");function g(e){return`'${e.replace(/'/g,"''")}'`}c(g,"powershellQuote");function $(e){return`'${e.replace(/'/g,"'\\''")}'`}c($,"bashQuote");function T(e){const r=m.dirname(e),o=m.dirname(r);return m.basename(r).toLowerCase()==="bin"&&m.basename(o).toLowerCase()==="usr"?m.dirname(o):m.basename(r).toLowerCase()==="bin"?o:r}c(T,"shellInstallRoot");function _(e,r){const o=m.relative(r,e);return o===""||!o.startsWith("..")&&!m.isAbsolute(o)}c(_,"isWithinWindows");function C(e){const r=c(n=>[...new Set(n.map(l))],"unique"),o=r([...e.rules.allowWrite,...e.tools.readwritePaths]),t=e.rules.denyWrite.filter(n=>!/[*?]/.test(n)&&e.exists(n)&&o.some(b=>_(l(n),b))),a=r([...e.tools.readonlyPaths,e.shellRoot,e.runDir,...e.level==="read-only"?[e.cwd]:[],...t]).filter(n=>!o.includes(n)),s=r(e.rules.denyRead.filter(n=>!/[*?]/.test(n)&&e.exists(n))),i=e.proxyPort!==void 0?{proxy:{localhost:e.proxyPort}}:{allowOutbound:!1,allowLocalNetwork:e.allowLocalNetwork};return{version:P,filesystem:{readwritePaths:o,readonlyPaths:a,deniedPaths:s},network:i,ui:{allowWindows:!0,clipboard:"none",allowInputInjection:!1}}}c(C,"windowsSandboxPolicy");function R(e,r){const o={};for(const[s,i]of Object.entries(e))typeof i=="string"&&(o[s]=i);const t=c((s,i)=>{for(const n of Object.keys(o))n.toLowerCase()===s.toLowerCase()&&delete o[n];o[s]=i},"set"),a=l(r.scratchDir);if(t("TMP",a),t("TEMP",a),t("TMPDIR",a),t("DAL_SANDBOX_RUN",r.runId),r.proxyPort!==void 0){const s=`http://127.0.0.1:${r.proxyPort}`;t("HTTP_PROXY",s),t("HTTPS_PROXY",s),o.http_proxy=s,o.https_proxy=s}return Object.entries(o).map(([s,i])=>`${s}=${i}`)}c(R,"windowsSandboxEnvironment");const N="try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}";function W(e,r,o,t){return e==="powershell"?{script:`${N}
1
+ var S=Object.defineProperty;var c=(e,r)=>S(e,"name",{value:r,configurable:!0});import{spawnSync as D}from"node:child_process";import{existsSync as u,mkdtempSync as I,readFileSync as v,rmSync as w,writeFileSync as p}from"node:fs";import{createRequire as y}from"node:module";import{tmpdir as L}from"node:os";import{join as d,win32 as m}from"node:path";const x="DAL_MXC_SDK_DIR",P="0.6.0-alpha",O=/^0\.6\.\d+$/,H=["Allowlisted domains are reached through dal's filtering proxy, handed to mxc as its network proxy; mxc does not enforce per-host allow or block lists on Windows.","A background process that may listen locally gets mxc's local-network access, which also reaches other machines on the private network, not only localhost.","Protected names inside a writable folder (.env, .git/hooks, .vscode, .dal, \u2026) are protected only if they already exist when the command starts; creating a missing one is not blocked.","Protected credential files (~/.ssh, cloud credentials, \u2026) are denied only if they exist when the command starts."];let h;function V(e){h=e}c(V,"setMxcRuntimeForTesting");function E(e){const r=e[x]?.trim();if(r)return u(d(r,"package.json"))?{dir:r}:{error:`${x} is set to ${r}, but there is no package there.`};try{const o=y(import.meta.url);return{dir:d(o.resolve("@microsoft/mxc-sdk/package.json"),"..")}}catch{return{error:`Microsoft eXecution Containers (mxc) is not installed. Install it with \`npm install -g @microsoft/mxc-sdk@0.6.0\`, or set ${x} to an @microsoft/mxc-sdk 0.6 package directory.`}}}c(E,"sdkDirectory");function B(e={}){if(h)return h;const r=e.env??process.env,o=E(r);if("error"in o)return o;let t;try{t=JSON.parse(v(d(o.dir,"package.json"),"utf8")).version??""}catch(n){return{error:`cannot read the mxc SDK at ${o.dir}: ${n instanceof Error?n.message:n}`}}if(!O.test(t))return{error:`dal supports @microsoft/mxc-sdk 0.6.x, but ${o.dir} is version ${t||"(unknown)"}. Install @microsoft/mxc-sdk@0.6.0.`};const a=(e.arch??process.arch)==="arm64"?"arm64":"x64",s=d(o.dir,"bin",a,"wxc-exec.exe");if(!u(s))return{error:`the mxc SDK at ${o.dir} has no ${a} wxc-exec.exe.`};let i;try{i=y(import.meta.url)(d(o.dir,"dist","index.js"))}catch(n){return{error:`cannot load the mxc SDK at ${o.dir}: ${n instanceof Error?n.message:n}`}}return{sdkDir:o.dir,sdkVersion:t,wxcExec:s,api:i}}c(B,"loadMxcRuntime");function l(e){return e.replace(/\//g,"\\")}c(l,"toWindowsPath");function f(e){return e.length>0&&!/[\s"]/.test(e)?e:`"${e.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\+)$/,"$1$1")}"`}c(f,"quoteWindowsArgument");function g(e){return`'${e.replace(/'/g,"''")}'`}c(g,"powershellQuote");function $(e){return`'${e.replace(/'/g,"'\\''")}'`}c($,"bashQuote");function T(e){const r=m.dirname(e),o=m.dirname(r);return m.basename(r).toLowerCase()==="bin"&&m.basename(o).toLowerCase()==="usr"?m.dirname(o):m.basename(r).toLowerCase()==="bin"?o:r}c(T,"shellInstallRoot");function _(e,r){const o=m.relative(r,e);return o===""||o!==".."&&!o.startsWith("..\\")&&!m.isAbsolute(o)}c(_,"isWithinWindows");function C(e){const r=c(n=>[...new Set(n.map(l))],"unique"),o=r([...e.rules.allowWrite,...e.tools.readwritePaths]),t=e.rules.denyWrite.filter(n=>!/[*?]/.test(n)&&e.exists(n)&&o.some(b=>_(l(n),b))),a=r([...e.tools.readonlyPaths,e.shellRoot,e.runDir,...e.level==="read-only"?[e.cwd]:[],...t]).filter(n=>!o.includes(n)),s=r(e.rules.denyRead.filter(n=>!/[*?]/.test(n)&&e.exists(n))),i=e.proxyPort!==void 0?{proxy:{localhost:e.proxyPort}}:{allowOutbound:!1,allowLocalNetwork:e.allowLocalNetwork};return{version:P,filesystem:{readwritePaths:o,readonlyPaths:a,deniedPaths:s},network:i,ui:{allowWindows:!0,clipboard:"none",allowInputInjection:!1}}}c(C,"windowsSandboxPolicy");function R(e,r){const o={};for(const[s,i]of Object.entries(e))typeof i=="string"&&(o[s]=i);const t=c((s,i)=>{for(const n of Object.keys(o))n.toLowerCase()===s.toLowerCase()&&delete o[n];o[s]=i},"set"),a=l(r.scratchDir);if(t("TMP",a),t("TEMP",a),t("TMPDIR",a),t("DAL_SANDBOX_RUN",r.runId),r.proxyPort!==void 0){const s=`http://127.0.0.1:${r.proxyPort}`;t("HTTP_PROXY",s),t("HTTPS_PROXY",s),o.http_proxy=s,o.https_proxy=s}return Object.entries(o).map(([s,i])=>`${s}=${i}`)}c(R,"windowsSandboxEnvironment");const N="try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}";function W(e,r,o,t){return e==="powershell"?{script:`${N}
2
2
  ${o}
3
3
  if (-not $?) { if ($LASTEXITCODE) { exit $LASTEXITCODE } else { exit 1 } }
4
4
  `,commandLine:[f(r),"-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",f(t)].join(" ")}:{script:`${o}
@@ -12,6 +12,7 @@ export interface BuildSystemPromptOptions {
12
12
  sections?: Record<string, string>;
13
13
  cwd: string;
14
14
  gitState?: boolean;
15
+ projectFacts?: boolean;
15
16
  contextFiles?: Array<{
16
17
  path: string;
17
18
  content: string;
@@ -1,28 +1,28 @@
1
- var P=Object.defineProperty;var c=(e,t)=>P(e,"name",{value:t,configurable:!0});import{join as v}from"node:path";import{getSystemMessageText as E}from"@earendil-works/pi-ai";import{APP_NAME as $,APP_TITLE as f,getDalDocsPath as j,getDocsPath as T,getExamplesPath as O,getReadmePath as _,IS_WHITE_LABEL_BUILD as I}from"../config.js";import{describeGitState as N}from"./git-state.js";import{INJECTED_CONTEXT_TAG as A}from"./messages.js";import{formatSkillsForPrompt as D}from"./skills.js";const M=/^[a-z][a-z0-9_-]*$/;function R(e){return{customPrompt:e.customPrompt,forceSystemPrompt:e.forceSystemPrompt,selectedTools:[...e.selectedTools??["read","bash","edit","write"]],hiddenTools:[...e.hiddenTools??[]],toolSnippets:{...e.toolSnippets??{}},toolGuidelines:Object.fromEntries(Object.entries(e.toolGuidelines??{}).map(([t,n])=>[t,[...n]])),promptGuidelines:[...e.promptGuidelines??[]],appendSystemPrompt:e.appendSystemPrompt??"",sections:{...e.sections??{}},cwd:e.cwd,gitState:e.gitState,contextFiles:(e.contextFiles??[]).map(t=>({...t})),skills:(e.skills??[]).map(t=>({...t}))}}c(R,"normalizeBuildSystemPromptOptions");function G(e){return["Project-specific instructions and guidelines:",...e.map(({path:t,content:n})=>`<project_instructions path="${t}">
1
+ var v=Object.defineProperty;var c=(e,t)=>v(e,"name",{value:t,configurable:!0});import{join as P}from"node:path";import{getSystemMessageText as j}from"@earendil-works/pi-ai";import{APP_NAME as E,APP_TITLE as p,getDalDocsPath as $,getDocsPath as T,getExamplesPath as O,getReadmePath as _,IS_WHITE_LABEL_BUILD as I}from"../config.js";import{describeGitState as N}from"./git-state.js";import{INJECTED_CONTEXT_TAG as A}from"./messages.js";import{describeProjectFacts as D}from"./project-facts.js";import{formatSkillsForPrompt as F}from"./skills.js";const M=/^[a-z][a-z0-9_-]*$/;function R(e){return{customPrompt:e.customPrompt,forceSystemPrompt:e.forceSystemPrompt,selectedTools:[...e.selectedTools??["read","bash","edit","write"]],hiddenTools:[...e.hiddenTools??[]],toolSnippets:{...e.toolSnippets??{}},toolGuidelines:Object.fromEntries(Object.entries(e.toolGuidelines??{}).map(([t,n])=>[t,[...n]])),promptGuidelines:[...e.promptGuidelines??[]],appendSystemPrompt:e.appendSystemPrompt??"",sections:{...e.sections??{}},cwd:e.cwd,gitState:e.gitState,projectFacts:e.projectFacts,contextFiles:(e.contextFiles??[]).map(t=>({...t})),skills:(e.skills??[]).map(t=>({...t}))}}c(R,"normalizeBuildSystemPromptOptions");function C(e){return["Project-specific instructions and guidelines:",...e.map(({path:t,content:n})=>`<project_instructions path="${t}">
2
2
  ${n}
3
3
  </project_instructions>`)].join(`
4
4
 
5
- `)}c(G,"renderProjectContext");function L(e,t,n){const i=[],d=new Set,o=c(l=>{const m=l.trim();!m||d.has(m)||(d.add(m),i.push(m))},"addRule"),p=e.includes("bash"),h=e.includes("powershell"),a=e.includes("grep"),g=e.includes("find"),y=e.includes("ls");(p||h)&&!a&&!g&&!y&&o(p&&h?"Use bash or PowerShell for file operations like listing, searching, and finding files":h?"Use PowerShell for file operations like listing, searching, and finding files":"Use bash for file operations like ls, rg, find");for(const l of e)for(const m of t[l]??[])o(m);for(const l of n)o(l);return e.length>0&&(o("When several tool calls do not depend on each other's results (reading multiple files, independent searches or commands), make them all in one response; they run in parallel. Each extra round trip costs the user seconds"),o("Answer as soon as you can: once you know enough, give the answer or your best current conclusion, then offer to dig further. Do not investigate everything before saying anything"),o("During longer work, tell the user every few tool rounds, in a sentence or two, what you found and what you will check next"),o("If you cannot tell which product, project or file the user means, ask instead of searching widely on a guess. When the user writes while you are working, respond to that message first: it may change the direction"),o("In a small project, read every source file the task touches in one response (parallel reads, or one command that prints them) instead of exploring one file per round"),o("Verify the behaviours the request names and the edge cases it implies; do not write exhaustive or randomized test sweeps unless asked"),o("Before reporting done, run every code path you added at least once, including backward-compatibility, fallback and error branches: a branch that never ran is not verified"),o("If the request's premise does not match what the code, data or tests show (the reported bug is absent, the named text is already correct), say so with the evidence and do not change anything just to satisfy the request; ask how to proceed or stop")),o(`Text inside <${A} type="..."> tags comes from ${f} itself, not from the user: follow its instructions, but do not mistake it for the user's request or reply to it as if the user had written it`),o("Be concise in your responses"),o("Show file paths clearly when working with files"),i.map(l=>`- ${l}`).join(`
6
- `)}c(L,"buildRules");function F(e){const t=R(e),{customPrompt:n,selectedTools:i,hiddenTools:d,toolSnippets:o,toolGuidelines:p,promptGuidelines:h,appendSystemPrompt:a,sections:g,cwd:y,contextFiles:l,skills:m}=t;for(const s of Object.keys(g))if(!M.test(s)||s==="preamble")throw new Error(`Invalid system prompt section name: ${s}`);const w=i.filter(s=>!d.includes(s)),r={};if(n)r.preamble=n;else{r.preamble=`You are an expert coding assistant operating inside ${f} (${$}). You help users by reading files, executing commands, editing code, and writing new files.`;const s=w.filter(b=>!!o[b]),u=s.length>0?s.map(b=>`- ${b}: ${o[b]}`).join(`
7
- `):"(none)";r.tools=`${u}
5
+ `)}c(C,"renderProjectContext");function G(e,t,n){const r=[],d=new Set,s=c(l=>{const m=l.trim();!m||d.has(m)||(d.add(m),r.push(m))},"addRule"),h=e.includes("bash"),f=e.includes("powershell"),a=e.includes("grep"),u=e.includes("find"),y=e.includes("ls");(h||f)&&!a&&!u&&!y&&s(h&&f?"Use bash or PowerShell for file operations like listing, searching, and finding files":f?"Use PowerShell for file operations like listing, searching, and finding files":"Use bash for file operations like ls, rg, find");for(const l of e)for(const m of t[l]??[])s(m);for(const l of n)s(l);return e.length>0&&(s("When several tool calls do not depend on each other's results (reading multiple files, independent searches or commands), make them all in one response; they run in parallel. Each extra round trip costs the user seconds"),s("Answer as soon as you can: once you know enough, give the answer or your best current conclusion, then offer to dig further. Do not investigate everything before saying anything"),s("During longer work, tell the user every few tool rounds, in a sentence or two, what you found and what you will check next"),s("If you cannot tell which product, project or file the user means, ask instead of searching widely on a guess. When the user writes while you are working, respond to that message first: it may change the direction"),s("In a small project, read every source file the task touches in one response (parallel reads, or one command that prints them) instead of exploring one file per round"),s("Verify the behaviours the request names and the edge cases it implies; do not write exhaustive or randomized test sweeps unless asked"),s("Before reporting done, run every code path you added at least once, including backward-compatibility, fallback and error branches: a branch that never ran is not verified"),s("If the request's premise does not match what the code, data or tests show (the reported bug is absent, the named text is already correct), say so with the evidence and do not change anything just to satisfy the request; ask how to proceed or stop"),s("When a protection refuses a call, stop that step and tell the user why; never reach the same data another way (a copy, another tool or path)"),s(`Adapt instructions written for another agent before following or delegating them; drop what conflicts with your protections. You are ${p}: co-author trailer "Co-Authored-By: ${p} <noreply@deepailab.ai>", never Claude, Codex or Copilot`),s("Before calling a multi-part task done, match each part to its evidence and name what is not done or partly done; a load check is not a review")),s(`Text inside <${A} type="..."> tags comes from ${p} itself, not from the user: follow its instructions, but do not mistake it for the user's request or reply to it as if the user had written it`),s("Be concise in your responses"),s("Show file paths clearly when working with files"),r.map(l=>`- ${l}`).join(`
6
+ `)}c(G,"buildRules");function B(e){const t=R(e),{customPrompt:n,selectedTools:r,hiddenTools:d,toolSnippets:s,toolGuidelines:h,promptGuidelines:f,appendSystemPrompt:a,sections:u,cwd:y,contextFiles:l,skills:m}=t;for(const o of Object.keys(u))if(!M.test(o)||o==="preamble")throw new Error(`Invalid system prompt section name: ${o}`);const b=r.filter(o=>!d.includes(o)),i={};if(n)i.preamble=n;else{i.preamble=`You are an expert coding assistant operating inside ${p} (${E}). You help users by reading files, executing commands, editing code, and writing new files.`;const o=b.filter(w=>!!s[w]),g=o.length>0?o.map(w=>`- ${w}: ${s[w]}`).join(`
7
+ `):"(none)";i.tools=`${g}
8
8
 
9
- In addition to the tools above, you may have access to other custom tools depending on the project.`,r.rules=L(w,p,h),r.docs=W()}a&&(r.addendum=a),l.length>0&&(r.project_context=G(l));const S=["read","bash"],k=S.find(s=>w.includes(s))??(S.some(s=>i.includes(s))?"indirect":void 0);if(k&&m.length>0){const s=D(m,k).trim();s&&(r.skills=s)}r.cwd=y.replace(/\\/g,"/"),t.gitState&&!g.git_state&&(r.git=N(y));for(const[s,u]of Object.entries(g))u&&(r[s]=u);const x={preamble:r.preamble};for(const[s,u]of Object.entries(r))s!=="preamble"&&(x[s]=`<${s}>
10
- ${u}
11
- </${s}>`);return x}c(F,"buildSystemPromptSections");const U="cwd",B="Environment of this session, part of the system prompt. Later updates to these sections arrive as system prompt updates.";function X(e){const t=e[0];if(!t||t.role!=="system"||!t.sections)return e;const n=Object.keys(t.sections),i=n.indexOf(U);if(i===-1)return e;const d=n.slice(i).map(a=>t.sections?.[a]).filter(a=>typeof a=="string"&&a.length>0),o=Object.fromEntries(n.slice(0,i).map(a=>[a,t.sections?.[a]??null])),p={...t,sections:o};if(d.length===0)return[p,...e.slice(1)];const h={role:"user",content:[{type:"text",text:`<session_environment>
12
- ${B}
9
+ In addition to the tools above, you may have access to other custom tools depending on the project.`,i.rules=G(b,h,f),i.docs=z()}a&&(i.addendum=a),l.length>0&&(i.project_context=C(l));const k=["read","bash"],S=k.find(o=>b.includes(o))??(k.some(o=>r.includes(o))?"indirect":void 0);if(S&&m.length>0){const o=F(m,S).trim();o&&(i.skills=o)}if(i.cwd=y.replace(/\\/g,"/"),t.gitState&&!u.git_state&&(i.git=N(y)),t.projectFacts&&!u.project){const o=D(y);o&&(i.project=o)}for(const[o,g]of Object.entries(u))g&&(i[o]=g);const x={preamble:i.preamble};for(const[o,g]of Object.entries(i))o!=="preamble"&&(x[o]=`<${o}>
10
+ ${g}
11
+ </${o}>`);return x}c(B,"buildSystemPromptSections");const L="cwd",U="Environment of this session, part of the system prompt. Later updates to these sections arrive as system prompt updates.";function Z(e){const t=e[0];if(!t||t.role!=="system"||!t.sections)return e;const n=Object.keys(t.sections),r=n.indexOf(L);if(r===-1)return e;const d=n.slice(r).map(a=>t.sections?.[a]).filter(a=>typeof a=="string"&&a.length>0),s=Object.fromEntries(n.slice(0,r).map(a=>[a,t.sections?.[a]??null])),h={...t,sections:s};if(d.length===0)return[h,...e.slice(1)];const f={role:"user",content:[{type:"text",text:`<session_environment>
12
+ ${U}
13
13
 
14
14
  ${d.join(`
15
15
 
16
16
  `)}
17
- </session_environment>`}],timestamp:t.timestamp};return[p,h,...e.slice(1)]}c(X,"moveSessionEnvironmentOutOfSystemPrompt");function C(e){return e.forceSystemPrompt!==void 0?{content:e.forceSystemPrompt}:{content:"",sections:F(e)}}c(C,"buildSystemPromptState");function Q(e){return E({role:"system",...C(e),timestamp:0})}c(Q,"buildSystemPrompt");function Z(e,t){const n={};for(const[i,d]of Object.entries(t))e[i]!==d&&(n[i]=d);for(const i of Object.keys(e))t[i]===void 0&&(n[i]=null);return Object.keys(n).length>0?n:void 0}c(Z,"diffSystemPromptSections");function W(){if(I){const e=j();return`${f} documentation (read only when the user asks about ${f} itself: its commands, settings, skills, prompt templates, extensions, packages, themes or keybindings):
18
- - Start with: ${v(e,"README.md")}
17
+ </session_environment>`}],timestamp:t.timestamp};return[h,f,...e.slice(1)]}c(Z,"moveSessionEnvironmentOutOfSystemPrompt");function W(e){return e.forceSystemPrompt!==void 0?{content:e.forceSystemPrompt}:{content:"",sections:B(e)}}c(W,"buildSystemPromptState");function ee(e){return j({role:"system",...W(e),timestamp:0})}c(ee,"buildSystemPrompt");function te(e,t){const n={};for(const[r,d]of Object.entries(t))e[r]!==d&&(n[r]=d);for(const r of Object.keys(e))t[r]===void 0&&(n[r]=null);return Object.keys(n).length>0?n:void 0}c(te,"diffSystemPromptSections");function z(){if(I){const e=$();return`${p} documentation (read only when the user asks about ${p} itself: its commands, settings, skills, prompt templates, extensions, packages, themes or keybindings):
18
+ - Start with: ${P(e,"README.md")}
19
19
  - Topics, in the same folder: skills.md, prompt-templates.md, extensions.md, packages.md, themes.md, keybindings.md, settings.md
20
20
  - Resolve those file names under ${e}, not the current working directory
21
- - Read the relevant file completely before answering or implementing, and describe the product as ${f}`}return`${f} documentation (read only when the user asks about ${f} itself, its SDK, extensions, themes, skills, or TUI):
21
+ - Read the relevant file completely before answering or implementing, and describe the product as ${p}`}return`${p} documentation (read only when the user asks about ${p} itself, its SDK, extensions, themes, skills, or TUI):
22
22
  - Main documentation: ${_()}
23
23
  - Additional docs: ${T()}
24
24
  - Examples: ${O()} (extensions, custom tools, SDK)
25
25
  - When reading these docs or examples, resolve docs/... under Additional docs and examples/... under Examples, not the current working directory
26
26
  - When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), packages (docs/packages.md), environment variables (docs/environment-variables.md), MCP servers (docs/mcp.md), codemode scripts and non-LLM models such as classifiers and image models (docs/codemode.md)
27
27
  - When working on these topics, read the docs and examples, and follow .md cross-references before implementing
28
- - Always read these .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`}c(W,"buildDocumentationSection");export{U as SESSION_ENVIRONMENT_FIRST_SECTION,Q as buildSystemPrompt,F as buildSystemPromptSections,C as buildSystemPromptState,Z as diffSystemPromptSections,X as moveSessionEnvironmentOutOfSystemPrompt,R as normalizeBuildSystemPromptOptions};
28
+ - Always read these .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`}c(z,"buildDocumentationSection");export{L as SESSION_ENVIRONMENT_FIRST_SECTION,ee as buildSystemPrompt,B as buildSystemPromptSections,W as buildSystemPromptState,te as diffSystemPromptSections,Z as moveSessionEnvironmentOutOfSystemPrompt,R as normalizeBuildSystemPromptOptions};
@@ -0,0 +1,29 @@
1
+ export declare const WORKSPACE_LOCK_FILE = "dal-workspace.lock";
2
+ export declare const STALE_AFTER_MS: number;
3
+ export interface WorkspaceLock {
4
+ pid: number;
5
+ host: string;
6
+ sessionId: string;
7
+ startedAt: string;
8
+ refreshedAt: string;
9
+ worktree?: string;
10
+ }
11
+ export interface WorkspaceClaim {
12
+ gitDir: string;
13
+ worktree?: string;
14
+ heldBy?: WorkspaceLock;
15
+ }
16
+ export declare function gitDirOf(dir: string): {
17
+ gitDir: string;
18
+ worktree?: string;
19
+ } | undefined;
20
+ export declare function workspaceOwnerSessionId(sessionId: string, env?: NodeJS.ProcessEnv): string;
21
+ export declare function readWorkspaceLock(gitDir: string): WorkspaceLock | undefined;
22
+ export declare function workspaceLockIsLive(lock: WorkspaceLock, now?: number): boolean;
23
+ export declare function claimWorkspace(dir: string, sessionId: string, options?: {
24
+ now?: number;
25
+ env?: NodeJS.ProcessEnv;
26
+ force?: boolean;
27
+ }): WorkspaceClaim | undefined;
28
+ export declare function releaseWorkspace(gitDir: string): void;
29
+ export declare function shellCommandDirectory(command: string, cwd: string): string;
@@ -0,0 +1,3 @@
1
+ var l=Object.defineProperty;var c=(t,e)=>l(t,"name",{value:e,configurable:!0});import{execFileSync as m}from"node:child_process";import{readFileSync as k,renameSync as y,rmSync as D,writeFileSync as A}from"node:fs";import{hostname as p}from"node:os";import{isAbsolute as E,join as u,resolve as f}from"node:path";const a="dal-workspace.lock",I=7200*1e3,O=60*1e3,x="DALCODE_PARENT_SESSION_ID",w=new Map;function _(t){const e=f(t),n=w.get(e);if(n!==void 0)return n??void 0;let r=null;try{const i=m("git",["rev-parse","--git-dir","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e3}).trim().split(`
2
+ `),o=i[0]?.trim();o&&(r={gitDir:E(o)?o:f(e,o),worktree:i[1]?.trim()})}catch{r=null}return w.set(e,r),r??void 0}c(_,"gitDirOf");function v(t,e=process.env){return e[x]||t}c(v,"workspaceOwnerSessionId");function S(t){try{const e=JSON.parse(k(u(t,a),"utf8"));return typeof e.pid!="number"||typeof e.sessionId!="string"||typeof e.host!="string"?void 0:{pid:e.pid,host:e.host,sessionId:e.sessionId,startedAt:typeof e.startedAt=="string"?e.startedAt:new Date(0).toISOString(),refreshedAt:typeof e.refreshedAt=="string"?e.refreshedAt:new Date(0).toISOString(),...typeof e.worktree=="string"?{worktree:e.worktree}:{}}}catch{return}}c(S,"readWorkspaceLock");function L(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}c(L,"processAlive");function g(t,e=Date.now()){const n=Date.parse(t.refreshedAt);return!Number.isFinite(n)||e-n>I?!1:t.host===p()?L(t.pid):!0}c(g,"workspaceLockIsLive");function h(t,e){const n=u(t,a),r=`${n}.${process.pid}.tmp`;A(r,`${JSON.stringify(e,null,2)}
3
+ `),y(r,n)}c(h,"writeLock");function $(t,e,n={}){const r=_(t);if(!r)return;const i=n.now??Date.now(),o=v(e,n.env),s=S(r.gitDir),d={gitDir:r.gitDir,...r.worktree?{worktree:r.worktree}:{}};if(s&&s.sessionId!==o&&g(s,i)&&!n.force)return{...d,heldBy:s};if(s?.sessionId===o&&g(s,i)){if(!(s.pid===process.pid&&s.host===p())||i-Date.parse(s.refreshedAt)<O)return d;try{h(r.gitDir,{...s,refreshedAt:new Date(i).toISOString()})}catch{}return d}try{h(r.gitDir,{pid:process.pid,host:p(),sessionId:o,startedAt:new Date(i).toISOString(),refreshedAt:new Date(i).toISOString(),...r.worktree?{worktree:r.worktree}:{}})}catch{return}return d}c($,"claimWorkspace");function H(t){const e=S(t);if(!(!e||e.pid!==process.pid||e.host!==p()))try{D(u(t,a),{force:!0})}catch{}}c(H,"releaseWorkspace");function P(t,e){let n=e;for(const i of t.split(/&&|;|\n/)){const o=/^\s*cd\s+("([^"]+)"|'([^']+)'|(\S+))\s*$/.exec(i);if(!o)break;const s=(o[2]??o[3]??o[4]??"").replace(/^~(?=\/|$)/,process.env.HOME??"~");n=f(n,s)}const r=/\bgit\s+-C\s+("([^"]+)"|'([^']+)'|(\S+))/.exec(t);return r&&(n=f(n,r[2]??r[3]??r[4]??".")),n}c(P,"shellCommandDirectory");export{I as STALE_AFTER_MS,a as WORKSPACE_LOCK_FILE,$ as claimWorkspace,_ as gitDirOf,S as readWorkspaceLock,H as releaseWorkspace,P as shellCommandDirectory,g as workspaceLockIsLive,v as workspaceOwnerSessionId};
package/dist/index.d.ts CHANGED
@@ -19,6 +19,7 @@ export type { PackageManager, PathMetadata, ProgressCallback, ProgressEvent, Res
19
19
  export { DefaultPackageManager } from "./core/package-manager.ts";
20
20
  export { buildRuleSet, matchPermissionRules, type PermissionBehavior, type PermissionRule, type PermissionRuleSet, type PermissionRuleSource, parsePermissionRule, type RuleCall, type RuleVerdict, } from "./core/permissions/rules.ts";
21
21
  export { evaluateToolPolicy, type PermissionAskHandler, type PermissionAskRequest, readAccessDenial, registerPermissionAskHandler, type ToolPolicyDecision, } from "./core/permissions/tool-policy.ts";
22
+ export { describeProjectFacts, detectProjectFacts, type PackageManagerName, type ProjectFacts, projectPackageManager, } from "./core/project-facts.ts";
22
23
  export { buildProjectMap, formatProjectMapPrompt, type ProjectMap, type ProjectMapOptions, } from "./core/project-map.ts";
23
24
  export type { ResourceCollision, ResourceDiagnostic, ResourceLoader } from "./core/resource-loader.ts";
24
25
  export { DefaultResourceLoader, loadProjectContextFiles } from "./core/resource-loader.ts";
@@ -32,6 +33,7 @@ export { type EditDiffResult, generateDiffString, generateUnifiedPatch } from ".
32
33
  export { type BashOperations, type BashSpawnContext, type BashSpawnHook, type BashToolDetails, type BashToolInput, type BashToolOptions, createBashToolDefinition, createEditToolDefinition, createFindToolDefinition, createGrepToolDefinition, createLocalBashOperations, createLocalPowerShellOperations, createLsToolDefinition, createPowerShellToolDefinition, createProcessToolDefinition, createReadToolDefinition, createWriteToolDefinition, DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, type EditOperations, type EditToolDetails, type EditToolInput, type EditToolOptions, type FindOperations, type FindToolDetails, type FindToolInput, type FindToolOptions, formatSize, type GrepOperations, type GrepToolDetails, type GrepToolInput, type GrepToolOptions, type LsOperations, type LsToolDetails, type LsToolInput, type LsToolOptions, type PowerShellOperations, type PowerShellSpawnContext, type PowerShellSpawnHook, type PowerShellToolDetails, type PowerShellToolInput, type PowerShellToolOptions, type ProcessToolDetails, type ProcessToolInput, type ReadOperations, type ReadToolDetails, type ReadToolInput, type ReadToolOptions, registerShellExecutionGuard, type ShellExecutionGuard, type ShellExecutionRequest, type ToolsOptions, type TruncationOptions, type TruncationResult, truncateHead, truncateLine, truncateTail, type WriteOperations, type WriteToolInput, type WriteToolOptions, withFileMutationQueue, } from "./core/tools/index.ts";
33
34
  export { hasTrustRequiringProjectResources, type ProjectTrustDecision, ProjectTrustStore, type ProjectTrustStoreEntry, type ProjectTrustUpdate, } from "./core/trust-manager.ts";
34
35
  export { type ModelRoute, type ModelRouteReason, type ModelRouteRequest, VIRTUAL_MODEL_STATE_ENTRY, type VirtualModelDefinition, type VirtualModelStateData, } from "./core/virtual-models.ts";
36
+ export { claimWorkspace, gitDirOf, readWorkspaceLock, releaseWorkspace, STALE_AFTER_MS, shellCommandDirectory, WORKSPACE_LOCK_FILE, type WorkspaceClaim, type WorkspaceLock, workspaceLockIsLive, workspaceOwnerSessionId, } from "./core/workspace-lock.ts";
35
37
  export { applyShellEnvironmentPolicy, DEFAULT_SHELL_ENV_EXCLUDES, isDalCodeCredentialName, type ShellEnvironmentPolicy, withoutDalCodeCredentials, } from "./dal/child-env.ts";
36
38
  export * from "./dal/hooks/index.ts";
37
39
  export { isHostExtensionPath, markHostExtensionPaths } from "./dal/host-extensions.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 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};
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 d,parseSkillBlock as T}from"./core/agent-session.js";import{readStoredCredential as f}from"./core/auth-storage.js";import{BackgroundProcessManager as E,MAX_BACKGROUND_PROCESSES as C}from"./core/background-processes.js";import{calculateContextTokens as h,collectEntriesForBranchSummary as R,compact as P,DEFAULT_COMPACTION_SETTINGS as D,estimateTokens as L,findCutPoint as A,findTurnStartIndex as M,generateBranchSummary as _,generateSummary as I,generateSummaryWithUsage as k,getLastAssistantUsage as y,prepareBranchEntries as F,serializeConversation as O,shouldCompact as N}from"./core/compaction/index.js";import{createEventBus as B}from"./core/event-bus.js";import{createExtensionRuntime as b,defineTool as w,discoverAndLoadExtensions as U,ExtensionRunner as j,isBashToolResult as V,isEditToolResult as W,isFindToolResult as G,isGrepToolResult as K,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 de,resolveModelScopeWithDiagnostics as Te}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 Pe}from"./core/permissions/rules.js";import{evaluateToolPolicy as Le,readAccessDenial as Ae,registerPermissionAskHandler as Me}from"./core/permissions/tool-policy.js";import{describeProjectFacts as Ie,detectProjectFacts as ke,projectPackageManager as ye}from"./core/project-facts.js";import{buildProjectMap as Oe,formatProjectMapPrompt as Ne}from"./core/project-map.js";import{DefaultResourceLoader as Be,loadProjectContextFiles as He}from"./core/resource-loader.js";import{detectSandboxAvailability as we,getProcessShellSandbox as Ue,registerSandboxEscalationHandler as je,resolveSandboxPolicy as Ve,SANDBOX_ENV as We,ShellSandbox as Ge}from"./core/sandbox/index.js";import{AgentSessionRuntime as Xe,createAgentSession as ze,createAgentSessionFromServices as Ye,createAgentSessionRuntime as qe,createAgentSessionServices as Qe,createBashTool as Je,createCodingTools as Ze,createEditTool as $e,createFindTool as eo,createGrepTool as oo,createLsTool as to,createPowerShellTool as ro,createReadOnlyTools as no,createReadTool as io,createWriteTool as ao}from"./core/sdk.js";import{buildContextEntries as lo,buildSessionContext as mo,buildSessionProjection as co,CURRENT_SESSION_VERSION as po,getLatestCompactionEntry as So,migrateSessionEntries as To,parseSessionEntries as go,SessionManager as fo,sessionEntryToContextMessages as xo}from"./core/session-manager.js";import{SettingsManager as Co}from"./core/settings-manager.js";import{formatSkillsForPrompt as ho,loadSkills as Ro,loadSkillsFromDir as Po}from"./core/skills.js";import{createSyntheticSourceInfo as Lo}from"./core/source-info.js";import{generateDiffString as Mo,generateUnifiedPatch as _o}from"./core/tools/edit-diff.js";import{createBashToolDefinition as ko,createEditToolDefinition as yo,createFindToolDefinition as Fo,createGrepToolDefinition as Oo,createLocalBashOperations as No,createLocalPowerShellOperations as vo,createLsToolDefinition as Bo,createPowerShellToolDefinition as Ho,createProcessToolDefinition as bo,createReadToolDefinition as wo,createWriteToolDefinition as Uo,DEFAULT_MAX_BYTES as jo,DEFAULT_MAX_LINES as Vo,formatSize as Wo,registerShellExecutionGuard as Go,truncateHead as Ko,truncateLine as Xo,truncateTail as zo,withFileMutationQueue as Yo}from"./core/tools/index.js";import{hasTrustRequiringProjectResources as Qo,ProjectTrustStore as Jo}from"./core/trust-manager.js";import{VIRTUAL_MODEL_STATE_ENTRY as $o}from"./core/virtual-models.js";import{claimWorkspace as ot,gitDirOf as tt,readWorkspaceLock as rt,releaseWorkspace as nt,STALE_AFTER_MS as it,shellCommandDirectory as at,WORKSPACE_LOCK_FILE as st,workspaceLockIsLive as lt,workspaceOwnerSessionId as mt}from"./core/workspace-lock.js";import{applyShellEnvironmentPolicy as pt,DEFAULT_SHELL_ENV_EXCLUDES as St,isDalCodeCredentialName as dt,withoutDalCodeCredentials as Tt}from"./dal/child-env.js";export*from"./dal/hooks/index.js";import{isHostExtensionPath as xt,markHostExtensionPaths as Et}from"./dal/host-extensions.js";import{createCodemodeExtension as ut}from"./extensions/codemode/index.js";import{createMcpExtension as Rt}from"./extensions/mcp/index.js";import{createToolSearchExtension as Dt}from"./extensions/tool-search/index.js";import{main as At}from"./main.js";import{InteractiveMode as _t,RpcClient as It,runPrintMode as kt,runRpcMode as yt}from"./modes/index.js";import{ArminComponent as Ot,AssistantMessageComponent as Nt,BashExecutionComponent as vt,BorderedLoader as Bt,BranchSummaryMessageComponent as Ht,CompactionSummaryMessageComponent as bt,CustomEditor as wt,CustomMessageComponent as Ut,DynamicBorder as jt,ExtensionEditorComponent as Vt,ExtensionInputComponent as Wt,ExtensionSelectorComponent as Gt,FooterComponent as Kt,keyHint as Xt,keyText as zt,LoginDialogComponent as Yt,ModelSelectorComponent as qt,OAuthSelectorComponent as Qt,rawKeyHint as Jt,renderDiff as Zt,SessionSelectorComponent as $t,SettingsSelectorComponent as er,ShowImagesSelectorComponent as or,SkillInvocationMessageComponent as tr,ThemeSelectorComponent as rr,ThinkingSelectorComponent as nr,ToolExecutionComponent as ir,TreeSelectorComponent as ar,truncateToVisualLines as sr,UserMessageComponent as lr,UserMessageSelectorComponent as mr}from"./modes/interactive/components/index.js";import{getLanguageFromPath as pr,getMarkdownTheme as Sr,getSelectListTheme as dr,getSettingsListTheme as Tr,highlightCode as gr,initTheme as fr,Theme as xr}from"./modes/interactive/theme/theme.js";import{copyToClipboard as Cr}from"./utils/clipboard.js";import{parseFrontmatter as hr,stripFrontmatter as Rr}from"./utils/frontmatter.js";import{convertToPng as Dr}from"./utils/image-convert.js";import{formatDimensionNote as Ar,resizeImage as Mr}from"./utils/image-resize.js";import{detectSupportedImageMimeTypeFromFile as Ir}from"./utils/mime.js";import{getPowerShellConfig as yr,getShellConfig as Fr,getShellEnv as Or}from"./utils/shell.js";export{d as AgentSession,Xe as AgentSessionRuntime,Ot as ArminComponent,Nt as AssistantMessageComponent,E as BackgroundProcessManager,vt as BashExecutionComponent,Bt as BorderedLoader,Ht as BranchSummaryMessageComponent,n as CONFIG_DIR_NAME,po as CURRENT_SESSION_VERSION,bt as CompactionSummaryMessageComponent,fe as CredentialSynchronizationError,wt as CustomEditor,Ut as CustomMessageComponent,D as DEFAULT_COMPACTION_SETTINGS,jo as DEFAULT_MAX_BYTES,Vo as DEFAULT_MAX_LINES,St as DEFAULT_SHELL_ENV_EXCLUDES,Ce as DefaultPackageManager,Be as DefaultResourceLoader,jt as DynamicBorder,Vt as ExtensionEditorComponent,Wt as ExtensionInputComponent,j as ExtensionRunner,Gt as ExtensionSelectorComponent,Kt 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,_t as InteractiveMode,Yt as LoginDialogComponent,C as MAX_BACKGROUND_PROCESSES,pe as ModelRegistry,xe as ModelRuntime,qt as ModelSelectorComponent,Qt as OAuthSelectorComponent,Jo as ProjectTrustStore,It as RpcClient,We as SANDBOX_ENV,c as SHARED_SKILL_CONFIG_DIRS,it as STALE_AFTER_MS,fo as SessionManager,$t as SessionSelectorComponent,Co as SettingsManager,er as SettingsSelectorComponent,Ge as ShellSandbox,or as ShowImagesSelectorComponent,tr as SkillInvocationMessageComponent,xr as Theme,rr as ThemeSelectorComponent,nr as ThinkingSelectorComponent,ir as ToolExecutionComponent,ar as TreeSelectorComponent,lr as UserMessageComponent,mr as UserMessageSelectorComponent,p as VERSION,$o as VIRTUAL_MODEL_STATE_ENTRY,st as WORKSPACE_LOCK_FILE,pt as applyShellEnvironmentPolicy,lo as buildContextEntries,Oe as buildProjectMap,he as buildRuleSet,mo as buildSessionContext,co as buildSessionProjection,h as calculateContextTokens,ot as claimWorkspace,R as collectEntriesForBranchSummary,P as compact,me as convertToLlm,Dr as convertToPng,Cr as copyToClipboard,ze as createAgentSession,Ye as createAgentSessionFromServices,qe as createAgentSessionRuntime,Qe as createAgentSessionServices,Je as createBashTool,ko as createBashToolDefinition,ut as createCodemodeExtension,Ze as createCodingTools,$e as createEditTool,yo as createEditToolDefinition,B as createEventBus,b as createExtensionRuntime,eo as createFindTool,Fo as createFindToolDefinition,oo as createGrepTool,Oo as createGrepToolDefinition,No as createLocalBashOperations,vo as createLocalPowerShellOperations,to as createLsTool,Bo as createLsToolDefinition,Rt as createMcpExtension,ro as createPowerShellTool,Ho as createPowerShellToolDefinition,bo as createProcessToolDefinition,no as createReadOnlyTools,io as createReadTool,wo as createReadToolDefinition,Lo as createSyntheticSourceInfo,Dt as createToolSearchExtension,ao as createWriteTool,Uo as createWriteToolDefinition,w as defineTool,Ie as describeProjectFacts,ke as detectProjectFacts,we as detectSandboxAvailability,Ir as detectSupportedImageMimeTypeFromFile,U as discoverAndLoadExtensions,L as estimateTokens,Le as evaluateToolPolicy,A as findCutPoint,M as findTurnStartIndex,Ar as formatDimensionNote,Ne as formatProjectMapPrompt,Wo as formatSize,ho as formatSkillsForPrompt,_ as generateBranchSummary,Mo as generateDiffString,I as generateSummary,k as generateSummaryWithUsage,_o as generateUnifiedPatch,i as getAgentDir,a as getDocsPath,s as getExamplesPath,ee as getHostCapabilities,pr as getLanguageFromPath,y as getLastAssistantUsage,So as getLatestCompactionEntry,Sr as getMarkdownTheme,l as getPackageDir,yr as getPowerShellConfig,Ue as getProcessShellSandbox,m as getReadmePath,dr as getSelectListTheme,Tr as getSettingsListTheme,Fr as getShellConfig,Or as getShellEnv,tt as gitDirOf,Qo as hasTrustRequiringProjectResources,gr as highlightCode,fr as initTheme,V as isBashToolResult,dt as isDalCodeCredentialName,W as isEditToolResult,G as isFindToolResult,K as isGrepToolResult,xt as isHostExtensionPath,X as isLsToolResult,z as isPowerShellToolResult,Y as isReadToolResult,q as isToolCallEventType,Q as isWriteToolResult,Xt as keyHint,zt as keyText,He as loadProjectContextFiles,Ro as loadSkills,Po as loadSkillsFromDir,At as main,Et as markHostExtensionPaths,Re as matchPermissionRules,To as migrateSessionEntries,t as parseArgs,hr as parseFrontmatter,se as parseHostCapabilities,Pe as parsePermissionRule,go as parseSessionEntries,T as parseSkillBlock,F as prepareBranchEntries,ye as projectPackageManager,Jt as rawKeyHint,Ae as readAccessDenial,f as readStoredCredential,rt as readWorkspaceLock,Me as registerPermissionAskHandler,je as registerSandboxEscalationHandler,Go as registerShellExecutionGuard,nt as releaseWorkspace,Zt as renderDiff,Mr as resizeImage,de as resolveCliModel,Te as resolveModelScopeWithDiagnostics,Ve as resolveSandboxPolicy,kt as runPrintMode,yt as runRpcMode,O as serializeConversation,xo as sessionEntryToContextMessages,at as shellCommandDirectory,N as shouldCompact,Rr as stripFrontmatter,Ko as truncateHead,Xo as truncateLine,zo as truncateTail,sr as truncateToVisualLines,Yo as withFileMutationQueue,Tt as withoutDalCodeCredentials,lt as workspaceLockIsLive,mt as workspaceOwnerSessionId,J as wrapRegisteredTool,Z as wrapRegisteredTools};
package/dist/main.js CHANGED
@@ -1,4 +1,4 @@
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(`
1
+ var Be=Object.defineProperty;var m=(e,t)=>Be(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 K,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 St}from"./core/auth-storage.js";import{exportFromFile as wt}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 B}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 _t,dalBuiltinExtensionPaths as jt}from"./dal/builtins.js";import{markHostExtensionPaths as Ot}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 Kt,showDeprecationWarnings as Bt}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 Se}from"./utils/offline.js";import{isLocalPath as Jt,normalizePath as Qt,resolvePath as we}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 K?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 K(s.diagnostics.map(o=>o.message).join(`
2
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};
3
+ `),!0}const l=et(s,t.kind);let n,a;try{const o=t.noRefresh?new St: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 K?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: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(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,w=A?t.find(x=>We(x.model,A)):void 0;w?(a.model=w.model,!e.thinking&&w.thinkingLevel&&(a.thinkingLevel=w.thinkingLevel)):(a.model=t[0].model,!e.thinking&&t[0].thinkingLevel&&(a.thinkingLevel=t[0].thinkingLevel))}return e.thinking&&(a.thinkingLevel=e.thinking),t.length>0&&(a.scopedModels=t.map(i=>({model:i.model,thinkingLevel:i.thinkingLevel}))),e.noTools?a.noTools="all":e.noBuiltinTools&&(a.noTools="builtin"),e.tools&&(a.tools=[...e.tools]),e.excludeTools&&(a.excludeTools=[...e.excludeTools]),a.sandbox={defaultLevel:"workspace-write",...e.sandbox?{level:e.sandbox}:{},...e.sandboxAllowDomains?{allowedDomains:[...e.sandboxAllowDomains]}:{}},a.defaultActiveTools=["read","bash","edit","write","process"],{options:a,cliThinkingFromModel:o,diagnostics:p}}m(uo,"buildSessionOptions");function L(e,t){return t?.map(s=>Jt(s)?we(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")||Se(process.env.PI_OFFLINE);if(l&&(process.env.PI_OFFLINE="1",process.env.PI_SKIP_VERSION_CHECK="1",process.env.DAL_SKIP_VERSION_CHECK="1"),await no(e))return;process.platform==="win32"&&Xt(ut()),zt();const n=process.cwd(),a=mt(),p=B.create(n,a,{projectTrusted:!1});if(pe(p.getGlobalSettings().httpProxy),_t(),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 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=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:w}=Kt(n);h("runMigrations");const x=B.create(n,a),_=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)??[];Ot(Q);const Me=[...jt(),...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,_e=ce?!1:ae??o.projectTrustOverride??(!le||z.get(r)===!0),je=B.create(r,f,{projectTrusted:_e}),F=await ht({cwd:r,agentDir:f,settingsManager:je,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(Ke=>re.push({type:"warning",message:Ke}),"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(),Oe=H&&H.length>0?await Tt(H,D,{signal:AbortSignal.timeout(15e3)}):[],{options:v,cliThinkingFromModel:Ne,diagnostics:De}=uo(o,Oe,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 S=await pt(Ae,{cwd:y.getCwd(),agentDir:a,sessionManager:y});h("createAgentSessionRuntime");const{services:be,session:Ee,modelFallbackMessage:Fe}=S,{settingsManager:j,modelRuntime:X,resourceLoader:Re}=be;if(pe(j.getGlobalSettings().httpProxy),ge(j.getHttpIdleTimeoutMs()),o.help){W(_);const r=Re.getExtensions().extensions.flatMap(f=>Array.from(f.flags.values()));Ue(r),process.exit(0)}if(o.listModels!==void 0){W(ve([..._,...S.diagnostics]));const r=typeof o.listModels=="string"?o.listModels:void 0;await st(X,r,AbortSignal.timeout(15e3)),process.exit(0)}let O;i!=="rpc"&&i!=="acp"&&(O=await eo(),O!==void 0&&i==="interactive"&&(i="print")),h("readPipedStdin");const{initialMessage:Z,initialImages:ee}=await io(o,O);h("prepareInitialMessage"),Vt(j.getTheme(),i==="interactive"),h("initTheme"),i==="interactive"&&w.length>0&&await Bt(w),h("resolveModelScope");const te=ve([..._,...S.diagnostics]),oe=S.diagnostics.some(r=>r.type==="error");(i!=="interactive"||oe)&&W(te),oe&&(S.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=Se(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(S);else if(i==="acp")I(),await Wt(S);else if(i==="interactive"){const r=new $t(S,{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(S,{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.38",
3
+ "version": "1.0.39",
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.38",
21
+ "@dalcode/dal-pi-kit": "1.0.39",
22
22
  "typebox": "1.3.7"
23
23
  },
24
24
  "peerDependencies": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-gateway",
3
- "version": "1.0.38",
3
+ "version": "1.0.39",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -17,7 +17,7 @@
17
17
  ]
18
18
  },
19
19
  "dependencies": {
20
- "@dalcode/deepailab": "1.0.38"
20
+ "@dalcode/deepailab": "1.0.39"
21
21
  },
22
22
  "peerDependencies": {
23
23
  "@earendil-works/pi-coding-agent": "^1.0.9"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-goal",
3
- "version": "1.0.38",
3
+ "version": "1.0.39",
4
4
  "private": true,
5
5
  "description": "Goal mode for DAL: /goal keeps the agent working on one objective until it is verified complete, with token and continuation limits. Adapted from @narumitw/pi-goal 0.54.11 (MIT, narumiruna).",
6
6
  "license": "MIT",
@@ -21,7 +21,7 @@
21
21
  ]
22
22
  },
23
23
  "dependencies": {
24
- "@dalcode/dal-pi-kit": "1.0.38",
24
+ "@dalcode/dal-pi-kit": "1.0.39",
25
25
  "typebox": "1.3.27"
26
26
  },
27
27
  "peerDependencies": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-guard",
3
- "version": "1.0.38",
3
+ "version": "1.0.39",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -18,9 +18,9 @@
18
18
  ]
19
19
  },
20
20
  "dependencies": {
21
- "@dalcode/dal-pi-kit": "1.0.38",
22
- "@dalcode/dal-bridge": "1.0.38",
23
- "@dalcode/dal-halo": "1.0.38"
21
+ "@dalcode/dal-pi-kit": "1.0.39",
22
+ "@dalcode/dal-bridge": "1.0.39",
23
+ "@dalcode/dal-halo": "1.0.39"
24
24
  },
25
25
  "peerDependencies": {
26
26
  "@earendil-works/pi-coding-agent": "^1.0.9"
@@ -0,0 +1 @@
1
+ var h=Object.defineProperty;var o=(t,e)=>h(t,"name",{value:e,configurable:!0});var d=Object.defineProperty,n=o((t,e)=>d(t,"name",{value:e,configurable:!0}),"r");import{readFileSync as A,statSync as b}from"node:fs";import{resolve as C}from"node:path";const u="Co-Authored-By: DAL Code <noreply@deepailab.ai>",l=/\b(?:claude|anthropic|codex|openai|chatgpt|gpt-?\d|copilot|gemini|cursor|devin|grok)\b/i,m=/co-authored-by:[^\n\r"'`]*/gi,y=/(?:^|[;&|\n(`]|\$\()\s*(?:\w+=\S*\s+)*git(?:\s+(?:-[Cc]\s+\S+|--[\w-]+(?:=\S+)?))*\s+commit\b/;function s(t){return y.test(t)}o(s,"f"),n(s,"isGitCommit");function c(t){return(t.match(m)??[]).filter(e=>l.test(e))}o(c,"g"),n(c,"foreignCoAuthors");function g(t){if(!s(t)||c(t).length===0)return;let e=!1;return t.replace(m,i=>l.test(i)?t.includes(u)||e?"":(e=!0,u):i)}o(g,"x"),n(g,"rewriteCommitAttribution");const S=64*1024;function f(t){const e=[],i=/(?:\s-F\s*|\s--file(?:=|\s+))(?:"([^"]+)"|'([^']+)'|(\S+))/g;for(const r of t.matchAll(i)){const a=r[1]??r[2]??r[3];a&&a!=="-"&&e.push(a)}return e}o(f,"S"),n(f,"commitMessageFiles");function p(t,e){if(s(t))for(const i of f(t)){const r=C(e,i);try{if(b(r).size>S)continue;if(c(A(r,"utf8")).length>0)return i}catch{}}}o(p,"E"),n(p,"foreignAttributionInMessageFile");export{u as DAL_CO_AUTHOR,f as commitMessageFiles,p as foreignAttributionInMessageFile,c as foreignCoAuthors,s as isGitCommit,g as rewriteCommitAttribution};
@@ -1 +1 @@
1
- var k=Object.defineProperty;var s=(e,r)=>k(e,"name",{value:r,configurable:!0});var x=Object.defineProperty,a=s((e,r)=>x(e,"name",{value:r,configurable:!0}),"i");import{readFileSync as N,realpathSync as y,statSync as O}from"node:fs";import{homedir as l}from"node:os";import{basename as w,dirname as R,isAbsolute as T,join as F,resolve as _}from"node:path";import{t as $}from"@dalcode/dal-pi-kit";import{getAgentDir as h}from"@earendil-works/pi-coding-agent";const g=["auth.json","factory.json","web.json"],L=16,I=new Set(["access","refresh","vk","key","apiKey","api_key","token","accessToken","refreshToken"]),A="[DAL \u51ED\u636E\u5DF2\u9690\u85CF]";function f(e){try{return y(e)}catch{try{return F(y(R(e)),w(e))}catch{return e}}}s(f,"u"),a(f,"realPathBestEffort");function d(){const e=h();return g.map(r=>F(e,r))}s(d,"E"),a(d,"dalCredentialFiles");function C(e){return e==="~"?l():e.startsWith("~/")||e.startsWith("~\\")?F(l(),e.slice(2)):e}s(C,"b"),a(C,"expandHome");function S(e){const r=[],u=a((n,t)=>{if(!(t>3)){if(typeof n=="string")r.push(n);else if(Array.isArray(n))for(const o of n)u(o,t+1);else if(n&&typeof n=="object")for(const o of Object.values(n))u(o,t+1)}},"visit");return u(e,0),r}s(S,"F"),a(S,"pathArguments");function j(e,r){const u=d(),n=new Set(u.map(f)),t=h(),o=[t,t.replace(l(),"~"),t.replace(l(),"$HOME"),".dal/agent"];for(const B of S(e.input)){const i=B.trim();if(i){if(!/\s/.test(i)){const c=_(r,C(i));if(n.has(f(c))||(e.toolName==="grep"||e.toolName==="find")&&T(c)&&f(c)===f(t))return c}if((o.some(c=>i.includes(c))||i.includes("DAL_CODING_AGENT_DIR"))&&g.some(c=>i.includes(c)))return i}}}s(j,"W"),a(j,"namesDalCredential");function b(){return $("dal-guard\uFF1A\u8FD9\u662F DAL \u81EA\u5DF1\u7684\u51ED\u636E\u6587\u4EF6\uFF08~/.dal/agent \u4E0B\u7684\u767B\u5F55\u4EE4\u724C\u548C\u670D\u52A1\u5BC6\u94A5\uFF09\uFF0C\u4E0D\u5C5E\u4E8E\u4F60\u7684\u9879\u76EE\uFF0C\u5DF2\u62D2\u7EDD\u8BFB\u53D6\u6216\u4FEE\u6539\u3002\u9700\u8981\u7BA1\u7406\u8D26\u53F7\u8BF7\u7528 /login\u3001/logout \u6216 /account\u3002")}s(b,"z"),a(b,"credentialBlockReason");let D;function m(e,r,u){if(typeof e=="string"){u&&I.has(u)&&e.length>=L&&r.add(e);return}if(Array.isArray(e)){for(const n of e)m(n,r,u);return}if(e&&typeof e=="object")for(const[n,t]of Object.entries(e))m(t,r,n)}s(m,"d"),a(m,"collectSecrets");function p(){const e=d(),r=e.map(t=>{try{const o=O(t);return`${t}:${o.mtimeMs}:${o.size}`}catch{return`${t}:-`}}).join("|");if(D?.signature===r)return D.values;const u=new Set;for(const t of e)try{m(JSON.parse(N(t,"utf8")),u)}catch{}const n=[...u].sort((t,o)=>o.length-t.length);return D={signature:r,values:n},n}s(p,"x"),a(p,"dalSecretValues");function E(e,r=p()){let u=e;for(const n of r)u.includes(n)&&(u=u.split(n).join(A));return u}s(E,"I"),a(E,"redactDalSecrets");function v(e){const r=p();if(r.length===0)return;let u=!1;const n=e.map(t=>{if(t.type!=="text"||typeof t.text!="string")return t;const o=E(t.text,r);return o===t.text?t:(u=!0,{...t,text:o})});return u?n:void 0}s(v,"J"),a(v,"redactContent");export{A as REDACTED,b as credentialBlockReason,d as dalCredentialFiles,p as dalSecretValues,j as namesDalCredential,v as redactContent,E as redactDalSecrets};
1
+ var J=Object.defineProperty;var o=(e,u)=>J(e,"name",{value:u,configurable:!0});var K=Object.defineProperty,a=o((e,u)=>K(e,"name",{value:u,configurable:!0}),"i");import{readFileSync as $,realpathSync as x,statSync as j}from"node:fs";import{homedir as m}from"node:os";import{basename as v,dirname as X,isAbsolute as Y,join as F,relative as Q,resolve as b}from"node:path";import{t as k}from"@dalcode/dal-pi-kit";import{getAgentDir as N}from"@earendil-works/pi-coding-agent";const _=["auth.json","factory.json","web.json"],R=16,U=new Set(["access","refresh","vk","key","apiKey","api_key","token","accessToken","refreshToken"]),M="[DAL \u51ED\u636E\u5DF2\u9690\u85CF]";function p(e){try{return x(e)}catch{try{return F(x(X(e)),v(e))}catch{return e}}}o(p,"d"),a(p,"realPathBestEffort");function h(){const e=N();return _.map(u=>F(e,u))}o(h,"M"),a(h,"dalCredentialFiles");function E(e){return e==="~"?m():e.startsWith("~/")||e.startsWith("~\\")?F(m(),e.slice(2)):e}o(E,"S"),a(E,"expandHome");const Z=new Set(["content","text","oldText","newText","old_string","new_string","edits","prompt","description","message","summary","title","reason","body","note","notes","pattern","query"]),ee=new Set(["command","script","code","cmd"]);function O(e){const u=[],r=[],s=a((t,n,c)=>{if(!(n>3||c!==void 0&&Z.has(c))){if(typeof t=="string")c!==void 0&&ee.has(c)?r.push(t):u.push(t);else if(Array.isArray(t))for(const i of t)s(i,n+1,c);else if(t&&typeof t=="object")for(const[i,f]of Object.entries(t))s(f,n+1,i)}},"visit");return s(e,0,void 0),{paths:u,commands:r}}o(O,"z"),a(O,"toolArguments");function A(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}o(A,"R"),a(A,"escapeRegExp");function H(e){const u=m(),r=[e,e.replace(u,"~"),e.replace(u,"$HOME"),".dal/agent"],s=Q(u,e);s&&!s.startsWith("..")&&!Y(s)&&r.push(s);const t=[...new Set(r)].map(n=>A(n.replace(/\\/g,"/"))).join("|");return new RegExp(`(?:^|[^\\w.~$-])(?:${t})(?![\\w.-])`)}o(H,"B"),a(H,"agentDirPattern");const te=new RegExp(`(?<![\\w.-])(?:${_.map(A).join("|")})(?![\\w.-])`);function T(e,u){const r=h(),s=new Set(r.map(p)),t=N(),{paths:n,commands:c}=O(e.input);for(const f of n){const l=f.trim();if(!l||/\s/.test(l))continue;const C=b(u,E(l));if(s.has(p(C))||(e.toolName==="grep"||e.toolName==="find")&&p(C)===p(t))return C}const i=H(t);for(const f of c){const l=f.replace(/\\/g,"/");if((i.test(l)||l.includes("DAL_CODING_AGENT_DIR"))&&te.test(l))return f}}o(T,"rt"),a(T,"namesDalCredential");const z=64*1024,ue=64,ne=new Set(["rm","unlink","shred","trash","srm"]),D=new Map;function L(e){try{return j(e)}catch{return}}o(L,"V"),a(L,"statBestEffort");function B(e,u=d()){if(u.length===0)return!1;const r=L(e);if(!r?.isFile()||r.size>z||r.size<R)return!1;const s=`${p(e)}\0${r.mtimeMs}\0${r.size}\0${g?.signature??""}`,t=D.get(s);if(t!==void 0)return t;let n=!1;try{const c=$(e,"utf8");n=u.some(i=>c.includes(i))}catch{n=!1}return D.size>2048&&D.clear(),D.set(s,n),n}o(B,"X"),a(B,"fileHoldsDalSecret");const P=/^\$(?:HOME|\{HOME\})(?=\/|$)/;function W(e){const u=P.exec(e);return u?F(m(),e.slice(u[0].length)):E(e)}o(W,"q"),a(W,"expandShellHome");function S(e){const u=[];for(const r of e.split(/[;&|\n]+/)){const s=r.split(/[\s'"`()<>{}]+/).flatMap(n=>n.split("=")).map(n=>n.replace(/^[,:]+|[,:]+$/g,"")).filter(n=>n.length>0),t=/^\s*(?:\w+=\S*\s+)*(?:(?:sudo|command|exec)\s+)*(\S+)/.exec(r)?.[1];if(!(t&&ne.has(v(t))))for(const n of s)n.startsWith("-")||/[*?[\]]/.test(n)||n.includes("$(")||n.includes("$")&&!P.test(n)||u.push(W(n))}return[...new Set(u)]}o(S,"J"),a(S,"shellPathCandidates");function I(e,u){let r;if(e.toolName==="bash"||e.toolName==="powershell"){const t=e.input.command;r=typeof t=="string"?S(t):[]}else if(e.toolName==="read"||e.toolName==="grep"){const t=e.input,n=t.path??t.file_path;r=typeof n=="string"&&n.trim()?[E(n.trim())]:[]}else return;if(r.length===0)return;const s=d();if(s.length!==0){for(const t of r.slice(0,ue))if(B(b(u,t),s))return t}}o(I,"st"),a(I,"readsDalSecretCopy");function G(e){return k("dal-guard\uFF1A{path} \u91CC\u6709 DAL \u5F53\u524D\u8D26\u53F7\u7684\u767B\u5F55\u4EE4\u724C\uFF08\u662F ~/.dal/agent \u51ED\u636E\u6587\u4EF6\u7684\u526F\u672C\uFF09\uFF0C\u5DF2\u62D2\u7EDD\u8BFB\u53D6\u3001\u641C\u7D22\u6216\u590D\u5236\u3002\u4E0D\u8981\u6362\u522B\u7684\u529E\u6CD5\u62FF\u8FD9\u4E9B\u6570\u636E\uFF1A\u505C\u4E0B\u6765\u544A\u8BC9\u7528\u6237\u8FD9\u4E00\u6B65\u88AB\u62E6\u4E0B\u4EE5\u53CA\u539F\u56E0\u3002\u9700\u8981\u8D26\u53F7\u8BF7\u8BA9\u7528\u6237\u7528 /login\u3002").replace("{path}",e)}o(G,"ot"),a(G,"secretCopyBlockReason");function V(){return k("dal-guard\uFF1A\u8FD9\u662F DAL \u81EA\u5DF1\u7684\u51ED\u636E\u6587\u4EF6\uFF08~/.dal/agent \u4E0B\u7684\u767B\u5F55\u4EE4\u724C\u548C\u670D\u52A1\u5BC6\u94A5\uFF09\uFF0C\u4E0D\u5C5E\u4E8E\u4F60\u7684\u9879\u76EE\uFF0C\u5DF2\u62D2\u7EDD\u8BFB\u53D6\u6216\u4FEE\u6539\u3002\u9700\u8981\u7BA1\u7406\u8D26\u53F7\u8BF7\u7528 /login\u3001/logout \u6216 /account\u3002")}o(V,"it"),a(V,"credentialBlockReason");let g;function y(e,u,r){if(typeof e=="string"){r&&U.has(r)&&e.length>=R&&u.add(e);return}if(Array.isArray(e)){for(const s of e)y(s,u,r);return}if(e&&typeof e=="object")for(const[s,t]of Object.entries(e))y(t,u,s)}o(y,"x"),a(y,"collectSecrets");function d(){const e=h(),u=e.map(t=>{try{const n=j(t);return`${t}:${n.mtimeMs}:${n.size}`}catch{return`${t}:-`}}).join("|");if(g?.signature===u)return g.values;const r=new Set;for(const t of e)try{y(JSON.parse($(t,"utf8")),r)}catch{}const s=[...r].sort((t,n)=>n.length-t.length);return g={signature:u,values:s},s}o(d,"E"),a(d,"dalSecretValues");function w(e,u=d()){let r=e;for(const s of u)r.includes(s)&&(r=r.split(s).join(M));return r}o(w,"Q"),a(w,"redactDalSecrets");function q(e){const u=d();if(u.length===0)return;let r=!1;const s=e.map(t=>{if(t.type!=="text"||typeof t.text!="string")return t;const n=w(t.text,u);return n===t.text?t:(r=!0,{...t,text:n})});return r?s:void 0}o(q,"ct"),a(q,"redactContent");export{z as MAX_SCANNED_FILE_BYTES,M as REDACTED,V as credentialBlockReason,h as dalCredentialFiles,d as dalSecretValues,B as fileHoldsDalSecret,T as namesDalCredential,I as readsDalSecretCopy,q as redactContent,w as redactDalSecrets,G as secretCopyBlockReason,S as shellPathCandidates};
@@ -1 +1 @@
1
- var U=Object.defineProperty;var l=(u,s)=>U(u,"name",{value:s,configurable:!0});var H=Object.defineProperty,r=l((u,s)=>H(u,"name",{value:s,configurable:!0}),"a");import{realpathSync as N}from"node:fs";import{basename as L,dirname as V,isAbsolute as G,join as q,relative as W,resolve as C,sep as J}from"node:path";import{readBridgeConfig as c}from"@dalcode/dal-bridge/client";import{getOwnTty as K,requestHaloApproval as Z}from"@dalcode/dal-halo";import{hasChosenLanguage as Q,t as e}from"@dalcode/dal-pi-kit";import{DAL_HOOK_NOTIFICATION_CHANNEL as X,getAgentDir as A,registerSandboxEscalationHandler as Y}from"@earendil-works/pi-coding-agent";import{credentialBlockReason as uu,namesDalCredential as eu,redactContent as au}from"./credentials.js";import{exportGuardMode as su,saveGuardMode as I,shouldAskGuardMode as tu,startupGuardMode as ou}from"./mode.js";import{reviewBashCommand as ru}from"./review.js";import{dalSecretValues as nu,namesDalCredential as iu,REDACTED as lu,redactContent as Fu,redactDalSecrets as du}from"./credentials.js";import{GUARD_MODE_ENV as Eu,savedGuardMode as cu,saveGuardMode as Au,shouldAskGuardMode as Du,startupGuardMode as mu}from"./mode.js";import{reviewBashCommand as Bu,suspicionFor as fu}from"./review.js";function g(u){try{return N(u)}catch{try{return q(N(V(u)),L(u))}catch{return u}}}l(g,"x"),r(g,"realPathBestEffort");const F=r(u=>s=>u.test(s),"has"),pu=[{id:"sudo",label:e("\u7279\u6743\u6267\u884C\uFF08sudo/doas\uFF09"),test:F(/(^|[;&|\n]\s*)(sudo|doas)\s/)},{id:"force-push",label:e("\u5F3A\u5236\u63A8\u9001\u5C06\u6539\u5199\u8FDC\u7A0B\u5386\u53F2"),test:F(/git\s+push\b[^;&|]*(--force\b|--force-with-lease\b|\s-f\b)/)},{id:"hard-reset",label:e("\u786C\u91CD\u7F6E\u4F1A\u4E22\u5F03\u672C\u5730\u6539\u52A8"),test:F(/git\s+reset\b[^;&|]*--hard/)},{id:"git-clean",label:e("git clean \u4F1A\u5220\u9664\u672A\u8DDF\u8E2A\u6587\u4EF6"),test:F(/git\s+clean\b[^;&|]*(-[a-z]*f|--force)/)},{id:"pipe-to-shell",label:e("\u5C06\u4E0B\u8F7D\u5185\u5BB9\u76F4\u63A5\u7BA1\u9053\u6267\u884C"),test:F(/(curl|wget)\b[^;&|]*\|\s*(ba|z|da|fi)?sh\b/)},{id:"exec-download",label:e("\u6267\u884C\u4E0B\u8F7D\u7684\u811A\u672C"),test:F(/\b(ba|z|da|fi)?sh\s+<\(\s*(curl|wget)\b|eval\b[^;&|\n]*\$\(\s*(curl|wget)\b/)},{id:"recursive-perms",label:e("\u9012\u5F52\u4FEE\u6539\u6743\u9650/\u5C5E\u4E3B"),test:F(/(chmod|chown)\b[^;&|]*-[a-zA-Z]*R/)},{id:"publish",label:e("\u53D1\u5E03\u8F6F\u4EF6\u5305"),test:F(/(npm|pnpm|yarn)\s+publish\b/)},{id:"kill",label:e("\u6309\u540D\u79F0\u7ED3\u675F\u8FDB\u7A0B"),test:F(/(^|[;&|\n]\s*)(killall|pkill)\s/)},{id:"disk",label:e("\u5E95\u5C42\u78C1\u76D8\u64CD\u4F5C"),test:F(/(^|[;&|\n]\s*)(dd|mkfs\w*|diskutil|fdisk)\s/)}];function h(u){return pu.find(s=>s.test(u))}l(h,"X"),r(h,"riskForBash");function b(u,s){const t=g(G(u)?C(u):C(s,u)),a=g(C(s)),o=W(a,t);return o===".."||o.startsWith(`..${J}`)||G(o)}l(b,"Y"),r(b,"pathOutsideProject");function y(u,s){if(u.toolName.startsWith("mcp__")){const t=u.toolName.split("__")[1]||"unknown",a=JSON.stringify(u.input??{});return{ruleId:`mcp:${t}`,title:`${e("\u7B2C\u4E09\u65B9 MCP \u5DE5\u5177\u8C03\u7528\uFF08")}${t}${e("\uFF09")}`,detail:`${u.toolName} ${a.length>200?`${a.slice(0,200)}\u2026`:a}`}}if(u.toolName==="bash"){const t=String(u.input.command??""),a=h(t);return a?{ruleId:`bash:${a.id}`,title:a.label,detail:t}:void 0}if(u.toolName==="edit"||u.toolName==="write"){const t=String(u.input.path??u.input.file_path??"");if(t&&b(t,s))return{ruleId:`${u.toolName}:outside-project`,title:e("\u9879\u76EE\u76EE\u5F55\u4E4B\u5916\u7684\u6587\u4EF6\u6539\u52A8"),detail:t}}}l(y,"ee"),r(y,"classify");async function S(u,s){if(u.toolName!=="bash")return;const t=String(u.input.command??""),a=await ru(t,s);if(a)return{ruleId:`bash:jev-${a.suspicion.id}`,title:`${e("jev \u590D\u6838\u5224\u5B9A\u53EF\u7591")} (${Math.round(a.confidence*100)}%)`,detail:t}}l(S,"oe"),r(S,"secondOpinion");const Cu=r(()=>e("\u4EC5\u672C\u6B21\u5141\u8BB8"),"allowOnce"),gu=r(()=>e("\u672C\u6B21\u4F1A\u8BDD\u5185\u5141\u8BB8\uFF08\u540C\u7C7B\u64CD\u4F5C\uFF09"),"allowSession"),hu=r(()=>e("\u62D2\u7EDD"),"deny"),O=Symbol.for("dalcode.guard.state"),T=globalThis;T[O]??={mode:"default",sessionAllows:new Set};const i=T[O];function D(u){i.mode=u,su(u)}l(D,"w"),r(D,"setGuardMode");function P(){i.escalationApprover||(i.escalationApprover=Y(()=>{if(!(i.mode!=="yolo"||c(process.env)))return{approved:!0,scope:"once"}}))}l(P,"re"),r(P,"registerEscalationApprover");const m=i.sessionAllows;async function v(u,s,t,a,o,d=process.env,B){if(eu(u,s))return{block:!0,reason:uu()};if(i.mode==="yolo"||c(d))return;const n=y(u,s)??await S(u,s);if(!n||m.has(n.ruleId))return;if(!t||!a)return{block:!0,reason:`${e('dal-guard\uFF1A"')}${n.title}${e('"\u9700\u8981\u4EA4\u4E92\u5F0F\u5BA1\u6279\uFF08')}${n.detail}${e("\uFF09\u3002\u8BF7\u5728\u4EA4\u4E92\u6A21\u5F0F\u4E0B\u91CD\u8BD5\uFF0C\u6216\u7528 /guard yolo \u5173\u95ED\u5BA1\u6279\u95E8\u3002")}`};const f=o?Z({session_id:o.sessionId,cwd:s,event:"PermissionRequest",status:"waiting_for_approval",pid:process.pid,tty:K(),tool:u.toolName,tool_input:{command:n.detail},tool_use_id:u.toolCallId,productName:"dal"}):void 0;B?.({type:"permission_prompt",message:`DAL needs your permission to use ${u.toolName}`});const $=new AbortController,[p,w,_]=[Cu(),gu(),hu()],R=a.select(`${e("\u9700\u8981\u5BA1\u6279\uFF1A")}${n.title} \u2014 ${n.detail}`,[p,w,_],{signal:$.signal}).then(E=>({surface:"terminal",choice:E})),z=f?f.decision.then(E=>E===void 0?new Promise(()=>{}):{surface:"halo",choice:E==="allow"?p:_}):new Promise(()=>{}),M=await Promise.race([R,z]);M.surface==="halo"?$.abort():f?.cancel();const k=M.choice;if(k!==p){if(k===w){m.add(n.ruleId);return}return{block:!0,reason:`${e("dal-guard\uFF1A\u7528\u6237\u5DF2\u62D2\u7EDD\uFF08")}${n.title}${e("\uFF09\u3002")}`}}}l(v,"ae"),r(v,"evaluateToolCall");async function j(u){const s=e("\u5168\u81EA\u52A8\uFF1A\u4E0D\u518D\u8BE2\u95EE\uFF0C\u53EA\u62E6\u622A\u7834\u574F\u6027\u547D\u4EE4\uFF08\u63A8\u8350\u719F\u6089\u7684\u7528\u6237\uFF09"),t=e("\u6BCF\u6B21\u8BE2\u95EE\uFF1A\u9AD8\u98CE\u9669\u64CD\u4F5C\u548C\u8D8A\u51FA\u6C99\u7BB1\u524D\u5148\u95EE\u6211"),a=await u.ui.select(e("\u9009\u62E9 dal \u7684\u5DE5\u4F5C\u65B9\u5F0F\uFF08\u4EE5\u540E\u53EF\u7528 /guard \u4FEE\u6539\uFF09"),[s,t]);if(a===void 0)return;const o=a===s?"yolo":"default";D(o);try{I(A(),o)}catch(d){u.ui.notify(`${e("\u4FDD\u5B58\u5931\u8D25\uFF1A")}${d instanceof Error?d.message:String(d)}`,"error");return}u.ui.notify(o==="yolo"?e("\u5DF2\u8BBE\u4E3A\u5168\u81EA\u52A8\u3002\u6539\u56DE\u6BCF\u6B21\u8BE2\u95EE\uFF1A/guard default save"):e("\u5DF2\u8BBE\u4E3A\u6BCF\u6B21\u8BE2\u95EE\u3002\u6539\u6210\u5168\u81EA\u52A8\uFF1A/guard yolo save"),"info")}l(j,"ie"),r(j,"askGuardModeOnce");function x(u){u.registerFlag("yolo",{description:e("\u4EE5\u5168\u81EA\u52A8\u6A21\u5F0F\u542F\u52A8\uFF1A\u4E0D\u518D\u5F39\u51FA\u4EFB\u4F55\u5BA1\u6279\uFF08\u542B\u6C99\u7BB1\u8D8A\u6743\uFF09\uFF0C\u53EA\u62E6\u622A\u7834\u574F\u6027\u547D\u4EE4\u548C\u767B\u5F55\u51ED\u636E"),type:"boolean",default:!1}),P();let s="default";u.on("session_start",async(t,a)=>{if(s="default",i.started)return;i.started=!0;const o=u.getFlag("yolo")===!0;D(ou(A(),o)),t.reason==="startup"&&tu({agentDir:A(),mode:a.mode,hasUI:a.hasUI,flag:o,underDalCode:!!c(process.env),languageChosen:Q()})&&await j(a)}),u.on("before_agent_start",async()=>{if(!(i.mode===s||c(process.env)))return s=i.mode,{message:{customType:"dal-guard-mode",content:i.mode==="yolo"?e("[\u5168\u81EA\u52A8\u6A21\u5F0F] \u7528\u6237\u5F00\u542F\u4E86\u5168\u81EA\u52A8\uFF1A\u6240\u6709\u5BA1\u6279\uFF08\u5305\u62EC sandbox_escalation \u8D8A\u6743\uFF09\u90FD\u4F1A\u81EA\u52A8\u901A\u8FC7\uFF0C\u4E0D\u4F1A\u6709\u4EBA\u6765\u786E\u8BA4\u3002\u547D\u4EE4\u88AB\u6C99\u7BB1\u6321\u4F4F\u3001\u800C\u4EFB\u52A1\u786E\u5B9E\u9700\u8981\u65F6\uFF0C\u76F4\u63A5\u5E26 sandbox_escalation \u91CD\u8BD5\uFF0C\u4E0D\u8981\u505C\u4E0B\u6765\u95EE\u7528\u6237\u8981\u4E0D\u8981\u653E\u884C\u3002\u7834\u574F\u6027\u547D\u4EE4\u548C\u767B\u5F55\u51ED\u636E\u4ECD\u4F1A\u88AB\u62E6\u622A\u3002"):e("[\u5BA1\u6279\u5DF2\u6062\u590D] \u5168\u81EA\u52A8\u5DF2\u5173\u95ED\uFF1A\u8D8A\u6743\u548C\u9AD8\u98CE\u9669\u547D\u4EE4\u4F1A\u5148\u8BE2\u95EE\u7528\u6237\u3002"),display:!1}}}),u.on("tool_call",async(t,a)=>v(t,a.cwd,a.hasUI,a.ui,{sessionId:a.sessionManager.getSessionId()},process.env,o=>u.events.emit(X,o))),u.on("tool_result",async t=>{const a=au(t.content);return a?{content:a}:void 0}),u.registerCommand("guard",{description:e("\u67E5\u770B\u6216\u5207\u6362\u5BA1\u6279\u95E8\uFF08default | yolo\uFF0C\u52A0 save \u8BB0\u4E3A\u9ED8\u8BA4\uFF09"),handler:r(async(t,a)=>{const[o,d]=t.trim().split(/\s+/);if((o==="yolo"||o==="default")&&(D(o),d==="save"))try{I(A(),o),a.ui.notify(o==="yolo"?e("\u5DF2\u8BBE\u4E3A\u9ED8\u8BA4\uFF1A\u4EE5\u540E\u542F\u52A8\u90FD\u662F\u5168\u81EA\u52A8"):e("\u5DF2\u6062\u590D\u9ED8\u8BA4\uFF1A\u4EE5\u540E\u542F\u52A8\u90FD\u4F1A\u8BE2\u95EE"),"info")}catch(n){a.ui.notify(`${e("\u4FDD\u5B58\u5931\u8D25\uFF1A")}${n instanceof Error?n.message:String(n)}`,"error")}const B=m.size?`${e(" \xB7 \u672C\u6B21\u4F1A\u8BDD\u5DF2\u5141\u8BB8\uFF1A")}${[...m].join(", ")}`:"";a.ui.notify(`${e("dal-guard \u6A21\u5F0F\uFF1A")}${i.mode}${B}`,i.mode==="yolo"?"warning":"info")},"handler")})}l(x,"le"),r(x,"default");export{Eu as GUARD_MODE_ENV,lu as REDACTED,y as classify,nu as dalSecretValues,x as default,v as evaluateToolCall,iu as namesDalCredential,b as pathOutsideProject,Fu as redactContent,du as redactDalSecrets,Bu as reviewBashCommand,h as riskForBash,Au as saveGuardMode,cu as savedGuardMode,Du as shouldAskGuardMode,mu as startupGuardMode,fu as suspicionFor};
1
+ var J=Object.defineProperty;var l=(u,a)=>J(u,"name",{value:a,configurable:!0});var K=Object.defineProperty,n=l((u,a)=>K(u,"name",{value:a,configurable:!0}),"l");import{realpathSync as O}from"node:fs";import{basename as Q,dirname as X,isAbsolute as N,join as Y,relative as Z,resolve as b,sep as uu}from"node:path";import{readBridgeConfig as C}from"@dalcode/dal-bridge/client";import{getOwnTty as eu,requestHaloApproval as au}from"@dalcode/dal-halo";import{hasChosenLanguage as ou,t as e}from"@dalcode/dal-pi-kit";import{DAL_HOOK_NOTIFICATION_CHANNEL as tu,getAgentDir as D,registerSandboxEscalationHandler as su}from"@earendil-works/pi-coding-agent";import{DAL_CO_AUTHOR as P,foreignAttributionInMessageFile as ru,rewriteCommitAttribution as iu}from"./attribution.js";import{credentialBlockReason as nu,namesDalCredential as lu,readsDalSecretCopy as du,redactContent as Fu,secretCopyBlockReason as cu}from"./credentials.js";import{exportGuardMode as Eu,saveGuardMode as T,shouldAskGuardMode as Au,startupGuardMode as mu}from"./mode.js";import{wrongPackageManager as fu}from"./package-manager.js";import{reviewBashCommand as Cu}from"./review.js";import{createWorkspaceGate as Du}from"./workspace.js";import{DAL_CO_AUTHOR as pu,foreignAttributionInMessageFile as Bu,foreignCoAuthors as gu,isGitCommit as hu,rewriteCommitAttribution as bu}from"./attribution.js";import{dalSecretValues as yu,fileHoldsDalSecret as wu,namesDalCredential as vu,REDACTED as $u,readsDalSecretCopy as ku,redactContent as _u,redactDalSecrets as Mu,shellPathCandidates as Iu}from"./credentials.js";import{GUARD_MODE_ENV as Su,savedGuardMode as Gu,saveGuardMode as Ou,shouldAskGuardMode as Nu,startupGuardMode as Pu}from"./mode.js";import{installingManager as Tu,wrongPackageManager as Uu}from"./package-manager.js";import{reviewBashCommand as Ru,suspicionFor as xu}from"./review.js";import{createWorkspaceGate as Lu,modifiedDirectory as ju}from"./workspace.js";const U=new Set;function R(u,a){if(u.toolName!=="bash"&&u.toolName!=="powershell")return;const s=u.input;if(typeof s.command!="string")return;const r=ru(s.command,a);if(r)return{block:!0,reason:e("dal-guard\uFF1A\u63D0\u4EA4\u8BF4\u660E\u6587\u4EF6 {file} \u628A\u53E6\u4E00\u4E2A\u4EA7\u54C1\u7684\u52A9\u624B\uFF08Claude\u3001Codex\u3001Copilot \u7B49\uFF09\u5199\u6210\u4E86\u5171\u540C\u4F5C\u8005\u3002\u4F60\u662F DAL Code\uFF1A\u628A\u90A3\u884C\u6539\u6210 {trailer} \u6216\u5220\u6389\uFF0C\u518D\u63D0\u4EA4\u3002").replace("{file}",r).replace("{trailer}",P)};const o=iu(s.command);o!==void 0&&(s.command=o,U.add(u.toolCallId))}l(R,"le"),n(R,"checkCommitAttribution");function y(u){try{return O(u)}catch{try{return Y(O(X(u)),Q(u))}catch{return u}}}l(y,"N"),n(y,"realPathBestEffort");const E=n(u=>a=>u.test(a),"has"),Hu=[{id:"sudo",label:e("\u7279\u6743\u6267\u884C\uFF08sudo/doas\uFF09"),test:E(/(^|[;&|\n]\s*)(sudo|doas)\s/)},{id:"force-push",label:e("\u5F3A\u5236\u63A8\u9001\u5C06\u6539\u5199\u8FDC\u7A0B\u5386\u53F2"),test:E(/git\s+push\b[^;&|]*(--force\b|--force-with-lease\b|\s-f\b)/)},{id:"hard-reset",label:e("\u786C\u91CD\u7F6E\u4F1A\u4E22\u5F03\u672C\u5730\u6539\u52A8"),test:E(/git\s+reset\b[^;&|]*--hard/)},{id:"git-clean",label:e("git clean \u4F1A\u5220\u9664\u672A\u8DDF\u8E2A\u6587\u4EF6"),test:E(/git\s+clean\b[^;&|]*(-[a-z]*f|--force)/)},{id:"pipe-to-shell",label:e("\u5C06\u4E0B\u8F7D\u5185\u5BB9\u76F4\u63A5\u7BA1\u9053\u6267\u884C"),test:E(/(curl|wget)\b[^;&|]*\|\s*(ba|z|da|fi)?sh\b/)},{id:"exec-download",label:e("\u6267\u884C\u4E0B\u8F7D\u7684\u811A\u672C"),test:E(/\b(ba|z|da|fi)?sh\s+<\(\s*(curl|wget)\b|eval\b[^;&|\n]*\$\(\s*(curl|wget)\b/)},{id:"recursive-perms",label:e("\u9012\u5F52\u4FEE\u6539\u6743\u9650/\u5C5E\u4E3B"),test:E(/(chmod|chown)\b[^;&|]*-[a-zA-Z]*R/)},{id:"publish",label:e("\u53D1\u5E03\u8F6F\u4EF6\u5305"),test:E(/(npm|pnpm|yarn)\s+publish\b/)},{id:"kill",label:e("\u6309\u540D\u79F0\u7ED3\u675F\u8FDB\u7A0B"),test:E(/(^|[;&|\n]\s*)(killall|pkill)\s/)},{id:"disk",label:e("\u5E95\u5C42\u78C1\u76D8\u64CD\u4F5C"),test:E(/(^|[;&|\n]\s*)(dd|mkfs\w*|diskutil|fdisk)\s/)}];function w(u){return Hu.find(a=>a.test(u))}l(w,"ue"),n(w,"riskForBash");function v(u,a){const s=y(N(u)?b(u):b(a,u)),r=y(b(a)),o=Z(r,s);return o===".."||o.startsWith(`..${uu}`)||N(o)}l(v,"ce"),n(v,"pathOutsideProject");function $(u,a){if(u.toolName.startsWith("mcp__")){const s=u.toolName.split("__")[1]||"unknown",r=JSON.stringify(u.input??{});return{ruleId:`mcp:${s}`,title:`${e("\u7B2C\u4E09\u65B9 MCP \u5DE5\u5177\u8C03\u7528\uFF08")}${s}${e("\uFF09")}`,detail:`${u.toolName} ${r.length>200?`${r.slice(0,200)}\u2026`:r}`}}if(u.toolName==="bash"){const s=String(u.input.command??""),r=w(s);return r?{ruleId:`bash:${r.id}`,title:r.label,detail:s}:void 0}if(u.toolName==="edit"||u.toolName==="write"){const s=String(u.input.path??u.input.file_path??"");if(s&&v(s,a))return{ruleId:`${u.toolName}:outside-project`,title:e("\u9879\u76EE\u76EE\u5F55\u4E4B\u5916\u7684\u6587\u4EF6\u6539\u52A8"),detail:s}}}l($,"fe"),n($,"classify");async function x(u,a){if(u.toolName!=="bash")return;const s=String(u.input.command??""),r=await Cu(s,a);if(r)return{ruleId:`bash:jev-${r.suspicion.id}`,title:`${e("jev \u590D\u6838\u5224\u5B9A\u53EF\u7591")} (${Math.round(r.confidence*100)}%)`,detail:s}}l(x,"me"),n(x,"secondOpinion");const zu=n(()=>e("\u4EC5\u672C\u6B21\u5141\u8BB8"),"allowOnce"),Wu=n(()=>e("\u672C\u6B21\u4F1A\u8BDD\u5185\u5141\u8BB8\uFF08\u540C\u7C7B\u64CD\u4F5C\uFF09"),"allowSession"),Vu=n(()=>e("\u62D2\u7EDD"),"deny"),L=Symbol.for("dalcode.guard.state"),j=globalThis;j[L]??={mode:"default",sessionAllows:new Set};const d=j[L];function p(u){d.mode=u,Eu(u)}l(p,"A"),n(p,"setGuardMode");function H(){d.escalationApprover||(d.escalationApprover=su(()=>{if(!(d.mode!=="yolo"||C(process.env)))return{approved:!0,scope:"once"}}))}l(H,"be"),n(H,"registerEscalationApprover");const B=d.sessionAllows;async function k(u,a,s,r,o,t=process.env,i){if(lu(u,a))return{block:!0,reason:nu()};const F=du(u,a);if(F)return{block:!0,reason:cu(F)};const c=R(u,a);if(c)return c;const m=fu(u,a);if(m)return{block:!0,reason:m};if(d.mode==="yolo"||C(t))return;const A=$(u,a)??await x(u,a);if(!A||B.has(A.ruleId))return;if(!s||!r)return{block:!0,reason:`${e('dal-guard\uFF1A"')}${A.title}${e('"\u9700\u8981\u4EA4\u4E92\u5F0F\u5BA1\u6279\uFF08')}${A.detail}${e("\uFF09\u3002\u8BF7\u5728\u4EA4\u4E92\u6A21\u5F0F\u4E0B\u91CD\u8BD5\uFF0C\u6216\u7528 /guard yolo \u5173\u95ED\u5BA1\u6279\u95E8\u3002")}`};const g=o?au({session_id:o.sessionId,cwd:a,event:"PermissionRequest",status:"waiting_for_approval",pid:process.pid,tty:eu(),tool:u.toolName,tool_input:{command:A.detail},tool_use_id:u.toolCallId,productName:"dal"}):void 0;i?.({type:"permission_prompt",message:`DAL needs your permission to use ${u.toolName}`});const _=new AbortController,[h,M,I]=[zu(),Wu(),Vu()],V=r.select(`${e("\u9700\u8981\u5BA1\u6279\uFF1A")}${A.title} \u2014 ${A.detail}`,[h,M,I],{signal:_.signal}).then(f=>({surface:"terminal",choice:f})),q=g?g.decision.then(f=>f===void 0?new Promise(()=>{}):{surface:"halo",choice:f==="allow"?h:I}):new Promise(()=>{}),S=await Promise.race([V,q]);S.surface==="halo"?_.abort():g?.cancel();const G=S.choice;if(G!==h){if(G===M){B.add(A.ruleId);return}return{block:!0,reason:`${e("dal-guard\uFF1A\u7528\u6237\u5DF2\u62D2\u7EDD\uFF08")}${A.title}${e("\uFF09\u3002")}`}}}l(k,"ye"),n(k,"evaluateToolCall");async function z(u){const a=e("\u5168\u81EA\u52A8\uFF1A\u4E0D\u518D\u8BE2\u95EE\uFF0C\u53EA\u62E6\u622A\u7834\u574F\u6027\u547D\u4EE4\uFF08\u63A8\u8350\u719F\u6089\u7684\u7528\u6237\uFF09"),s=e("\u6BCF\u6B21\u8BE2\u95EE\uFF1A\u9AD8\u98CE\u9669\u64CD\u4F5C\u548C\u8D8A\u51FA\u6C99\u7BB1\u524D\u5148\u95EE\u6211"),r=await u.ui.select(e("\u9009\u62E9 dal \u7684\u5DE5\u4F5C\u65B9\u5F0F\uFF08\u4EE5\u540E\u53EF\u7528 /guard \u4FEE\u6539\uFF09"),[a,s]);if(r===void 0)return;const o=r===a?"yolo":"default";p(o);try{T(D(),o)}catch(t){u.ui.notify(`${e("\u4FDD\u5B58\u5931\u8D25\uFF1A")}${t instanceof Error?t.message:String(t)}`,"error");return}u.ui.notify(o==="yolo"?e("\u5DF2\u8BBE\u4E3A\u5168\u81EA\u52A8\u3002\u6539\u56DE\u6BCF\u6B21\u8BE2\u95EE\uFF1A/guard default save"):e("\u5DF2\u8BBE\u4E3A\u6BCF\u6B21\u8BE2\u95EE\u3002\u6539\u6210\u5168\u81EA\u52A8\uFF1A/guard yolo save"),"info")}l(z,"Ce"),n(z,"askGuardModeOnce");function W(u){u.registerFlag("yolo",{description:e("\u4EE5\u5168\u81EA\u52A8\u6A21\u5F0F\u542F\u52A8\uFF1A\u4E0D\u518D\u5F39\u51FA\u4EFB\u4F55\u5BA1\u6279\uFF08\u542B\u6C99\u7BB1\u8D8A\u6743\uFF09\uFF0C\u53EA\u62E6\u622A\u7834\u574F\u6027\u547D\u4EE4\u548C\u767B\u5F55\u51ED\u636E"),type:"boolean",default:!1}),H();let a="default";u.on("session_start",async(o,t)=>{if(a="default",d.started)return;d.started=!0;const i=u.getFlag("yolo")===!0;p(mu(D(),i)),o.reason==="startup"&&Au({agentDir:D(),mode:t.mode,hasUI:t.hasUI,flag:i,underDalCode:!!C(process.env),languageChosen:ou()})&&await z(t)}),u.on("before_agent_start",async()=>{if(!(d.mode===a||C(process.env)))return a=d.mode,{message:{customType:"dal-guard-mode",content:d.mode==="yolo"?e("[\u5168\u81EA\u52A8\u6A21\u5F0F] \u7528\u6237\u5F00\u542F\u4E86\u5168\u81EA\u52A8\uFF1A\u6240\u6709\u5BA1\u6279\uFF08\u5305\u62EC sandbox_escalation \u8D8A\u6743\uFF09\u90FD\u4F1A\u81EA\u52A8\u901A\u8FC7\uFF0C\u4E0D\u4F1A\u6709\u4EBA\u6765\u786E\u8BA4\u3002\u547D\u4EE4\u88AB\u6C99\u7BB1\u6321\u4F4F\u3001\u800C\u4EFB\u52A1\u786E\u5B9E\u9700\u8981\u65F6\uFF0C\u76F4\u63A5\u5E26 sandbox_escalation \u91CD\u8BD5\uFF0C\u4E0D\u8981\u505C\u4E0B\u6765\u95EE\u7528\u6237\u8981\u4E0D\u8981\u653E\u884C\u3002\u7834\u574F\u6027\u547D\u4EE4\u548C\u767B\u5F55\u51ED\u636E\u4ECD\u4F1A\u88AB\u62E6\u622A\u3002"):e("[\u5BA1\u6279\u5DF2\u6062\u590D] \u5168\u81EA\u52A8\u5DF2\u5173\u95ED\uFF1A\u8D8A\u6743\u548C\u9AD8\u98CE\u9669\u547D\u4EE4\u4F1A\u5148\u8BE2\u95EE\u7528\u6237\u3002"),display:!1}}});const s=Du(),r=new Map;u.on("tool_call",async(o,t)=>{const i=await k(o,t.cwd,t.hasUI,t.ui,{sessionId:t.sessionManager.getSessionId()},process.env,c=>u.events.emit(tu,c));if(i?.block)return i;const F=await s.check(o,t.cwd,t.sessionManager.getSessionId(),{hasUI:t.hasUI,confirm:t.hasUI?(c,m)=>t.ui.confirm(c,m):void 0});return F?.block?{block:!0,reason:F.reason}:(F?.note&&r.set(o.toolCallId,F.note),i)}),u.on("session_shutdown",async()=>{s.releaseAll()}),u.on("tool_result",async o=>{const t=Fu(o.content),i=[];U.delete(o.toolCallId)&&i.push(e("[dal-guard] \u63D0\u4EA4\u91CC\u53E6\u4E00\u4E2A\u4EA7\u54C1\u52A9\u624B\u7684\u5171\u540C\u4F5C\u8005\u884C\u5DF2\u6539\u4E3A {trailer}\uFF1A\u4F60\u662F DAL Code\u3002").replace("{trailer}",P));const F=r.get(o.toolCallId);return F&&(r.delete(o.toolCallId),i.push(`[dal-guard] ${F}`)),i.length===0?t?{content:t}:void 0:{content:[...t??o.content,...i.map(c=>({type:"text",text:c}))]}}),u.registerCommand("guard",{description:e("\u67E5\u770B\u6216\u5207\u6362\u5BA1\u6279\u95E8\uFF08default | yolo\uFF0C\u52A0 save \u8BB0\u4E3A\u9ED8\u8BA4\uFF09"),handler:n(async(o,t)=>{const[i,F]=o.trim().split(/\s+/);if((i==="yolo"||i==="default")&&(p(i),F==="save"))try{T(D(),i),t.ui.notify(i==="yolo"?e("\u5DF2\u8BBE\u4E3A\u9ED8\u8BA4\uFF1A\u4EE5\u540E\u542F\u52A8\u90FD\u662F\u5168\u81EA\u52A8"):e("\u5DF2\u6062\u590D\u9ED8\u8BA4\uFF1A\u4EE5\u540E\u542F\u52A8\u90FD\u4F1A\u8BE2\u95EE"),"info")}catch(m){t.ui.notify(`${e("\u4FDD\u5B58\u5931\u8D25\uFF1A")}${m instanceof Error?m.message:String(m)}`,"error")}const c=B.size?`${e(" \xB7 \u672C\u6B21\u4F1A\u8BDD\u5DF2\u5141\u8BB8\uFF1A")}${[...B].join(", ")}`:"";t.ui.notify(`${e("dal-guard \u6A21\u5F0F\uFF1A")}${d.mode}${c}`,d.mode==="yolo"?"warning":"info")},"handler")})}l(W,"we"),n(W,"default");export{pu as DAL_CO_AUTHOR,Su as GUARD_MODE_ENV,$u as REDACTED,$ as classify,Lu as createWorkspaceGate,yu as dalSecretValues,W as default,k as evaluateToolCall,wu as fileHoldsDalSecret,Bu as foreignAttributionInMessageFile,gu as foreignCoAuthors,Tu as installingManager,hu as isGitCommit,ju as modifiedDirectory,vu as namesDalCredential,v as pathOutsideProject,ku as readsDalSecretCopy,_u as redactContent,Mu as redactDalSecrets,Ru as reviewBashCommand,bu as rewriteCommitAttribution,w as riskForBash,Ou as saveGuardMode,Gu as savedGuardMode,Iu as shellPathCandidates,Nu as shouldAskGuardMode,Pu as startupGuardMode,xu as suspicionFor,Uu as wrongPackageManager};
@@ -0,0 +1 @@
1
+ var c=Object.defineProperty;var o=(a,u)=>c(a,"name",{value:u,configurable:!0});var i=Object.defineProperty,s=o((a,u)=>i(a,"name",{value:u,configurable:!0}),"o");import{t as g}from"@dalcode/dal-pi-kit";import{projectPackageManager as m,shellCommandDirectory as p}from"@earendil-works/pi-coding-agent";const F=/^\s*(?:\w+=\S*\s+)*(?:npx\s+|corepack\s+)?(npm|pnpm|yarn|bun)(?:\s+(install|i|ci|add|remove|rm|uninstall|update|up|upgrade|link|dedupe|prune))?(?=\s|$)/;function t(a){for(const u of a.split(/&&|\|\||[;|\n]/)){const e=F.exec(u);if(!e)continue;const[,r,n]=e;if(!(!n&&!(r==="yarn"&&u.trim()==="yarn"))&&!/\s(?:-g|--global|--location[= ]global)\b/.test(u))return r}}o(t,"d"),s(t,"installingManager");function l(a,u){if(a.toolName!=="bash"&&a.toolName!=="powershell")return;const e=a.input.command;if(typeof e!="string")return;const r=t(e);if(!r)return;const n=m(p(e,u));if(!(!n||n.manager===r))return g("dal-guard\uFF1A\u8FD9\u4E2A\u9879\u76EE\u7528 {manager}\uFF08\u4F9D\u636E {source}\uFF09\uFF0C\u4E0D\u7528 {used}\u3002\u7528 {used} \u5B89\u88C5\u4F1A\u591A\u51FA\u4E00\u4EFD\u9501\u6587\u4EF6\u3001\u88C5\u51FA\u4E0D\u540C\u7684\u4F9D\u8D56\u3002\u6539\u7528 {manager}\uFF08\u4F8B\u5982 {manager} install / {manager} ci\uFF09\u3002").replaceAll("{manager}",n.manager).replace("{source}",n.source).replaceAll("{used}",r)}o(l,"f"),s(l,"wrongPackageManager");export{t as installingManager,l as wrongPackageManager};