dal-code 1.0.25 → 1.0.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/NOTICE +7 -0
  3. package/dal-docs/README.md +13 -0
  4. package/dal-docs/settings.md +18 -2
  5. package/dist/cli/args.d.ts +3 -0
  6. package/dist/cli/args.js +14 -14
  7. package/dist/core/agent-session-services.d.ts +2 -0
  8. package/dist/core/agent-session-services.js +1 -1
  9. package/dist/core/agent-session.d.ts +27 -1
  10. package/dist/core/agent-session.js +9 -8
  11. package/dist/core/background-processes.d.ts +73 -0
  12. package/dist/core/background-processes.js +7 -0
  13. package/dist/core/extensions/index.d.ts +1 -1
  14. package/dist/core/extensions/loader.js +1 -1
  15. package/dist/core/extensions/permission-surface.js +1 -1
  16. package/dist/core/extensions/runner.js +1 -1
  17. package/dist/core/extensions/types.d.ts +6 -0
  18. package/dist/core/host-capabilities.d.ts +50 -0
  19. package/dist/core/host-capabilities.js +2 -0
  20. package/dist/core/permissions/rules.d.ts +45 -0
  21. package/dist/core/permissions/rules.js +1 -0
  22. package/dist/core/permissions/shell-words.js +2 -0
  23. package/dist/core/permissions/tool-policy.d.ts +46 -0
  24. package/dist/core/permissions/tool-policy.js +1 -0
  25. package/dist/core/sandbox/availability.d.ts +14 -0
  26. package/dist/core/sandbox/availability.js +1 -0
  27. package/dist/core/sandbox/denial.d.ts +25 -0
  28. package/dist/core/sandbox/denial.js +3 -0
  29. package/dist/core/sandbox/index.d.ts +5 -0
  30. package/dist/core/sandbox/index.js +1 -0
  31. package/dist/core/sandbox/policy.d.ts +66 -0
  32. package/dist/core/sandbox/policy.js +1 -0
  33. package/dist/core/sandbox/runtime.d.ts +41 -0
  34. package/dist/core/sandbox/runtime.js +1 -0
  35. package/dist/core/sandbox/shell-sandbox.d.ts +125 -0
  36. package/dist/core/sandbox/shell-sandbox.js +5 -0
  37. package/dist/core/sandbox/windows.d.ts +122 -0
  38. package/dist/core/sandbox/windows.js +5 -0
  39. package/dist/core/sdk.d.ts +3 -0
  40. package/dist/core/sdk.js +1 -1
  41. package/dist/core/settings-manager.d.ts +20 -0
  42. package/dist/core/settings-manager.js +1 -1
  43. package/dist/core/tools/bash.d.ts +16 -1
  44. package/dist/core/tools/bash.js +16 -14
  45. package/dist/core/tools/find.js +11 -11
  46. package/dist/core/tools/grep.js +10 -10
  47. package/dist/core/tools/index.d.ts +1 -0
  48. package/dist/core/tools/index.js +1 -1
  49. package/dist/core/tools/ls.js +6 -6
  50. package/dist/core/tools/powershell.d.ts +1 -1
  51. package/dist/core/tools/powershell.js +2 -2
  52. package/dist/core/tools/process.d.ts +26 -0
  53. package/dist/core/tools/process.js +22 -0
  54. package/dist/core/tools/read.js +15 -15
  55. package/dist/dal/builtins.js +2 -2
  56. package/dist/dal/child-env.js +1 -1
  57. package/dist/dal/manifest.d.ts +32 -0
  58. package/dist/dal/manifest.js +1 -0
  59. package/dist/index.d.ts +8 -3
  60. package/dist/index.js +1 -1
  61. package/dist/main.js +4 -4
  62. package/dist/modes/index.d.ts +2 -2
  63. package/dist/modes/print-mode.js +6 -4
  64. package/dist/modes/rpc/environment-update.js +1 -0
  65. package/dist/modes/rpc/rpc-client.d.ts +38 -1
  66. package/dist/modes/rpc/rpc-client.js +4 -1
  67. package/dist/modes/rpc/rpc-mode.d.ts +1 -0
  68. package/dist/modes/rpc/rpc-mode.js +1 -1
  69. package/dist/modes/rpc/rpc-types.d.ts +95 -0
  70. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  71. package/dist/node_modules/@dalcode/dal-bridge/src/index.js +1 -1
  72. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  73. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  74. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  75. package/dist/node_modules/@dalcode/dal-interactive/LICENSE +21 -0
  76. package/dist/node_modules/@dalcode/dal-interactive/package.json +33 -0
  77. package/dist/node_modules/@dalcode/dal-interactive/src/handoff.js +28 -0
  78. package/dist/node_modules/@dalcode/dal-interactive/src/index.js +1 -0
  79. package/dist/node_modules/@dalcode/dal-interactive/src/interactive-shell.js +1 -0
  80. package/dist/node_modules/@dalcode/dal-interactive/src/questionnaire.js +3 -0
  81. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  82. package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
  83. package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
  84. package/dist/node_modules/@dalcode/dal-mcp/src/add-wizard.js +1 -1
  85. package/dist/node_modules/@dalcode/dal-mcp/src/config.d.ts +1 -1
  86. package/dist/node_modules/@dalcode/dal-mcp/src/config.js +1 -1
  87. package/dist/node_modules/@dalcode/dal-mcp/src/index.js +18 -18
  88. package/dist/node_modules/@dalcode/dal-mcp/src/proxy.js +6 -6
  89. package/dist/node_modules/@dalcode/dal-mcp/src/report.js +1 -1
  90. package/dist/node_modules/@dalcode/dal-mcp/src/types.d.ts +1 -1
  91. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  92. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +2 -2
  93. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  94. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +2 -2
  95. package/dist/node_modules/@dalcode/dal-plugins/package.json +2 -2
  96. package/dist/node_modules/@dalcode/dal-review/LICENSE +21 -0
  97. package/dist/node_modules/@dalcode/dal-review/package.json +34 -0
  98. package/dist/node_modules/@dalcode/dal-review/src/args.d.ts +13 -0
  99. package/dist/node_modules/@dalcode/dal-review/src/args.js +1 -0
  100. package/dist/node_modules/@dalcode/dal-review/src/core.d.ts +6 -0
  101. package/dist/node_modules/@dalcode/dal-review/src/core.js +1 -0
  102. package/dist/node_modules/@dalcode/dal-review/src/findings.d.ts +23 -0
  103. package/dist/node_modules/@dalcode/dal-review/src/findings.js +4 -0
  104. package/dist/node_modules/@dalcode/dal-review/src/index.js +1 -0
  105. package/dist/node_modules/@dalcode/dal-review/src/prompt.d.ts +3 -0
  106. package/dist/node_modules/@dalcode/dal-review/src/prompt.js +29 -0
  107. package/dist/node_modules/@dalcode/dal-review/src/runner.d.ts +91 -0
  108. package/dist/node_modules/@dalcode/dal-review/src/runner.js +2 -0
  109. package/dist/node_modules/@dalcode/dal-review/src/targets.d.ts +33 -0
  110. package/dist/node_modules/@dalcode/dal-review/src/targets.js +17 -0
  111. package/dist/node_modules/@dalcode/dal-review/src/types.d.ts +94 -0
  112. package/dist/node_modules/@dalcode/dal-review/src/types.js +1 -0
  113. package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
  114. package/dist/node_modules/@dalcode/dal-router/package.json +4 -4
  115. package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
  116. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  117. package/dist/node_modules/@dalcode/dal-subagent/src/agents.js +2 -2
  118. package/dist/node_modules/@dalcode/dal-subagent/src/index.js +12 -12
  119. package/dist/node_modules/@dalcode/dal-subagent/src/process-runner.js +3 -3
  120. package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
  121. package/dist/node_modules/@dalcode/dal-terminal/LICENSE +21 -0
  122. package/dist/node_modules/@dalcode/dal-terminal/package.json +33 -0
  123. package/dist/node_modules/@dalcode/dal-terminal/src/contract.d.ts +60 -0
  124. package/dist/node_modules/@dalcode/dal-terminal/src/contract.js +7 -0
  125. package/dist/node_modules/@dalcode/dal-terminal/src/index.js +6 -0
  126. package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
  127. package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
  128. package/dist/node_modules/@dalcode/dal-web/src/config.js +2 -2
  129. package/dist/node_modules/@dalcode/dal-web/src/index.js +4 -4
  130. package/dist/node_modules/@dalcode/dal-web/src/search.js +4 -4
  131. package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
  132. package/dist/node_modules/@dalcode/dal-workflow/src/index.js +4 -4
  133. package/dist/node_modules/@dalcode/dal-workflow/src/plan-mode.js +13 -13
  134. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  135. package/dist/node_modules/@earendil-works/chord/package.json +1 -1
  136. package/dist/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.d.ts +4 -0
  137. package/dist/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.js +1 -1
  138. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +4 -4
  139. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  140. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/amazon-bedrock.json +1 -1
  141. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/anthropic.json +1 -1
  142. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
  143. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-workers-ai.json +1 -1
  144. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/mistral.json +1 -1
  145. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  146. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  147. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/radius.json +1 -1
  148. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/together.json +1 -1
  149. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  150. package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
  151. package/dist/node_modules/@earendil-works/pi-client/package.json +3 -3
  152. package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
  153. package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
  154. package/dist/node_modules/@earendil-works/pi-server/package.json +5 -5
  155. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/package.json +3 -3
  156. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  157. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  158. package/dist/sdk/index.d.ts +6 -2
  159. package/dist/sdk/index.js +1 -1
  160. package/dist/sdk/review.d.ts +1 -0
  161. package/dist/sdk/review.js +1 -0
  162. package/dist/sdk/subagents.d.ts +8 -0
  163. package/dist/sdk/subagents.js +1 -0
  164. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  165. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  166. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  167. package/examples/extensions/gondolin/package-lock.json +2 -2
  168. package/examples/extensions/gondolin/package.json +1 -1
  169. package/examples/extensions/sandbox/index.ts +6 -0
  170. package/examples/extensions/sandbox/package-lock.json +2 -2
  171. package/examples/extensions/sandbox/package.json +1 -1
  172. package/examples/extensions/with-deps/package-lock.json +2 -2
  173. package/examples/extensions/with-deps/package.json +1 -1
  174. package/npm-shrinkwrap.json +83 -5
  175. package/package.json +14 -1
@@ -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 ve,str as Z,truncateDisplay as Ce}from"./render-utils.js";import{wrapToolDefinition as _e}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?ve(x):s?x.fg("dim",Ce(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,g=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:g.command,cwd:g.cwd,shell:e.sandboxShell(i?.shellPath),shellKind:e.sandboxShellKind??"bash",env:g.env,toolCallId:h,toolName:e.name,escalation:n.sandbox_escalation,ctx:u})}const L=new Pe({tempFilePrefix:e.tempFilePrefix});let H=!0,_,B=!1,V=0;const R=d(()=>{if(!o||!B)return;B=!1,V=Date.now();const r=L.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(()=>{_&&(clearTimeout(_),_=void 0)},"clearUpdateTimer"),ae=d(()=>{if(!o)return;B=!0;const r=je-(Date.now()-V);if(r<=0){G(),R();return}_??=setTimeout(()=>{_=void 0,R()},r)},"scheduleOutputUpdate"),re=d(r=>{H&&(L.append(r),ae())},"handleData"),K=d(async()=>{H=!1,L.finish(),G(),R();const r=L.snapshot({persistIfTruncated:!0});return await L.closeTempFile(),r},"finishOutput"),X=d((r,v="(no output)")=>{const S=r.truncation;let T=r.content||v,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(L.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,v)=>`${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
+ `:""}${v}`,"appendStatus");try{let r;try{r=(await s.exec(y?.command??g.command,g.cwd,{onData:re,signal:m,timeout:P,env:g.env})).exitCode}catch(E){const j=await K(),{text:z}=X(j,"");if(await y?.finish(null,""),E instanceof Error&&E.message==="aborted")throw new Error(I(z,"Command aborted"));if(E instanceof Error&&E.message.startsWith("timeout:")){const de=E.message.split(":")[1];throw new Error(I(z,`Command timed out after ${de} seconds`))}throw E}const v=await K(),{text:S,details:T}=X(v),D=await y?.finish(r,v.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 Ke={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 Xe(t,e){return Ve(t,Ke,e)}d(Xe,"createBashToolDefinition");function wt(t,e){const i=Xe(t,e),s=_e(i);return Object.assign(s,{promptSnippet:i.promptSnippet,promptGuidelines:i.promptGuidelines}),s}d(wt,"createBashTool");export{ie as bashToolSystemPromptContribution,wt as createBashTool,Xe 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};
@@ -1,13 +1,13 @@
1
- var mt=Object.defineProperty;var i=(n,o)=>mt(n,"name",{value:o,configurable:!0});import{readFile as ht,stat as gt}from"node:fs/promises";import{createInterface as xt}from"node:readline";import{Text as ot}from"@earendil-works/pi-tui";import{spawn as Tt}from"child_process";import it from"path";import{Type as a}from"typebox";import{fill as v,t as b}from"../../dal/i18n.js";import{keyHint as $t}from"../../modes/interactive/components/keybinding-hints.js";import{ensureTool as bt}from"../../utils/tools-manager.js";import{resolveToCwd as wt}from"./path-utils.js";import{countOutputLines as yt,formatCollapsedSummary as Lt,getTextOutput as at,invalidArgText as Ot,shortenPath as Et,str as B}from"./render-utils.js";import{wrapToolDefinition as St}from"./tool-definition-wrapper.js";import{DEFAULT_MAX_BYTES as I,formatSize as st,GREP_MAX_LINE_LENGTH as ct,truncateHead as vt,truncateLine as lt}from"./truncate.js";const Ct=a.Object({pattern:a.String({description:"Search pattern (regex or literal string)"}),path:a.Optional(a.String({description:"Directory or file to search (default: current directory)"})),glob:a.Optional(a.String({description:"Filter files by glob pattern, e.g. '*.ts' or '**/*.spec.ts'"})),ignoreCase:a.Optional(a.Boolean({description:"Case-insensitive search (default: false)"})),literal:a.Optional(a.Boolean({description:"Treat pattern as literal string instead of regex (default: false)"})),context:a.Optional(a.Number({description:"Number of lines to show before and after each match (default: 0)"})),limit:a.Optional(a.Number({description:"Maximum number of matches to return (default: 100)"}))}),Mt={snippet:"Search file contents for patterns (respects .gitignore)",guidelines:[]},pt=100,_t={isDirectory:i(async n=>(await gt(n)).isDirectory(),"isDirectory"),readFile:i(n=>ht(n,"utf-8"),"readFile")};function Dt(n,o){const f=B(n?.pattern),d=B(n?.path),m=d!==null?Et(d||"."):null,c=B(n?.glob),r=n?.limit,l=Ot(o);let x=o.fg("toolTitle",o.bold("grep"))+" "+(f===null?l:o.fg("accent",`/${f||""}/`))+o.fg("toolOutput",v(b(" \u4F4D\u4E8E {path}"),{path:m===null?l:m}));return c&&(x+=o.fg("toolOutput",` (${c})`)),r!==void 0&&(x+=o.fg("toolOutput",` limit ${r}`)),x}i(Dt,"formatGrepCall");function Ft(n,o,f,d,m){if(!o.expanded&&!m){const s=yt(at(n,d));return Lt(f,s>0?[v(b("{count} \u884C"),{count:s})]:[])}const c=at(n,d).trim();let r="";if(c){const s=c.split(`
2
- `),O=o.expanded?s.length:15,z=s.slice(0,O),D=s.length-O;r+=`
3
- ${z.map(F=>f.fg("toolOutput",F)).join(`
4
- `)}`,D>0&&(r+=`${f.fg("muted",`
5
- ${v(b("... (\u8FD8\u6709 {count} \u884C\uFF0C"),{count:D})}`)} ${$t("app.tools.expand",b("\u5373\u53EF\u5C55\u5F00"))}${f.fg("muted",")")}`)}const l=n.details?.matchLimitReached,x=n.details?.truncation,L=n.details?.linesTruncated;if(l||x?.truncated||L){const s=[];l&&s.push(v(b("\u4E0A\u9650 {count} \u5904\u5339\u914D"),{count:l})),x?.truncated&&s.push(v(b("\u4E0A\u9650 {size}"),{size:st(x.maxBytes??I)})),L&&s.push(b("\u90E8\u5206\u884C\u88AB\u622A\u65AD")),r+=`
6
- ${f.fg("warning",v(b("[\u5DF2\u622A\u65AD\uFF1A{reasons}]"),{reasons:s.join(", ")}))}`}return r}i(Ft,"formatGrepResult");function Pt(n,o){const f=o?.operations;return{name:"grep",label:"grep",description:`Search file contents for a pattern. Returns matching lines with file paths and line numbers. Respects .gitignore. Output is truncated to ${pt} matches or ${I/1024}KB (whichever is hit first). Long lines are truncated to ${ct} chars.`,promptSnippet:Mt.snippet,parameters:Ct,async execute(d,{pattern:m,path:c,glob:r,ignoreCase:l,literal:x,context:L,limit:s},O,z,D){return new Promise((F,w)=>{if(O?.aborted){w(new Error("Operation aborted"));return}let U=!1;const $=i(E=>{U||(U=!0,E())},"settle");(async()=>{try{const E=await bt("rg");if(!E){$(()=>w(new Error("ripgrep (rg) is not available and could not be downloaded")));return}const P=wt(c||".",D?.cwd||n),H=f??_t;let X;try{X=await H.isDirectory(P)}catch{$(()=>w(new Error(`Path not found: ${P}`)));return}const C=L&&L>0?L:0,M=Math.max(1,s??pt),j=i(e=>{if(X){const t=it.relative(P,e);if(t&&!t.startsWith(".."))return t.replace(/\\/g,"/")}return it.basename(e)},"formatPath"),J=new Map,ut=i(async e=>{let t=J.get(e);if(!t){try{t=(await H.readFile(e)).replace(/\r\n/g,`
1
+ var gt=Object.defineProperty;var i=(n,o)=>gt(n,"name",{value:o,configurable:!0});import{readFile as xt,stat as Tt}from"node:fs/promises";import{createInterface as wt}from"node:readline";import{Text as at}from"@earendil-works/pi-tui";import{spawn as $t}from"child_process";import B from"path";import{Type as a}from"typebox";import{fill as C,t as b}from"../../dal/i18n.js";import{keyHint as bt}from"../../modes/interactive/components/keybinding-hints.js";import{ensureTool as yt}from"../../utils/tools-manager.js";import{readAccessDenial as st}from"../permissions/tool-policy.js";import{resolveToCwd as Lt}from"./path-utils.js";import{countOutputLines as Ot,formatCollapsedSummary as Et,getTextOutput as ct,invalidArgText as St,shortenPath as vt,str as I}from"./render-utils.js";import{wrapToolDefinition as Ct}from"./tool-definition-wrapper.js";import{DEFAULT_MAX_BYTES as z,formatSize as lt,GREP_MAX_LINE_LENGTH as pt,truncateHead as Dt,truncateLine as ut}from"./truncate.js";const Mt=a.Object({pattern:a.String({description:"Search pattern (regex or literal string)"}),path:a.Optional(a.String({description:"Directory or file to search (default: current directory)"})),glob:a.Optional(a.String({description:"Filter files by glob pattern, e.g. '*.ts' or '**/*.spec.ts'"})),ignoreCase:a.Optional(a.Boolean({description:"Case-insensitive search (default: false)"})),literal:a.Optional(a.Boolean({description:"Treat pattern as literal string instead of regex (default: false)"})),context:a.Optional(a.Number({description:"Number of lines to show before and after each match (default: 0)"})),limit:a.Optional(a.Number({description:"Maximum number of matches to return (default: 100)"}))}),_t={snippet:"Search file contents for patterns (respects .gitignore)",guidelines:[]},ft=100,At={isDirectory:i(async n=>(await Tt(n)).isDirectory(),"isDirectory"),readFile:i(n=>xt(n,"utf-8"),"readFile")};function Ft(n,o){const l=I(n?.pattern),d=I(n?.path),m=d!==null?vt(d||"."):null,p=I(n?.glob),r=n?.limit,u=St(o);let x=o.fg("toolTitle",o.bold("grep"))+" "+(l===null?u:o.fg("accent",`/${l||""}/`))+o.fg("toolOutput",C(b(" \u4F4D\u4E8E {path}"),{path:m===null?u:m}));return p&&(x+=o.fg("toolOutput",` (${p})`)),r!==void 0&&(x+=o.fg("toolOutput",` limit ${r}`)),x}i(Ft,"formatGrepCall");function Pt(n,o,l,d,m){if(!o.expanded&&!m){const s=Ot(ct(n,d));return Et(l,s>0?[C(b("{count} \u884C"),{count:s})]:[])}const p=ct(n,d).trim();let r="";if(p){const s=p.split(`
2
+ `),O=o.expanded?s.length:15,U=s.slice(0,O),F=s.length-O;r+=`
3
+ ${U.map(P=>l.fg("toolOutput",P)).join(`
4
+ `)}`,F>0&&(r+=`${l.fg("muted",`
5
+ ${C(b("... (\u8FD8\u6709 {count} \u884C\uFF0C"),{count:F})}`)} ${bt("app.tools.expand",b("\u5373\u53EF\u5C55\u5F00"))}${l.fg("muted",")")}`)}const u=n.details?.matchLimitReached,x=n.details?.truncation,L=n.details?.linesTruncated;if(u||x?.truncated||L){const s=[];u&&s.push(C(b("\u4E0A\u9650 {count} \u5904\u5339\u914D"),{count:u})),x?.truncated&&s.push(C(b("\u4E0A\u9650 {size}"),{size:lt(x.maxBytes??z)})),L&&s.push(b("\u90E8\u5206\u884C\u88AB\u622A\u65AD")),r+=`
6
+ ${l.fg("warning",C(b("[\u5DF2\u622A\u65AD\uFF1A{reasons}]"),{reasons:s.join(", ")}))}`}return r}i(Pt,"formatGrepResult");function Rt(n,o){const l=o?.operations;return{name:"grep",label:"grep",description:`Search file contents for a pattern. Returns matching lines with file paths and line numbers. Respects .gitignore. Output is truncated to ${ft} matches or ${z/1024}KB (whichever is hit first). Long lines are truncated to ${pt} chars.`,promptSnippet:_t.snippet,parameters:Mt,async execute(d,{pattern:m,path:p,glob:r,ignoreCase:u,literal:x,context:L,limit:s},O,U,F){return new Promise((P,$)=>{if(O?.aborted){$(new Error("Operation aborted"));return}let H=!1;const T=i(E=>{H||(H=!0,E())},"settle");(async()=>{try{const E=await yt("rg");if(!E){T(()=>$(new Error("ripgrep (rg) is not available and could not be downloaded")));return}const S=Lt(p||".",F?.cwd||n),X=l??At,J=l?void 0:st(S);if(J){T(()=>$(new Error(J)));return}let K;try{K=await X.isDirectory(S)}catch{T(()=>$(new Error(`Path not found: ${S}`)));return}const D=L&&L>0?L:0,M=Math.max(1,s??ft),V=i(e=>{if(K){const t=B.relative(S,e);if(t&&!t.startsWith(".."))return t.replace(/\\/g,"/")}return B.basename(e)},"formatPath"),W=new Map,dt=i(async e=>{let t=W.get(e);if(!t){try{t=(await X.readFile(e)).replace(/\r\n/g,`
7
7
  `).replace(/\r/g,`
8
8
  `).split(`
9
- `)}catch{t=[]}J.set(e,t)}return t},"getFileLines"),_=["--json","--line-number","--color=never","--hidden"];l&&_.push("--ignore-case"),x&&_.push("--fixed-strings"),r&&_.push("--glob",r),_.push("--",m,P);const S=Tt(E,_,{stdio:["ignore","pipe","pipe"]}),K=xt({input:S.stdout});let V="",R=0,W=!1,A=!1,Y=!1,q=!1;const k=[],Q=i(()=>{K.close(),O?.removeEventListener("abort",tt)},"cleanup"),Z=i((e=!1)=>{S.killed||(q=e,S.kill())},"stopChild"),tt=i(()=>{Y=!0,Z()},"onAbort");O?.addEventListener("abort",tt,{once:!0}),S.stderr?.on("data",e=>{V+=e.toString()});const ft=i(async(e,t)=>{const p=j(e),T=await ut(e);if(!T.length)return[`${p}:${t}: (unable to read file)`];const u=[],y=C>0?Math.max(1,t-C):t,h=C>0?Math.min(T.length,t+C):t;for(let g=y;g<=h;g++){const G=(T[g-1]??"").replace(/\r/g,""),N=g===t,{text:rt,wasTruncated:dt}=lt(G);dt&&(A=!0),N?u.push(`${p}:${g}: ${rt}`):u.push(`${p}-${g}- ${rt}`)}return u},"formatBlock"),et=[];K.on("line",e=>{if(!e.trim()||R>=M)return;let t;try{t=JSON.parse(e)}catch{return}if(t.type==="match"){R++;const p=t.data?.path?.text,T=t.data?.line_number,u=t.data?.lines?.text;p&&typeof T=="number"&&et.push({filePath:p,lineNumber:T,lineText:u}),R>=M&&(W=!0,Z(!0))}}),S.on("error",e=>{Q(),$(()=>w(new Error(`Failed to run ripgrep: ${e.message}`)))}),S.on("close",async e=>{if(Q(),Y){$(()=>w(new Error("Operation aborted")));return}if(!q&&e!==0&&e!==1){const h=V.trim()||`ripgrep exited with code ${e}`;$(()=>w(new Error(h)));return}if(R===0){$(()=>F({content:[{type:"text",text:"No matches found"}],details:void 0}));return}for(const h of et)if(C===0&&h.lineText!==void 0){const g=j(h.filePath),nt=h.lineText.replace(/\r\n/g,`
10
- `).replace(/\r/g,"").replace(/\n$/,""),{text:G,wasTruncated:N}=lt(nt);N&&(A=!0),k.push(`${g}:${h.lineNumber}: ${G}`)}else{const g=await ft(h.filePath,h.lineNumber);k.push(...g)}const t=k.join(`
11
- `),p=vt(t,{maxLines:Number.MAX_SAFE_INTEGER});let T=p.content;const u={},y=[];W&&(y.push(`${M} matches limit reached. Use limit=${M*2} for more, or refine pattern`),u.matchLimitReached=M),p.truncated&&(y.push(`${st(I)} limit reached`),u.truncation=p),A&&(y.push(`Some lines truncated to ${ct} chars. Use read tool to see full lines`),u.linesTruncated=!0),y.length>0&&(T+=`
9
+ `)}catch{t=[]}W.set(e,t)}return t},"getFileLines"),_=["--json","--line-number","--color=never","--hidden"];u&&_.push("--ignore-case"),x&&_.push("--fixed-strings"),r&&_.push("--glob",r),_.push("--",m,S);const v=$t(E,_,{stdio:["ignore","pipe","pipe"]}),Y=wt({input:v.stdout});let j="",A=0,q=!1,R=!1,Q=!1,Z=!1;const k=[],tt=i(()=>{Y.close(),O?.removeEventListener("abort",nt)},"cleanup"),et=i((e=!1)=>{v.killed||(Z=e,v.kill())},"stopChild"),nt=i(()=>{Q=!0,et()},"onAbort");O?.addEventListener("abort",nt,{once:!0}),v.stderr?.on("data",e=>{j+=e.toString()});const mt=i(async(e,t)=>{const c=V(e),w=await dt(e);if(!w.length)return[`${c}:${t}: (unable to read file)`];const f=[],y=D>0?Math.max(1,t-D):t,h=D>0?Math.min(w.length,t+D):t;for(let g=y;g<=h;g++){const G=(w[g-1]??"").replace(/\r/g,""),N=g===t,{text:it,wasTruncated:ht}=ut(G);ht&&(R=!0),N?f.push(`${c}:${g}: ${it}`):f.push(`${c}-${g}- ${it}`)}return f},"formatBlock"),rt=[];Y.on("line",e=>{if(!e.trim()||A>=M)return;let t;try{t=JSON.parse(e)}catch{return}if(t.type==="match"){A++;const c=t.data?.path?.text,w=t.data?.line_number,f=t.data?.lines?.text;if(c&&!l&&st(B.resolve(S,c))){A--;return}c&&typeof w=="number"&&rt.push({filePath:c,lineNumber:w,lineText:f}),A>=M&&(q=!0,et(!0))}}),v.on("error",e=>{tt(),T(()=>$(new Error(`Failed to run ripgrep: ${e.message}`)))}),v.on("close",async e=>{if(tt(),Q){T(()=>$(new Error("Operation aborted")));return}if(!Z&&e!==0&&e!==1){const h=j.trim()||`ripgrep exited with code ${e}`;T(()=>$(new Error(h)));return}if(A===0){T(()=>P({content:[{type:"text",text:"No matches found"}],details:void 0}));return}for(const h of rt)if(D===0&&h.lineText!==void 0){const g=V(h.filePath),ot=h.lineText.replace(/\r\n/g,`
10
+ `).replace(/\r/g,"").replace(/\n$/,""),{text:G,wasTruncated:N}=ut(ot);N&&(R=!0),k.push(`${g}:${h.lineNumber}: ${G}`)}else{const g=await mt(h.filePath,h.lineNumber);k.push(...g)}const t=k.join(`
11
+ `),c=Dt(t,{maxLines:Number.MAX_SAFE_INTEGER});let w=c.content;const f={},y=[];q&&(y.push(`${M} matches limit reached. Use limit=${M*2} for more, or refine pattern`),f.matchLimitReached=M),c.truncated&&(y.push(`${lt(z)} limit reached`),f.truncation=c),R&&(y.push(`Some lines truncated to ${pt} chars. Use read tool to see full lines`),f.linesTruncated=!0),y.length>0&&(w+=`
12
12
 
13
- [${y.join(". ")}]`),$(()=>F({content:[{type:"text",text:T}],details:Object.keys(u).length>0?u:void 0}))})}catch(E){$(()=>w(E))}})()})},renderCall(d,m,c){const r=c.lastComponent??new ot("",0,0);return r.setText(Dt(d,m)),r},renderResult(d,m,c,r){const l=r.lastComponent??new ot("",0,0);return l.setText(Ft(d,m,c,r.showImages,r.isError)),l}}}i(Pt,"createGrepToolDefinition");function Vt(n,o){return St(Pt(n,o))}i(Vt,"createGrepTool");export{Vt as createGrepTool,Pt as createGrepToolDefinition,Mt as grepToolSystemPromptContribution};
13
+ [${y.join(". ")}]`),T(()=>P({content:[{type:"text",text:w}],details:Object.keys(f).length>0?f:void 0}))})}catch(E){T(()=>$(E))}})()})},renderCall(d,m,p){const r=p.lastComponent??new at("",0,0);return r.setText(Ft(d,m)),r},renderResult(d,m,p,r){const u=r.lastComponent??new at("",0,0);return u.setText(Pt(d,m,p,r.showImages,r.isError)),u}}}i(Rt,"createGrepToolDefinition");function qt(n,o){return Ct(Rt(n,o))}i(qt,"createGrepTool");export{qt as createGrepTool,Rt as createGrepToolDefinition,_t as grepToolSystemPromptContribution};
@@ -5,6 +5,7 @@ export { createFindTool, createFindToolDefinition, type FindOperations, type Fin
5
5
  export { createGrepTool, createGrepToolDefinition, type GrepOperations, type GrepToolDetails, type GrepToolInput, type GrepToolOptions, } from "./grep.ts";
6
6
  export { createLsTool, createLsToolDefinition, type LsOperations, type LsToolDetails, type LsToolInput, type LsToolOptions, } from "./ls.ts";
7
7
  export { createLocalPowerShellOperations, createPowerShellTool, createPowerShellToolDefinition, type PowerShellOperations, type PowerShellSpawnContext, type PowerShellSpawnHook, type PowerShellToolDetails, type PowerShellToolInput, type PowerShellToolOptions, } from "./powershell.ts";
8
+ export { createProcessToolDefinition, type ProcessToolDetails, type ProcessToolInput } from "./process.ts";
8
9
  export { createReadTool, createReadToolDefinition, type ReadOperations, type ReadToolDetails, type ReadToolInput, type ReadToolOptions, } from "./read.ts";
9
10
  export { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationOptions, type TruncationResult, truncateHead, truncateLine, truncateTail, } from "./truncate.ts";
10
11
  export { createWriteTool, createWriteToolDefinition, type WriteOperations, type WriteToolInput, type WriteToolOptions, } from "./write.ts";
@@ -1 +1 @@
1
- var b=Object.defineProperty;var a=(r,e)=>b(r,"name",{value:e,configurable:!0});import{createBashTool as H,createBashToolDefinition as I,createLocalBashOperations as Q,registerShellExecutionGuard as Y}from"./bash.js";import{createEditTool as q,createEditToolDefinition as v}from"./edit.js";import{withFileMutationQueue as K}from"./file-mutation-queue.js";import{createFindTool as V,createFindToolDefinition as Z}from"./find.js";import{createGrepTool as ee,createGrepToolDefinition as re}from"./grep.js";import{createLsTool as ae,createLsToolDefinition as oe}from"./ls.js";import{createLocalPowerShellOperations as ie,createPowerShellTool as ne,createPowerShellToolDefinition as fe}from"./powershell.js";import{createReadTool as ue,createReadToolDefinition as he}from"./read.js";import{DEFAULT_MAX_BYTES as se,DEFAULT_MAX_LINES as me,formatSize as De,truncateHead as xe,truncateLine as de,truncateTail as ge}from"./truncate.js";import{createWriteTool as be,createWriteToolDefinition as Ee}from"./write.js";import{createBashTool as i,createBashToolDefinition as n}from"./bash.js";import{createEditTool as f,createEditToolDefinition as T}from"./edit.js";import{createFindTool as u,createFindToolDefinition as h}from"./find.js";import{createGrepTool as c,createGrepToolDefinition as s}from"./grep.js";import{createLsTool as m,createLsToolDefinition as D}from"./ls.js";import{createPowerShellTool as g,createPowerShellToolDefinition as p}from"./powershell.js";import{createReadTool as o,createReadToolDefinition as l}from"./read.js";import{createWriteTool as x,createWriteToolDefinition as d}from"./write.js";const O=new Set(["read","bash","powershell","edit","write","grep","find","ls"]);function U(r,e,t){switch(r){case"read":return l(e,t?.read);case"bash":return n(e,t?.bash);case"powershell":return p(e,t?.powershell);case"edit":return T(e,t?.edit);case"write":return d(e,t?.write);case"grep":return s(e,t?.grep);case"find":return h(e,t?.find);case"ls":return D(e,t?.ls);default:throw new Error(`Unknown tool name: ${r}`)}}a(U,"createToolDefinition");function W(r,e,t){switch(r){case"read":return o(e,t?.read);case"bash":return i(e,t?.bash);case"powershell":return g(e,t?.powershell);case"edit":return f(e,t?.edit);case"write":return x(e,t?.write);case"grep":return c(e,t?.grep);case"find":return u(e,t?.find);case"ls":return m(e,t?.ls);default:throw new Error(`Unknown tool name: ${r}`)}}a(W,"createTool");function _(r,e){return[l(r,e?.read),n(r,e?.bash),T(r,e?.edit),d(r,e?.write)]}a(_,"createCodingToolDefinitions");function M(r,e){return[l(r,e?.read),s(r,e?.grep),h(r,e?.find),D(r,e?.ls)]}a(M,"createReadOnlyToolDefinitions");function k(r,e){return{read:l(r,e?.read),bash:n(r,e?.bash),powershell:p(r,e?.powershell),edit:T(r,e?.edit),write:d(r,e?.write),grep:s(r,e?.grep),find:h(r,e?.find),ls:D(r,e?.ls)}}a(k,"createAllToolDefinitions");function y(r,e){return[o(r,e?.read),i(r,e?.bash),f(r,e?.edit),x(r,e?.write)]}a(y,"createCodingTools");function C(r,e){return[o(r,e?.read),c(r,e?.grep),u(r,e?.find),m(r,e?.ls)]}a(C,"createReadOnlyTools");function X(r,e){return{read:o(r,e?.read),bash:i(r,e?.bash),powershell:g(r,e?.powershell),edit:f(r,e?.edit),write:x(r,e?.write),grep:c(r,e?.grep),find:u(r,e?.find),ls:m(r,e?.ls)}}a(X,"createAllTools");export{se as DEFAULT_MAX_BYTES,me as DEFAULT_MAX_LINES,O as allToolNames,k as createAllToolDefinitions,X as createAllTools,H as createBashTool,I as createBashToolDefinition,_ as createCodingToolDefinitions,y as createCodingTools,q as createEditTool,v as createEditToolDefinition,V as createFindTool,Z as createFindToolDefinition,ee as createGrepTool,re as createGrepToolDefinition,Q as createLocalBashOperations,ie as createLocalPowerShellOperations,ae as createLsTool,oe as createLsToolDefinition,ne as createPowerShellTool,fe as createPowerShellToolDefinition,M as createReadOnlyToolDefinitions,C as createReadOnlyTools,ue as createReadTool,he as createReadToolDefinition,W as createTool,U as createToolDefinition,be as createWriteTool,Ee as createWriteToolDefinition,De as formatSize,Y as registerShellExecutionGuard,xe as truncateHead,de as truncateLine,ge as truncateTail,K as withFileMutationQueue};
1
+ var b=Object.defineProperty;var o=(r,e)=>b(r,"name",{value:e,configurable:!0});import{createBashTool as H,createBashToolDefinition as I,createLocalBashOperations as Q,registerShellExecutionGuard as Y}from"./bash.js";import{createEditTool as q,createEditToolDefinition as v}from"./edit.js";import{withFileMutationQueue as K}from"./file-mutation-queue.js";import{createFindTool as V,createFindToolDefinition as Z}from"./find.js";import{createGrepTool as ee,createGrepToolDefinition as re}from"./grep.js";import{createLsTool as oe,createLsToolDefinition as ae}from"./ls.js";import{createLocalPowerShellOperations as le,createPowerShellTool as ne,createPowerShellToolDefinition as fe}from"./powershell.js";import{createProcessToolDefinition as ue}from"./process.js";import{createReadTool as he,createReadToolDefinition as se}from"./read.js";import{DEFAULT_MAX_BYTES as De,DEFAULT_MAX_LINES as xe,formatSize as de,truncateHead as ge,truncateLine as pe,truncateTail as be}from"./truncate.js";import{createWriteTool as Le,createWriteToolDefinition as Se}from"./write.js";import{createBashTool as l,createBashToolDefinition as n}from"./bash.js";import{createEditTool as f,createEditToolDefinition as T}from"./edit.js";import{createFindTool as u,createFindToolDefinition as c}from"./find.js";import{createGrepTool as h,createGrepToolDefinition as s}from"./grep.js";import{createLsTool as m,createLsToolDefinition as D}from"./ls.js";import{createPowerShellTool as g,createPowerShellToolDefinition as p}from"./powershell.js";import{createReadTool as a,createReadToolDefinition as i}from"./read.js";import{createWriteTool as x,createWriteToolDefinition as d}from"./write.js";const O=new Set(["read","bash","powershell","edit","write","grep","find","ls"]);function U(r,e,t){switch(r){case"read":return i(e,t?.read);case"bash":return n(e,t?.bash);case"powershell":return p(e,t?.powershell);case"edit":return T(e,t?.edit);case"write":return d(e,t?.write);case"grep":return s(e,t?.grep);case"find":return c(e,t?.find);case"ls":return D(e,t?.ls);default:throw new Error(`Unknown tool name: ${r}`)}}o(U,"createToolDefinition");function W(r,e,t){switch(r){case"read":return a(e,t?.read);case"bash":return l(e,t?.bash);case"powershell":return g(e,t?.powershell);case"edit":return f(e,t?.edit);case"write":return x(e,t?.write);case"grep":return h(e,t?.grep);case"find":return u(e,t?.find);case"ls":return m(e,t?.ls);default:throw new Error(`Unknown tool name: ${r}`)}}o(W,"createTool");function _(r,e){return[i(r,e?.read),n(r,e?.bash),T(r,e?.edit),d(r,e?.write)]}o(_,"createCodingToolDefinitions");function M(r,e){return[i(r,e?.read),s(r,e?.grep),c(r,e?.find),D(r,e?.ls)]}o(M,"createReadOnlyToolDefinitions");function k(r,e){return{read:i(r,e?.read),bash:n(r,e?.bash),powershell:p(r,e?.powershell),edit:T(r,e?.edit),write:d(r,e?.write),grep:s(r,e?.grep),find:c(r,e?.find),ls:D(r,e?.ls)}}o(k,"createAllToolDefinitions");function y(r,e){return[a(r,e?.read),l(r,e?.bash),f(r,e?.edit),x(r,e?.write)]}o(y,"createCodingTools");function C(r,e){return[a(r,e?.read),h(r,e?.grep),u(r,e?.find),m(r,e?.ls)]}o(C,"createReadOnlyTools");function X(r,e){return{read:a(r,e?.read),bash:l(r,e?.bash),powershell:g(r,e?.powershell),edit:f(r,e?.edit),write:x(r,e?.write),grep:h(r,e?.grep),find:u(r,e?.find),ls:m(r,e?.ls)}}o(X,"createAllTools");export{De as DEFAULT_MAX_BYTES,xe as DEFAULT_MAX_LINES,O as allToolNames,k as createAllToolDefinitions,X as createAllTools,H as createBashTool,I as createBashToolDefinition,_ as createCodingToolDefinitions,y as createCodingTools,q as createEditTool,v as createEditToolDefinition,V as createFindTool,Z as createFindToolDefinition,ee as createGrepTool,re as createGrepToolDefinition,Q as createLocalBashOperations,le as createLocalPowerShellOperations,oe as createLsTool,ae as createLsToolDefinition,ne as createPowerShellTool,fe as createPowerShellToolDefinition,ue as createProcessToolDefinition,M as createReadOnlyToolDefinitions,C as createReadOnlyTools,he as createReadTool,se as createReadToolDefinition,W as createTool,U as createToolDefinition,Le as createWriteTool,Se as createWriteToolDefinition,de as formatSize,Y as registerShellExecutionGuard,ge as truncateHead,pe as truncateLine,be as truncateTail,K as withFileMutationQueue};
@@ -1,9 +1,9 @@
1
- var I=Object.defineProperty;var m=(e,n)=>I(e,"name",{value:n,configurable:!0});import{readdir as k,stat as F}from"node:fs/promises";import{Text as R}from"@earendil-works/pi-tui";import M from"path";import{Type as L}from"typebox";import{fill as y,t as d}from"../../dal/i18n.js";import{keyHint as N}from"../../modes/interactive/components/keybinding-hints.js";import{pathExists as U,resolveToCwd as z}from"./path-utils.js";import{countOutputLines as B,formatCollapsedSummary as j,getTextOutput as v,renderToolPath as H,str as X}from"./render-utils.js";import{wrapToolDefinition as G}from"./tool-definition-wrapper.js";import{DEFAULT_MAX_BYTES as O,formatSize as P,truncateHead as K}from"./truncate.js";const Y=L.Object({path:L.Optional(L.String({description:"Directory to list (default: current directory)"})),limit:L.Optional(L.Number({description:"Maximum number of entries to return (default: 500)"}))}),q={snippet:"List directory contents",guidelines:[]},_=500,J={exists:U,stat:F,readdir:k};function Q(e,n,o){const a=e?.limit,c=H(X(e?.path),n,o,{emptyFallback:"."});let i=`${n.fg("toolTitle",n.bold("ls"))} ${c}`;return a!==void 0&&(i+=n.fg("toolOutput",y(d(" (\u4E0A\u9650 {limit})"),{limit:a}))),i}m(Q,"formatLsCall");function V(e,n,o,a,c){if(!n.expanded&&!c){const r=B(v(e,a));return j(o,r>0?[y(d("{count} \u884C"),{count:r})]:[])}const i=v(e,a).trim();let t="";if(i){const r=i.split(`
2
- `),u=n.expanded?r.length:20,x=r.slice(0,u),s=r.length-u;t+=`
1
+ var k=Object.defineProperty;var m=(n,e)=>k(n,"name",{value:e,configurable:!0});import{readdir as F,stat as M}from"node:fs/promises";import{Text as v}from"@earendil-works/pi-tui";import N from"path";import{Type as w}from"typebox";import{fill as y,t as d}from"../../dal/i18n.js";import{keyHint as U}from"../../modes/interactive/components/keybinding-hints.js";import{readAccessDenial as z}from"../permissions/tool-policy.js";import{pathExists as B,resolveToCwd as H}from"./path-utils.js";import{countOutputLines as X,formatCollapsedSummary as j,getTextOutput as A,renderToolPath as G,str as K}from"./render-utils.js";import{wrapToolDefinition as Y}from"./tool-definition-wrapper.js";import{DEFAULT_MAX_BYTES as O,formatSize as P,truncateHead as q}from"./truncate.js";const J=w.Object({path:w.Optional(w.String({description:"Directory to list (default: current directory)"})),limit:w.Optional(w.Number({description:"Maximum number of entries to return (default: 500)"}))}),Q={snippet:"List directory contents",guidelines:[]},_=500,V={exists:B,stat:M,readdir:F};function W(n,e,o){const a=n?.limit,u=G(K(n?.path),e,o,{emptyFallback:"."});let i=`${e.fg("toolTitle",e.bold("ls"))} ${u}`;return a!==void 0&&(i+=e.fg("toolOutput",y(d(" (\u4E0A\u9650 {limit})"),{limit:a}))),i}m(W,"formatLsCall");function Z(n,e,o,a,u){if(!e.expanded&&!u){const r=X(A(n,a));return j(o,r>0?[y(d("{count} \u884C"),{count:r})]:[])}const i=A(n,a).trim();let t="";if(i){const r=i.split(`
2
+ `),c=e.expanded?r.length:20,x=r.slice(0,c),s=r.length-c;t+=`
3
3
  ${x.map(p=>o.fg("toolOutput",p)).join(`
4
4
  `)}`,s>0&&(t+=`${o.fg("muted",`
5
- ${y(d("... (\u8FD8\u6709 {count} \u884C\uFF0C"),{count:s})}`)} ${N("app.tools.expand",d("\u5373\u53EF\u5C55\u5F00"))}${o.fg("muted",")")}`)}const l=e.details?.entryLimitReached,h=e.details?.truncation;if(l||h?.truncated){const r=[];l&&r.push(y(d("\u4E0A\u9650 {count} \u4E2A\u6761\u76EE"),{count:l})),h?.truncated&&r.push(y(d("\u4E0A\u9650 {size}"),{size:P(h.maxBytes??O)})),t+=`
6
- ${o.fg("warning",y(d("[\u5DF2\u622A\u65AD\uFF1A{reasons}]"),{reasons:r.join(", ")}))}`}return t}m(V,"formatLsResult");function W(e,n){const o=n?.operations??J;return{name:"ls",label:"ls",description:`List directory contents. Returns entries sorted alphabetically, with '/' suffix for directories. Includes dotfiles. Output is truncated to ${_} entries or ${O/1024}KB (whichever is hit first).`,promptSnippet:q.snippet,parameters:Y,async execute(a,{path:c,limit:i},t,l,h){return new Promise((r,u)=>{if(t?.aborted){u(new Error("Operation aborted"));return}const x=m(()=>u(new Error("Operation aborted")),"onAbort");t?.addEventListener("abort",x,{once:!0}),(async()=>{try{const s=z(c||".",h?.cwd||e),p=i??_;if(!await o.exists(s)){u(new Error(`Path not found: ${s}`));return}if(!(await o.stat(s)).isDirectory()){u(new Error(`Not a directory: ${s}`));return}let $;try{$=await o.readdir(s)}catch(f){u(new Error(`Cannot read directory: ${f.message}`));return}$.sort((f,g)=>f.toLowerCase().localeCompare(g.toLowerCase()));const w=[];let C=!1;for(const f of $){if(w.length>=p){C=!0;break}const g=M.join(s,f);let D="";try{(await o.stat(g)).isDirectory()&&(D="/")}catch{continue}w.push(f+D)}if(t?.removeEventListener("abort",x),w.length===0){r({content:[{type:"text",text:"(empty directory)"}],details:void 0});return}const A=w.join(`
7
- `),E=K(A,{maxLines:Number.MAX_SAFE_INTEGER});let S=E.content;const b={},T=[];C&&(T.push(`${p} entries limit reached. Use limit=${p*2} for more`),b.entryLimitReached=p),E.truncated&&(T.push(`${P(O)} limit reached`),b.truncation=E),T.length>0&&(S+=`
5
+ ${y(d("... (\u8FD8\u6709 {count} \u884C\uFF0C"),{count:s})}`)} ${U("app.tools.expand",d("\u5373\u53EF\u5C55\u5F00"))}${o.fg("muted",")")}`)}const l=n.details?.entryLimitReached,h=n.details?.truncation;if(l||h?.truncated){const r=[];l&&r.push(y(d("\u4E0A\u9650 {count} \u4E2A\u6761\u76EE"),{count:l})),h?.truncated&&r.push(y(d("\u4E0A\u9650 {size}"),{size:P(h.maxBytes??O)})),t+=`
6
+ ${o.fg("warning",y(d("[\u5DF2\u622A\u65AD\uFF1A{reasons}]"),{reasons:r.join(", ")}))}`}return t}m(Z,"formatLsResult");function tt(n,e){const o=e?.operations??V;return{name:"ls",label:"ls",description:`List directory contents. Returns entries sorted alphabetically, with '/' suffix for directories. Includes dotfiles. Output is truncated to ${_} entries or ${O/1024}KB (whichever is hit first).`,promptSnippet:Q.snippet,parameters:J,async execute(a,{path:u,limit:i},t,l,h){return new Promise((r,c)=>{if(t?.aborted){c(new Error("Operation aborted"));return}const x=m(()=>c(new Error("Operation aborted")),"onAbort");t?.addEventListener("abort",x,{once:!0}),(async()=>{try{const s=H(u||".",h?.cwd||n),p=i??_,C=e?.operations?void 0:z(s);if(C){c(new Error(C));return}if(!await o.exists(s)){c(new Error(`Path not found: ${s}`));return}if(!(await o.stat(s)).isDirectory()){c(new Error(`Not a directory: ${s}`));return}let T;try{T=await o.readdir(s)}catch(f){c(new Error(`Cannot read directory: ${f.message}`));return}T.sort((f,g)=>f.toLowerCase().localeCompare(g.toLowerCase()));const L=[];let S=!1;for(const f of T){if(L.length>=p){S=!0;break}const g=N.join(s,f);let R="";try{(await o.stat(g)).isDirectory()&&(R="/")}catch{continue}L.push(f+R)}if(t?.removeEventListener("abort",x),L.length===0){r({content:[{type:"text",text:"(empty directory)"}],details:void 0});return}const I=L.join(`
7
+ `),$=q(I,{maxLines:Number.MAX_SAFE_INTEGER});let D=$.content;const b={},E=[];S&&(E.push(`${p} entries limit reached. Use limit=${p*2} for more`),b.entryLimitReached=p),$.truncated&&(E.push(`${P(O)} limit reached`),b.truncation=$),E.length>0&&(D+=`
8
8
 
9
- [${T.join(". ")}]`),r({content:[{type:"text",text:S}],details:Object.keys(b).length>0?b:void 0})}catch(s){t?.removeEventListener("abort",x),u(s)}})()})},renderCall(a,c,i){const t=i.lastComponent??new R("",0,0);return t.setText(Q(a,c,i.cwd)),t},renderResult(a,c,i,t){const l=t.lastComponent??new R("",0,0);return l.setText(V(a,c,i,t.showImages,t.isError)),l}}}m(W,"createLsToolDefinition");function pt(e,n){return G(W(e,n))}m(pt,"createLsTool");export{pt as createLsTool,W as createLsToolDefinition,q as lsToolSystemPromptContribution};
9
+ [${E.join(". ")}]`),r({content:[{type:"text",text:D}],details:Object.keys(b).length>0?b:void 0})}catch(s){t?.removeEventListener("abort",x),c(s)}})()})},renderCall(a,u,i){const t=i.lastComponent??new v("",0,0);return t.setText(W(a,u,i.cwd)),t},renderResult(a,u,i,t){const l=t.lastComponent??new v("",0,0);return l.setText(Z(a,u,i,t.showImages,t.isError)),l}}}m(tt,"createLsToolDefinition");function yt(n,e){return Y(tt(n,e))}m(yt,"createLsTool");export{yt as createLsTool,tt as createLsToolDefinition,Q as lsToolSystemPromptContribution};
@@ -10,7 +10,7 @@ export type PowerShellSpawnContext = BashSpawnContext;
10
10
  export type PowerShellSpawnHook = BashSpawnHook;
11
11
  export type PowerShellToolDetails = BashToolDetails;
12
12
  export type PowerShellToolInput = BashToolInput;
13
- export interface PowerShellToolOptions extends Pick<BashToolOptions, "operations" | "exposeSessionEnvironment" | "spawnHook"> {
13
+ export interface PowerShellToolOptions extends Pick<BashToolOptions, "operations" | "exposeSessionEnvironment" | "spawnHook" | "sandbox"> {
14
14
  }
15
15
  export declare function createLocalPowerShellOperations(): PowerShellOperations;
16
16
  export declare function createPowerShellToolDefinition(cwd: string, options?: PowerShellToolOptions): ReturnType<typeof createShellToolDefinition>;
@@ -1,2 +1,2 @@
1
- var l=Object.defineProperty;var n=(o,e)=>l(o,"name",{value:e,configurable:!0});import{getPowerShellConfig as p}from"../../utils/shell.js";import{createLocalShellOperations as s,createShellToolDefinition as c}from"./bash.js";import{wrapToolDefinition as a}from"./tool-definition-wrapper.js";const m=`try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}
2
- `,i={snippet:"Execute PowerShell commands",guidelines:["You can inspect PI_* environment variables for current model and session details."]};function u(){const o=s("PowerShell",p);return{exec:n((e,t,r)=>o.exec(`${m}${e}`,t,r),"exec")}}n(u,"createLocalPowerShellOperations");const h={name:"powershell",label:"powershell",shellName:"PowerShell",prompt:"PS>",promptSnippet:i.snippet,promptGuidelines:i.guidelines,tempFilePrefix:"pi-powershell"};function S(o,e){return c(o,h,{...e,operations:e?.operations??u()})}n(S,"createPowerShellToolDefinition");function T(o,e){const t=S(o,e),r=a(t);return Object.assign(r,{promptSnippet:t.promptSnippet,promptGuidelines:t.promptGuidelines}),r}n(T,"createPowerShellTool");export{u as createLocalPowerShellOperations,T as createPowerShellTool,S as createPowerShellToolDefinition,i as powershellToolSystemPromptContribution};
1
+ var p=Object.defineProperty;var t=(e,o)=>p(e,"name",{value:o,configurable:!0});import{getPowerShellConfig as r}from"../../utils/shell.js";import{createLocalShellOperations as s,createShellToolDefinition as c}from"./bash.js";import{wrapToolDefinition as a}from"./tool-definition-wrapper.js";const m=`try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}
2
+ `,i={snippet:"Execute PowerShell commands",guidelines:["You can inspect PI_* environment variables for current model and session details."]};function h(){const e=s("PowerShell",r);return{exec:t((o,n,l)=>e.exec(`${m}${o}`,n,l),"exec")}}t(h,"createLocalPowerShellOperations");const u={name:"powershell",label:"powershell",shellName:"PowerShell",prompt:"PS>",promptSnippet:i.snippet,promptGuidelines:i.guidelines,tempFilePrefix:"pi-powershell",defaultOperations:h,sandboxShell:t(()=>process.platform==="win32"?r().shell:"pwsh","sandboxShell"),sandboxShellKind:"powershell"};function S(e,o){return c(e,u,o)}t(S,"createPowerShellToolDefinition");function x(e,o){const n=S(e,o),l=a(n);return Object.assign(l,{promptSnippet:n.promptSnippet,promptGuidelines:n.promptGuidelines}),l}t(x,"createPowerShellTool");export{h as createLocalPowerShellOperations,x as createPowerShellTool,S as createPowerShellToolDefinition,i as powershellToolSystemPromptContribution};
@@ -0,0 +1,26 @@
1
+ import { type Static, Type } from "typebox";
2
+ import type { BackgroundProcessInfo, BackgroundProcessManager } from "../background-processes.ts";
3
+ import type { ToolDefinition } from "../extensions/types.ts";
4
+ declare const processSchema: Type.TObject<{
5
+ action: Type.TUnion<[
6
+ Type.TLiteral<"start">,
7
+ Type.TLiteral<"output">,
8
+ Type.TLiteral<"status">,
9
+ Type.TLiteral<"stop">,
10
+ Type.TLiteral<"list">
11
+ ]>;
12
+ command: Type.TOptional<Type.TString>;
13
+ name: Type.TOptional<Type.TString>;
14
+ id: Type.TOptional<Type.TString>;
15
+ tail: Type.TOptional<Type.TNumber>;
16
+ wait_seconds: Type.TOptional<Type.TNumber>;
17
+ }>;
18
+ export type ProcessToolInput = Static<typeof processSchema>;
19
+ export interface ProcessToolDetails {
20
+ process?: BackgroundProcessInfo;
21
+ processes?: BackgroundProcessInfo[];
22
+ }
23
+ export declare function createProcessToolDefinition(cwd: string, manager: BackgroundProcessManager, options?: {
24
+ sandboxed?: boolean;
25
+ }): ToolDefinition<typeof processSchema, ProcessToolDetails | undefined>;
26
+ export {};
@@ -0,0 +1,22 @@
1
+ var L=Object.defineProperty;var l=(t,e)=>L(t,"name",{value:e,configurable:!0});import{ToolExecutionError as _}from"@earendil-works/pi-agent-core";import{Text as $}from"@earendil-works/pi-tui";import{Type as n}from"typebox";import{theme as x}from"../../modes/interactive/theme/theme.js";import{describeDenialForModel as g}from"../sandbox/denial.js";import{sandboxEscalationSchema as E}from"./bash.js";import{getTextOutput as U}from"./render-utils.js";import{truncateTail as k}from"./truncate.js";const S=n.Object({action:n.Union([n.Literal("start"),n.Literal("output"),n.Literal("status"),n.Literal("stop"),n.Literal("list")],{description:'"start" a command; read its "output" (new output since the last read, or the last `tail` lines); "status" (running?, exit code, listening ports); "stop" it; "list" all.'}),command:n.Optional(n.String({description:'Shell command to start (action "start")'})),name:n.Optional(n.String({description:'Short label, e.g. "dev server" (action "start")'})),id:n.Optional(n.String({description:'Process id returned by "start" (output / status / stop)'})),tail:n.Optional(n.Number({description:'Return the last N lines instead of new output (action "output")'})),wait_seconds:n.Optional(n.Number({description:'Seconds to wait before reporting, so a starting server can print its URL (start / output; default 2 for "start", max 30)'}))}),P=n.Object({...S.properties,sandbox_escalation:E}),j=400,v=32*1024;function p(t){const e=[`${t.id}${t.name?` (${t.name})`:""}: ${t.state}`];t.pid&&e.push(`pid ${t.pid}`),t.state!=="running"&&t.exitCode!==void 0&&e.push(`exit code ${t.exitCode??"none"}`),t.signal&&e.push(`signal ${t.signal}`),t.ports.length>0&&e.push(`ports ${t.ports.join(", ")}`),t.urls.length>0&&e.push(`urls ${t.urls.join(" ")}`),t.sandboxed&&e.push("sandboxed");const i=[e.join(", "),`command: ${t.command}`,`log: ${t.logFile}`];return t.sandboxed&&!t.portsReachableFromHost&&t.ports.length>0&&i.push("note: on Linux the sandbox gives the process its own network namespace; these ports are not reachable from outside the sandbox."),i.join(`
2
+ `)}l(p,"describe");function y(t,e){return new Promise(i=>{if(t<=0||e?.aborted)return i();const a=setTimeout(i,t);e?.addEventListener("abort",()=>{clearTimeout(a),i()},{once:!0})})}l(y,"sleep");function T(t,e){const i=typeof t=="number"&&Number.isFinite(t)&&t>=0?t:e;return Math.min(i,30)*1e3}l(T,"waitMs");function f(t){if(!t)return"(no new output)";const e=k(t,{maxLines:j,maxBytes:v});return e.truncated?`[showing the last ${e.outputLines} of ${e.totalLines} lines]
3
+ ${e.content}`:e.content}l(f,"limitOutput");function G(t,e,i={}){return{name:"process",label:"process",description:'Run long-lived commands in the background \u2014 dev servers, watchers, anything that does not exit by itself \u2014 and check on them later. "start" returns an id right away; use "output" to read what it printed, "status" to see whether it runs and which ports it listens on, "stop" to end it. Use bash, not this, for commands that finish. Processes are stopped when the session ends.'+(i.sandboxed?" Processes run in the same OS sandbox as bash; they may listen on localhost, but outbound network follows the sandbox rules.":""),promptSnippet:"Start and manage background processes (dev servers, watchers)",promptGuidelines:['Start dev servers and watchers with the process tool (action "start"), not bash: bash waits for the command to finish and kills it at its timeout.'],parameters:i.sandboxed?P:S,async execute(a,s,m,h,d){const r=s.action;if(r==="list"){const o=e.list();return{content:[{type:"text",text:o.length>0?o.map(p).join(`
4
+
5
+ `):"No background processes."}],details:{processes:o}}}if(r==="start"){const o=s.command?.trim();if(!o)throw new Error('action "start" needs a command');const b=await e.start({command:o,cwd:d?.cwd||t,...s.name?{name:s.name}:{},toolCallId:a,escalation:s.sandbox_escalation,ctx:d});await y(T(s.wait_seconds,2),m);const{text:w,info:c}=e.read(b.id);if(c.denial)throw new _(`${p(c)}
6
+
7
+ ${f(w)}
8
+
9
+ ${g(c.denial)}`,{process:c});return{content:[{type:"text",text:`Started.
10
+ ${p(c)}
11
+
12
+ Output so far:
13
+ ${f(w)}`}],details:{process:c}}}const u=s.id?.trim();if(!u)throw new Error(`action "${r}" needs the id returned by "start"`);if(r==="output"){await y(T(s.wait_seconds,0),m);const o=typeof s.tail=="number"&&s.tail>0?Math.floor(s.tail):void 0,{text:b,truncated:w,info:c}=e.read(u,o!==void 0?{tail:o}:{}),O=w?`
14
+ [earlier output is in ${c.logFile}]`:"";return{content:[{type:"text",text:`${p(c)}
15
+
16
+ ${f(b)}${O}`}],details:{process:c}}}if(r==="status"){const o=e.status(u),b=o.denial?`
17
+
18
+ ${g(o.denial)}`:"";return{content:[{type:"text",text:`${p(o)}${b}`}],details:{process:o}}}if(r==="stop"){const o=await e.stop(u);return{content:[{type:"text",text:`Stopped.
19
+ ${p(o)}`}],details:{process:o}}}throw new Error(`Unknown action: ${String(r)}`)},renderCall(a,s,m){const h=m.lastComponent??new $("",0,0),d=a?.action??"\u2026",r=d==="start"?a?.name??a?.command??"":a?.id??"";return h.setText(`${x.fg("toolTitle",x.bold(`process ${d}`))} ${x.fg("dim",String(r))}`),h},renderResult(a,s,m,h){const d=h.lastComponent??new $("",0,0),r=U(a,!1).trim(),u=r.split(`
20
+ `);return d.setText(s.expanded?`
21
+ ${x.fg("toolOutput",r)}`:`
22
+ ${x.fg("toolOutput",u[0]??"")}`),d}}}l(G,"createProcessToolDefinition");export{G as createProcessToolDefinition};
@@ -1,22 +1,22 @@
1
- var q=Object.defineProperty;var r=(e,t)=>q(e,"name",{value:t,configurable:!0});import{basename as j,dirname as W,isAbsolute as Y,relative as J,resolve as G,sep as K}from"node:path";import{Text as H}from"@earendil-works/pi-tui";import{constants as Q}from"fs";import{access as Z,readFile as ee}from"fs/promises";import{Type as T}from"typebox";import{getReadmePath as te}from"../../config.js";import{fill as I,t as S}from"../../dal/i18n.js";import{keyHint as ne}from"../../modes/interactive/components/keybinding-hints.js";import{getLanguageFromPath as ie,highlightCode as oe}from"../../modes/interactive/theme/theme.js";import{processImage as se}from"../../utils/image-process.js";import{detectSupportedImageMimeTypeFromFile as re}from"../../utils/mime.js";import{formatPathRelativeToCwdOrAbsolute as ae}from"../../utils/paths.js";import{resolveReadPathAsync as le,resolveToCwd as fe}from"./path-utils.js";import{getTextOutput as de,renderToolPath as ce,replaceTabs as F,str as N}from"./render-utils.js";import{wrapToolDefinition as me}from"./tool-definition-wrapper.js";import{DEFAULT_MAX_BYTES as y,DEFAULT_MAX_LINES as V,formatSize as O,truncateHead as ue}from"./truncate.js";const pe=T.Object({path:T.String({description:"Path to the file to read (relative or absolute)"}),offset:T.Optional(T.Number({description:"Line number to start reading from (1-indexed)"})),limit:T.Optional(T.Number({description:"Maximum number of lines to read"}))}),X={snippet:"Read file contents",guidelines:["Use read to examine files instead of cat or sed."]},ge=new Set(["AGENTS.override.md","AGENTS.md","AGENTS.MD","CLAUDE.md","CLAUDE.MD"]),he={readFile:r(e=>ee(e),"readFile"),access:r(e=>Z(e,Q.R_OK),"access"),detectImageMimeType:re};function k(e,t){if(e?.offset===void 0&&e?.limit===void 0)return"";const n=e.offset??1,i=e.limit!==void 0?n+e.limit-1:"";return t.fg("warning",`:${n}${i?`-${i}`:""}`)}r(k,"formatReadLineRange");function $e(e,t,n){const i=ce(N(e?.file_path??e?.path),t,n);return`${t.fg("toolTitle",t.bold("read"))} ${i}${k(e,t)}`}r($e,"formatReadCall");function be(e){let t=e.length;for(;t>0&&e[t-1]==="";)t--;return e.slice(0,t)}r(be,"trimTrailingEmptyLines");function Le(e){if(!(!e||e.input.includes("image")))return"[Current model does not support images. The image will be omitted from this request.]"}r(Le,"getNonVisionImageNote");function we(e){return e.split(K).join("/")}r(we,"toPosixPath");function xe(e){const t=W(te()),n=J(G(t),G(e));if(n===""||n===".."||n.startsWith(`..${K}`)||Y(n))return;const i=we(n);if(i==="README.md"||i.startsWith("docs/")||i.startsWith("dal-docs/")||i.startsWith("examples/"))return{kind:"docs",label:i}}r(xe,"getPiDocsClassification");function Te(e,t){const n=N(e?.file_path??e?.path);if(!n)return;const i=fe(n,t),d=j(i);if(d==="SKILL.md")return{kind:"skill",label:j(W(i))||d};const c=xe(i);if(c)return c;if(ge.has(d))return{kind:"resource",label:ae(i,t)}}r(Te,"getCompactReadClassification");function ye(e,t,n){return e.kind==="skill"?n.fg("customMessageLabel","\x1B[1m[skill]\x1B[22m ")+n.fg("customMessageText",e.label)+k(t,n):n.fg("toolTitle",n.bold(`read ${e.kind}`))+" "+n.fg("accent",e.label)+k(t,n)}r(ye,"formatCompactReadCall");function Re(e,t,n,i,d,c,m){if(!n.expanded&&!m)return"";const f=N(e?.file_path??e?.path),a=de(t,d),l=!m&&f?ie(f):void 0,U=l?oe(F(a),l):a.split(`
2
- `),L=be(U),P=n.expanded?L.length:10,R=L.slice(0,P),$=L.length-P;let g=`
3
- ${R.map(x=>l?F(x):i.fg("toolOutput",F(x))).join(`
1
+ var Y=Object.defineProperty;var r=(e,t)=>Y(e,"name",{value:t,configurable:!0});import{basename as W,dirname as G,isAbsolute as J,relative as Q,resolve as K,sep as H}from"node:path";import{Text as V}from"@earendil-works/pi-tui";import{constants as Z}from"fs";import{access as ee,readFile as te}from"fs/promises";import{Type as x}from"typebox";import{getReadmePath as ne}from"../../config.js";import{fill as I,t as S}from"../../dal/i18n.js";import{keyHint as ie}from"../../modes/interactive/components/keybinding-hints.js";import{getLanguageFromPath as oe,highlightCode as se}from"../../modes/interactive/theme/theme.js";import{processImage as re}from"../../utils/image-process.js";import{detectSupportedImageMimeTypeFromFile as ae}from"../../utils/mime.js";import{formatPathRelativeToCwdOrAbsolute as le}from"../../utils/paths.js";import{readAccessDenial as fe}from"../permissions/tool-policy.js";import{resolveReadPathAsync as de,resolveToCwd as ce}from"./path-utils.js";import{getTextOutput as me,renderToolPath as ue,replaceTabs as N,str as k}from"./render-utils.js";import{wrapToolDefinition as pe}from"./tool-definition-wrapper.js";import{DEFAULT_MAX_BYTES as T,DEFAULT_MAX_LINES as X,formatSize as A,truncateHead as ge}from"./truncate.js";const he=x.Object({path:x.String({description:"Path to the file to read (relative or absolute)"}),offset:x.Optional(x.Number({description:"Line number to start reading from (1-indexed)"})),limit:x.Optional(x.Number({description:"Maximum number of lines to read"}))}),q={snippet:"Read file contents",guidelines:["Use read to examine files instead of cat or sed."]},$e=new Set(["AGENTS.override.md","AGENTS.md","AGENTS.MD","CLAUDE.md","CLAUDE.MD"]),be={readFile:r(e=>te(e),"readFile"),access:r(e=>ee(e,Z.R_OK),"access"),detectImageMimeType:ae};function U(e,t){if(e?.offset===void 0&&e?.limit===void 0)return"";const n=e.offset??1,i=e.limit!==void 0?n+e.limit-1:"";return t.fg("warning",`:${n}${i?`-${i}`:""}`)}r(U,"formatReadLineRange");function Le(e,t,n){const i=ue(k(e?.file_path??e?.path),t,n);return`${t.fg("toolTitle",t.bold("read"))} ${i}${U(e,t)}`}r(Le,"formatReadCall");function we(e){let t=e.length;for(;t>0&&e[t-1]==="";)t--;return e.slice(0,t)}r(we,"trimTrailingEmptyLines");function xe(e){if(!(!e||e.input.includes("image")))return"[Current model does not support images. The image will be omitted from this request.]"}r(xe,"getNonVisionImageNote");function Te(e){return e.split(H).join("/")}r(Te,"toPosixPath");function ye(e){const t=G(ne()),n=Q(K(t),K(e));if(n===""||n===".."||n.startsWith(`..${H}`)||J(n))return;const i=Te(n);if(i==="README.md"||i.startsWith("docs/")||i.startsWith("dal-docs/")||i.startsWith("examples/"))return{kind:"docs",label:i}}r(ye,"getPiDocsClassification");function Re(e,t){const n=k(e?.file_path??e?.path);if(!n)return;const i=ce(n,t),d=W(i);if(d==="SKILL.md")return{kind:"skill",label:W(G(i))||d};const c=ye(i);if(c)return c;if($e.has(d))return{kind:"resource",label:le(i,t)}}r(Re,"getCompactReadClassification");function Ee(e,t,n){return e.kind==="skill"?n.fg("customMessageLabel","\x1B[1m[skill]\x1B[22m ")+n.fg("customMessageText",e.label)+U(t,n):n.fg("toolTitle",n.bold(`read ${e.kind}`))+" "+n.fg("accent",e.label)+U(t,n)}r(Ee,"formatCompactReadCall");function Ce(e,t,n,i,d,c,m){if(!n.expanded&&!m)return"";const f=k(e?.file_path??e?.path),a=me(t,d),l=!m&&f?oe(f):void 0,z=l?se(N(a),l):a.split(`
2
+ `),L=we(z),O=n.expanded?L.length:10,y=L.slice(0,O),$=L.length-O;let g=`
3
+ ${y.map(R=>l?N(R):i.fg("toolOutput",N(R))).join(`
4
4
  `)}`;$>0&&(g+=`${i.fg("muted",`
5
- ${I(S("... (\u8FD8\u6709 {count} \u884C\uFF0C"),{count:$})}`)} ${ne("app.tools.expand",S("\u5373\u53EF\u5C55\u5F00"))}${i.fg("muted",")")}`);const o=t.details?.truncation;return o?.truncated&&(o.firstLineExceedsLimit?g+=`
6
- ${i.fg("warning",I(S("[\u9996\u884C\u8D85\u51FA {limit} \u4E0A\u9650]"),{limit:O(o.maxBytes??y)}))}`:o.truncatedBy==="lines"?g+=`
7
- ${i.fg("warning",I(S("[\u5DF2\u622A\u65AD\uFF1A\u663E\u793A {shown}/{total} \u884C\uFF08\u4E0A\u9650 {max} \u884C\uFF09]"),{shown:o.outputLines,total:o.totalLines,max:o.maxLines??V}))}`:g+=`
8
- ${i.fg("warning",I(S("[\u5DF2\u622A\u65AD\uFF1A\u663E\u793A\u4E86 {shown} \u884C\uFF08\u4E0A\u9650 {limit}\uFF09]"),{shown:o.outputLines,limit:O(o.maxBytes??y)}))}`),g}r(Re,"formatReadResult");function Ce(e,t){const n=t?.autoResizeImages??!0,i=t?.resizeOptions,d=t?.operations??he;return{name:"read",label:"read",description:`Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to ${V} lines or ${y/1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.`,promptSnippet:X.snippet,promptGuidelines:[...X.guidelines],parameters:pe,constrainedSampling:{type:"json_schema",strict:"prefer"},async execute(c,{path:m,offset:f,limit:a},l,U,L){return new Promise((P,R)=>{if(l?.aborted){R(new Error("Operation aborted"));return}let $=!1;const g=r(()=>{$=!0,R(new Error("Operation aborted"))},"onAbort");l?.addEventListener("abort",g,{once:!0}),(async()=>{try{const o=await le(m,L?.cwd||e);if($||(await d.access(o),$))return;const x=d.detectImageMimeType?await d.detectImageMimeType(o):void 0;let A,_;const M=Le(L?.model);if(x){const z=await d.readFile(o),b=await se(z,x,{autoResizeImages:n,resizeOptions:L?.model?.inputLimits?.images?.resize??i});if(b.ok){let s=`Read image file [${b.mimeType}]`;b.hints.length>0&&(s+=`
5
+ ${I(S("... (\u8FD8\u6709 {count} \u884C\uFF0C"),{count:$})}`)} ${ie("app.tools.expand",S("\u5373\u53EF\u5C55\u5F00"))}${i.fg("muted",")")}`);const o=t.details?.truncation;return o?.truncated&&(o.firstLineExceedsLimit?g+=`
6
+ ${i.fg("warning",I(S("[\u9996\u884C\u8D85\u51FA {limit} \u4E0A\u9650]"),{limit:A(o.maxBytes??T)}))}`:o.truncatedBy==="lines"?g+=`
7
+ ${i.fg("warning",I(S("[\u5DF2\u622A\u65AD\uFF1A\u663E\u793A {shown}/{total} \u884C\uFF08\u4E0A\u9650 {max} \u884C\uFF09]"),{shown:o.outputLines,total:o.totalLines,max:o.maxLines??X}))}`:g+=`
8
+ ${i.fg("warning",I(S("[\u5DF2\u622A\u65AD\uFF1A\u663E\u793A\u4E86 {shown} \u884C\uFF08\u4E0A\u9650 {limit}\uFF09]"),{shown:o.outputLines,limit:A(o.maxBytes??T)}))}`),g}r(Ce,"formatReadResult");function Se(e,t){const n=t?.autoResizeImages??!0,i=t?.resizeOptions,d=t?.operations??be;return{name:"read",label:"read",description:`Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to ${X} lines or ${T/1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.`,promptSnippet:q.snippet,promptGuidelines:[...q.guidelines],parameters:he,constrainedSampling:{type:"json_schema",strict:"prefer"},async execute(c,{path:m,offset:f,limit:a},l,z,L){return new Promise((O,y)=>{if(l?.aborted){y(new Error("Operation aborted"));return}let $=!1;const g=r(()=>{$=!0,y(new Error("Operation aborted"))},"onAbort");l?.addEventListener("abort",g,{once:!0}),(async()=>{try{const o=await de(m,L?.cwd||e);if($)return;const R=t?.operations?void 0:fe(o);if(R)throw new Error(R);if(await d.access(o),$)return;const _=d.detectImageMimeType?await d.detectImageMimeType(o):void 0;let P,D;const M=xe(L?.model);if(_){const B=await d.readFile(o),b=await re(B,_,{autoResizeImages:n,resizeOptions:L?.model?.inputLimits?.images?.resize??i});if(b.ok){let s=`Read image file [${b.mimeType}]`;b.hints.length>0&&(s+=`
9
9
  ${b.hints.join(`
10
10
  `)}`),M&&(s+=`
11
- ${M}`),A=[{type:"text",text:s},{type:"image",data:b.data,mimeType:b.mimeType}]}else{let s=`Read image file [${x}]
11
+ ${M}`),P=[{type:"text",text:s},{type:"image",data:b.data,mimeType:b.mimeType}]}else{let s=`Read image file [${_}]
12
12
  ${b.message}`;M&&(s+=`
13
- ${M}`),A=[{type:"text",text:s}]}}else{const s=(await d.readFile(o)).toString("utf-8").split(`
14
- `),B=s.length,u=f?Math.max(0,f-1):0,C=u+1;if(u>=s.length)throw new Error(`Offset ${f} is beyond end of file (${s.length} lines total)`);let D,E;if(a!==void 0){const p=Math.min(u+a,s.length);D=s.slice(u,p).join(`
15
- `),E=p-u}else D=s.slice(u).join(`
16
- `);const h=ue(D);let w;if(h.firstLineExceedsLimit){const p=O(Buffer.byteLength(s[u],"utf-8"));w=`[Line ${C} is ${p}, exceeds ${O(y)} limit. Use bash: sed -n '${C}p' ${m} | head -c ${y}]`,_={truncation:h}}else if(h.truncated){const p=C+h.outputLines-1,v=p+1;w=h.content,h.truncatedBy==="lines"?w+=`
13
+ ${M}`),P=[{type:"text",text:s}]}}else{const s=(await d.readFile(o)).toString("utf-8").split(`
14
+ `),j=s.length,u=f?Math.max(0,f-1):0,E=u+1;if(u>=s.length)throw new Error(`Offset ${f} is beyond end of file (${s.length} lines total)`);let F,C;if(a!==void 0){const p=Math.min(u+a,s.length);F=s.slice(u,p).join(`
15
+ `),C=p-u}else F=s.slice(u).join(`
16
+ `);const h=ge(F);let w;if(h.firstLineExceedsLimit){const p=A(Buffer.byteLength(s[u],"utf-8"));w=`[Line ${E} is ${p}, exceeds ${A(T)} limit. Use bash: sed -n '${E}p' ${m} | head -c ${T}]`,D={truncation:h}}else if(h.truncated){const p=E+h.outputLines-1,v=p+1;w=h.content,h.truncatedBy==="lines"?w+=`
17
17
 
18
- [Showing lines ${C}-${p} of ${B}. Use offset=${v} to continue.]`:w+=`
18
+ [Showing lines ${E}-${p} of ${j}. Use offset=${v} to continue.]`:w+=`
19
19
 
20
- [Showing lines ${C}-${p} of ${B} (${O(y)} limit). Use offset=${v} to continue.]`,_={truncation:h}}else if(E!==void 0&&u+E<s.length){const p=s.length-(u+E),v=u+E+1;w=`${h.content}
20
+ [Showing lines ${E}-${p} of ${j} (${A(T)} limit). Use offset=${v} to continue.]`,D={truncation:h}}else if(C!==void 0&&u+C<s.length){const p=s.length-(u+C),v=u+C+1;w=`${h.content}
21
21
 
22
- [${p} more lines in file. Use offset=${v} to continue.]`}else w=h.content;A=[{type:"text",text:w}]}if($)return;l?.removeEventListener("abort",g),P({content:A,details:_})}catch(o){l?.removeEventListener("abort",g),$||R(o)}})()})},renderCall(c,m,f){const a=f.lastComponent??new H("",0,0),l=f.expanded?void 0:Te(c,f.cwd);return a.setText(l?ye(l,c,m):$e(c,m,f.cwd)),a},renderResult(c,m,f,a){const l=a.lastComponent??new H("",0,0);return l.setText(Re(a.args,c,m,f,a.showImages,a.cwd,a.isError)),l}}}r(Ce,"createReadToolDefinition");function We(e,t){return me(Ce(e,t))}r(We,"createReadTool");export{We as createReadTool,Ce as createReadToolDefinition,X as readToolSystemPromptContribution};
22
+ [${p} more lines in file. Use offset=${v} to continue.]`}else w=h.content;P=[{type:"text",text:w}]}if($)return;l?.removeEventListener("abort",g),O({content:P,details:D})}catch(o){l?.removeEventListener("abort",g),$||y(o)}})()})},renderCall(c,m,f){const a=f.lastComponent??new V("",0,0),l=f.expanded?void 0:Re(c,f.cwd);return a.setText(l?Ee(l,c,m):Le(c,m,f.cwd)),a},renderResult(c,m,f,a){const l=a.lastComponent??new V("",0,0);return l.setText(Ce(a.args,c,m,f,a.showImages,a.cwd,a.isError)),l}}}r(Se,"createReadToolDefinition");function He(e,t){return pe(Se(e,t))}r(He,"createReadTool");export{He as createReadTool,Se as createReadToolDefinition,q as readToolSystemPromptContribution};
@@ -1,3 +1,3 @@
1
- var c=Object.defineProperty;var r=(a,e)=>c(a,"name",{value:e,configurable:!0});import{execFileSync as s}from"node:child_process";import{readFileSync as i}from"node:fs";import{createRequire as p}from"node:module";import{dirname as f,join as P}from"node:path";import{setAmbientAuthPolicy as u,setEnvApiKeyPolicy as y}from"@earendil-works/pi-ai";import{houseProvidersEnforced as m,isProviderConfigurable as T}from"../core/house-providers.js";function b(){if(!m())return;const a=r(e=>T(e),"allowed");y(a),u(a)}r(b,"applyDalEnvApiKeyPolicy");const g=["@dalcode/dal-plugins","@dalcode/deepailab","@dalcode/dal-gateway","@dalcode/dal-guard","@dalcode/dal-lsp","@dalcode/dal-subagent","@dalcode/dal-router","@dalcode/dal-mcp","@dalcode/dal-skills","@dalcode/dal-office","@dalcode/dal-web","@dalcode/dal-workflow","@dalcode/dal-tool-catalog","@dalcode/dal-halo","@dalcode/dal-lang","@dalcode/dal-bridge","@dalcode/dal-telemetry","@dalcode/dal-rewind","cc-safety-net"],x=new Set(["@dalcode/dal-guard","cc-safety-net"]);function h(){const a=p(import.meta.url),e=[];for(const o of g)try{const t=a.resolve(`${o}/package.json`),n=JSON.parse(i(t,"utf8"));for(const l of n.pi?.extensions??[])e.push(P(f(t),l))}catch(t){x.has(o)&&process.stderr.write(`dal: \u5B89\u5168\u6269\u5C55 ${o} \u52A0\u8F7D\u5931\u8D25\uFF0C\u5371\u9669\u547D\u4EE4\u7684\u5BA1\u6279\u95E8\u5DF2\u5931\u6548 \u2014 ${t instanceof Error?t.message:String(t)}
1
+ var p=Object.defineProperty;var t=(n,o)=>p(n,"name",{value:o,configurable:!0});import{execFileSync as a}from"node:child_process";import{readFileSync as P}from"node:fs";import{createRequire as l}from"node:module";import{dirname as f,join as u}from"node:path";import{setAmbientAuthPolicy as m,setEnvApiKeyPolicy as T}from"@earendil-works/pi-ai";import{houseProvidersEnforced as y,isProviderConfigurable as d}from"../core/house-providers.js";import{BUNDLED_EXTENSION_PACKAGES as E,SAFETY_CRITICAL_PACKAGES as S}from"./manifest.js";function C(){if(!y())return;const n=t(o=>d(o),"allowed");T(n),m(n)}t(C,"applyDalEnvApiKeyPolicy");import{BUNDLED_EXTENSION_PACKAGES as K,SAFETY_CRITICAL_PACKAGES as b}from"./manifest.js";function x(){const n=l(import.meta.url),o=[];for(const e of E)try{const r=n.resolve(`${e}/package.json`),s=JSON.parse(P(r,"utf8"));for(const c of s.pi?.extensions??[])o.push(u(f(r),c))}catch(r){S.has(e)&&process.stderr.write(`dal: \u5B89\u5168\u6269\u5C55 ${e} \u52A0\u8F7D\u5931\u8D25\uFF0C\u5371\u9669\u547D\u4EE4\u7684\u5BA1\u6279\u95E8\u5DF2\u5931\u6548 \u2014 ${r instanceof Error?r.message:String(r)}
2
2
  \u91CD\u65B0\u5B89\u88C5\u53EF\u6062\u590D\uFF1Anpm i -g dal-code@latest
3
- `)}return e}r(h,"bundledPackageExtensionPaths");function H(){return h()}r(H,"dalBuiltinExtensionPaths");function R(){if(!(process.platform!=="darwin"||["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy","ALL_PROXY","all_proxy"].some(e=>process.env[e])))try{const e=s("scutil",["--proxy"],{encoding:"utf8",timeout:2e3}),o=r(d=>e.match(new RegExp(`${d}\\s*:\\s*(\\S+)`))?.[1],"get"),t=r(d=>o(`${d}Enable`)==="1","enabled"),n=t("HTTPS")?`http://${o("HTTPSProxy")}:${o("HTTPSPort")}`:t("HTTP")?`http://${o("HTTPProxy")}:${o("HTTPPort")}`:void 0;if(!n||n.includes("undefined"))return;process.env.HTTPS_PROXY=n,process.env.HTTP_PROXY=n;const l=new Set((process.env.NO_PROXY??process.env.no_proxy??"").split(",").filter(Boolean));for(const d of["localhost","127.0.0.1","::1"])l.add(d);process.env.NO_PROXY=[...l].join(",")}catch{}}r(R,"applyDalSystemProxyFallback");export{g as BUNDLED_EXTENSION_PACKAGES,b as applyDalEnvApiKeyPolicy,R as applyDalSystemProxyFallback,H as dalBuiltinExtensionPaths};
3
+ `)}return o}t(x,"bundledPackageExtensionPaths");function N(){return x()}t(N,"dalBuiltinExtensionPaths");function X(){if(!(process.platform!=="darwin"||["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy","ALL_PROXY","all_proxy"].some(o=>process.env[o])))try{const o=a("scutil",["--proxy"],{encoding:"utf8",timeout:2e3}),e=t(i=>o.match(new RegExp(`${i}\\s*:\\s*(\\S+)`))?.[1],"get"),r=t(i=>e(`${i}Enable`)==="1","enabled"),s=r("HTTPS")?`http://${e("HTTPSProxy")}:${e("HTTPSPort")}`:r("HTTP")?`http://${e("HTTPProxy")}:${e("HTTPPort")}`:void 0;if(!s||s.includes("undefined"))return;process.env.HTTPS_PROXY=s,process.env.HTTP_PROXY=s;const c=new Set((process.env.NO_PROXY??process.env.no_proxy??"").split(",").filter(Boolean));for(const i of["localhost","127.0.0.1","::1"])c.add(i);process.env.NO_PROXY=[...c].join(",")}catch{}}t(X,"applyDalSystemProxyFallback");export{K as BUNDLED_EXTENSION_PACKAGES,b as SAFETY_CRITICAL_PACKAGES,C as applyDalEnvApiKeyPolicy,X as applyDalSystemProxyFallback,N as dalBuiltinExtensionPaths};
@@ -1 +1 @@
1
- var T=Object.defineProperty;var E=(e,n)=>T(e,"name",{value:n,configurable:!0});const A=["*KEY*","*SECRET*","*TOKEN*","*PASSWORD*","*CREDENTIAL*","AWS_*","AZURE_*","GOOGLE_APPLICATION_CREDENTIALS","GH_*","GITHUB_TOKEN","NPM_TOKEN"],f=["PATH","HOME","USER","LOGNAME","SHELL","TMPDIR","TMP","TEMP","LANG","LC_*","TERM","COLORTERM","NO_COLOR","TZ","XDG_*","SYSTEMROOT","WINDIR","COMSPEC","PATHEXT","USERPROFILE","APPDATA","LOCALAPPDATA"];function i(e){const n=e.map(t=>new RegExp(`^${t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`,"i"));return t=>n.some(r=>r.test(t))}E(i,"patternMatcher");const L=i(A),R=i(f);function u(e){return/^DALCODE_/i.test(e)&&/(TOKEN|SECRET|KEY|PASSWORD|CREDENTIAL)/i.test(e)}E(u,"isDalCodeCredentialName");function C(e){const n={};for(const[t,r]of Object.entries(e))u(t)||(n[t]=r);return n}E(C,"withoutDalCodeCredentials");function S(e,n={}){const t=n.inherit??"all",r=i(n.include??[]),O=i(n.exclude??[]),c={};for(const[o,s]of Object.entries(e))t==="none"||t==="core"&&!R(o)||u(o)||L(o)&&!r(o)||O(o)||(c[o]=s);for(const[o,s]of Object.entries(n.set??{}))u(o)||(c[o]=s);return c}E(S,"applyShellEnvironmentPolicy");let l={};function P(e){l=e??{}}E(P,"configureShellEnvironment");function D(){return l}E(D,"currentShellEnvironmentPolicy");export{A as DEFAULT_SHELL_ENV_EXCLUDES,S as applyShellEnvironmentPolicy,P as configureShellEnvironment,D as currentShellEnvironmentPolicy,u as isDalCodeCredentialName,C as withoutDalCodeCredentials};
1
+ var T=Object.defineProperty;var E=(e,n)=>T(e,"name",{value:n,configurable:!0});const A=["*KEY*","*SECRET*","*TOKEN*","*PASSWORD*","*CREDENTIAL*","AWS_*","AZURE_*","GOOGLE_APPLICATION_CREDENTIALS","GH_*","GITHUB_TOKEN","NPM_TOKEN"],L=["PATH","HOME","USER","LOGNAME","SHELL","TMPDIR","TMP","TEMP","LANG","LC_*","TERM","COLORTERM","NO_COLOR","TZ","XDG_*","SYSTEMROOT","WINDIR","COMSPEC","PATHEXT","USERPROFILE","APPDATA","LOCALAPPDATA"];function i(e){const n=e.map(t=>new RegExp(`^${t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`,"i"));return t=>n.some(r=>r.test(t))}E(i,"patternMatcher");const f=i(A),R=i(L);function u(e){return/^(DALCODE_|DAL_HOST_)/i.test(e)&&/(TOKEN|SECRET|KEY|PASSWORD|CREDENTIAL)/i.test(e)}E(u,"isDalCodeCredentialName");function a(e){const n={};for(const[t,r]of Object.entries(e))u(t)||(n[t]=r);return n}E(a,"withoutDalCodeCredentials");function C(e,n={}){const t=n.inherit??"all",r=i(n.include??[]),O=i(n.exclude??[]),c={};for(const[o,s]of Object.entries(e))t==="none"||t==="core"&&!R(o)||u(o)||f(o)&&!r(o)||O(o)||(c[o]=s);for(const[o,s]of Object.entries(n.set??{}))u(o)||(c[o]=s);return c}E(C,"applyShellEnvironmentPolicy");let l={};function P(e){l=e??{}}E(P,"configureShellEnvironment");function D(){return l}E(D,"currentShellEnvironmentPolicy");export{A as DEFAULT_SHELL_ENV_EXCLUDES,C as applyShellEnvironmentPolicy,P as configureShellEnvironment,D as currentShellEnvironmentPolicy,u as isDalCodeCredentialName,a as withoutDalCodeCredentials};
@@ -0,0 +1,32 @@
1
+ export type ManifestLanguage = "zh" | "en";
2
+ export type BundledExtensionActivation = "always" | "dal-code" | "host-capability" | "halo-app" | "tui";
3
+ export declare const BUNDLED_EXTENSION_PACKAGES: readonly string[];
4
+ export declare const SAFETY_CRITICAL_PACKAGES: ReadonlySet<string>;
5
+ export interface BundledExtensionInfo {
6
+ name: string;
7
+ label: string;
8
+ description: string;
9
+ enabledByDefault: true;
10
+ canDisable: false;
11
+ safetyCritical: boolean;
12
+ activation: BundledExtensionActivation;
13
+ installed: boolean;
14
+ version: string;
15
+ extensions: string[];
16
+ }
17
+ export declare function listBundledExtensions(language?: ManifestLanguage): BundledExtensionInfo[];
18
+ export type ToolAvailability = "default" | "opt-in" | "on-demand" | "dal-code" | "host" | "reviewer" | "mcp" | "tui";
19
+ export declare const DAL_TOOL_NAMES: {
20
+ readonly builtin: readonly string[];
21
+ readonly extensions: Readonly<Record<string, readonly string[]>>;
22
+ };
23
+ export interface ToolCatalogEntry {
24
+ name: string;
25
+ label: string;
26
+ summary: string;
27
+ source: string;
28
+ readOnly: boolean;
29
+ availability: ToolAvailability;
30
+ }
31
+ export declare function listToolCatalog(language?: ManifestLanguage): ToolCatalogEntry[];
32
+ export declare function toolDisplayLabel(name: string, language?: ManifestLanguage): string;