dal-code 1.0.25 → 1.0.26

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 (154) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/NOTICE +7 -0
  3. package/dal-docs/README.md +13 -0
  4. package/dist/cli/args.d.ts +3 -0
  5. package/dist/cli/args.js +14 -14
  6. package/dist/core/agent-session-services.d.ts +2 -0
  7. package/dist/core/agent-session-services.js +1 -1
  8. package/dist/core/agent-session.d.ts +14 -1
  9. package/dist/core/agent-session.js +8 -7
  10. package/dist/core/background-processes.d.ts +73 -0
  11. package/dist/core/background-processes.js +7 -0
  12. package/dist/core/extensions/index.d.ts +1 -1
  13. package/dist/core/extensions/loader.js +1 -1
  14. package/dist/core/extensions/permission-surface.js +1 -1
  15. package/dist/core/extensions/runner.js +1 -1
  16. package/dist/core/extensions/types.d.ts +3 -0
  17. package/dist/core/host-capabilities.d.ts +50 -0
  18. package/dist/core/host-capabilities.js +2 -0
  19. package/dist/core/permissions/rules.d.ts +45 -0
  20. package/dist/core/permissions/rules.js +1 -0
  21. package/dist/core/permissions/shell-words.js +2 -0
  22. package/dist/core/permissions/tool-policy.d.ts +46 -0
  23. package/dist/core/permissions/tool-policy.js +1 -0
  24. package/dist/core/sandbox/availability.d.ts +9 -0
  25. package/dist/core/sandbox/availability.js +1 -0
  26. package/dist/core/sandbox/denial.d.ts +25 -0
  27. package/dist/core/sandbox/denial.js +3 -0
  28. package/dist/core/sandbox/index.d.ts +5 -0
  29. package/dist/core/sandbox/index.js +1 -0
  30. package/dist/core/sandbox/policy.d.ts +66 -0
  31. package/dist/core/sandbox/policy.js +1 -0
  32. package/dist/core/sandbox/runtime.d.ts +31 -0
  33. package/dist/core/sandbox/runtime.js +1 -0
  34. package/dist/core/sandbox/shell-sandbox.d.ts +119 -0
  35. package/dist/core/sandbox/shell-sandbox.js +5 -0
  36. package/dist/core/sdk.d.ts +3 -0
  37. package/dist/core/sdk.js +1 -1
  38. package/dist/core/settings-manager.d.ts +20 -0
  39. package/dist/core/settings-manager.js +1 -1
  40. package/dist/core/tools/bash.d.ts +15 -1
  41. package/dist/core/tools/bash.js +16 -14
  42. package/dist/core/tools/find.js +11 -11
  43. package/dist/core/tools/grep.js +10 -10
  44. package/dist/core/tools/index.d.ts +1 -0
  45. package/dist/core/tools/index.js +1 -1
  46. package/dist/core/tools/ls.js +6 -6
  47. package/dist/core/tools/powershell.d.ts +1 -1
  48. package/dist/core/tools/powershell.js +2 -2
  49. package/dist/core/tools/process.d.ts +26 -0
  50. package/dist/core/tools/process.js +22 -0
  51. package/dist/core/tools/read.js +15 -15
  52. package/dist/dal/builtins.js +2 -2
  53. package/dist/dal/child-env.js +1 -1
  54. package/dist/dal/manifest.d.ts +32 -0
  55. package/dist/dal/manifest.js +1 -0
  56. package/dist/index.d.ts +8 -3
  57. package/dist/index.js +1 -1
  58. package/dist/main.js +4 -4
  59. package/dist/modes/index.d.ts +2 -2
  60. package/dist/modes/print-mode.js +6 -4
  61. package/dist/modes/rpc/rpc-client.d.ts +24 -1
  62. package/dist/modes/rpc/rpc-client.js +4 -1
  63. package/dist/modes/rpc/rpc-mode.js +1 -1
  64. package/dist/modes/rpc/rpc-types.d.ts +82 -0
  65. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  66. package/dist/node_modules/@dalcode/dal-bridge/src/index.js +1 -1
  67. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  68. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  69. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  70. package/dist/node_modules/@dalcode/dal-interactive/LICENSE +21 -0
  71. package/dist/node_modules/@dalcode/dal-interactive/package.json +33 -0
  72. package/dist/node_modules/@dalcode/dal-interactive/src/handoff.js +28 -0
  73. package/dist/node_modules/@dalcode/dal-interactive/src/index.js +1 -0
  74. package/dist/node_modules/@dalcode/dal-interactive/src/interactive-shell.js +1 -0
  75. package/dist/node_modules/@dalcode/dal-interactive/src/questionnaire.js +3 -0
  76. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  77. package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
  78. package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
  79. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  80. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +2 -2
  81. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  82. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +2 -2
  83. package/dist/node_modules/@dalcode/dal-plugins/package.json +2 -2
  84. package/dist/node_modules/@dalcode/dal-review/LICENSE +21 -0
  85. package/dist/node_modules/@dalcode/dal-review/package.json +34 -0
  86. package/dist/node_modules/@dalcode/dal-review/src/args.d.ts +13 -0
  87. package/dist/node_modules/@dalcode/dal-review/src/args.js +1 -0
  88. package/dist/node_modules/@dalcode/dal-review/src/core.d.ts +6 -0
  89. package/dist/node_modules/@dalcode/dal-review/src/core.js +1 -0
  90. package/dist/node_modules/@dalcode/dal-review/src/findings.d.ts +23 -0
  91. package/dist/node_modules/@dalcode/dal-review/src/findings.js +4 -0
  92. package/dist/node_modules/@dalcode/dal-review/src/index.js +1 -0
  93. package/dist/node_modules/@dalcode/dal-review/src/prompt.d.ts +3 -0
  94. package/dist/node_modules/@dalcode/dal-review/src/prompt.js +29 -0
  95. package/dist/node_modules/@dalcode/dal-review/src/runner.d.ts +91 -0
  96. package/dist/node_modules/@dalcode/dal-review/src/runner.js +2 -0
  97. package/dist/node_modules/@dalcode/dal-review/src/targets.d.ts +33 -0
  98. package/dist/node_modules/@dalcode/dal-review/src/targets.js +17 -0
  99. package/dist/node_modules/@dalcode/dal-review/src/types.d.ts +94 -0
  100. package/dist/node_modules/@dalcode/dal-review/src/types.js +1 -0
  101. package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
  102. package/dist/node_modules/@dalcode/dal-router/package.json +4 -4
  103. package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
  104. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  105. package/dist/node_modules/@dalcode/dal-subagent/src/agents.js +2 -2
  106. package/dist/node_modules/@dalcode/dal-subagent/src/index.js +12 -12
  107. package/dist/node_modules/@dalcode/dal-subagent/src/process-runner.js +3 -3
  108. package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
  109. package/dist/node_modules/@dalcode/dal-terminal/LICENSE +21 -0
  110. package/dist/node_modules/@dalcode/dal-terminal/package.json +33 -0
  111. package/dist/node_modules/@dalcode/dal-terminal/src/contract.d.ts +60 -0
  112. package/dist/node_modules/@dalcode/dal-terminal/src/contract.js +7 -0
  113. package/dist/node_modules/@dalcode/dal-terminal/src/index.js +6 -0
  114. package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
  115. package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
  116. package/dist/node_modules/@dalcode/dal-web/src/config.js +2 -2
  117. package/dist/node_modules/@dalcode/dal-web/src/index.js +4 -4
  118. package/dist/node_modules/@dalcode/dal-web/src/search.js +4 -4
  119. package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
  120. package/dist/node_modules/@dalcode/dal-workflow/src/index.js +4 -4
  121. package/dist/node_modules/@dalcode/dal-workflow/src/plan-mode.js +13 -13
  122. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  123. package/dist/node_modules/@earendil-works/chord/package.json +1 -1
  124. package/dist/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.d.ts +4 -0
  125. package/dist/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.js +1 -1
  126. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +4 -4
  127. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  128. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  129. package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
  130. package/dist/node_modules/@earendil-works/pi-client/package.json +3 -3
  131. package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
  132. package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
  133. package/dist/node_modules/@earendil-works/pi-server/package.json +5 -5
  134. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/package.json +3 -3
  135. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  136. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  137. package/dist/sdk/index.d.ts +6 -2
  138. package/dist/sdk/index.js +1 -1
  139. package/dist/sdk/review.d.ts +1 -0
  140. package/dist/sdk/review.js +1 -0
  141. package/dist/sdk/subagents.d.ts +8 -0
  142. package/dist/sdk/subagents.js +1 -0
  143. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  144. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  145. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  146. package/examples/extensions/gondolin/package-lock.json +2 -2
  147. package/examples/extensions/gondolin/package.json +1 -1
  148. package/examples/extensions/sandbox/index.ts +6 -0
  149. package/examples/extensions/sandbox/package-lock.json +2 -2
  150. package/examples/extensions/sandbox/package.json +1 -1
  151. package/examples/extensions/with-deps/package-lock.json +2 -2
  152. package/examples/extensions/with-deps/package.json +1 -1
  153. package/npm-shrinkwrap.json +75 -5
  154. package/package.json +6 -1
@@ -0,0 +1,119 @@
1
+ import type { ExtensionContext } from "../extensions/types.ts";
2
+ import { type SandboxAvailability } from "./availability.ts";
3
+ import { type SandboxDenial } from "./denial.ts";
4
+ import { type ResolvedSandboxPolicy, type SandboxLevel, type SandboxOverride } from "./policy.ts";
5
+ export interface SandboxEscalationInput {
6
+ mode: "allow" | "unsandboxed";
7
+ justification: string;
8
+ allow_domains?: string[];
9
+ allow_write?: string[];
10
+ }
11
+ export interface SandboxEscalationRequest {
12
+ toolCallId: string;
13
+ toolName: string;
14
+ command: string;
15
+ cwd: string;
16
+ level: SandboxLevel;
17
+ mode: "allow" | "unsandboxed";
18
+ justification: string;
19
+ allowDomains: string[];
20
+ allowWrite: string[];
21
+ background: boolean;
22
+ }
23
+ export interface SandboxEscalationDecision {
24
+ approved: boolean;
25
+ scope?: "once" | "session";
26
+ message?: string;
27
+ }
28
+ export type SandboxEscalationHandler = (request: SandboxEscalationRequest, ctx: ExtensionContext | undefined) => Promise<SandboxEscalationDecision | undefined> | SandboxEscalationDecision | undefined;
29
+ export type SandboxEvent = {
30
+ type: "sandbox_denied";
31
+ toolCallId: string;
32
+ toolName: string;
33
+ denial: SandboxDenial;
34
+ } | {
35
+ type: "sandbox_escalation";
36
+ toolCallId: string;
37
+ toolName: string;
38
+ request: SandboxEscalationRequest;
39
+ decision: SandboxEscalationDecision;
40
+ decidedBy: "sdk" | "handler" | "ui" | "none";
41
+ };
42
+ export interface SandboxStatus {
43
+ level: SandboxLevel;
44
+ levelSource: ResolvedSandboxPolicy["levelSource"];
45
+ enforced: boolean;
46
+ platform: NodeJS.Platform;
47
+ mechanism?: SandboxAvailability["mechanism"];
48
+ unavailableReason?: string;
49
+ network: {
50
+ allowedDomains: string[];
51
+ deniedDomains: string[];
52
+ proxyError?: string;
53
+ };
54
+ sessionAllowances: {
55
+ domains: string[];
56
+ writablePaths: string[];
57
+ };
58
+ }
59
+ export interface SandboxOptions extends SandboxOverride {
60
+ defaultLevel?: SandboxLevel;
61
+ onEscalation?: SandboxEscalationHandler;
62
+ }
63
+ export interface ShellSandboxOptions {
64
+ policy: ResolvedSandboxPolicy;
65
+ onEscalation?: SandboxEscalationHandler;
66
+ onEvent?: (event: SandboxEvent) => void;
67
+ availability?: SandboxAvailability;
68
+ scratchDir?: () => string;
69
+ }
70
+ export interface PreparedCommand {
71
+ command: string;
72
+ sandboxed: boolean;
73
+ details: SandboxRunDetails;
74
+ finish(exitCode: number | null, output: string): Promise<SandboxDenial | undefined>;
75
+ }
76
+ export interface SandboxRunDetails {
77
+ level: SandboxLevel;
78
+ sandboxed: boolean;
79
+ escalation?: {
80
+ request: SandboxEscalationRequest;
81
+ decision: SandboxEscalationDecision;
82
+ };
83
+ denial?: SandboxDenial;
84
+ }
85
+ export declare function registerSandboxEscalationHandler(handler: SandboxEscalationHandler): () => void;
86
+ export declare function setProcessShellSandbox(sandbox: ShellSandbox | undefined): void;
87
+ export declare function getProcessShellSandbox(): ShellSandbox | undefined;
88
+ export declare class ShellSandbox {
89
+ readonly policy: ResolvedSandboxPolicy;
90
+ private readonly onEscalation?;
91
+ private readonly onEvent?;
92
+ private readonly availabilityOverride?;
93
+ private readonly sessionDomains;
94
+ private readonly sessionWritable;
95
+ private holdsRuntime;
96
+ private readonly sharedScratch?;
97
+ private ownScratch;
98
+ constructor(options: ShellSandboxOptions);
99
+ scratchDir(): string;
100
+ dispose(): Promise<void>;
101
+ get level(): SandboxLevel;
102
+ get active(): boolean;
103
+ private availability;
104
+ status(): SandboxStatus;
105
+ describeForModel(): string | undefined;
106
+ unavailableRefusal(): string | undefined;
107
+ prepare(request: {
108
+ command: string;
109
+ cwd: string;
110
+ shell: string;
111
+ toolCallId: string;
112
+ toolName: string;
113
+ escalation?: SandboxEscalationInput;
114
+ background?: boolean;
115
+ ctx?: ExtensionContext;
116
+ }): Promise<PreparedCommand>;
117
+ private approveEscalation;
118
+ }
119
+ export declare function createScratchDir(): string;
@@ -0,0 +1,5 @@
1
+ var M=Object.defineProperty;var r=(o,e)=>M(o,"name",{value:e,configurable:!0});import{spawnSync as O}from"node:child_process";import{mkdtempSync as B,rmSync as L}from"node:fs";import{tmpdir as U}from"node:os";import{isAbsolute as W,join as H,relative as F,resolve as K}from"node:path";import{fill as f,t as d}from"../../dal/i18n.js";import{detectSandboxAvailability as Q}from"./availability.js";import{collectBlockedAccesses as X}from"./denial.js";import{expandPath as Y,filesystemRules as z}from"./policy.js";import{acquireSandboxRuntime as G,proxyUnavailableReason as R,releaseSandboxRuntime as J,violationsForCommand as V,wrapCommand as Z}from"./runtime.js";const v=Symbol.for("dal.sandbox.escalationHandlers"),x=globalThis;x[v]instanceof Set||(x[v]=new Set);const g=x[v];function ue(o){return g.add(o),()=>{g.delete(o)}}r(ue,"registerSandboxEscalationHandler");let $;function pe(o){$=o}r(pe,"setProcessShellSandbox");function we(){return $}r(we,"getProcessShellSandbox");const j=new Map;function q(o){const e=j.get(o);if(e)return e;const t=O("git",["rev-parse","--absolute-git-dir","--git-common-dir"],{cwd:o,encoding:"utf8",timeout:3e3}),a=[];if(t.status===0)for(const l of t.stdout.split(`
2
+ `)){const n=l.trim();if(!n)continue;const s=W(n)?n:K(o,n),c=F(o,s);(c.startsWith("..")||W(c))&&a.push(s)}const i=[...new Set(a)];return j.set(o,i),i}r(q,"gitDirsOutside");function C(o){return Array.isArray(o)?o.filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()):[]}r(C,"cleanList");let ee=0;class be{static{r(this,"ShellSandbox")}policy;onEscalation;onEvent;availabilityOverride;sessionDomains=new Set;sessionWritable=new Set;holdsRuntime=!1;sharedScratch;ownScratch;constructor(e){this.policy=e.policy,this.onEscalation=e.onEscalation,this.onEvent=e.onEvent,this.availabilityOverride=e.availability,this.sharedScratch=e.scratchDir,this.active&&(G(),this.holdsRuntime=!0)}scratchDir(){return this.sharedScratch?this.sharedScratch():(this.ownScratch??=oe(),this.ownScratch)}async dispose(){this.ownScratch&&(L(this.ownScratch,{recursive:!0,force:!0}),this.ownScratch=void 0),this.holdsRuntime&&(this.holdsRuntime=!1,await J())}get level(){return this.policy.level}get active(){return this.policy.level!=="off"}availability(){return this.availabilityOverride??Q()}status(){const e=this.availability(),t=R();return{level:this.policy.level,levelSource:this.policy.levelSource,enforced:this.active&&e.available,platform:e.platform,...e.mechanism?{mechanism:e.mechanism}:{},...this.active&&!e.available&&e.reason?{unavailableReason:e.reason}:{},network:{allowedDomains:[...this.policy.network.allowedDomains],deniedDomains:[...this.policy.network.deniedDomains],...t?{proxyError:t}:{}},sessionAllowances:{domains:[...this.sessionDomains],writablePaths:[...this.sessionWritable]}}}describeForModel(){if(!this.active)return;const e=this.policy.level==="read-only"?"nothing may be written except $TMPDIR (a scratch directory for this session)":"writes are limited to the working directory and $TMPDIR (a scratch directory for this session; agent/editor config, git hooks and .env files stay read-only)",t=this.policy.network.allowedDomains,a=t.length>0?`network is off except ${t.join(", ")}`:"network is off";return`Commands run inside an OS sandbox (${this.policy.level}): ${e}; ${a}; credential files such as ~/.ssh cannot be read. When the sandbox blocks something the result says what; only then, and only if the task needs it, retry with sandbox_escalation.`}unavailableRefusal(){if(!this.active)return;const e=this.availability();if(e.available)return;const t=e.platform==="win32";return[`Command refused: the sandbox level is "${this.policy.level}", but ${e.reason??"the OS sandbox is unavailable."}`,"Commands are not run without the sandbox unless the user says so explicitly.",t?'To run commands on Windows, the user must opt out: `dal --sandbox off`, or "sandbox": { "level": "off" } in ~/.dal/agent/settings.json.':'The user can fix the sandbox, or opt out explicitly with `dal --sandbox off` or "sandbox": { "level": "off" } in ~/.dal/agent/settings.json.','A single command can still run if the user approves it: retry with sandbox_escalation {"mode":"unsandboxed","justification":"..."}.'].join(`
3
+ `)}async prepare(e){const t=this.policy.level;if(t==="off")return I(e.command,{level:t,sandboxed:!1});const a=this.unavailableRefusal();if(a&&e.escalation?.mode!=="unsandboxed")throw new Error(a);let i=[],l=[],n;if(e.escalation){const h=await this.approveEscalation(e,e.escalation);if(n=h,!h.decision.approved)throw new Error(`Sandbox escalation refused${h.decision.message?`: ${h.decision.message}`:"."} Do not retry the same escalation; continue without it or ask the user.`);if(h.request.mode==="unsandboxed")return I(e.command,{level:t,sandboxed:!1,escalation:n});i=h.request.allowDomains,l=h.request.allowWrite}const s=this.availability(),c=this.scratchDir(),m=z(this.policy,e.cwd,{gitDirs:this.policy.level==="workspace-write"?q(e.cwd):[],extraWrite:[...this.sessionWritable,...l],scratchDir:c}),S={allowedDomains:[...this.policy.network.allowedDomains,...this.sessionDomains,...i],deniedDomains:this.policy.network.deniedDomains,refusals:[]},A=`${process.pid}-${++ee}`,u=te(c),D=`export DAL_SANDBOX_RUN=${A} TMPDIR=${u} TMP=${u} TEMP=${u}
4
+ ${e.command}`,_=Date.now(),p=await Z({command:D,shell:e.shell,allowWrite:m.allowWrite,denyWrite:m.denyWrite,denyRead:m.denyRead,allowLocalBinding:e.background===!0||this.policy.network.allowLocalBinding,...s.ripgrep?{ripgrep:s.ripgrep}:{}},S),w={level:t,sandboxed:!0,...n?{escalation:n}:{}};let k=!1;return{command:p.command,sandboxed:!0,details:w,finish:r(async(h,P)=>{if(k)return w.denial;if(k=!0,p.release(),h===0)return;const N=s.platform==="darwin"?await V(D,_,400):[],b=X({refusals:S.refusals,violations:N,output:P});if(!b)return;const E=p.proxied?void 0:R(),y={level:t,platform:s.platform,command:e.command,cwd:e.cwd,blocked:b,...E&&b.some(T=>T.kind==="network")?{networkProxyError:E}:{}};return w.denial=y,this.onEvent?.({type:"sandbox_denied",toolCallId:e.toolCallId,toolName:e.toolName,denial:y}),y},"finish")}}async approveEscalation(e,t){const a=t.mode==="unsandboxed"?"unsandboxed":"allow",i={toolCallId:e.toolCallId,toolName:e.toolName,command:e.command,cwd:e.cwd,level:this.policy.level,mode:a,justification:typeof t.justification=="string"?t.justification.trim():"",allowDomains:a==="allow"?C(t.allow_domains):[],allowWrite:a==="allow"?C(t.allow_write).map(n=>Y(n,e.cwd)):[],background:e.background===!0},l=r((n,s)=>{const c=n.approved&&n.scope==="session"&&a==="unsandboxed"?{...n,scope:"once"}:n;if(c.approved&&c.scope==="session"){for(const m of i.allowDomains)this.sessionDomains.add(m);for(const m of i.allowWrite)this.sessionWritable.add(m)}return this.onEvent?.({type:"sandbox_escalation",toolCallId:e.toolCallId,toolName:e.toolName,request:i,decision:c,decidedBy:s}),{request:i,decision:c}},"finish");if(!i.justification)return l({approved:!1,message:"an escalation needs a justification"},"none");if(a==="allow"&&i.allowDomains.length===0&&i.allowWrite.length===0)return l({approved:!1,message:'mode "allow" needs allow_domains or allow_write'},"none");if(this.onEscalation){const n=await this.onEscalation(i,e.ctx);if(n)return l(n,"sdk")}for(const n of g){const s=await n(i,e.ctx);if(s)return l(s,"handler")}return e.ctx?.hasUI?l(await ne(i,e.ctx),"ui"):l({approved:!1,message:"nobody is available to approve it (no interactive UI and no approver configured)"},"none")}}function I(o,e){return{command:o,sandboxed:!1,details:e,finish:r(async()=>{},"finish")}}r(I,"passthrough");function oe(){return B(H(U(),"dal-sandbox-"))}r(oe,"createScratchDir");function te(o){return`'${o.replace(/'/g,"'\\''")}'`}r(te,"shellQuote");async function ne(o,e){const t=d("\u4EC5\u672C\u6B21\u5141\u8BB8"),a=d("\u672C\u4F1A\u8BDD\u5185\u90FD\u5141\u8BB8"),i=d("\u62D2\u7EDD"),l=o.mode==="unsandboxed"?d("\u5728\u6C99\u7BB1\u4E4B\u5916\u8FD0\u884C\u547D\u4EE4\uFF08\u53EF\u8BBF\u95EE\u4F60\u7684\u5168\u90E8\u6587\u4EF6\u548C\u7F51\u7EDC\uFF09"):[o.allowDomains.length>0?f(d("\u8BBF\u95EE {domains}"),{domains:o.allowDomains.join(", ")}):"",o.allowWrite.length>0?f(d("\u5199\u5165 {paths}"),{paths:o.allowWrite.join(", ")}):""].filter(Boolean).join(d("\uFF0C\u5E76")),n=[f(d("\u52A9\u624B\u60F3\u8981{what}\u3002"),{what:l}),f(d("\u547D\u4EE4\uFF1A{command}"),{command:o.command}),f(d("\u76EE\u5F55\uFF1A{cwd}"),{cwd:o.cwd}),f(d("\u52A9\u624B\u7ED9\u7684\u7406\u7531\uFF08\u672A\u7ECF\u6838\u5B9E\uFF09\uFF1A{reason}"),{reason:o.justification})].join(`
5
+ `),s=o.mode==="unsandboxed"?[t,i]:[t,a,i],c=await e.ui.select(n,s);return c===t?{approved:!0,scope:"once"}:c===a?{approved:!0,scope:"session"}:{approved:!1,message:"the user declined"}}r(ne,"askThroughUi");export{be as ShellSandbox,oe as createScratchDir,we as getProcessShellSandbox,ue as registerSandboxEscalationHandler,pe as setProcessShellSandbox};
@@ -4,6 +4,7 @@ import { AgentSession } from "./agent-session.ts";
4
4
  import type { LoadExtensionsResult, SessionStartEvent, ToolDefinition } from "./extensions/index.ts";
5
5
  import { ModelRuntime } from "./model-runtime.ts";
6
6
  import type { ResourceLoader } from "./resource-loader.ts";
7
+ import type { SandboxOptions } from "./sandbox/shell-sandbox.ts";
7
8
  import { SessionManager } from "./session-manager.ts";
8
9
  import { SettingsManager } from "./settings-manager.ts";
9
10
  import { createBashTool, createCodingTools, createEditTool, createFindTool, createGrepTool, createLsTool, createPowerShellTool, createReadOnlyTools, createReadTool, createWriteTool, withFileMutationQueue } from "./tools/index.ts";
@@ -25,6 +26,8 @@ export interface CreateAgentSessionOptions {
25
26
  sessionManager?: SessionManager;
26
27
  settingsManager?: SettingsManager;
27
28
  sessionStartEvent?: SessionStartEvent;
29
+ sandbox?: SandboxOptions;
30
+ defaultActiveTools?: string[];
28
31
  }
29
32
  export interface CreateAgentSessionResult {
30
33
  session: AgentSession;
package/dist/core/sdk.js CHANGED
@@ -1 +1 @@
1
- var q=Object.defineProperty;var d=(r,u)=>q(r,"name",{value:u,configurable:!0});import{join as w}from"node:path";import{Agent as K,setDefaultStreamFn as Q}from"@earendil-works/pi-agent-core";import{clampThinkingLevel as V,streamSimple as z}from"@earendil-works/pi-ai/compat";import{getAgentDir as J}from"../config.js";import{resolvePath as C}from"../utils/paths.js";import{AgentSession as X}from"./agent-session.js";import{formatNoModelsAvailableMessage as Y}from"./auth-guidance.js";import{CacheWarmer as Z}from"./cache-warmer.js";import{DEFAULT_THINKING_LEVEL as P}from"./defaults.js";import{convertToLlm as ee}from"./messages.js";import{findInitialModel as te}from"./model-resolver.js";import{ModelRuntime as re}from"./model-runtime.js";import{mergeProviderAttributionHeaders as oe}from"./provider-attribution.js";import{DefaultResourceLoader as ne}from"./resource-loader.js";import{getDefaultSessionDir as se,SessionManager as ie}from"./session-manager.js";import{SettingsManager as ae}from"./settings-manager.js";import{time as de}from"./timings.js";import{createBashTool as le,createCodingTools as me,createEditTool as ce,createFindTool as ge,createGrepTool as ue,createLsTool as fe,createPowerShellTool as he,createReadOnlyTools as ve,createReadTool as Te,createWriteTool as pe,withFileMutationQueue as Me}from"./tools/index.js";Q(z);export*from"./agent-session-runtime.js";function ye(){return J()}d(ye,"getDefaultAgentDir");async function Oe(r={}){const u=C(r.cwd??r.sessionManager?.getCwd()??process.cwd()),v=r.agentDir?C(r.agentDir):ye();let T=r.resourceLoader;const b=r.agentDir?w(v,"auth.json"):void 0,A=r.agentDir?w(v,"models.json"):void 0,f=r.modelRuntime??await re.create({authPath:b,modelsPath:A}),o=r.settingsManager??ae.create(u,v),m=r.sessionManager??ie.create(u,se(u,v));T||(T=new ne({cwd:u,agentDir:v,settingsManager:o}),await T.reload(),de("resourceLoader.reload"));const l=m.buildSessionContext(),x=l.messages.length>0,I=m.getBranch().some(e=>e.type==="thinking_level_change");let n=r.model,p,L;if(!n&&x&&l.model){const e=f.getModel(l.model.provider,l.model.modelId);e&&f.hasConfiguredAuth(e.provider)&&(n=e),n||(p=`Could not restore model ${l.model.provider}/${l.model.modelId}`,L={provider:l.model.provider,modelId:l.model.modelId})}if(!n){const e=o.getDefaultProvider(),t=o.getDefaultModel();n=(await te({scopedModels:[],isContinuing:x,defaultProvider:e,defaultModelId:t,defaultThinkingLevel:o.getDefaultThinkingLevel(),modelThinkingLevels:o.getAllModelThinkingLevels(),modelRuntime:f})).model,n?p&&(p+=`. Using ${n.provider}/${n.id}`):p=Y(),e&&t&&(!n||n.provider!==e||n.id!==t)&&(L={provider:e,modelId:t})}let i=r.thinkingLevel;if(i===void 0&&x&&(i=I?l.thinkingLevel:o.getDefaultThinkingLevel()??P),i===void 0&&n){const e=o.getModelThinkingLevel(n.provider,n.id);e&&(i=e)}i===void 0&&(i=o.getDefaultThinkingLevel()??P),n?i=V(n,i):i="off";const _=["read","bash","edit","write"],E=o.getDefaultTools(),N=r.tools??(r.noTools==="all"?[]:void 0),R=r.excludeTools,B=R?new Set(R):void 0,H=(r.tools??(r.noTools?[]:E??_)).filter(e=>!B?.has(e)),F=d(e=>{const t=ee(e);return o.getBlockImages()?t.map(s=>{if(s.role==="user"||s.role==="toolResult"){const a=s.content;if(Array.isArray(a)&&a.some(c=>c.type==="image")){const c=a.map(g=>g.type==="image"?{type:"text",text:"Image reading is disabled."}:g).filter((g,M,y)=>!(g.type==="text"&&g.text==="Image reading is disabled."&&M>0&&y[M-1].type==="text"&&y[M-1].text==="Image reading is disabled."));return{...s,content:c}}}return s}):t},"convertToLlmWithBlockImages"),h={},S=new Z(f,m,()=>o.getCacheWarmingMode(),async e=>h.current?.emitCacheWarmingDecision(e)??e.action),W=d((e,t={})=>{const s=o.getProviderRetrySettings(),a=o.getHttpIdleTimeoutMs(),D=a===0?2147483647:a,c=h.current,g=o.getOutputTokenLimit(e.maxTokens);return{...t,maxTokens:t.maxTokens??(g!==e.maxTokens?g:void 0),timeoutMs:t.timeoutMs??s.timeoutMs??D,websocketConnectTimeoutMs:t.websocketConnectTimeoutMs??o.getWebSocketConnectTimeoutMs(),maxRetries:t.maxRetries??s.maxRetries,maxRetryDelayMs:t.maxRetryDelayMs??s.maxRetryDelayMs,transformHeaders:d(async M=>{const y=oe(e,o,t.sessionId,M);return c?.hasHandlers("before_provider_headers")?c.emitBeforeProviderHeaders(y??{}):y??{}},"transformHeaders")}},"buildRequestOptions"),O=d(e=>{const t=k.state.messages;return()=>{const s=k.state.model,a=k.state.messages;return s.provider===e.provider&&s.id===e.id&&t.length<=a.length&&t.every((D,c)=>a[c]===D)}},"cacheContextIsCurrent"),U=d(async e=>{const t=h.current;return t?.hasHandlers("before_provider_request")?t.emitBeforeProviderRequest(e):e},"transformProviderPayload"),$=d(async e=>{const t=h.current;t?.hasHandlers("after_provider_response")&&await t.emit({type:"after_provider_response",status:e.status,headers:e.headers})},"handleProviderResponse"),k=new K({initialState:{systemPrompt:"",model:n,thinkingLevel:i,tools:[],messages:l.messages},convertToLlm:F,streamFn:d(async(e,t,s)=>{const a=W(e,s);return s?.sessionId===m.getSessionId()&&S.start({model:e,context:t,options:a},O(e)),f.streamSimple(e,t,a)},"streamFn"),onPayload:U,onResponse:$,sessionId:m.getSessionId(),transformContext:d(async e=>{const t=h.current;return t?t.emitContext(e):e},"transformContext"),steeringMode:o.getSteeringMode(),followUpMode:o.getFollowUpMode(),transport:o.getTransport(),thinkingBudgets:o.getThinkingBudgets(),maxRetryDelayMs:o.getProviderRetrySettings().maxRetryDelayMs});x?I||m.appendThinkingLevelChange(i):(n&&m.appendModelChange(n.provider,n.id),m.appendThinkingLevelChange(i));const j=new X({agent:k,sessionManager:m,settingsManager:o,cwd:u,scopedModels:r.scopedModels,resourceLoader:T,customTools:r.customTools,modelRuntime:f,cacheWarmer:S,initialActiveToolNames:H,allowedToolNames:N,excludedToolNames:R,extensionRunnerRef:h,sessionStartEvent:r.sessionStartEvent,desiredModel:L}),G=T.getExtensions();return{session:j,extensionsResult:G,modelFallbackMessage:p}}d(Oe,"createAgentSession");export{Oe as createAgentSession,le as createBashTool,me as createCodingTools,ce as createEditTool,ge as createFindTool,ue as createGrepTool,fe as createLsTool,he as createPowerShellTool,ve as createReadOnlyTools,Te as createReadTool,pe as createWriteTool,Me as withFileMutationQueue};
1
+ var q=Object.defineProperty;var d=(r,u)=>q(r,"name",{value:u,configurable:!0});import{join as w}from"node:path";import{Agent as K,setDefaultStreamFn as Q}from"@earendil-works/pi-agent-core";import{clampThinkingLevel as V,streamSimple as z}from"@earendil-works/pi-ai/compat";import{getAgentDir as J}from"../config.js";import{resolvePath as C}from"../utils/paths.js";import{AgentSession as X}from"./agent-session.js";import{formatNoModelsAvailableMessage as Y}from"./auth-guidance.js";import{CacheWarmer as Z}from"./cache-warmer.js";import{DEFAULT_THINKING_LEVEL as b}from"./defaults.js";import{convertToLlm as ee}from"./messages.js";import{findInitialModel as te}from"./model-resolver.js";import{ModelRuntime as re}from"./model-runtime.js";import{mergeProviderAttributionHeaders as oe}from"./provider-attribution.js";import{DefaultResourceLoader as ne}from"./resource-loader.js";import{getDefaultSessionDir as se,SessionManager as ie}from"./session-manager.js";import{SettingsManager as ae}from"./settings-manager.js";import{time as de}from"./timings.js";import{createBashTool as le,createCodingTools as me,createEditTool as ce,createFindTool as ge,createGrepTool as ue,createLsTool as fe,createPowerShellTool as he,createReadOnlyTools as ve,createReadTool as Te,createWriteTool as pe,withFileMutationQueue as Me}from"./tools/index.js";Q(z);export*from"./agent-session-runtime.js";function xe(){return J()}d(xe,"getDefaultAgentDir");async function Oe(r={}){const u=C(r.cwd??r.sessionManager?.getCwd()??process.cwd()),v=r.agentDir?C(r.agentDir):xe();let T=r.resourceLoader;const P=r.agentDir?w(v,"auth.json"):void 0,A=r.agentDir?w(v,"models.json"):void 0,f=r.modelRuntime??await re.create({authPath:P,modelsPath:A}),o=r.settingsManager??ae.create(u,v),m=r.sessionManager??ie.create(u,se(u,v));T||(T=new ne({cwd:u,agentDir:v,settingsManager:o}),await T.reload(),de("resourceLoader.reload"));const l=m.buildSessionContext(),y=l.messages.length>0,I=m.getBranch().some(e=>e.type==="thinking_level_change");let n=r.model,p,L;if(!n&&y&&l.model){const e=f.getModel(l.model.provider,l.model.modelId);e&&f.hasConfiguredAuth(e.provider)&&(n=e),n||(p=`Could not restore model ${l.model.provider}/${l.model.modelId}`,L={provider:l.model.provider,modelId:l.model.modelId})}if(!n){const e=o.getDefaultProvider(),t=o.getDefaultModel();n=(await te({scopedModels:[],isContinuing:y,defaultProvider:e,defaultModelId:t,defaultThinkingLevel:o.getDefaultThinkingLevel(),modelThinkingLevels:o.getAllModelThinkingLevels(),modelRuntime:f})).model,n?p&&(p+=`. Using ${n.provider}/${n.id}`):p=Y(),e&&t&&(!n||n.provider!==e||n.id!==t)&&(L={provider:e,modelId:t})}let i=r.thinkingLevel;if(i===void 0&&y&&(i=I?l.thinkingLevel:o.getDefaultThinkingLevel()??b),i===void 0&&n){const e=o.getModelThinkingLevel(n.provider,n.id);e&&(i=e)}i===void 0&&(i=o.getDefaultThinkingLevel()??b),n?i=V(n,i):i="off";const _=["read","bash","edit","write"],E=o.getDefaultTools(),N=r.tools??(r.noTools==="all"?[]:void 0),R=r.excludeTools,B=R?new Set(R):void 0,H=(r.tools??(r.noTools?[]:E??r.defaultActiveTools??_)).filter(e=>!B?.has(e)),F=d(e=>{const t=ee(e);return o.getBlockImages()?t.map(s=>{if(s.role==="user"||s.role==="toolResult"){const a=s.content;if(Array.isArray(a)&&a.some(c=>c.type==="image")){const c=a.map(g=>g.type==="image"?{type:"text",text:"Image reading is disabled."}:g).filter((g,M,x)=>!(g.type==="text"&&g.text==="Image reading is disabled."&&M>0&&x[M-1].type==="text"&&x[M-1].text==="Image reading is disabled."));return{...s,content:c}}}return s}):t},"convertToLlmWithBlockImages"),h={},S=new Z(f,m,()=>o.getCacheWarmingMode(),async e=>h.current?.emitCacheWarmingDecision(e)??e.action),W=d((e,t={})=>{const s=o.getProviderRetrySettings(),a=o.getHttpIdleTimeoutMs(),D=a===0?2147483647:a,c=h.current,g=o.getOutputTokenLimit(e.maxTokens);return{...t,maxTokens:t.maxTokens??(g!==e.maxTokens?g:void 0),timeoutMs:t.timeoutMs??s.timeoutMs??D,websocketConnectTimeoutMs:t.websocketConnectTimeoutMs??o.getWebSocketConnectTimeoutMs(),maxRetries:t.maxRetries??s.maxRetries,maxRetryDelayMs:t.maxRetryDelayMs??s.maxRetryDelayMs,transformHeaders:d(async M=>{const x=oe(e,o,t.sessionId,M);return c?.hasHandlers("before_provider_headers")?c.emitBeforeProviderHeaders(x??{}):x??{}},"transformHeaders")}},"buildRequestOptions"),O=d(e=>{const t=k.state.messages;return()=>{const s=k.state.model,a=k.state.messages;return s.provider===e.provider&&s.id===e.id&&t.length<=a.length&&t.every((D,c)=>a[c]===D)}},"cacheContextIsCurrent"),U=d(async e=>{const t=h.current;return t?.hasHandlers("before_provider_request")?t.emitBeforeProviderRequest(e):e},"transformProviderPayload"),$=d(async e=>{const t=h.current;t?.hasHandlers("after_provider_response")&&await t.emit({type:"after_provider_response",status:e.status,headers:e.headers})},"handleProviderResponse"),k=new K({initialState:{systemPrompt:"",model:n,thinkingLevel:i,tools:[],messages:l.messages},convertToLlm:F,streamFn:d(async(e,t,s)=>{const a=W(e,s);return s?.sessionId===m.getSessionId()&&S.start({model:e,context:t,options:a},O(e)),f.streamSimple(e,t,a)},"streamFn"),onPayload:U,onResponse:$,sessionId:m.getSessionId(),transformContext:d(async e=>{const t=h.current;return t?t.emitContext(e):e},"transformContext"),steeringMode:o.getSteeringMode(),followUpMode:o.getFollowUpMode(),transport:o.getTransport(),thinkingBudgets:o.getThinkingBudgets(),maxRetryDelayMs:o.getProviderRetrySettings().maxRetryDelayMs});y?I||m.appendThinkingLevelChange(i):(n&&m.appendModelChange(n.provider,n.id),m.appendThinkingLevelChange(i));const j=new X({agent:k,sessionManager:m,settingsManager:o,cwd:u,scopedModels:r.scopedModels,resourceLoader:T,customTools:r.customTools,modelRuntime:f,cacheWarmer:S,initialActiveToolNames:H,allowedToolNames:N,excludedToolNames:R,extensionRunnerRef:h,sessionStartEvent:r.sessionStartEvent,desiredModel:L,sandbox:r.sandbox}),G=T.getExtensions();return{session:j,extensionsResult:G,modelFallbackMessage:p}}d(Oe,"createAgentSession");export{Oe as createAgentSession,le as createBashTool,me as createCodingTools,ce as createEditTool,ge as createFindTool,ue as createGrepTool,fe as createLsTool,he as createPowerShellTool,ve as createReadOnlyTools,Te as createReadTool,pe as createWriteTool,Me as withFileMutationQueue};
@@ -2,6 +2,7 @@ import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
2
2
  import { type Model, type Transport } from "@earendil-works/pi-ai";
3
3
  import type { TuiMode as RendererTuiMode, ScrollViewScrollbar, TerminalCapabilities } from "@earendil-works/pi-tui";
4
4
  import type { ShellEnvironmentPolicy } from "../dal/child-env.ts";
5
+ import type { SandboxSettings, SandboxSettingsSources } from "./sandbox/policy.ts";
5
6
  export interface CompactionModelOverride {
6
7
  reserveTokens?: number;
7
8
  keepRecentTokens?: number;
@@ -99,6 +100,12 @@ export interface Settings {
99
100
  defaultProjectTrust?: DefaultProjectTrust;
100
101
  shellCommandPrefix?: string;
101
102
  shellEnvironment?: ShellEnvironmentPolicy;
103
+ sandbox?: SandboxSettings;
104
+ permissions?: {
105
+ allow?: string[];
106
+ deny?: string[];
107
+ ask?: string[];
108
+ };
102
109
  npmCommand?: string[];
103
110
  collapseChangelog?: boolean;
104
111
  enableInstallTelemetry?: boolean;
@@ -274,6 +281,19 @@ export declare class SettingsManager {
274
281
  setDefaultProjectTrust(defaultProjectTrust: DefaultProjectTrust): void;
275
282
  getShellCommandPrefix(): string | undefined;
276
283
  getShellEnvironmentPolicy(): ShellEnvironmentPolicy;
284
+ getPermissionRuleSources(): {
285
+ user?: {
286
+ allow?: unknown;
287
+ deny?: unknown;
288
+ ask?: unknown;
289
+ };
290
+ project?: {
291
+ allow?: unknown;
292
+ deny?: unknown;
293
+ ask?: unknown;
294
+ };
295
+ };
296
+ getSandboxSettingsSources(): SandboxSettingsSources;
277
297
  setShellCommandPrefix(prefix: string | undefined): void;
278
298
  getNpmCommand(): string[] | undefined;
279
299
  setNpmCommand(command: string[] | undefined): void;
@@ -1 +1 @@
1
- var w=Object.defineProperty;var g=(l,e)=>w(l,"name",{value:e,configurable:!0});import{DEFAULT_MAX_AGENT_RETRY_DELAY_MS as x}from"@earendil-works/pi-ai";import{randomUUID as F}from"crypto";import{existsSync as k,mkdirSync as L,readFileSync as I,writeFileSync as A}from"fs";import{dirname as N,join as u}from"path";import O from"proper-lockfile";import{CONFIG_DIR_NAME as M,getAgentDir as D}from"../config.js";import{normalizePath as v,resolvePath as m}from"../utils/paths.js";import{stripBom as y}from"../utils/text.js";import{DEFAULT_HTTP_IDLE_TIMEOUT_MS as R,parseHttpIdleTimeoutMs as W}from"./http-dispatcher.js";const $={reserveTokens:16384,keepRecentTokens:2e4},_=128e3,U=32e3,B=5,H=["off","streaming","idle"];function f(l){return typeof l=="object"&&l!==null&&!Array.isArray(l)}g(f,"isMergeableObject");function T(l,e){const t={...l};for(const s of Object.keys(e)){const i=e[s];if(i===void 0)continue;const r=l[s];t[s]=f(r)&&f(i)?T(r,i):i}return t}g(T,"deepMergeObjects");function h(l,e){return T(l,e)}g(h,"deepMergeSettings");function P(l,e){const t=W(l);if(t!==void 0)return t;if(l!==void 0)throw new Error(`Invalid ${e} setting: ${String(l)}`)}g(P,"parseTimeoutSetting");function p(l,e,t){return{scope:l,...t?{path:t}:{},error:e instanceof Error?e:new Error(String(e))}}g(p,"toSettingsError");class q{static{g(this,"FileSettingsStorage")}globalSettingsPath;projectSettingsPath;constructor(e,t){const s=m(e),i=m(t);this.globalSettingsPath=u(i,"settings.json"),this.projectSettingsPath=u(s,M,"settings.json")}acquireLockSyncWithRetry(e){let i;for(let r=1;r<=10;r++)try{return O.lockSync(e,{realpath:!1})}catch(o){if((typeof o=="object"&&o!==null&&"code"in o?String(o.code):void 0)!=="ELOCKED"||r===10)throw o;i=o;const d=Date.now();for(;Date.now()-d<20;);}throw i??new Error("Failed to acquire settings lock")}withLock(e,t){const s=e==="global"?this.globalSettingsPath:this.projectSettingsPath,i=N(s);let r;try{const o=k(s);o&&(r=this.acquireLockSyncWithRetry(s));const n=o?I(s,"utf-8"):void 0,d=t(n);d!==void 0&&(k(i)||L(i,{recursive:!0}),r||(r=this.acquireLockSyncWithRetry(s)),A(s,d,"utf-8"))}finally{r&&r()}}}class V{static{g(this,"InMemorySettingsStorage")}global;project;withLock(e,t){const s=e==="global"?this.global:this.project,i=t(s);i!==void 0&&(e==="global"?this.global=i:this.project=i)}}class a{static{g(this,"SettingsManager")}storage;globalSettings;projectSettings;settings;projectTrusted;modifiedFields=new Set;modifiedNestedFields=new Map;modifiedProjectFields=new Set;modifiedProjectNestedFields=new Map;globalSettingsLoadError=null;projectSettingsLoadError=null;writeQueue=Promise.resolve();errors;settingsPaths;constructor(e,t,s,i=null,r=null,o=[],n=!0,d={}){this.storage=e,this.globalSettings=t,this.projectSettings=s,this.projectTrusted=n,this.globalSettingsLoadError=i,this.projectSettingsLoadError=r,this.errors=[...o],this.settingsPaths=d,this.settings=h(this.globalSettings,this.projectSettings)}static create(e,t=D(),s={}){const i=m(e),r=m(t),o=new q(i,r);return a.fromStorageWithPaths(o,s,{global:u(r,"settings.json"),project:u(i,M,"settings.json")})}static fromStorage(e,t={}){return a.fromStorageWithPaths(e,t)}static fromStorageWithPaths(e,t,s={}){const i=t.projectTrusted??!0,r=a.tryLoadFromStorage(e,"global"),o=a.tryLoadFromStorage(e,"project",i),n=[];return r.error&&n.push(p("global",r.error,s.global)),o.error&&n.push(p("project",o.error,s.project)),new a(e,r.settings,o.settings,r.error,o.error,n,i,s)}static inMemory(e={},t={}){const s=new V,i=a.migrateSettings(structuredClone(e));return s.withLock("global",()=>JSON.stringify(i,null,2)),a.fromStorage(s,t)}static loadFromStorage(e,t,s=!0){if(t==="project"&&!s)return{};let i;if(e.withLock(t,o=>{i=o}),!i)return{};const r=JSON.parse(y(i));return a.migrateSettings(r)}static tryLoadFromStorage(e,t,s=!0){try{return{settings:a.loadFromStorage(e,t,s),error:null}}catch(i){return{settings:{},error:i}}}static migrateSettings(e){if("queueMode"in e&&!("steeringMode"in e)&&(e.steeringMode=e.queueMode,delete e.queueMode),!("transport"in e)&&typeof e.websockets=="boolean"&&(e.transport=e.websockets?"websocket":"sse",delete e.websockets),"skills"in e&&typeof e.skills=="object"&&e.skills!==null&&!Array.isArray(e.skills)){const t=e.skills;t.enableSkillCommands!==void 0&&e.enableSkillCommands===void 0&&(e.enableSkillCommands=t.enableSkillCommands),Array.isArray(t.customDirectories)&&t.customDirectories.length>0?e.skills=t.customDirectories:delete e.skills}if("retry"in e&&typeof e.retry=="object"&&e.retry!==null&&!Array.isArray(e.retry)){const t=e.retry,s=typeof t.provider=="object"&&t.provider!==null?t.provider:void 0;typeof t.maxDelayMs=="number"&&(s?.maxRetryDelayMs===void 0||s?.maxRetryDelayMs===null)&&(t.provider={...s??{},maxRetryDelayMs:t.maxDelayMs}),delete t.maxDelayMs}return e}getGlobalSettings(){return structuredClone(this.globalSettings)}getProjectSettings(){return structuredClone(this.projectSettings)}isProjectTrusted(){return this.projectTrusted}setProjectTrusted(e){if(this.projectTrusted===e)return;if(this.projectTrusted=e,this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear(),!e){this.projectSettings={},this.projectSettingsLoadError=null,this.settings=h(this.globalSettings,this.projectSettings);return}const t=a.tryLoadFromStorage(this.storage,"project",e);this.projectSettings=t.settings,this.projectSettingsLoadError=t.error,t.error&&this.recordError("project",t.error),this.settings=h(this.globalSettings,this.projectSettings)}async reload(){await this.writeQueue;const e=a.tryLoadFromStorage(this.storage,"global");e.error?(this.globalSettingsLoadError=e.error,this.recordError("global",e.error)):(this.globalSettings=e.settings,this.globalSettingsLoadError=null),this.modifiedFields.clear(),this.modifiedNestedFields.clear(),this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear();const t=a.tryLoadFromStorage(this.storage,"project",this.projectTrusted);t.error?(this.projectSettingsLoadError=t.error,this.recordError("project",t.error)):(this.projectSettings=t.settings,this.projectSettingsLoadError=null),this.settings=h(this.globalSettings,this.projectSettings)}applyOverrides(e){this.settings=h(this.settings,e)}markModified(e,t){this.modifiedFields.add(e),t&&(this.modifiedNestedFields.has(e)||this.modifiedNestedFields.set(e,new Set),this.modifiedNestedFields.get(e).add(t))}markProjectModified(e,t){this.modifiedProjectFields.add(e),t&&(this.modifiedProjectNestedFields.has(e)||this.modifiedProjectNestedFields.set(e,new Set),this.modifiedProjectNestedFields.get(e).add(t))}assertProjectTrustedForWrite(){if(!this.projectTrusted)throw new Error("Project is not trusted; refusing to write project settings")}recordError(e,t){this.errors.push(p(e,t,this.settingsPaths[e]))}clearModifiedScope(e){if(e==="global"){this.modifiedFields.clear(),this.modifiedNestedFields.clear();return}this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear()}enqueueWrite(e,t){this.writeQueue=this.writeQueue.then(()=>{e==="project"&&this.assertProjectTrustedForWrite(),t(),this.clearModifiedScope(e)}).catch(s=>{this.recordError(e,s)})}cloneModifiedNestedFields(e){const t=new Map;for(const[s,i]of e.entries())t.set(s,new Set(i));return t}persistScopedSettings(e,t,s,i){this.storage.withLock(e,r=>{const o=r?a.migrateSettings(JSON.parse(y(r))):{},n={...o};for(const d of s){const c=t[d];if(i.has(d)&&typeof c=="object"&&c!==null){const j=i.get(d),E=o[d]??{},C=c,S={...E};for(const b of j)S[b]=C[b];n[d]=S}else n[d]=c}return JSON.stringify(n,null,2)})}save(){if(this.settings=h(this.globalSettings,this.projectSettings),this.globalSettingsLoadError)return;const e=structuredClone(this.globalSettings),t=new Set(this.modifiedFields),s=this.cloneModifiedNestedFields(this.modifiedNestedFields);this.enqueueWrite("global",()=>{this.persistScopedSettings("global",e,t,s)})}saveProjectSettings(e){if(this.assertProjectTrustedForWrite(),this.projectSettings=structuredClone(e),this.settings=h(this.globalSettings,this.projectSettings),this.projectSettingsLoadError)return;const t=structuredClone(this.projectSettings),s=new Set(this.modifiedProjectFields),i=this.cloneModifiedNestedFields(this.modifiedProjectNestedFields);this.enqueueWrite("project",()=>{this.persistScopedSettings("project",t,s,i)})}updateProjectSettings(e,t){this.assertProjectTrustedForWrite();const s=structuredClone(this.projectSettings);t(s),this.markProjectModified(e),this.saveProjectSettings(s)}async flush(){await this.writeQueue}drainErrors(){const e=[...this.errors];return this.errors=[],e}getLastChangelogVersion(){return this.settings.lastChangelogVersion}setLastChangelogVersion(e){this.globalSettings.lastChangelogVersion=e,this.markModified("lastChangelogVersion"),this.save()}getSessionDir(){const e=this.settings.sessionDir;return e&&v(e)}getDefaultProvider(){return this.settings.defaultProvider}getDefaultModel(){return this.settings.defaultModel}setDefaultProvider(e){this.globalSettings.defaultProvider=e,this.markModified("defaultProvider"),this.save()}setDefaultModel(e){this.globalSettings.defaultModel=e,this.markModified("defaultModel"),this.save()}setDefaultModelAndProvider(e,t){this.globalSettings.defaultProvider=e,this.globalSettings.defaultModel=t,this.markModified("defaultProvider"),this.markModified("defaultModel"),this.save()}getSteeringMode(){return this.settings.steeringMode||"one-at-a-time"}setSteeringMode(e){this.globalSettings.steeringMode=e,this.markModified("steeringMode"),this.save()}getFollowUpMode(){return this.settings.followUpMode||"one-at-a-time"}setFollowUpMode(e){this.globalSettings.followUpMode=e,this.markModified("followUpMode"),this.save()}getThemeSetting(){const e=this.settings.theme;if(typeof e=="string")return e}getTheme(){const e=this.getThemeSetting();return e?.includes("/")?void 0:e}setTheme(e){this.globalSettings.theme=e,this.markModified("theme"),this.save()}getDefaultThinkingLevel(){return this.settings.defaultThinkingLevel}setDefaultThinkingLevel(e){this.globalSettings.defaultThinkingLevel=e,this.markModified("defaultThinkingLevel"),this.save()}getModelThinkingLevel(e,t){return this.settings.modelThinkingLevels?.[`${e}/${t}`]}getAllModelThinkingLevels(){return{...this.settings.modelThinkingLevels??{}}}setModelThinkingLevel(e,t,s){this.globalSettings.modelThinkingLevels||(this.globalSettings.modelThinkingLevels={}),this.globalSettings.modelThinkingLevels[`${e}/${t}`]=s,this.markModified("modelThinkingLevels"),this.save()}removeModelThinkingLevel(e,t){this.globalSettings.modelThinkingLevels&&(delete this.globalSettings.modelThinkingLevels[`${e}/${t}`],Object.keys(this.globalSettings.modelThinkingLevels).length===0&&delete this.globalSettings.modelThinkingLevels,this.markModified("modelThinkingLevels"),this.save())}getTransport(){return this.settings.transport??"auto"}setTransport(e){this.globalSettings.transport=e,this.markModified("transport"),this.save()}getCompactionEnabled(){return this.settings.compaction?.enabled??!0}setCompactionEnabled(e){this.globalSettings.compaction||(this.globalSettings.compaction={}),this.globalSettings.compaction.enabled=e,this.markModified("compaction","enabled"),this.save()}getCompactionTokenSetting(e,t){const s=this.settings.compaction,i=s?.[e];if(i!==void 0&&(typeof i!="number"||!Number.isSafeInteger(i)||i<0))throw new Error(`Invalid compaction.${e} setting: ${String(i)}. Expected a non-negative safe integer.`);const r=t?`${t.provider}/${t.id}`:void 0,o=r!==void 0?s?.modelOverrides?.[r]:void 0;if(o!==void 0&&!f(o))throw new Error(`Invalid compaction.modelOverrides["${r}"] setting: ${String(o)}. Expected an object.`);const n=o?.[e];if(n!==void 0&&(typeof n!="number"||!Number.isSafeInteger(n)||n<0))throw new Error(`Invalid compaction.modelOverrides["${r}"].${e} setting: ${String(n)}. Expected a non-negative safe integer.`);return n??i??$[e]}getCompactionReserveTokens(e){return this.getCompactionTokenSetting("reserveTokens",e)}getCompactionKeepRecentTokens(e){return this.getCompactionTokenSetting("keepRecentTokens",e)}getCompactionSettings(e){return{enabled:this.getCompactionEnabled(),reserveTokens:this.getCompactionReserveTokens(e),keepRecentTokens:this.getCompactionKeepRecentTokens(e),maxContextTokens:this.getCompactionMaxContextTokens()}}getCompactionMaxContextTokens(){const e=this.settings.compaction?.maxContextTokens;if(e===void 0)return _;if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw new Error(`Invalid compaction.maxContextTokens setting: ${String(e)}. Expected a non-negative safe integer.`);return e}getBranchSummarySettings(){return{reserveTokens:this.settings.branchSummary?.reserveTokens??16384,skipPrompt:this.settings.branchSummary?.skipPrompt??!1}}getBranchSummarySkipPrompt(){return this.settings.branchSummary?.skipPrompt??!1}getRetryEnabled(){return this.settings.retry?.enabled??!0}setRetryEnabled(e){this.globalSettings.retry||(this.globalSettings.retry={}),this.globalSettings.retry.enabled=e,this.markModified("retry","enabled"),this.save()}getRetrySettings(){return{enabled:this.getRetryEnabled(),maxRetries:this.settings.retry?.maxRetries??B,baseDelayMs:this.settings.retry?.baseDelayMs??2e3,maxAgentDelayMs:this.settings.retry?.maxAgentDelayMs??x}}getMaxOutputTokens(){const e=this.settings.maxOutputTokens;if(e===void 0)return U;if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw new Error(`Invalid maxOutputTokens setting: ${String(e)}. Expected a non-negative safe integer.`);return e}getOutputTokenLimit(e){const t=this.getMaxOutputTokens();return t>0&&(e<=0||e>t)?t:e}getHttpIdleTimeoutMs(){return P(this.settings.httpIdleTimeoutMs,"httpIdleTimeoutMs")??R}setHttpIdleTimeoutMs(e){if(!Number.isFinite(e)||e<0)throw new Error(`Invalid httpIdleTimeoutMs setting: ${String(e)}`);this.globalSettings.httpIdleTimeoutMs=Math.floor(e),this.markModified("httpIdleTimeoutMs"),this.save()}getCacheWarmingMode(){const e=this.globalSettings.cacheWarming;return e!==void 0&&H.includes(e)?e:"streaming"}setCacheWarmingMode(e){this.globalSettings.cacheWarming=e,this.markModified("cacheWarming"),this.save()}getProviderRetrySettings(){return{timeoutMs:this.settings.retry?.provider?.timeoutMs,maxRetries:this.settings.retry?.provider?.maxRetries,maxRetryDelayMs:this.settings.retry?.provider?.maxRetryDelayMs??6e4}}getWebSocketConnectTimeoutMs(){return P(this.settings.websocketConnectTimeoutMs,"websocketConnectTimeoutMs")}getHideThinkingBlock(){return this.settings.hideThinkingBlock??!0}getShowCacheMissNotices(){return this.settings.showCacheMissNotices??!1}getExternalEditorCommand(){const e=this.settings.externalEditor;if(typeof e=="string"&&e.trim()!=="")return e;const t=process.env.VISUAL||process.env.EDITOR;return t||(process.platform==="win32"?"notepad":"nano")}setHideThinkingBlock(e){this.globalSettings.hideThinkingBlock=e,this.markModified("hideThinkingBlock"),this.save()}setShowCacheMissNotices(e){this.globalSettings.showCacheMissNotices=e,this.markModified("showCacheMissNotices"),this.save()}getShellPath(){const e=this.settings.shellPath;return e&&v(e)}setShellPath(e){this.globalSettings.shellPath=e,this.markModified("shellPath"),this.save()}getQuietStartup(){return this.settings.quietStartup??!0}setQuietStartup(e){this.globalSettings.quietStartup=e,this.markModified("quietStartup"),this.save()}getDefaultProjectTrust(){const e=this.globalSettings.defaultProjectTrust;return e==="always"||e==="never"?e:"ask"}setDefaultProjectTrust(e){this.globalSettings.defaultProjectTrust=e,this.markModified("defaultProjectTrust"),this.save()}getShellCommandPrefix(){return this.settings.shellCommandPrefix}getShellEnvironmentPolicy(){const e=this.globalSettings.shellEnvironment??{},t=[...e.exclude??[],...this.projectSettings.shellEnvironment?.exclude??[]];return{...e.inherit!==void 0?{inherit:e.inherit}:{},...t.length>0?{exclude:t}:{},...e.include!==void 0?{include:[...e.include]}:{},...e.set!==void 0?{set:{...e.set}}:{}}}setShellCommandPrefix(e){this.globalSettings.shellCommandPrefix=e,this.markModified("shellCommandPrefix"),this.save()}getNpmCommand(){return this.settings.npmCommand?[...this.settings.npmCommand]:void 0}setNpmCommand(e){this.globalSettings.npmCommand=e?[...e]:void 0,this.markModified("npmCommand"),this.save()}getCollapseChangelog(){return this.settings.collapseChangelog??!0}setCollapseChangelog(e){this.globalSettings.collapseChangelog=e,this.markModified("collapseChangelog"),this.save()}getEnableInstallTelemetry(){return this.settings.enableInstallTelemetry??!0}setEnableInstallTelemetry(e){this.globalSettings.enableInstallTelemetry=e,this.markModified("enableInstallTelemetry"),this.save()}getEnableAnalytics(){return this.settings.enableAnalytics??!1}getTrackingId(){return this.settings.trackingId}setEnableAnalytics(e){this.globalSettings.enableAnalytics=e,this.markModified("enableAnalytics"),e&&!this.globalSettings.trackingId&&(this.globalSettings.trackingId=F(),this.markModified("trackingId")),this.save()}getPackages(){return[...this.settings.packages??[]]}setPackages(e){this.globalSettings.packages=e,this.markModified("packages"),this.save()}setProjectPackages(e){this.updateProjectSettings("packages",t=>{t.packages=e})}getExtensionPaths(){return[...this.settings.extensions??[]]}setExtensionPaths(e){this.globalSettings.extensions=e,this.markModified("extensions"),this.save()}setProjectExtensionPaths(e){this.updateProjectSettings("extensions",t=>{t.extensions=e})}getSkillPaths(){return[...this.settings.skills??[]]}setSkillPaths(e){this.globalSettings.skills=e,this.markModified("skills"),this.save()}setProjectSkillPaths(e){this.updateProjectSettings("skills",t=>{t.skills=e})}getPromptTemplatePaths(){return[...this.settings.prompts??[]]}setPromptTemplatePaths(e){this.globalSettings.prompts=e,this.markModified("prompts"),this.save()}setProjectPromptTemplatePaths(e){this.updateProjectSettings("prompts",t=>{t.prompts=e})}getThemePaths(){return[...this.settings.themes??[]]}setThemePaths(e){this.globalSettings.themes=e,this.markModified("themes"),this.save()}setProjectThemePaths(e){this.updateProjectSettings("themes",t=>{t.themes=e})}getEnableSkillCommands(){return this.settings.enableSkillCommands??!0}setEnableSkillCommands(e){this.globalSettings.enableSkillCommands=e,this.markModified("enableSkillCommands"),this.save()}getFactoryEnabled(){return this.settings.factoryEnabled??!0}setFactoryEnabled(e){this.globalSettings.factoryEnabled=e,this.markModified("factoryEnabled"),this.save()}getThinkingBudgets(){return this.settings.thinkingBudgets}getTerminalCapabilityOverrides(){const e=this.settings.terminal,t=e?.images;return{...t==="kitty"||t==="iterm2"?{images:t}:t===!1?{images:null}:{},...typeof e?.trueColor=="boolean"?{trueColor:e.trueColor}:{},...typeof e?.hyperlinks=="boolean"?{hyperlinks:e.hyperlinks}:{}}}getShowImages(){return this.settings.terminal?.showImages??!0}setShowImages(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showImages=e,this.markModified("terminal","showImages"),this.save()}getImageWidthCells(){const e=this.settings.terminal?.imageWidthCells;return typeof e!="number"||!Number.isFinite(e)?60:Math.max(1,Math.floor(e))}setImageWidthCells(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.imageWidthCells=Math.max(1,Math.floor(e)),this.markModified("terminal","imageWidthCells"),this.save()}getClearOnShrink(){return this.settings.terminal?.clearOnShrink!==void 0?this.settings.terminal.clearOnShrink:process.env.PI_CLEAR_ON_SHRINK==="1"}setClearOnShrink(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.clearOnShrink=e,this.markModified("terminal","clearOnShrink"),this.save()}getShowTerminalProgress(){return this.settings.terminal?.showTerminalProgress??!1}setShowTerminalProgress(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showTerminalProgress=e,this.markModified("terminal","showTerminalProgress"),this.save()}getTuiMode(){return this.settings.tuiMode==="fullscreen"?"fullscreen":(this.settings.tuiMode==="regular"||this.settings.tuiMode,"regular")}setTuiMode(e){this.globalSettings.tuiMode=e,this.markModified("tuiMode"),this.save()}getFullscreenExitOutput(){return this.settings.fullscreenExitOutput==="resume-hint"?"resume-hint":"transcript"}setFullscreenExitOutput(e){this.globalSettings.fullscreenExitOutput=e,this.markModified("fullscreenExitOutput"),this.save()}getFullscreenScrollbar(){const e=this.settings.fullscreenScrollbar;return e==="always"||e==="hidden"?e:"auto"}setFullscreenScrollbar(e){this.globalSettings.fullscreenScrollbar=e,this.markModified("fullscreenScrollbar"),this.save()}getFullscreenCopyOnSelect(){return this.settings.fullscreenCopyOnSelect??!0}setFullscreenCopyOnSelect(e){this.globalSettings.fullscreenCopyOnSelect=e,this.markModified("fullscreenCopyOnSelect"),this.save()}getImageAutoResize(){return this.settings.images?.autoResize??!0}setImageAutoResize(e){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.autoResize=e,this.markModified("images","autoResize"),this.save()}getBlockImages(){return this.settings.images?.blockImages??!1}setBlockImages(e){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.blockImages=e,this.markModified("images","blockImages"),this.save()}getEnabledModels(){return this.settings.enabledModels}getDefaultTools(){const e=this.settings.defaultTools;return e?[...e]:void 0}setEnabledModels(e){this.globalSettings.enabledModels=e,this.markModified("enabledModels"),this.save()}getDoubleEscapeAction(){return this.settings.doubleEscapeAction??"tree"}setDoubleEscapeAction(e){this.globalSettings.doubleEscapeAction=e,this.markModified("doubleEscapeAction"),this.save()}getTreeFilterMode(){const e=this.settings.treeFilterMode;return e&&["default","no-tools","user-only","labeled-only","all"].includes(e)?e:"default"}setTreeFilterMode(e){this.globalSettings.treeFilterMode=e,this.markModified("treeFilterMode"),this.save()}getShowHardwareCursor(){return this.settings.showHardwareCursor??process.env.PI_HARDWARE_CURSOR==="1"}setShowHardwareCursor(e){this.globalSettings.showHardwareCursor=e,this.markModified("showHardwareCursor"),this.save()}getEditorPaddingX(){return this.settings.editorPaddingX??1}setEditorPaddingX(e){this.globalSettings.editorPaddingX=Math.max(0,Math.min(3,Math.floor(e))),this.markModified("editorPaddingX"),this.save()}getOutputPad(){return this.settings.outputPad===1?1:0}setOutputPad(e){this.globalSettings.outputPad=e,this.markModified("outputPad"),this.save()}getAutocompleteMaxVisible(){return this.settings.autocompleteMaxVisible??5}setAutocompleteMaxVisible(e){this.globalSettings.autocompleteMaxVisible=Math.max(3,Math.min(20,Math.floor(e))),this.markModified("autocompleteMaxVisible"),this.save()}getCodeBlockIndent(){return this.settings.markdown?.codeBlockIndent??" "}getMermaidRenderingMode(){const e=this.settings.markdown?.mermaid;return e==="off"||e==="final"?e:"streaming"}setMermaidRenderingMode(e){this.globalSettings.markdown??={},this.globalSettings.markdown.mermaid=e,this.markModified("markdown","mermaid"),this.save()}getWarnings(){return{...this.settings.warnings??{}}}setWarnings(e){this.globalSettings.warnings={...e},this.markModified("warnings"),this.save()}}export{H as CACHE_WARMING_MODES,_ as DEFAULT_COMPACTION_MAX_CONTEXT_TOKENS,U as DEFAULT_MAX_OUTPUT_TOKENS,B as DEFAULT_MAX_RETRIES,q as FileSettingsStorage,V as InMemorySettingsStorage,a as SettingsManager};
1
+ var w=Object.defineProperty;var g=(l,e)=>w(l,"name",{value:e,configurable:!0});import{DEFAULT_MAX_AGENT_RETRY_DELAY_MS as x}from"@earendil-works/pi-ai";import{randomUUID as F}from"crypto";import{existsSync as k,mkdirSync as L,readFileSync as I,writeFileSync as A}from"fs";import{dirname as N,join as u}from"path";import O from"proper-lockfile";import{CONFIG_DIR_NAME as M,getAgentDir as D}from"../config.js";import{normalizePath as v,resolvePath as m}from"../utils/paths.js";import{stripBom as y}from"../utils/text.js";import{DEFAULT_HTTP_IDLE_TIMEOUT_MS as R,parseHttpIdleTimeoutMs as W}from"./http-dispatcher.js";const $={reserveTokens:16384,keepRecentTokens:2e4},_=128e3,U=32e3,B=5,H=["off","streaming","idle"];function f(l){return typeof l=="object"&&l!==null&&!Array.isArray(l)}g(f,"isMergeableObject");function T(l,e){const t={...l};for(const s of Object.keys(e)){const i=e[s];if(i===void 0)continue;const r=l[s];t[s]=f(r)&&f(i)?T(r,i):i}return t}g(T,"deepMergeObjects");function h(l,e){return T(l,e)}g(h,"deepMergeSettings");function P(l,e){const t=W(l);if(t!==void 0)return t;if(l!==void 0)throw new Error(`Invalid ${e} setting: ${String(l)}`)}g(P,"parseTimeoutSetting");function S(l,e,t){return{scope:l,...t?{path:t}:{},error:e instanceof Error?e:new Error(String(e))}}g(S,"toSettingsError");class q{static{g(this,"FileSettingsStorage")}globalSettingsPath;projectSettingsPath;constructor(e,t){const s=m(e),i=m(t);this.globalSettingsPath=u(i,"settings.json"),this.projectSettingsPath=u(s,M,"settings.json")}acquireLockSyncWithRetry(e){let i;for(let r=1;r<=10;r++)try{return O.lockSync(e,{realpath:!1})}catch(o){if((typeof o=="object"&&o!==null&&"code"in o?String(o.code):void 0)!=="ELOCKED"||r===10)throw o;i=o;const d=Date.now();for(;Date.now()-d<20;);}throw i??new Error("Failed to acquire settings lock")}withLock(e,t){const s=e==="global"?this.globalSettingsPath:this.projectSettingsPath,i=N(s);let r;try{const o=k(s);o&&(r=this.acquireLockSyncWithRetry(s));const n=o?I(s,"utf-8"):void 0,d=t(n);d!==void 0&&(k(i)||L(i,{recursive:!0}),r||(r=this.acquireLockSyncWithRetry(s)),A(s,d,"utf-8"))}finally{r&&r()}}}class V{static{g(this,"InMemorySettingsStorage")}global;project;withLock(e,t){const s=e==="global"?this.global:this.project,i=t(s);i!==void 0&&(e==="global"?this.global=i:this.project=i)}}class a{static{g(this,"SettingsManager")}storage;globalSettings;projectSettings;settings;projectTrusted;modifiedFields=new Set;modifiedNestedFields=new Map;modifiedProjectFields=new Set;modifiedProjectNestedFields=new Map;globalSettingsLoadError=null;projectSettingsLoadError=null;writeQueue=Promise.resolve();errors;settingsPaths;constructor(e,t,s,i=null,r=null,o=[],n=!0,d={}){this.storage=e,this.globalSettings=t,this.projectSettings=s,this.projectTrusted=n,this.globalSettingsLoadError=i,this.projectSettingsLoadError=r,this.errors=[...o],this.settingsPaths=d,this.settings=h(this.globalSettings,this.projectSettings)}static create(e,t=D(),s={}){const i=m(e),r=m(t),o=new q(i,r);return a.fromStorageWithPaths(o,s,{global:u(r,"settings.json"),project:u(i,M,"settings.json")})}static fromStorage(e,t={}){return a.fromStorageWithPaths(e,t)}static fromStorageWithPaths(e,t,s={}){const i=t.projectTrusted??!0,r=a.tryLoadFromStorage(e,"global"),o=a.tryLoadFromStorage(e,"project",i),n=[];return r.error&&n.push(S("global",r.error,s.global)),o.error&&n.push(S("project",o.error,s.project)),new a(e,r.settings,o.settings,r.error,o.error,n,i,s)}static inMemory(e={},t={}){const s=new V,i=a.migrateSettings(structuredClone(e));return s.withLock("global",()=>JSON.stringify(i,null,2)),a.fromStorage(s,t)}static loadFromStorage(e,t,s=!0){if(t==="project"&&!s)return{};let i;if(e.withLock(t,o=>{i=o}),!i)return{};const r=JSON.parse(y(i));return a.migrateSettings(r)}static tryLoadFromStorage(e,t,s=!0){try{return{settings:a.loadFromStorage(e,t,s),error:null}}catch(i){return{settings:{},error:i}}}static migrateSettings(e){if("queueMode"in e&&!("steeringMode"in e)&&(e.steeringMode=e.queueMode,delete e.queueMode),!("transport"in e)&&typeof e.websockets=="boolean"&&(e.transport=e.websockets?"websocket":"sse",delete e.websockets),"skills"in e&&typeof e.skills=="object"&&e.skills!==null&&!Array.isArray(e.skills)){const t=e.skills;t.enableSkillCommands!==void 0&&e.enableSkillCommands===void 0&&(e.enableSkillCommands=t.enableSkillCommands),Array.isArray(t.customDirectories)&&t.customDirectories.length>0?e.skills=t.customDirectories:delete e.skills}if("retry"in e&&typeof e.retry=="object"&&e.retry!==null&&!Array.isArray(e.retry)){const t=e.retry,s=typeof t.provider=="object"&&t.provider!==null?t.provider:void 0;typeof t.maxDelayMs=="number"&&(s?.maxRetryDelayMs===void 0||s?.maxRetryDelayMs===null)&&(t.provider={...s??{},maxRetryDelayMs:t.maxDelayMs}),delete t.maxDelayMs}return e}getGlobalSettings(){return structuredClone(this.globalSettings)}getProjectSettings(){return structuredClone(this.projectSettings)}isProjectTrusted(){return this.projectTrusted}setProjectTrusted(e){if(this.projectTrusted===e)return;if(this.projectTrusted=e,this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear(),!e){this.projectSettings={},this.projectSettingsLoadError=null,this.settings=h(this.globalSettings,this.projectSettings);return}const t=a.tryLoadFromStorage(this.storage,"project",e);this.projectSettings=t.settings,this.projectSettingsLoadError=t.error,t.error&&this.recordError("project",t.error),this.settings=h(this.globalSettings,this.projectSettings)}async reload(){await this.writeQueue;const e=a.tryLoadFromStorage(this.storage,"global");e.error?(this.globalSettingsLoadError=e.error,this.recordError("global",e.error)):(this.globalSettings=e.settings,this.globalSettingsLoadError=null),this.modifiedFields.clear(),this.modifiedNestedFields.clear(),this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear();const t=a.tryLoadFromStorage(this.storage,"project",this.projectTrusted);t.error?(this.projectSettingsLoadError=t.error,this.recordError("project",t.error)):(this.projectSettings=t.settings,this.projectSettingsLoadError=null),this.settings=h(this.globalSettings,this.projectSettings)}applyOverrides(e){this.settings=h(this.settings,e)}markModified(e,t){this.modifiedFields.add(e),t&&(this.modifiedNestedFields.has(e)||this.modifiedNestedFields.set(e,new Set),this.modifiedNestedFields.get(e).add(t))}markProjectModified(e,t){this.modifiedProjectFields.add(e),t&&(this.modifiedProjectNestedFields.has(e)||this.modifiedProjectNestedFields.set(e,new Set),this.modifiedProjectNestedFields.get(e).add(t))}assertProjectTrustedForWrite(){if(!this.projectTrusted)throw new Error("Project is not trusted; refusing to write project settings")}recordError(e,t){this.errors.push(S(e,t,this.settingsPaths[e]))}clearModifiedScope(e){if(e==="global"){this.modifiedFields.clear(),this.modifiedNestedFields.clear();return}this.modifiedProjectFields.clear(),this.modifiedProjectNestedFields.clear()}enqueueWrite(e,t){this.writeQueue=this.writeQueue.then(()=>{e==="project"&&this.assertProjectTrustedForWrite(),t(),this.clearModifiedScope(e)}).catch(s=>{this.recordError(e,s)})}cloneModifiedNestedFields(e){const t=new Map;for(const[s,i]of e.entries())t.set(s,new Set(i));return t}persistScopedSettings(e,t,s,i){this.storage.withLock(e,r=>{const o=r?a.migrateSettings(JSON.parse(y(r))):{},n={...o};for(const d of s){const c=t[d];if(i.has(d)&&typeof c=="object"&&c!==null){const j=i.get(d),C=o[d]??{},E=c,p={...C};for(const b of j)p[b]=E[b];n[d]=p}else n[d]=c}return JSON.stringify(n,null,2)})}save(){if(this.settings=h(this.globalSettings,this.projectSettings),this.globalSettingsLoadError)return;const e=structuredClone(this.globalSettings),t=new Set(this.modifiedFields),s=this.cloneModifiedNestedFields(this.modifiedNestedFields);this.enqueueWrite("global",()=>{this.persistScopedSettings("global",e,t,s)})}saveProjectSettings(e){if(this.assertProjectTrustedForWrite(),this.projectSettings=structuredClone(e),this.settings=h(this.globalSettings,this.projectSettings),this.projectSettingsLoadError)return;const t=structuredClone(this.projectSettings),s=new Set(this.modifiedProjectFields),i=this.cloneModifiedNestedFields(this.modifiedProjectNestedFields);this.enqueueWrite("project",()=>{this.persistScopedSettings("project",t,s,i)})}updateProjectSettings(e,t){this.assertProjectTrustedForWrite();const s=structuredClone(this.projectSettings);t(s),this.markProjectModified(e),this.saveProjectSettings(s)}async flush(){await this.writeQueue}drainErrors(){const e=[...this.errors];return this.errors=[],e}getLastChangelogVersion(){return this.settings.lastChangelogVersion}setLastChangelogVersion(e){this.globalSettings.lastChangelogVersion=e,this.markModified("lastChangelogVersion"),this.save()}getSessionDir(){const e=this.settings.sessionDir;return e&&v(e)}getDefaultProvider(){return this.settings.defaultProvider}getDefaultModel(){return this.settings.defaultModel}setDefaultProvider(e){this.globalSettings.defaultProvider=e,this.markModified("defaultProvider"),this.save()}setDefaultModel(e){this.globalSettings.defaultModel=e,this.markModified("defaultModel"),this.save()}setDefaultModelAndProvider(e,t){this.globalSettings.defaultProvider=e,this.globalSettings.defaultModel=t,this.markModified("defaultProvider"),this.markModified("defaultModel"),this.save()}getSteeringMode(){return this.settings.steeringMode||"one-at-a-time"}setSteeringMode(e){this.globalSettings.steeringMode=e,this.markModified("steeringMode"),this.save()}getFollowUpMode(){return this.settings.followUpMode||"one-at-a-time"}setFollowUpMode(e){this.globalSettings.followUpMode=e,this.markModified("followUpMode"),this.save()}getThemeSetting(){const e=this.settings.theme;if(typeof e=="string")return e}getTheme(){const e=this.getThemeSetting();return e?.includes("/")?void 0:e}setTheme(e){this.globalSettings.theme=e,this.markModified("theme"),this.save()}getDefaultThinkingLevel(){return this.settings.defaultThinkingLevel}setDefaultThinkingLevel(e){this.globalSettings.defaultThinkingLevel=e,this.markModified("defaultThinkingLevel"),this.save()}getModelThinkingLevel(e,t){return this.settings.modelThinkingLevels?.[`${e}/${t}`]}getAllModelThinkingLevels(){return{...this.settings.modelThinkingLevels??{}}}setModelThinkingLevel(e,t,s){this.globalSettings.modelThinkingLevels||(this.globalSettings.modelThinkingLevels={}),this.globalSettings.modelThinkingLevels[`${e}/${t}`]=s,this.markModified("modelThinkingLevels"),this.save()}removeModelThinkingLevel(e,t){this.globalSettings.modelThinkingLevels&&(delete this.globalSettings.modelThinkingLevels[`${e}/${t}`],Object.keys(this.globalSettings.modelThinkingLevels).length===0&&delete this.globalSettings.modelThinkingLevels,this.markModified("modelThinkingLevels"),this.save())}getTransport(){return this.settings.transport??"auto"}setTransport(e){this.globalSettings.transport=e,this.markModified("transport"),this.save()}getCompactionEnabled(){return this.settings.compaction?.enabled??!0}setCompactionEnabled(e){this.globalSettings.compaction||(this.globalSettings.compaction={}),this.globalSettings.compaction.enabled=e,this.markModified("compaction","enabled"),this.save()}getCompactionTokenSetting(e,t){const s=this.settings.compaction,i=s?.[e];if(i!==void 0&&(typeof i!="number"||!Number.isSafeInteger(i)||i<0))throw new Error(`Invalid compaction.${e} setting: ${String(i)}. Expected a non-negative safe integer.`);const r=t?`${t.provider}/${t.id}`:void 0,o=r!==void 0?s?.modelOverrides?.[r]:void 0;if(o!==void 0&&!f(o))throw new Error(`Invalid compaction.modelOverrides["${r}"] setting: ${String(o)}. Expected an object.`);const n=o?.[e];if(n!==void 0&&(typeof n!="number"||!Number.isSafeInteger(n)||n<0))throw new Error(`Invalid compaction.modelOverrides["${r}"].${e} setting: ${String(n)}. Expected a non-negative safe integer.`);return n??i??$[e]}getCompactionReserveTokens(e){return this.getCompactionTokenSetting("reserveTokens",e)}getCompactionKeepRecentTokens(e){return this.getCompactionTokenSetting("keepRecentTokens",e)}getCompactionSettings(e){return{enabled:this.getCompactionEnabled(),reserveTokens:this.getCompactionReserveTokens(e),keepRecentTokens:this.getCompactionKeepRecentTokens(e),maxContextTokens:this.getCompactionMaxContextTokens()}}getCompactionMaxContextTokens(){const e=this.settings.compaction?.maxContextTokens;if(e===void 0)return _;if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw new Error(`Invalid compaction.maxContextTokens setting: ${String(e)}. Expected a non-negative safe integer.`);return e}getBranchSummarySettings(){return{reserveTokens:this.settings.branchSummary?.reserveTokens??16384,skipPrompt:this.settings.branchSummary?.skipPrompt??!1}}getBranchSummarySkipPrompt(){return this.settings.branchSummary?.skipPrompt??!1}getRetryEnabled(){return this.settings.retry?.enabled??!0}setRetryEnabled(e){this.globalSettings.retry||(this.globalSettings.retry={}),this.globalSettings.retry.enabled=e,this.markModified("retry","enabled"),this.save()}getRetrySettings(){return{enabled:this.getRetryEnabled(),maxRetries:this.settings.retry?.maxRetries??B,baseDelayMs:this.settings.retry?.baseDelayMs??2e3,maxAgentDelayMs:this.settings.retry?.maxAgentDelayMs??x}}getMaxOutputTokens(){const e=this.settings.maxOutputTokens;if(e===void 0)return U;if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw new Error(`Invalid maxOutputTokens setting: ${String(e)}. Expected a non-negative safe integer.`);return e}getOutputTokenLimit(e){const t=this.getMaxOutputTokens();return t>0&&(e<=0||e>t)?t:e}getHttpIdleTimeoutMs(){return P(this.settings.httpIdleTimeoutMs,"httpIdleTimeoutMs")??R}setHttpIdleTimeoutMs(e){if(!Number.isFinite(e)||e<0)throw new Error(`Invalid httpIdleTimeoutMs setting: ${String(e)}`);this.globalSettings.httpIdleTimeoutMs=Math.floor(e),this.markModified("httpIdleTimeoutMs"),this.save()}getCacheWarmingMode(){const e=this.globalSettings.cacheWarming;return e!==void 0&&H.includes(e)?e:"streaming"}setCacheWarmingMode(e){this.globalSettings.cacheWarming=e,this.markModified("cacheWarming"),this.save()}getProviderRetrySettings(){return{timeoutMs:this.settings.retry?.provider?.timeoutMs,maxRetries:this.settings.retry?.provider?.maxRetries,maxRetryDelayMs:this.settings.retry?.provider?.maxRetryDelayMs??6e4}}getWebSocketConnectTimeoutMs(){return P(this.settings.websocketConnectTimeoutMs,"websocketConnectTimeoutMs")}getHideThinkingBlock(){return this.settings.hideThinkingBlock??!0}getShowCacheMissNotices(){return this.settings.showCacheMissNotices??!1}getExternalEditorCommand(){const e=this.settings.externalEditor;if(typeof e=="string"&&e.trim()!=="")return e;const t=process.env.VISUAL||process.env.EDITOR;return t||(process.platform==="win32"?"notepad":"nano")}setHideThinkingBlock(e){this.globalSettings.hideThinkingBlock=e,this.markModified("hideThinkingBlock"),this.save()}setShowCacheMissNotices(e){this.globalSettings.showCacheMissNotices=e,this.markModified("showCacheMissNotices"),this.save()}getShellPath(){const e=this.settings.shellPath;return e&&v(e)}setShellPath(e){this.globalSettings.shellPath=e,this.markModified("shellPath"),this.save()}getQuietStartup(){return this.settings.quietStartup??!0}setQuietStartup(e){this.globalSettings.quietStartup=e,this.markModified("quietStartup"),this.save()}getDefaultProjectTrust(){const e=this.globalSettings.defaultProjectTrust;return e==="always"||e==="never"?e:"ask"}setDefaultProjectTrust(e){this.globalSettings.defaultProjectTrust=e,this.markModified("defaultProjectTrust"),this.save()}getShellCommandPrefix(){return this.settings.shellCommandPrefix}getShellEnvironmentPolicy(){const e=this.globalSettings.shellEnvironment??{},t=[...e.exclude??[],...this.projectSettings.shellEnvironment?.exclude??[]];return{...e.inherit!==void 0?{inherit:e.inherit}:{},...t.length>0?{exclude:t}:{},...e.include!==void 0?{include:[...e.include]}:{},...e.set!==void 0?{set:{...e.set}}:{}}}getPermissionRuleSources(){return{...this.globalSettings.permissions?{user:structuredClone(this.globalSettings.permissions)}:{},...this.projectSettings.permissions?{project:structuredClone(this.projectSettings.permissions)}:{}}}getSandboxSettingsSources(){return{...this.globalSettings.sandbox?{global:structuredClone(this.globalSettings.sandbox)}:{},...this.projectSettings.sandbox?{project:structuredClone(this.projectSettings.sandbox)}:{}}}setShellCommandPrefix(e){this.globalSettings.shellCommandPrefix=e,this.markModified("shellCommandPrefix"),this.save()}getNpmCommand(){return this.settings.npmCommand?[...this.settings.npmCommand]:void 0}setNpmCommand(e){this.globalSettings.npmCommand=e?[...e]:void 0,this.markModified("npmCommand"),this.save()}getCollapseChangelog(){return this.settings.collapseChangelog??!0}setCollapseChangelog(e){this.globalSettings.collapseChangelog=e,this.markModified("collapseChangelog"),this.save()}getEnableInstallTelemetry(){return this.settings.enableInstallTelemetry??!0}setEnableInstallTelemetry(e){this.globalSettings.enableInstallTelemetry=e,this.markModified("enableInstallTelemetry"),this.save()}getEnableAnalytics(){return this.settings.enableAnalytics??!1}getTrackingId(){return this.settings.trackingId}setEnableAnalytics(e){this.globalSettings.enableAnalytics=e,this.markModified("enableAnalytics"),e&&!this.globalSettings.trackingId&&(this.globalSettings.trackingId=F(),this.markModified("trackingId")),this.save()}getPackages(){return[...this.settings.packages??[]]}setPackages(e){this.globalSettings.packages=e,this.markModified("packages"),this.save()}setProjectPackages(e){this.updateProjectSettings("packages",t=>{t.packages=e})}getExtensionPaths(){return[...this.settings.extensions??[]]}setExtensionPaths(e){this.globalSettings.extensions=e,this.markModified("extensions"),this.save()}setProjectExtensionPaths(e){this.updateProjectSettings("extensions",t=>{t.extensions=e})}getSkillPaths(){return[...this.settings.skills??[]]}setSkillPaths(e){this.globalSettings.skills=e,this.markModified("skills"),this.save()}setProjectSkillPaths(e){this.updateProjectSettings("skills",t=>{t.skills=e})}getPromptTemplatePaths(){return[...this.settings.prompts??[]]}setPromptTemplatePaths(e){this.globalSettings.prompts=e,this.markModified("prompts"),this.save()}setProjectPromptTemplatePaths(e){this.updateProjectSettings("prompts",t=>{t.prompts=e})}getThemePaths(){return[...this.settings.themes??[]]}setThemePaths(e){this.globalSettings.themes=e,this.markModified("themes"),this.save()}setProjectThemePaths(e){this.updateProjectSettings("themes",t=>{t.themes=e})}getEnableSkillCommands(){return this.settings.enableSkillCommands??!0}setEnableSkillCommands(e){this.globalSettings.enableSkillCommands=e,this.markModified("enableSkillCommands"),this.save()}getFactoryEnabled(){return this.settings.factoryEnabled??!0}setFactoryEnabled(e){this.globalSettings.factoryEnabled=e,this.markModified("factoryEnabled"),this.save()}getThinkingBudgets(){return this.settings.thinkingBudgets}getTerminalCapabilityOverrides(){const e=this.settings.terminal,t=e?.images;return{...t==="kitty"||t==="iterm2"?{images:t}:t===!1?{images:null}:{},...typeof e?.trueColor=="boolean"?{trueColor:e.trueColor}:{},...typeof e?.hyperlinks=="boolean"?{hyperlinks:e.hyperlinks}:{}}}getShowImages(){return this.settings.terminal?.showImages??!0}setShowImages(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showImages=e,this.markModified("terminal","showImages"),this.save()}getImageWidthCells(){const e=this.settings.terminal?.imageWidthCells;return typeof e!="number"||!Number.isFinite(e)?60:Math.max(1,Math.floor(e))}setImageWidthCells(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.imageWidthCells=Math.max(1,Math.floor(e)),this.markModified("terminal","imageWidthCells"),this.save()}getClearOnShrink(){return this.settings.terminal?.clearOnShrink!==void 0?this.settings.terminal.clearOnShrink:process.env.PI_CLEAR_ON_SHRINK==="1"}setClearOnShrink(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.clearOnShrink=e,this.markModified("terminal","clearOnShrink"),this.save()}getShowTerminalProgress(){return this.settings.terminal?.showTerminalProgress??!1}setShowTerminalProgress(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showTerminalProgress=e,this.markModified("terminal","showTerminalProgress"),this.save()}getTuiMode(){return this.settings.tuiMode==="fullscreen"?"fullscreen":(this.settings.tuiMode==="regular"||this.settings.tuiMode,"regular")}setTuiMode(e){this.globalSettings.tuiMode=e,this.markModified("tuiMode"),this.save()}getFullscreenExitOutput(){return this.settings.fullscreenExitOutput==="resume-hint"?"resume-hint":"transcript"}setFullscreenExitOutput(e){this.globalSettings.fullscreenExitOutput=e,this.markModified("fullscreenExitOutput"),this.save()}getFullscreenScrollbar(){const e=this.settings.fullscreenScrollbar;return e==="always"||e==="hidden"?e:"auto"}setFullscreenScrollbar(e){this.globalSettings.fullscreenScrollbar=e,this.markModified("fullscreenScrollbar"),this.save()}getFullscreenCopyOnSelect(){return this.settings.fullscreenCopyOnSelect??!0}setFullscreenCopyOnSelect(e){this.globalSettings.fullscreenCopyOnSelect=e,this.markModified("fullscreenCopyOnSelect"),this.save()}getImageAutoResize(){return this.settings.images?.autoResize??!0}setImageAutoResize(e){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.autoResize=e,this.markModified("images","autoResize"),this.save()}getBlockImages(){return this.settings.images?.blockImages??!1}setBlockImages(e){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.blockImages=e,this.markModified("images","blockImages"),this.save()}getEnabledModels(){return this.settings.enabledModels}getDefaultTools(){const e=this.settings.defaultTools;return e?[...e]:void 0}setEnabledModels(e){this.globalSettings.enabledModels=e,this.markModified("enabledModels"),this.save()}getDoubleEscapeAction(){return this.settings.doubleEscapeAction??"tree"}setDoubleEscapeAction(e){this.globalSettings.doubleEscapeAction=e,this.markModified("doubleEscapeAction"),this.save()}getTreeFilterMode(){const e=this.settings.treeFilterMode;return e&&["default","no-tools","user-only","labeled-only","all"].includes(e)?e:"default"}setTreeFilterMode(e){this.globalSettings.treeFilterMode=e,this.markModified("treeFilterMode"),this.save()}getShowHardwareCursor(){return this.settings.showHardwareCursor??process.env.PI_HARDWARE_CURSOR==="1"}setShowHardwareCursor(e){this.globalSettings.showHardwareCursor=e,this.markModified("showHardwareCursor"),this.save()}getEditorPaddingX(){return this.settings.editorPaddingX??1}setEditorPaddingX(e){this.globalSettings.editorPaddingX=Math.max(0,Math.min(3,Math.floor(e))),this.markModified("editorPaddingX"),this.save()}getOutputPad(){return this.settings.outputPad===1?1:0}setOutputPad(e){this.globalSettings.outputPad=e,this.markModified("outputPad"),this.save()}getAutocompleteMaxVisible(){return this.settings.autocompleteMaxVisible??5}setAutocompleteMaxVisible(e){this.globalSettings.autocompleteMaxVisible=Math.max(3,Math.min(20,Math.floor(e))),this.markModified("autocompleteMaxVisible"),this.save()}getCodeBlockIndent(){return this.settings.markdown?.codeBlockIndent??" "}getMermaidRenderingMode(){const e=this.settings.markdown?.mermaid;return e==="off"||e==="final"?e:"streaming"}setMermaidRenderingMode(e){this.globalSettings.markdown??={},this.globalSettings.markdown.mermaid=e,this.markModified("markdown","mermaid"),this.save()}getWarnings(){return{...this.settings.warnings??{}}}setWarnings(e){this.globalSettings.warnings={...e},this.markModified("warnings"),this.save()}}export{H as CACHE_WARMING_MODES,_ as DEFAULT_COMPACTION_MAX_CONTEXT_TOKENS,U as DEFAULT_MAX_OUTPUT_TOKENS,B as DEFAULT_MAX_RETRIES,q as FileSettingsStorage,V as InMemorySettingsStorage,a as SettingsManager};
@@ -1,13 +1,23 @@
1
- import type { AgentTool } from "@earendil-works/pi-agent-core";
1
+ import { type AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import { type Static, Type } from "typebox";
3
3
  import { type ShellConfig } from "../../utils/shell.ts";
4
4
  import type { ToolDefinition } from "../extensions/types.ts";
5
+ import { type SandboxRunDetails, type ShellSandbox } from "../sandbox/shell-sandbox.ts";
5
6
  import { type TruncationResult } from "./truncate.ts";
6
7
  declare const bashSchema: Type.TObject<{
7
8
  command: Type.TString;
8
9
  description: Type.TString;
9
10
  timeout: Type.TOptional<Type.TNumber>;
10
11
  }>;
12
+ export declare const sandboxEscalationSchema: Type.TOptional<Type.TObject<{
13
+ mode: Type.TUnion<[
14
+ Type.TLiteral<"allow">,
15
+ Type.TLiteral<"unsandboxed">
16
+ ]>;
17
+ justification: Type.TString;
18
+ allow_domains: Type.TOptional<Type.TArray<Type.TString>>;
19
+ allow_write: Type.TOptional<Type.TArray<Type.TString>>;
20
+ }>>;
11
21
  export declare const bashToolSystemPromptContribution: {
12
22
  readonly snippet: "Execute bash commands (ls, grep, find, etc.)";
13
23
  readonly guidelines: readonly [
@@ -18,6 +28,7 @@ export type BashToolInput = Static<typeof bashSchema>;
18
28
  export interface BashToolDetails {
19
29
  truncation?: TruncationResult;
20
30
  fullOutputPath?: string;
31
+ sandbox?: SandboxRunDetails;
21
32
  }
22
33
  export interface BashOperations {
23
34
  exec: (command: string, cwd: string, options: {
@@ -53,6 +64,7 @@ export interface BashToolOptions {
53
64
  shellPath?: string;
54
65
  exposeSessionEnvironment?: boolean;
55
66
  spawnHook?: BashSpawnHook;
67
+ sandbox?: ShellSandbox;
56
68
  }
57
69
  export type BashRenderState = {
58
70
  startedAt: number | undefined;
@@ -68,6 +80,8 @@ export interface ShellToolConfig {
68
80
  promptGuidelines?: readonly string[];
69
81
  tempFilePrefix: string;
70
82
  readOnlyCommand?: (command: unknown) => boolean;
83
+ sandboxShell?: (shellPath: string | undefined) => string;
84
+ defaultOperations?: () => BashOperations;
71
85
  }
72
86
  export declare function createShellToolDefinition(cwd: string, config: ShellToolConfig, options?: BashToolOptions): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState>;
73
87
  export declare function createBashToolDefinition(cwd: string, options?: BashToolOptions): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState>;
@@ -1,19 +1,21 @@
1
- var Z=Object.defineProperty;var u=(t,n)=>Z(t,"name",{value:n,configurable:!0});import{constants as ee}from"node:fs";import{access as te}from"node:fs/promises";import{constants as ne}from"node:os";import{Container as ie,Text as _,truncateToWidth as oe}from"@earendil-works/pi-tui";import{spawn as re}from"child_process";import{Type as I}from"typebox";import{fill as C,t as $}from"../../dal/i18n.js";import{keyHint as se}from"../../modes/interactive/components/keybinding-hints.js";import{truncateToVisualLines as ae}from"../../modes/interactive/components/visual-truncate.js";import{theme as h}from"../../modes/interactive/theme/theme.js";import{waitForChildProcess as de}from"../../utils/child-process.js";import{getShellConfig as ue,getShellEnv as U,killProcessTree as V,trackDetachedChildPid as le,untrackDetachedChildPid as ce}from"../../utils/shell.js";import{isReadOnlyBashCommand as me}from"./bash-read-only.js";import{OutputAccumulator as fe}from"./output-accumulator.js";import{countOutputLines as pe,formatCollapsedSummary as he,getTextOutput as j,invalidArgText as we,str as X,truncateDisplay as Se}from"./render-utils.js";import{wrapToolDefinition as Ee}from"./tool-definition-wrapper.js";import{DEFAULT_MAX_BYTES as R,DEFAULT_MAX_LINES as $e,formatSize as F}from"./truncate.js";const z=2147483647,Oe=z/1e3,K=12e4;function Te(t){if(t===void 0)return K;if(!Number.isFinite(t)||t<=0)throw new Error("Invalid timeout: must be a finite number of seconds");const n=t*1e3;if(n>z)throw new Error(`Invalid timeout: maximum is ${Oe} seconds`);return n}u(Te,"resolveTimeoutMs");const xe=I.Object({command:I.String({description:"Shell command to execute"}),description:I.String({description:`One short line, in the user's language, saying what this command does and why \u2014 shown in place of the command itself. Describe the intent, not the syntax: "Find hardcoded key names", not "run grep with --exclude-dir". 3-10 words.`}),timeout:I.Optional(I.Number({description:"Timeout in seconds. Defaults to 120; raise it for genuinely long-running commands."}))}),Y={snippet:"Execute bash commands (ls, grep, find, etc.)",guidelines:["You can inspect PI_* environment variables for current model and session details."]};function Pe(t,n){return{exec:u(async(i,o,{onData:l,signal:r,timeout:E,env:s})=>{const a=Te(E);if(r?.aborted)throw new Error("aborted");const f=n();try{await te(o,ee.F_OK)}catch{throw new Error(`Working directory does not exist: ${o}
2
- Cannot execute ${t} commands.`)}const m=f.commandTransport==="stdin",e=re(f.shell,m?f.args:[...f.args,i],{cwd:o,detached:process.platform!=="win32",env:s??U(),stdio:[m?"pipe":"ignore","pipe","pipe"],windowsHide:!0});m&&(e.stdin?.on("error",()=>{}),e.stdin?.end(i)),e.pid&&le(e.pid);let c=!1,p;const T=u(()=>{e.pid&&V(e.pid)},"onAbort");try{a!==void 0&&(p=setTimeout(()=>{c=!0,e.pid&&V(e.pid)},a)),e.stdout?.on("data",l),e.stderr?.on("data",l),r&&(r.aborted?T():r.addEventListener("abort",T,{once:!0}));const x=await de(e);if(r?.aborted)throw new Error("aborted");if(c)throw new Error(`timeout:${(a??K)/1e3}`);const S=e.signalCode;return{exitCode:x??(S?128+(ne.signals[S]??0):1)}}finally{e.pid&&ce(e.pid),p&&clearTimeout(p),r&&r.removeEventListener("abort",T)}},"exec")}}u(Pe,"createLocalShellOperations");function ge(t){return Pe("bash",()=>ue(t?.shellPath))}u(ge,"createLocalBashOperations");const B=new Set;function Ze(t){return B.add(t),()=>{B.delete(t)}}u(Ze,"registerShellExecutionGuard");async function Ce(t){for(const n of B){let i;try{i=await n(t)}catch(o){return`Command refused: the safety check could not run (${o instanceof Error?o.message:String(o)}).`}if(i!==void 0)return i}}u(Ce,"shellExecutionRefusal");function Le(t,n,i,o,l){const r={...U()};if(delete r.PI_SESSION_ID,delete r.PI_SESSION_FILE,delete r.PI_PROVIDER,delete r.PI_MODEL,delete r.PI_REASONING_LEVEL,o&&l){const s=l.model;r.PI_SESSION_ID=l.sessionManager.getSessionId();const a=l.sessionManager.getSessionFile();a&&(r.PI_SESSION_FILE=a),s&&(r.PI_PROVIDER=s.provider,r.PI_MODEL=s.id),l.thinkingLevel&&(r.PI_REASONING_LEVEL=l.thinkingLevel)}const E={command:t,cwd:n,env:r};return i?i(E):E}u(Le,"resolveSpawnContext");const ye=5,_e=100;class Ie extends ie{static{u(this,"BashResultRenderComponent")}state={cachedWidth:void 0,cachedLines:void 0,cachedSkipped:void 0}}function q(t){const n=t/1e3;if(n<60)return`${n.toFixed(1)}s`;const i=Math.floor(n),o=Math.floor(i/60),l=i%60;return o<60?`${o}m ${l}s`:`${Math.floor(o/60)}h ${o%60}m ${l}s`}u(q,"formatDuration");function be(t,n,i=!1){const o=X(t?.command),l=X(t?.description)?.trim(),r=t?.timeout,E=r?h.fg("muted",C($(" (\u8D85\u65F6 {seconds} \u79D2)"),{seconds:r})):"";if(l){const a=h.fg("toolTitle",h.bold(l))+E;return!i||!o?a:`${a}
3
- ${h.fg("muted",` \u23BF ${n} ${o.trim()}`)}`}const s=o===null?we(h):o?h.fg("dim",Se(o.replace(/\s+/g," ").trim(),42)):h.fg("dim","\u2026");return`${h.fg("toolTitle",h.bold(n))} ${s}${E}`}u(be,"formatShellCall");function ve(t,n,i,o,l,r,E){const s=t.state;if(t.clear(),!i.expanded&&!E){const e=j(n,o),c=pe(e),p=[];if(c>0&&p.push(C($("{count} \u884C"),{count:c})),l!==void 0){const S=(r??Date.now())-l;if(i.isPartial||S>=100){const b=i.isPartial?$("\u5DF2\u8FD0\u884C"):$("\u8017\u65F6");p.push(`${b} ${q(S)}`)}}const T=he(h,p);T&&t.addChild(new _(T,0,0));return}let a=j(n,o).trim();const f=n.details?.truncation,m=n.details?.fullOutputPath;if(!i.isPartial&&f?.truncated&&m&&a.endsWith("]")){const e=a.lastIndexOf(`
1
+ var le=Object.defineProperty;var d=(t,e)=>le(t,"name",{value:e,configurable:!0});import{constants as ue}from"node:fs";import{access as ce}from"node:fs/promises";import{constants as me}from"node:os";import{ToolExecutionError as pe}from"@earendil-works/pi-agent-core";import{Container as fe,Text as M,truncateToWidth as he}from"@earendil-works/pi-tui";import{spawn as we}from"child_process";import{Type as f}from"typebox";import{fill as C,t as $}from"../../dal/i18n.js";import{keyHint as Se}from"../../modes/interactive/components/keybinding-hints.js";import{truncateToVisualLines as xe}from"../../modes/interactive/components/visual-truncate.js";import{theme as x}from"../../modes/interactive/theme/theme.js";import{waitForChildProcess as be}from"../../utils/child-process.js";import{getShellConfig as Y,getShellEnv as q,killProcessTree as J,trackDetachedChildPid as Ee,untrackDetachedChildPid as $e}from"../../utils/shell.js";import{describeDenialForModel as Oe}from"../sandbox/denial.js";import{getProcessShellSandbox as ye}from"../sandbox/shell-sandbox.js";import{isReadOnlyBashCommand as Te}from"./bash-read-only.js";import{OutputAccumulator as Pe}from"./output-accumulator.js";import{countOutputLines as ge,formatCollapsedSummary as Le,getTextOutput as Q,invalidArgText as Ce,str as Z,truncateDisplay as _e}from"./render-utils.js";import{wrapToolDefinition as ve}from"./tool-definition-wrapper.js";import{DEFAULT_MAX_BYTES as U,DEFAULT_MAX_LINES as Ie,formatSize as A}from"./truncate.js";const ee=2147483647,De=ee/1e3,te=12e4;function Fe(t){if(t===void 0)return te;if(!Number.isFinite(t)||t<=0)throw new Error("Invalid timeout: must be a finite number of seconds");const e=t*1e3;if(e>ee)throw new Error(`Invalid timeout: maximum is ${De} seconds`);return e}d(Fe,"resolveTimeoutMs");const ne=f.Object({command:f.String({description:"Shell command to execute"}),description:f.String({description:`One short line, in the user's language, saying what this command does and why \u2014 shown in place of the command itself. Describe the intent, not the syntax: "Find hardcoded key names", not "run grep with --exclude-dir". 3-10 words.`}),timeout:f.Optional(f.Number({description:"Timeout in seconds. Defaults to 120; raise it for genuinely long-running commands."}))}),Me=f.Optional(f.Object({mode:f.Union([f.Literal("allow"),f.Literal("unsandboxed")],{description:'"allow": run sandboxed with the extra domains / writable paths below. "unsandboxed": run outside the sandbox entirely.'}),justification:f.String({description:"One sentence for the user saying why this access is needed. The user must approve it."}),allow_domains:f.Optional(f.Array(f.String(),{description:"Domains to allow, e.g. registry.npmjs.org"})),allow_write:f.Optional(f.Array(f.String(),{description:"Paths to make writable"}))},{description:"Only after the sandbox blocked this command: ask the user for the access it needs. Never use it pre-emptively."})),ke=f.Object({...ne.properties,sandbox_escalation:Me}),ie={snippet:"Execute bash commands (ls, grep, find, etc.)",guidelines:["You can inspect PI_* environment variables for current model and session details."]};function Ae(t,e){return{exec:d(async(i,s,{onData:c,signal:a,timeout:b,env:l})=>{const p=Fe(b);if(a?.aborted)throw new Error("aborted");const w=e();try{await ce(s,ue.F_OK)}catch{throw new Error(`Working directory does not exist: ${s}
2
+ Cannot execute ${t} commands.`)}const h=w.commandTransport==="stdin",n=we(w.shell,h?w.args:[...w.args,i],{cwd:s,detached:process.platform!=="win32",env:l??q(),stdio:[h?"pipe":"ignore","pipe","pipe"],windowsHide:!0});h&&(n.stdin?.on("error",()=>{}),n.stdin?.end(i)),n.pid&&Ee(n.pid);let m=!1,o;const u=d(()=>{n.pid&&J(n.pid)},"onAbort");try{p!==void 0&&(o=setTimeout(()=>{m=!0,n.pid&&J(n.pid)},p)),n.stdout?.on("data",c),n.stderr?.on("data",c),a&&(a.aborted?u():a.addEventListener("abort",u,{once:!0}));const O=await be(n);if(a?.aborted)throw new Error("aborted");if(m)throw new Error(`timeout:${(p??te)/1e3}`);const P=n.signalCode;return{exitCode:O??(P?128+(me.signals[P]??0):1)}}finally{n.pid&&$e(n.pid),o&&clearTimeout(o),a&&a.removeEventListener("abort",u)}},"exec")}}d(Ae,"createLocalShellOperations");function Ne(t){return Ae("bash",()=>Y(t?.shellPath))}d(Ne,"createLocalBashOperations");const W=new Set;function ht(t){return W.add(t),()=>{W.delete(t)}}d(ht,"registerShellExecutionGuard");async function Be(t){for(const e of W){let i;try{i=await e(t)}catch(s){return`Command refused: the safety check could not run (${s instanceof Error?s.message:String(s)}).`}if(i!==void 0)return i}}d(Be,"shellExecutionRefusal");function Re(t,e,i,s,c){const a={...q()};if(delete a.PI_SESSION_ID,delete a.PI_SESSION_FILE,delete a.PI_PROVIDER,delete a.PI_MODEL,delete a.PI_REASONING_LEVEL,s&&c){const l=c.model;a.PI_SESSION_ID=c.sessionManager.getSessionId();const p=c.sessionManager.getSessionFile();p&&(a.PI_SESSION_FILE=p),l&&(a.PI_PROVIDER=l.provider,a.PI_MODEL=l.id),c.thinkingLevel&&(a.PI_REASONING_LEVEL=c.thinkingLevel)}const b={command:t,cwd:e,env:a};return i?i(b):b}d(Re,"resolveSpawnContext");const Ge=5,je=100;class Ue extends fe{static{d(this,"BashResultRenderComponent")}state={cachedWidth:void 0,cachedLines:void 0,cachedSkipped:void 0}}function oe(t){const e=t/1e3;if(e<60)return`${e.toFixed(1)}s`;const i=Math.floor(e),s=Math.floor(i/60),c=i%60;return s<60?`${s}m ${c}s`:`${Math.floor(s/60)}h ${s%60}m ${c}s`}d(oe,"formatDuration");function We(t,e,i=!1){const s=Z(t?.command),c=Z(t?.description)?.trim(),a=t?.timeout,b=a?x.fg("muted",C($(" (\u8D85\u65F6 {seconds} \u79D2)"),{seconds:a})):"";if(c){const p=x.fg("toolTitle",x.bold(c))+b;return!i||!s?p:`${p}
3
+ ${x.fg("muted",` \u23BF ${e} ${s.trim()}`)}`}const l=s===null?Ce(x):s?x.fg("dim",_e(s.replace(/\s+/g," ").trim(),42)):x.fg("dim","\u2026");return`${x.fg("toolTitle",x.bold(e))} ${l}${b}`}d(We,"formatShellCall");function He(t,e,i,s,c,a,b){const l=t.state;if(t.clear(),!i.expanded&&!b){const n=Q(e,s),m=ge(n),o=[];if(m>0&&o.push(C($("{count} \u884C"),{count:m})),c!==void 0){const P=(a??Date.now())-c;if(i.isPartial||P>=100){const k=i.isPartial?$("\u5DF2\u8FD0\u884C"):$("\u8017\u65F6");o.push(`${k} ${oe(P)}`)}}const u=Le(x,o);u&&t.addChild(new M(u,0,0));return}let p=Q(e,s).trim();const w=e.details?.truncation,h=e.details?.fullOutputPath;if(!i.isPartial&&w?.truncated&&h&&p.endsWith("]")){const n=p.lastIndexOf(`
4
4
 
5
- [`);e!==-1&&a.slice(e).includes(m)&&(a=a.slice(0,e).trimEnd())}if(a){const e=a.split(`
6
- `).map(c=>h.fg("toolOutput",c)).join(`
7
- `);i.expanded?t.addChild(new _(`
8
- ${e}`,0,0)):t.addChild({render:u(c=>{if(s.cachedLines===void 0||s.cachedWidth!==c){const p=ae(e,ye,c);s.cachedLines=p.visualLines,s.cachedSkipped=p.skippedCount,s.cachedWidth=c}if(s.cachedSkipped&&s.cachedSkipped>0){const p=h.fg("muted",C($("... (\u524D\u9762\u8FD8\u6709 {count} \u884C\uFF0C"),{count:s.cachedSkipped}))+` ${se("app.tools.expand",$("\u5373\u53EF\u5C55\u5F00"))}${h.fg("muted",")")}`;return["",oe(p,c,"..."),...s.cachedLines??[]]}return["",...s.cachedLines??[]]},"render"),invalidate:u(()=>{s.cachedWidth=void 0,s.cachedLines=void 0,s.cachedSkipped=void 0},"invalidate")})}if(f?.truncated||m){const e=[];m&&e.push(C($("\u5B8C\u6574\u8F93\u51FA\uFF1A{path}"),{path:m})),f?.truncated&&(f.truncatedBy==="lines"?e.push(C($("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A {shown}/{total} \u884C"),{shown:f.outputLines,total:f.totalLines})):e.push(C($("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A\u4E86 {shown} \u884C\uFF08\u4E0A\u9650 {limit}\uFF09"),{shown:f.outputLines,limit:F(f.maxBytes??R)}))),t.addChild(new _(`
9
- ${h.fg("warning",`[${e.join(". ")}]`)}`,0,0))}if(l!==void 0){const c=(r??Date.now())-l;if(i.isPartial||c>=100){const p=i.isPartial?$("\u5DF2\u8FD0\u884C"):$("\u8017\u65F6");t.addChild(new _(`
10
- ${h.fg("muted",`${p} ${q(c)}`)}`,0,0))}}}u(ve,"rebuildBashResultRenderComponent");function De(t,n,i){const o=i?.operations??ge({shellPath:i?.shellPath}),l=i?.commandPrefix,r=i?.exposeSessionEnvironment??!0,E=i?.spawnHook;return{name:n.name,label:n.label,description:`Execute a ${n.shellName} command in the current working directory. Returns stdout and stderr. Output is truncated to last ${$e} lines or ${R/1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,promptSnippet:n.promptSnippet,promptGuidelines:r&&n.promptGuidelines?[...n.promptGuidelines]:void 0,executionMode:"sequential",executionModeFor:n.readOnlyCommand&&!l?s=>n.readOnlyCommand?.(s?.command)?"parallel":void 0:void 0,parameters:xe,constrainedSampling:{type:"json_schema",strict:"prefer"},async execute(s,{command:a,timeout:f},m,e,c){e&&e({content:[],details:void 0});const p=await Ce({toolName:n.name,command:a,cwd:c?.cwd||t,sessionFile:c?.sessionManager?.getSessionFile()});if(p!==void 0)throw new Error(p);const T=l?`${l}
11
- ${a}`:a,x=Le(T,c?.cwd||t,E,r,c),S=new fe({tempFilePrefix:n.tempFilePrefix});let b=!0,L,M=!1,G=0;const A=u(()=>{if(!e||!M)return;M=!1,G=Date.now();const d=S.snapshot({persistIfTruncated:!0});e({content:[{type:"text",text:d.content||""}],details:{truncation:d.truncation.truncated?d.truncation:void 0,fullOutputPath:d.fullOutputPath}})},"emitOutputUpdate"),k=u(()=>{L&&(clearTimeout(L),L=void 0)},"clearUpdateTimer"),J=u(()=>{if(!e)return;M=!0;const d=_e-(Date.now()-G);if(d<=0){k(),A();return}L??=setTimeout(()=>{L=void 0,A()},d)},"scheduleOutputUpdate"),Q=u(d=>{b&&(S.append(d),J())},"handleData"),W=u(async()=>{b=!1,S.finish(),k(),A();const d=S.snapshot({persistIfTruncated:!0});return await S.closeTempFile(),d},"finishOutput"),H=u((d,y="(no output)")=>{const w=d.truncation;let P=d.content||y,O;if(w.truncated){O={truncation:w,fullOutputPath:d.fullOutputPath};const D=w.totalLines-w.outputLines+1,g=w.totalLines;if(w.lastLinePartial){const N=F(S.getLastLineBytes());P+=`
5
+ [`);n!==-1&&p.slice(n).includes(h)&&(p=p.slice(0,n).trimEnd())}if(p){const n=p.split(`
6
+ `).map(m=>x.fg("toolOutput",m)).join(`
7
+ `);i.expanded?t.addChild(new M(`
8
+ ${n}`,0,0)):t.addChild({render:d(m=>{if(l.cachedLines===void 0||l.cachedWidth!==m){const o=xe(n,Ge,m);l.cachedLines=o.visualLines,l.cachedSkipped=o.skippedCount,l.cachedWidth=m}if(l.cachedSkipped&&l.cachedSkipped>0){const o=x.fg("muted",C($("... (\u524D\u9762\u8FD8\u6709 {count} \u884C\uFF0C"),{count:l.cachedSkipped}))+` ${Se("app.tools.expand",$("\u5373\u53EF\u5C55\u5F00"))}${x.fg("muted",")")}`;return["",he(o,m,"..."),...l.cachedLines??[]]}return["",...l.cachedLines??[]]},"render"),invalidate:d(()=>{l.cachedWidth=void 0,l.cachedLines=void 0,l.cachedSkipped=void 0},"invalidate")})}if(w?.truncated||h){const n=[];h&&n.push(C($("\u5B8C\u6574\u8F93\u51FA\uFF1A{path}"),{path:h})),w?.truncated&&(w.truncatedBy==="lines"?n.push(C($("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A {shown}/{total} \u884C"),{shown:w.outputLines,total:w.totalLines})):n.push(C($("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A\u4E86 {shown} \u884C\uFF08\u4E0A\u9650 {limit}\uFF09"),{shown:w.outputLines,limit:A(w.maxBytes??U)}))),t.addChild(new M(`
9
+ ${x.fg("warning",`[${n.join(". ")}]`)}`,0,0))}if(c!==void 0){const m=(a??Date.now())-c;if(i.isPartial||m>=100){const o=i.isPartial?$("\u5DF2\u8FD0\u884C"):$("\u8017\u65F6");t.addChild(new M(`
10
+ ${x.fg("muted",`${o} ${oe(m)}`)}`,0,0))}}}d(He,"rebuildBashResultRenderComponent");function Ve(t,e,i){const s=i?.operations??e.defaultOperations?.()??Ne({shellPath:i?.shellPath}),c=i?.commandPrefix,a=i?.exposeSessionEnvironment??!0,b=i?.spawnHook,l=i?.sandbox,p=i?.operations===void 0,w=l?.describeForModel();return{name:e.name,label:e.label,description:`Execute a ${e.shellName} command in the current working directory. Returns stdout and stderr. Output is truncated to last ${Ie} lines or ${U/1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.${w?` ${w}`:""}`,promptSnippet:e.promptSnippet,promptGuidelines:a&&e.promptGuidelines?[...e.promptGuidelines]:void 0,executionMode:"sequential",executionModeFor:e.readOnlyCommand&&!c?h=>e.readOnlyCommand?.(h?.command)?"parallel":void 0:void 0,parameters:l?.active?ke:ne,constrainedSampling:{type:"json_schema",strict:"prefer"},async execute(h,n,m,o,u){const{command:O,timeout:P}=n;o&&o({content:[],details:void 0});const k=await Be({toolName:e.name,command:O,cwd:u?.cwd||t,sessionFile:u?.sessionManager?.getSessionFile()});if(k!==void 0)throw new Error(k);const se=c?`${c}
11
+ ${O}`:O,_=Re(se,u?.cwd||t,b,a,u),N=l??(p?ye():void 0);let y;if(N?.active){if(!e.sandboxShell)throw new Error(`Command refused: ${e.shellName} commands cannot run inside the OS sandbox yet, and the sandbox level is "${N.level}". Use the bash tool, or the user can opt out with \`dal --sandbox off\`.`);y=await N.prepare({command:_.command,cwd:_.cwd,shell:e.sandboxShell(i?.shellPath),toolCallId:h,toolName:e.name,escalation:n.sandbox_escalation,ctx:u})}const g=new Pe({tempFilePrefix:e.tempFilePrefix});let H=!0,v,B=!1,V=0;const R=d(()=>{if(!o||!B)return;B=!1,V=Date.now();const r=g.snapshot({persistIfTruncated:!0});o({content:[{type:"text",text:r.content||""}],details:{truncation:r.truncation.truncated?r.truncation:void 0,fullOutputPath:r.fullOutputPath}})},"emitOutputUpdate"),G=d(()=>{v&&(clearTimeout(v),v=void 0)},"clearUpdateTimer"),ae=d(()=>{if(!o)return;B=!0;const r=je-(Date.now()-V);if(r<=0){G(),R();return}v??=setTimeout(()=>{v=void 0,R()},r)},"scheduleOutputUpdate"),re=d(r=>{H&&(g.append(r),ae())},"handleData"),X=d(async()=>{H=!1,g.finish(),G(),R();const r=g.snapshot({persistIfTruncated:!0});return await g.closeTempFile(),r},"finishOutput"),z=d((r,L="(no output)")=>{const S=r.truncation;let T=r.content||L,D;if(S.truncated){D={truncation:S,fullOutputPath:r.fullOutputPath};const F=S.totalLines-S.outputLines+1,E=S.totalLines;if(S.lastLinePartial){const j=A(g.getLastLineBytes());T+=`
12
12
 
13
- [Showing last ${F(w.outputBytes)} of line ${g} (line is ${N}). Full output: ${d.fullOutputPath}]`}else w.truncatedBy==="lines"?P+=`
13
+ [Showing last ${A(S.outputBytes)} of line ${E} (line is ${j}). Full output: ${r.fullOutputPath}]`}else S.truncatedBy==="lines"?T+=`
14
14
 
15
- [Showing lines ${D}-${g} of ${w.totalLines}. Full output: ${d.fullOutputPath}]`:P+=`
15
+ [Showing lines ${F}-${E} of ${S.totalLines}. Full output: ${r.fullOutputPath}]`:T+=`
16
16
 
17
- [Showing lines ${D}-${g} of ${w.totalLines} (${F(R)} limit). Full output: ${d.fullOutputPath}]`}return{text:P,details:O}},"formatOutput"),v=u((d,y)=>`${d?`${d}
17
+ [Showing lines ${F}-${E} of ${S.totalLines} (${A(U)} limit). Full output: ${r.fullOutputPath}]`}return{text:T,details:D}},"formatOutput"),I=d((r,L)=>`${r?`${r}
18
18
 
19
- `:""}${y}`,"appendStatus");try{let d;try{d=(await o.exec(x.command,x.cwd,{onData:Q,signal:m,timeout:f,env:x.env})).exitCode}catch(O){const D=await W(),{text:g}=H(D,"");if(O instanceof Error&&O.message==="aborted")throw new Error(v(g,"Command aborted"));if(O instanceof Error&&O.message.startsWith("timeout:")){const N=O.message.split(":")[1];throw new Error(v(g,`Command timed out after ${N} seconds`))}throw O}const y=await W(),{text:w,details:P}=H(y);if(d===null)throw new Error(v(w,"Command terminated without an exit code"));if(d!==0)throw new Error(v(w,`Command exited with code ${d}`));return{content:[{type:"text",text:w}],details:P}}finally{k()}},renderCall(s,a,f){const m=f.state;f.executionStarted&&m.startedAt===void 0&&(m.startedAt=Date.now(),m.endedAt=void 0);const e=f.lastComponent??new _("",0,0);return e.setText(be(s,n.prompt,f.expanded===!0)),e},renderResult(s,a,f,m){const e=m.state;e.startedAt!==void 0&&a.isPartial&&!e.interval&&(e.interval=setInterval(()=>m.invalidate(),1e3)),(!a.isPartial||m.isError)&&(e.endedAt??=Date.now(),e.interval&&(clearInterval(e.interval),e.interval=void 0));const c=m.lastComponent??new Ie;return ve(c,s,a,m.showImages,e.startedAt,e.endedAt,m.isError),c.invalidate(),c}}}u(De,"createShellToolDefinition");const Fe={name:"bash",label:"bash",shellName:"bash",prompt:"$",promptSnippet:Y.snippet,promptGuidelines:Y.guidelines,tempFilePrefix:"pi-bash",readOnlyCommand:me};function Me(t,n){return De(t,Fe,n)}u(Me,"createBashToolDefinition");function et(t,n){const i=Me(t,n),o=Ee(i);return Object.assign(o,{promptSnippet:i.promptSnippet,promptGuidelines:i.promptGuidelines}),o}u(et,"createBashTool");export{Y as bashToolSystemPromptContribution,et as createBashTool,Me as createBashToolDefinition,ge as createLocalBashOperations,Pe as createLocalShellOperations,De as createShellToolDefinition,Ze as registerShellExecutionGuard};
19
+ `:""}${L}`,"appendStatus");try{let r;try{r=(await s.exec(y?.command??_.command,_.cwd,{onData:re,signal:m,timeout:P,env:_.env})).exitCode}catch(E){const j=await X(),{text:K}=z(j,"");if(await y?.finish(null,""),E instanceof Error&&E.message==="aborted")throw new Error(I(K,"Command aborted"));if(E instanceof Error&&E.message.startsWith("timeout:")){const de=E.message.split(":")[1];throw new Error(I(K,`Command timed out after ${de} seconds`))}throw E}const L=await X(),{text:S,details:T}=z(L),D=await y?.finish(r,L.content||"");if(D&&y)throw new pe(`${I(S,`Command exited with code ${r??"(none)"}`)}
20
+
21
+ ${Oe(D)}`,{...T,sandbox:y.details});if(r===null)throw new Error(I(S,"Command terminated without an exit code"));if(r!==0)throw new Error(I(S,`Command exited with code ${r}`));const F=y?.details.escalation?y.details:void 0;return{content:[{type:"text",text:S}],details:F?{...T,sandbox:F}:T}}finally{G()}},renderCall(h,n,m){const o=m.state;m.executionStarted&&o.startedAt===void 0&&(o.startedAt=Date.now(),o.endedAt=void 0);const u=m.lastComponent??new M("",0,0);return u.setText(We(h,e.prompt,m.expanded===!0)),u},renderResult(h,n,m,o){const u=o.state;u.startedAt!==void 0&&n.isPartial&&!u.interval&&(u.interval=setInterval(()=>o.invalidate(),1e3)),(!n.isPartial||o.isError)&&(u.endedAt??=Date.now(),u.interval&&(clearInterval(u.interval),u.interval=void 0));const O=o.lastComponent??new Ue;return He(O,h,n,o.showImages,u.startedAt,u.endedAt,o.isError),O.invalidate(),O}}}d(Ve,"createShellToolDefinition");const Xe={name:"bash",label:"bash",shellName:"bash",prompt:"$",promptSnippet:ie.snippet,promptGuidelines:ie.guidelines,tempFilePrefix:"pi-bash",readOnlyCommand:Te,sandboxShell:d(t=>Y(t).shell,"sandboxShell")};function ze(t,e){return Ve(t,Xe,e)}d(ze,"createBashToolDefinition");function wt(t,e){const i=ze(t,e),s=ve(i);return Object.assign(s,{promptSnippet:i.promptSnippet,promptGuidelines:i.promptGuidelines}),s}d(wt,"createBashTool");export{ie as bashToolSystemPromptContribution,wt as createBashTool,ze as createBashToolDefinition,Ne as createLocalBashOperations,Ae as createLocalShellOperations,Ve as createShellToolDefinition,ht as registerShellExecutionGuard,Me as sandboxEscalationSchema};
@@ -1,13 +1,13 @@
1
- var Z=Object.defineProperty;var m=(t,n)=>Z(t,"name",{value:n,configurable:!0});import{createInterface as tt}from"node:readline";import{Text as M}from"@earendil-works/pi-tui";import{spawn as et}from"child_process";import z from"path";import{Type as T}from"typebox";import{fill as E,t as b}from"../../dal/i18n.js";import{keyHint as nt}from"../../modes/interactive/components/keybinding-hints.js";import{ensureTool as rt}from"../../utils/tools-manager.js";import{pathExists as q,resolveToCwd as it}from"./path-utils.js";import{countOutputLines as ot,formatCollapsedSummary as st,getTextOutput as K,invalidArgText as at,shortenPath as ct,str as Y}from"./render-utils.js";import{wrapToolDefinition as lt}from"./tool-definition-wrapper.js";import{DEFAULT_MAX_BYTES as C,formatSize as I,truncateHead as J}from"./truncate.js";function Q(t,n,r=z){const d=t.endsWith(r.sep)||r.sep==="\\"&&t.endsWith("/"),a=(r.isAbsolute(t)?r.relative(n,t):t).split(r.sep).join("/");return d&&!a.endsWith("/")?`${a}/`:a}m(Q,"relativizeFindResultPath");const ut=T.Object({pattern:T.String({description:"Glob pattern to match files, e.g. '*.ts', '**/*.json', or 'src/**/*.spec.ts'"}),path:T.Optional(T.String({description:"Directory to search in (default: current directory)"})),limit:T.Optional(T.Number({description:"Maximum number of results (default: 1000)"}))}),dt={snippet:"Find files by glob pattern (respects .gitignore)",guidelines:[]},V=1e3,pt={exists:q,glob:m(()=>[],"glob")};function ft(t,n){const r=Y(t?.pattern),d=Y(t?.path),i=d!==null?ct(d||"."):null,a=t?.limit,o=at(n);let e=n.fg("toolTitle",n.bold("find"))+" "+(r===null?o:n.fg("accent",r||""))+n.fg("toolOutput",E(b(" \u4F4D\u4E8E {path}"),{path:i===null?o:i}));return a!==void 0&&(e+=n.fg("toolOutput",E(b(" (\u4E0A\u9650 {limit})"),{limit:a}))),e}m(ft,"formatFindCall");function mt(t,n,r,d,i){if(!n.expanded&&!i){const p=ot(K(t,d));return st(r,p>0?[E(b("{count} \u884C"),{count:p})]:[])}const a=K(t,d).trim();let o="";if(a){const p=a.split(`
2
- `),w=n.expanded?p.length:20,l=p.slice(0,w),L=p.length-w;o+=`
3
- ${l.map(S=>r.fg("toolOutput",S)).join(`
4
- `)}`,L>0&&(o+=`${r.fg("muted",`
5
- ${E(b("... (\u8FD8\u6709 {count} \u884C\uFF0C"),{count:L})}`)} ${nt("app.tools.expand",b("\u5373\u53EF\u5C55\u5F00"))}${r.fg("muted",")")}`)}const e=t.details?.resultLimitReached,F=t.details?.truncation;if(e||F?.truncated){const p=[];e&&p.push(E(b("\u4E0A\u9650 {count} \u4E2A\u7ED3\u679C"),{count:e})),F?.truncated&&p.push(E(b("\u4E0A\u9650 {size}"),{size:I(F.maxBytes??C)})),o+=`
6
- ${r.fg("warning",E(b("[\u5DF2\u622A\u65AD\uFF1A{reasons}]"),{reasons:p.join(", ")}))}`}return o}m(mt,"formatFindResult");function ht(t,n){const r=n?.operations;return{name:"find",label:"find",description:`Search for files by glob pattern. Returns matching file paths relative to the search directory. Respects .gitignore. Output is truncated to ${V} results or ${C/1024}KB (whichever is hit first).`,promptSnippet:dt.snippet,parameters:ut,async execute(d,{pattern:i,path:a,limit:o},e,F,p){return new Promise((w,l)=>{if(e?.aborted){l(new Error("Operation aborted"));return}let L=!1,S;const c=m(u=>{L||(L=!0,e?.removeEventListener("abort",D),S=void 0,u())},"settle"),D=m(()=>{S?.(),c(()=>l(new Error("Operation aborted")))},"onAbort");e?.addEventListener("abort",D,{once:!0}),(async()=>{try{const u=it(a||".",p?.cwd||t),f=o??V,W=r??pt;if(r?.glob){if(!await W.exists(u)){c(()=>l(new Error(`Path not found: ${u}`)));return}if(e?.aborted){c(()=>l(new Error("Operation aborted")));return}const s=await W.glob(i,u,{ignore:["**/node_modules/**","**/.git/**"],limit:f});if(e?.aborted){c(()=>l(new Error("Operation aborted")));return}if(s.length===0){c(()=>w({content:[{type:"text",text:"No files found matching pattern"}],details:void 0}));return}const g=s.map(y=>Q(y,u)),R=g.length>=f,k=g.join(`
7
- `),A=J(k,{maxLines:Number.MAX_SAFE_INTEGER});let $=A.content;const x={},h=[];R&&(h.push(`${f} results limit reached`),x.resultLimitReached=f),A.truncated&&(h.push(`${I(C)} limit reached`),x.truncation=A),h.length>0&&($+=`
1
+ var tt=Object.defineProperty;var m=(t,r)=>tt(t,"name",{value:r,configurable:!0});import{createInterface as et}from"node:readline";import{Text as q}from"@earendil-works/pi-tui";import{spawn as nt}from"child_process";import z from"path";import{Type as T}from"typebox";import{fill as E,t as b}from"../../dal/i18n.js";import{keyHint as rt}from"../../modes/interactive/components/keybinding-hints.js";import{ensureTool as it}from"../../utils/tools-manager.js";import{readAccessDenial as ot}from"../permissions/tool-policy.js";import{pathExists as K,resolveToCwd as st}from"./path-utils.js";import{countOutputLines as at,formatCollapsedSummary as ct,getTextOutput as Y,invalidArgText as lt,shortenPath as ut,str as J}from"./render-utils.js";import{wrapToolDefinition as dt}from"./tool-definition-wrapper.js";import{DEFAULT_MAX_BYTES as C,formatSize as D,truncateHead as Q}from"./truncate.js";function V(t,r,e=z){const d=t.endsWith(e.sep)||e.sep==="\\"&&t.endsWith("/"),c=(e.isAbsolute(t)?e.relative(r,t):t).split(e.sep).join("/");return d&&!c.endsWith("/")?`${c}/`:c}m(V,"relativizeFindResultPath");const pt=T.Object({pattern:T.String({description:"Glob pattern to match files, e.g. '*.ts', '**/*.json', or 'src/**/*.spec.ts'"}),path:T.Optional(T.String({description:"Directory to search in (default: current directory)"})),limit:T.Optional(T.Number({description:"Maximum number of results (default: 1000)"}))}),ft={snippet:"Find files by glob pattern (respects .gitignore)",guidelines:[]},Z=1e3,mt={exists:K,glob:m(()=>[],"glob")};function ht(t,r){const e=J(t?.pattern),d=J(t?.path),i=d!==null?ut(d||"."):null,c=t?.limit,o=lt(r);let n=r.fg("toolTitle",r.bold("find"))+" "+(e===null?o:r.fg("accent",e||""))+r.fg("toolOutput",E(b(" \u4F4D\u4E8E {path}"),{path:i===null?o:i}));return c!==void 0&&(n+=r.fg("toolOutput",E(b(" (\u4E0A\u9650 {limit})"),{limit:c}))),n}m(ht,"formatFindCall");function gt(t,r,e,d,i){if(!r.expanded&&!i){const p=at(Y(t,d));return ct(e,p>0?[E(b("{count} \u884C"),{count:p})]:[])}const c=Y(t,d).trim();let o="";if(c){const p=c.split(`
2
+ `),w=r.expanded?p.length:20,l=p.slice(0,w),L=p.length-w;o+=`
3
+ ${l.map(S=>e.fg("toolOutput",S)).join(`
4
+ `)}`,L>0&&(o+=`${e.fg("muted",`
5
+ ${E(b("... (\u8FD8\u6709 {count} \u884C\uFF0C"),{count:L})}`)} ${rt("app.tools.expand",b("\u5373\u53EF\u5C55\u5F00"))}${e.fg("muted",")")}`)}const n=t.details?.resultLimitReached,F=t.details?.truncation;if(n||F?.truncated){const p=[];n&&p.push(E(b("\u4E0A\u9650 {count} \u4E2A\u7ED3\u679C"),{count:n})),F?.truncated&&p.push(E(b("\u4E0A\u9650 {size}"),{size:D(F.maxBytes??C)})),o+=`
6
+ ${e.fg("warning",E(b("[\u5DF2\u622A\u65AD\uFF1A{reasons}]"),{reasons:p.join(", ")}))}`}return o}m(gt,"formatFindResult");function bt(t,r){const e=r?.operations;return{name:"find",label:"find",description:`Search for files by glob pattern. Returns matching file paths relative to the search directory. Respects .gitignore. Output is truncated to ${Z} results or ${C/1024}KB (whichever is hit first).`,promptSnippet:ft.snippet,parameters:pt,async execute(d,{pattern:i,path:c,limit:o},n,F,p){return new Promise((w,l)=>{if(n?.aborted){l(new Error("Operation aborted"));return}let L=!1,S;const s=m(u=>{L||(L=!0,n?.removeEventListener("abort",I),S=void 0,u())},"settle"),I=m(()=>{S?.(),s(()=>l(new Error("Operation aborted")))},"onAbort");n?.addEventListener("abort",I,{once:!0}),(async()=>{try{const u=st(c||".",p?.cwd||t),f=o??Z,W=e??mt,G=e?void 0:ot(u);if(G){s(()=>l(new Error(G)));return}if(e?.glob){if(!await W.exists(u)){s(()=>l(new Error(`Path not found: ${u}`)));return}if(n?.aborted){s(()=>l(new Error("Operation aborted")));return}const a=await W.glob(i,u,{ignore:["**/node_modules/**","**/.git/**"],limit:f});if(n?.aborted){s(()=>l(new Error("Operation aborted")));return}if(a.length===0){s(()=>w({content:[{type:"text",text:"No files found matching pattern"}],details:void 0}));return}const g=a.map(y=>V(y,u)),A=g.length>=f,k=g.join(`
7
+ `),R=Q(k,{maxLines:Number.MAX_SAFE_INTEGER});let $=R.content;const x={},h=[];A&&(h.push(`${f} results limit reached`),x.resultLimitReached=f),R.truncated&&(h.push(`${D(C)} limit reached`),x.truncation=R),h.length>0&&($+=`
8
8
 
9
- [${h.join(". ")}]`),c(()=>w({content:[{type:"text",text:$}],details:Object.keys(x).length>0?x:void 0}));return}const G=await rt("fd");if(e?.aborted){c(()=>l(new Error("Operation aborted")));return}if(!G){c(()=>l(new Error("fd is not available and could not be downloaded")));return}const v=["--glob","--color=never","--hidden"];let U=!1;for(let s=u;;){if(await q(z.join(s,".git"))){U=!0;break}const g=z.dirname(s);if(g===s)break;s=g}U||v.push("--no-require-git"),v.push("--max-results",String(f));let _=i;i.includes("/")&&(v.push("--full-path"),!i.startsWith("/")&&!i.startsWith("**/")&&i!=="**"&&(_=`**/${i}`),process.platform==="win32"&&(_=_.replaceAll("/",String.raw`[/\\]`))),v.push("--",_,u);const O=et(G,v,{stdio:["ignore","pipe","pipe"]}),B=tt({input:O.stdout});let X="";const P=[];S=m(()=>{O.killed||O.kill()},"stopChild");const j=m(()=>{B.close()},"cleanup");O.stderr?.on("data",s=>{X+=s.toString()}),B.on("line",s=>{P.push(s)}),O.on("error",s=>{j(),c(()=>l(new Error(`Failed to run fd: ${s.message}`)))}),O.on("close",s=>{if(j(),e?.aborted){c(()=>l(new Error("Operation aborted")));return}const g=P.join(`
10
- `);if(s!==0){const N=X.trim()||`fd exited with code ${s}`;if(!g){c(()=>l(new Error(N)));return}}if(!g){c(()=>w({content:[{type:"text",text:"No files found matching pattern"}],details:void 0}));return}const R=[];for(const N of P){const H=N.replace(/\r$/,"").trim();H&&R.push(Q(H,u))}const k=R.length>=f,A=R.join(`
11
- `),$=J(A,{maxLines:Number.MAX_SAFE_INTEGER});let x=$.content;const h={},y=[];k&&(y.push(`${f} results limit reached. Use limit=${f*2} for more, or refine pattern`),h.resultLimitReached=f),$.truncated&&(y.push(`${I(C)} limit reached`),h.truncation=$),y.length>0&&(x+=`
9
+ [${h.join(". ")}]`),s(()=>w({content:[{type:"text",text:$}],details:Object.keys(x).length>0?x:void 0}));return}const U=await it("fd");if(n?.aborted){s(()=>l(new Error("Operation aborted")));return}if(!U){s(()=>l(new Error("fd is not available and could not be downloaded")));return}const v=["--glob","--color=never","--hidden"];let B=!1;for(let a=u;;){if(await K(z.join(a,".git"))){B=!0;break}const g=z.dirname(a);if(g===a)break;a=g}B||v.push("--no-require-git"),v.push("--max-results",String(f));let _=i;i.includes("/")&&(v.push("--full-path"),!i.startsWith("/")&&!i.startsWith("**/")&&i!=="**"&&(_=`**/${i}`),process.platform==="win32"&&(_=_.replaceAll("/",String.raw`[/\\]`))),v.push("--",_,u);const O=nt(U,v,{stdio:["ignore","pipe","pipe"]}),X=et({input:O.stdout});let H="";const P=[];S=m(()=>{O.killed||O.kill()},"stopChild");const M=m(()=>{X.close()},"cleanup");O.stderr?.on("data",a=>{H+=a.toString()}),X.on("line",a=>{P.push(a)}),O.on("error",a=>{M(),s(()=>l(new Error(`Failed to run fd: ${a.message}`)))}),O.on("close",a=>{if(M(),n?.aborted){s(()=>l(new Error("Operation aborted")));return}const g=P.join(`
10
+ `);if(a!==0){const N=H.trim()||`fd exited with code ${a}`;if(!g){s(()=>l(new Error(N)));return}}if(!g){s(()=>w({content:[{type:"text",text:"No files found matching pattern"}],details:void 0}));return}const A=[];for(const N of P){const j=N.replace(/\r$/,"").trim();j&&A.push(V(j,u))}const k=A.length>=f,R=A.join(`
11
+ `),$=Q(R,{maxLines:Number.MAX_SAFE_INTEGER});let x=$.content;const h={},y=[];k&&(y.push(`${f} results limit reached. Use limit=${f*2} for more, or refine pattern`),h.resultLimitReached=f),$.truncated&&(y.push(`${D(C)} limit reached`),h.truncation=$),y.length>0&&(x+=`
12
12
 
13
- [${y.join(". ")}]`),c(()=>w({content:[{type:"text",text:x}],details:Object.keys(h).length>0?h:void 0}))})}catch(u){if(e?.aborted){c(()=>l(new Error("Operation aborted")));return}const f=u instanceof Error?u:new Error(String(u));c(()=>l(f))}})()})},renderCall(d,i,a){const o=a.lastComponent??new M("",0,0);return o.setText(ft(d,i)),o},renderResult(d,i,a,o){const e=o.lastComponent??new M("",0,0);return e.setText(mt(d,i,a,o.showImages,o.isError)),e}}}m(ht,"createFindToolDefinition");function At(t,n){return lt(ht(t,n))}m(At,"createFindTool");export{At as createFindTool,ht as createFindToolDefinition,dt as findToolSystemPromptContribution,Q as relativizeFindResultPath};
13
+ [${y.join(". ")}]`),s(()=>w({content:[{type:"text",text:x}],details:Object.keys(h).length>0?h:void 0}))})}catch(u){if(n?.aborted){s(()=>l(new Error("Operation aborted")));return}const f=u instanceof Error?u:new Error(String(u));s(()=>l(f))}})()})},renderCall(d,i,c){const o=c.lastComponent??new q("",0,0);return o.setText(ht(d,i)),o},renderResult(d,i,c,o){const n=o.lastComponent??new q("",0,0);return n.setText(gt(d,i,c,o.showImages,o.isError)),n}}}m(bt,"createFindToolDefinition");function Ct(t,r){return dt(bt(t,r))}m(Ct,"createFindTool");export{Ct as createFindTool,bt as createFindToolDefinition,ft as findToolSystemPromptContribution,V as relativizeFindResultPath};