dal-code 1.0.25 → 1.0.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +37 -0
- package/NOTICE +7 -0
- package/dal-docs/README.md +13 -0
- package/dal-docs/settings.md +18 -2
- package/dist/cli/args.d.ts +3 -0
- package/dist/cli/args.js +14 -14
- package/dist/core/agent-session-services.d.ts +2 -0
- package/dist/core/agent-session-services.js +1 -1
- package/dist/core/agent-session.d.ts +27 -1
- package/dist/core/agent-session.js +9 -8
- package/dist/core/background-processes.d.ts +73 -0
- package/dist/core/background-processes.js +7 -0
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/loader.js +1 -1
- package/dist/core/extensions/permission-surface.js +1 -1
- package/dist/core/extensions/runner.js +1 -1
- package/dist/core/extensions/types.d.ts +6 -0
- package/dist/core/host-capabilities.d.ts +50 -0
- package/dist/core/host-capabilities.js +2 -0
- package/dist/core/permissions/rules.d.ts +45 -0
- package/dist/core/permissions/rules.js +1 -0
- package/dist/core/permissions/shell-words.js +2 -0
- package/dist/core/permissions/tool-policy.d.ts +46 -0
- package/dist/core/permissions/tool-policy.js +1 -0
- package/dist/core/sandbox/availability.d.ts +14 -0
- package/dist/core/sandbox/availability.js +1 -0
- package/dist/core/sandbox/denial.d.ts +25 -0
- package/dist/core/sandbox/denial.js +3 -0
- package/dist/core/sandbox/index.d.ts +5 -0
- package/dist/core/sandbox/index.js +1 -0
- package/dist/core/sandbox/policy.d.ts +66 -0
- package/dist/core/sandbox/policy.js +1 -0
- package/dist/core/sandbox/runtime.d.ts +41 -0
- package/dist/core/sandbox/runtime.js +1 -0
- package/dist/core/sandbox/shell-sandbox.d.ts +125 -0
- package/dist/core/sandbox/shell-sandbox.js +5 -0
- package/dist/core/sandbox/windows.d.ts +122 -0
- package/dist/core/sandbox/windows.js +5 -0
- package/dist/core/sdk.d.ts +3 -0
- package/dist/core/sdk.js +1 -1
- package/dist/core/settings-manager.d.ts +20 -0
- package/dist/core/settings-manager.js +1 -1
- package/dist/core/tools/bash.d.ts +16 -1
- package/dist/core/tools/bash.js +16 -14
- package/dist/core/tools/find.js +11 -11
- package/dist/core/tools/grep.js +10 -10
- package/dist/core/tools/index.d.ts +1 -0
- package/dist/core/tools/index.js +1 -1
- package/dist/core/tools/ls.js +6 -6
- package/dist/core/tools/powershell.d.ts +1 -1
- package/dist/core/tools/powershell.js +2 -2
- package/dist/core/tools/process.d.ts +26 -0
- package/dist/core/tools/process.js +22 -0
- package/dist/core/tools/read.js +15 -15
- package/dist/dal/builtins.js +2 -2
- package/dist/dal/child-env.js +1 -1
- package/dist/dal/manifest.d.ts +32 -0
- package/dist/dal/manifest.js +1 -0
- package/dist/index.d.ts +8 -3
- package/dist/index.js +1 -1
- package/dist/main.js +4 -4
- package/dist/modes/index.d.ts +2 -2
- package/dist/modes/print-mode.js +6 -4
- package/dist/modes/rpc/environment-update.js +1 -0
- package/dist/modes/rpc/rpc-client.d.ts +38 -1
- package/dist/modes/rpc/rpc-client.js +4 -1
- package/dist/modes/rpc/rpc-mode.d.ts +1 -0
- package/dist/modes/rpc/rpc-mode.js +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +95 -0
- package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-bridge/src/index.js +1 -1
- package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-interactive/LICENSE +21 -0
- package/dist/node_modules/@dalcode/dal-interactive/package.json +33 -0
- package/dist/node_modules/@dalcode/dal-interactive/src/handoff.js +28 -0
- package/dist/node_modules/@dalcode/dal-interactive/src/index.js +1 -0
- package/dist/node_modules/@dalcode/dal-interactive/src/interactive-shell.js +1 -0
- package/dist/node_modules/@dalcode/dal-interactive/src/questionnaire.js +3 -0
- package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
- package/dist/node_modules/@dalcode/dal-mcp/src/add-wizard.js +1 -1
- package/dist/node_modules/@dalcode/dal-mcp/src/config.d.ts +1 -1
- package/dist/node_modules/@dalcode/dal-mcp/src/config.js +1 -1
- package/dist/node_modules/@dalcode/dal-mcp/src/index.js +18 -18
- package/dist/node_modules/@dalcode/dal-mcp/src/proxy.js +6 -6
- package/dist/node_modules/@dalcode/dal-mcp/src/report.js +1 -1
- package/dist/node_modules/@dalcode/dal-mcp/src/types.d.ts +1 -1
- package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +2 -2
- package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +2 -2
- package/dist/node_modules/@dalcode/dal-plugins/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-review/LICENSE +21 -0
- package/dist/node_modules/@dalcode/dal-review/package.json +34 -0
- package/dist/node_modules/@dalcode/dal-review/src/args.d.ts +13 -0
- package/dist/node_modules/@dalcode/dal-review/src/args.js +1 -0
- package/dist/node_modules/@dalcode/dal-review/src/core.d.ts +6 -0
- package/dist/node_modules/@dalcode/dal-review/src/core.js +1 -0
- package/dist/node_modules/@dalcode/dal-review/src/findings.d.ts +23 -0
- package/dist/node_modules/@dalcode/dal-review/src/findings.js +4 -0
- package/dist/node_modules/@dalcode/dal-review/src/index.js +1 -0
- package/dist/node_modules/@dalcode/dal-review/src/prompt.d.ts +3 -0
- package/dist/node_modules/@dalcode/dal-review/src/prompt.js +29 -0
- package/dist/node_modules/@dalcode/dal-review/src/runner.d.ts +91 -0
- package/dist/node_modules/@dalcode/dal-review/src/runner.js +2 -0
- package/dist/node_modules/@dalcode/dal-review/src/targets.d.ts +33 -0
- package/dist/node_modules/@dalcode/dal-review/src/targets.js +17 -0
- package/dist/node_modules/@dalcode/dal-review/src/types.d.ts +94 -0
- package/dist/node_modules/@dalcode/dal-review/src/types.js +1 -0
- package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-router/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
- package/dist/node_modules/@dalcode/dal-subagent/src/agents.js +2 -2
- package/dist/node_modules/@dalcode/dal-subagent/src/index.js +12 -12
- package/dist/node_modules/@dalcode/dal-subagent/src/process-runner.js +3 -3
- package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-terminal/LICENSE +21 -0
- package/dist/node_modules/@dalcode/dal-terminal/package.json +33 -0
- package/dist/node_modules/@dalcode/dal-terminal/src/contract.d.ts +60 -0
- package/dist/node_modules/@dalcode/dal-terminal/src/contract.js +7 -0
- package/dist/node_modules/@dalcode/dal-terminal/src/index.js +6 -0
- package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-web/src/config.js +2 -2
- package/dist/node_modules/@dalcode/dal-web/src/index.js +4 -4
- package/dist/node_modules/@dalcode/dal-web/src/search.js +4 -4
- package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-workflow/src/index.js +4 -4
- package/dist/node_modules/@dalcode/dal-workflow/src/plan-mode.js +13 -13
- package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
- package/dist/node_modules/@earendil-works/chord/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.d.ts +4 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.js +1 -1
- package/dist/node_modules/@earendil-works/pi-agent-core/package.json +4 -4
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/amazon-bedrock.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/anthropic.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-workers-ai.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/mistral.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/radius.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/together.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-client/package.json +3 -3
- package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-server/package.json +5 -5
- package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/package.json +3 -3
- package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
- package/dist/sdk/index.d.ts +6 -2
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/review.d.ts +1 -0
- package/dist/sdk/review.js +1 -0
- package/dist/sdk/subagents.d.ts +8 -0
- package/dist/sdk/subagents.js +1 -0
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/index.ts +6 -0
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +83 -5
- package/package.json +14 -1
package/dist/core/tools/bash.js
CHANGED
|
@@ -1,19 +1,21 @@
|
|
|
1
|
-
var
|
|
2
|
-
Cannot execute ${t} commands.`)}const
|
|
3
|
-
${
|
|
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
|
-
[`);
|
|
6
|
-
`).map(
|
|
7
|
-
`);i.expanded?t.addChild(new
|
|
8
|
-
${
|
|
9
|
-
${
|
|
10
|
-
${
|
|
11
|
-
${
|
|
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 ${
|
|
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 ${
|
|
15
|
+
[Showing lines ${F}-${E} of ${S.totalLines}. Full output: ${r.fullOutputPath}]`:T+=`
|
|
16
16
|
|
|
17
|
-
[Showing lines ${
|
|
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
|
-
`:""}${
|
|
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};
|
package/dist/core/tools/find.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
var
|
|
2
|
-
`),w=
|
|
3
|
-
${l.map(S=>
|
|
4
|
-
`)}`,L>0&&(o+=`${
|
|
5
|
-
${E(b("... (\u8FD8\u6709 {count} \u884C\uFF0C"),{count:L})}`)} ${
|
|
6
|
-
${
|
|
7
|
-
`),
|
|
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(". ")}]`),
|
|
10
|
-
`);if(
|
|
11
|
-
`),$=
|
|
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(". ")}]`),
|
|
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};
|
package/dist/core/tools/grep.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
var
|
|
2
|
-
`),O=o.expanded?s.length:15,
|
|
3
|
-
${
|
|
4
|
-
`)}`,
|
|
5
|
-
${
|
|
6
|
-
${
|
|
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=[]}
|
|
10
|
-
`).replace(/\r/g,"").replace(/\n$/,""),{text:G,wasTruncated:N}=
|
|
11
|
-
`),
|
|
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(". ")}]`)
|
|
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";
|
package/dist/core/tools/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var b=Object.defineProperty;var
|
|
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};
|
package/dist/core/tools/ls.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var
|
|
2
|
-
`),
|
|
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})}`)} ${
|
|
6
|
-
${o.fg("warning",y(d("[\u5DF2\u622A\u65AD\uFF1A{reasons}]"),{reasons:r.join(", ")}))}`}return t}m(
|
|
7
|
-
`)
|
|
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
|
-
[${
|
|
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
|
|
2
|
-
`,i={snippet:"Execute PowerShell commands",guidelines:["You can inspect PI_* environment variables for current model and session details."]};function
|
|
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};
|
package/dist/core/tools/read.js
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
var
|
|
2
|
-
`),L=
|
|
3
|
-
${
|
|
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:$})}`)} ${
|
|
6
|
-
${i.fg("warning",I(S("[\u9996\u884C\u8D85\u51FA {limit} \u4E0A\u9650]"),{limit:
|
|
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??
|
|
8
|
-
${i.fg("warning",I(S("[\u5DF2\u622A\u65AD\uFF1A\u663E\u793A\u4E86 {shown} \u884C\uFF08\u4E0A\u9650 {limit}\uFF09]"),{shown:o.outputLines,limit:
|
|
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}`),
|
|
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}`),
|
|
14
|
-
`),
|
|
15
|
-
`),
|
|
16
|
-
`);const h=
|
|
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 ${
|
|
18
|
+
[Showing lines ${E}-${p} of ${j}. Use offset=${v} to continue.]`:w+=`
|
|
19
19
|
|
|
20
|
-
[Showing lines ${
|
|
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;
|
|
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};
|
package/dist/dal/builtins.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
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
|
|
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};
|
package/dist/dal/child-env.js
CHANGED
|
@@ -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"],
|
|
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;
|