dal-code 1.0.18 → 1.0.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/NOTICE +13 -3
- package/dist/cli/args.js +21 -182
- package/dist/cli/auth-check.js +1 -1
- package/dist/cli/auth-command.js +5 -5
- package/dist/cli/credential-print.js +1 -1
- package/dist/cli/file-processor.js +5 -5
- package/dist/cli/list-models.js +2 -2
- package/dist/cli/project-trust.js +2 -2
- package/dist/core/event-bus.js +1 -1
- package/dist/core/keybindings.js +1 -1
- package/dist/core/model-resolver.js +1 -1
- package/dist/core/resource-loader.js +1 -1
- package/dist/core/slash-commands.js +1 -1
- package/dist/core/tools/bash.js +13 -13
- package/dist/core/tools/find.js +11 -11
- package/dist/core/tools/grep.js +10 -10
- package/dist/core/tools/ls.js +7 -7
- package/dist/core/tools/read.js +17 -17
- package/dist/core/tools/render-utils.js +6 -6
- package/dist/core/tools/renderers/bash.js +8 -8
- package/dist/core/tools/renderers/find.js +6 -6
- package/dist/core/tools/renderers/grep.js +6 -6
- package/dist/core/tools/renderers/ls.js +6 -6
- package/dist/core/tools/renderers/read.js +8 -8
- package/dist/core/tools/renderers/write.js +10 -10
- package/dist/core/tools/write.js +11 -11
- package/dist/dal/builtins.js +1 -1
- package/dist/dal/i18n.js +1 -1
- package/dist/extensions/llama/client.js +4 -4
- package/dist/extensions/llama/index.js +6 -6
- package/dist/extensions/llama/provider.js +1 -1
- package/dist/extensions/llama/ui.js +3 -3
- package/dist/main.js +4 -4
- package/dist/migrations.js +5 -5
- package/dist/modes/interactive/bug-report.js +4 -7
- package/dist/modes/interactive/components/assistant-message.js +2 -2
- package/dist/modes/interactive/components/bash-execution.js +6 -6
- package/dist/modes/interactive/components/bordered-loader.js +1 -1
- package/dist/modes/interactive/components/branch-summary-message.js +2 -2
- package/dist/modes/interactive/components/compaction-summary-message.js +2 -2
- package/dist/modes/interactive/components/config-selector.js +1 -1
- package/dist/modes/interactive/components/custom-entry.js +1 -1
- package/dist/modes/interactive/components/extension-editor.js +1 -1
- package/dist/modes/interactive/components/extension-input.js +2 -2
- package/dist/modes/interactive/components/extension-selector.js +2 -2
- package/dist/modes/interactive/components/first-time-setup.js +4 -6
- package/dist/modes/interactive/components/login-dialog.js +1 -1
- package/dist/modes/interactive/components/model-selector.js +2 -2
- package/dist/modes/interactive/components/oauth-selector.js +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.js +1 -1
- package/dist/modes/interactive/components/session-selector.js +2 -2
- package/dist/modes/interactive/components/settings-selector.js +1 -1
- package/dist/modes/interactive/components/settings-submenu.js +1 -1
- package/dist/modes/interactive/components/show-images-selector.js +1 -1
- package/dist/modes/interactive/components/skill-invocation-message.js +2 -2
- package/dist/modes/interactive/components/status-indicator.js +1 -1
- package/dist/modes/interactive/components/theme-selector.js +1 -1
- package/dist/modes/interactive/components/thinking-selector.js +1 -1
- package/dist/modes/interactive/components/tool-execution.js +4 -4
- package/dist/modes/interactive/components/tree-selector.js +1 -1
- package/dist/modes/interactive/components/trust-selector.js +2 -2
- package/dist/modes/interactive/components/user-message-selector.js +1 -1
- package/dist/modes/interactive/external-editor.js +3 -3
- package/dist/modes/interactive/interactive-mode.js +58 -105
- package/dist/modes/interactive/session-share.js +2 -2
- package/dist/modes/interactive/theme/theme-controller.js +2 -2
- package/dist/modes/print-mode.js +4 -4
- package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
- 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-guard/src/index.js +1 -1
- package/dist/node_modules/@dalcode/dal-guard/src/review.js +3 -0
- package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
- 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-office/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-office/src/extract/pdf.js +4 -4
- package/dist/node_modules/@dalcode/dal-office/src/index.js +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +15 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +15 -1
- package/dist/node_modules/@dalcode/dal-plugins/package.json +3 -2
- package/dist/node_modules/@dalcode/dal-plugins/src/index.js +8 -8
- package/dist/node_modules/@dalcode/dal-plugins/src/rank.js +4 -0
- package/dist/node_modules/@dalcode/dal-rewind/LICENSE +21 -0
- package/dist/node_modules/@dalcode/dal-rewind/package.json +34 -0
- package/dist/node_modules/@dalcode/dal-rewind/src/commands.js +3 -0
- package/dist/node_modules/@dalcode/dal-rewind/src/core.js +4 -0
- package/dist/node_modules/@dalcode/dal-rewind/src/index.js +1 -0
- package/dist/node_modules/@dalcode/dal-rewind/src/state.js +1 -0
- package/dist/node_modules/@dalcode/dal-rewind/src/ui.js +1 -0
- package/dist/node_modules/@dalcode/dal-router/package.json +6 -4
- package/dist/node_modules/@dalcode/dal-router/src/compact-defer.js +3 -0
- package/dist/node_modules/@dalcode/dal-router/src/config.js +2 -2
- package/dist/node_modules/@dalcode/dal-router/src/index.js +4 -3
- package/dist/node_modules/@dalcode/dal-router/src/services.js +1 -0
- 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/index.js +8 -7
- package/dist/node_modules/@dalcode/dal-subagent/src/role-pick.js +2 -0
- package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-web/package.json +3 -2
- 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/providers.js +1 -1
- package/dist/node_modules/@dalcode/dal-web/src/search.js +5 -7
- package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
- package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
- package/dist/node_modules/@dalcode/deepailab/src/index.js +3 -3
- package/dist/node_modules/@earendil-works/chord/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-agent-core/package.json +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/openrouter.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-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/package-manager-cli.js +72 -74
- package/dist/utils/changelog.js +3 -3
- package/dist/utils/deprecation.js +1 -1
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/examples/sdk/03-custom-prompt.ts +1 -1
- package/npm-shrinkwrap.json +2 -9
- package/package.json +1 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
var V=Object.defineProperty;var P=(p,t)=>V(p,"name",{value:t,configurable:!0});import{existsSync as u,readdirSync as X,readFileSync as Y,statSync as w}from"node:fs";import{basename as Z,dirname as _,join as m,resolve as y,sep as D}from"node:path";import K from"chalk";import{CONFIG_DIR_NAME as x,getExamplesPath as tt}from"../config.js";import{loadThemeFromPath as et}from"../modes/interactive/theme/theme.js";import{canonicalizePath as k,isLocalPath as O,resolvePath as g}from"../utils/paths.js";import{stripBom as q}from"../utils/text.js";import{createEventBus as st}from"./event-bus.js";import{clearExtensionCache as ot,createExtensionRuntime as it,loadExtensionFromFactory as nt,loadExtensionsCached as b}from"./extensions/loader.js";import{findGitPaths as rt}from"./footer-data-provider.js";import{DefaultPackageManager as at}from"./package-manager.js";import{loadPromptTemplates as ht}from"./prompt-templates.js";import{SettingsManager as lt}from"./settings-manager.js";import{loadSkills as ct}from"./skills.js";import{createSourceInfo as E}from"./source-info.js";import{resetTimings as mt}from"./timings.js";function H(p,t){if(p){if(u(p))try{return q(Y(p,"utf-8"))}catch(o){return console.error(K.yellow(`Warning: Could not read ${t} file ${p}: ${o}`)),p}return p}}P(H,"resolvePromptInput");function R(p){const t=["AGENTS.override.md","AGENTS.md","AGENTS.MD","CLAUDE.md","CLAUDE.MD"];for(const o of t){const s=m(p,o);if(u(s))try{if(!w(s).isFile())continue;return{path:s,content:q(Y(s,"utf-8"))}}catch(i){console.error(K.yellow(`Warning: Could not read ${s}: ${i}`))}}return null}P(R,"loadContextFileFromDir");function dt(p){const t=rt(p);if(!t)return;const o=k(t.commonGitDir),s=k(t.repoDir),i=_(o);if(!s.startsWith(`${i}${D}`)||k(m(i,".git"))!==o)return;const e=R(s);return e?m(i,Z(e.path)):void 0}P(dt,"findShadowedContextFile");function pt(p){const t=g(p.cwd),o=g(p.agentDir),s=[],i=new Set,e=R(o);e&&(s.push(e),i.add(e.path));const n=[],r=dt(t);let d=t;for(;;){const l=R(d),f=r!==void 0&&k(l?.path??"")===r;l&&!f&&!i.has(l.path)&&(n.unshift(l),i.add(l.path));const h=_(d);if(h===d)break;d=h}return s.push(...n),s}P(pt,"loadProjectContextFiles");class bt{static{P(this,"DefaultResourceLoader")}cwd;agentDir;settingsManager;eventBus;packageManager;additionalExtensionPaths;additionalSkillPaths;additionalPromptTemplatePaths;additionalThemePaths;extensionFactories;noExtensions;noSkills;noPromptTemplates;noThemes;noContextFiles;systemPromptSource;appendSystemPromptSource;extensionsOverride;skillsOverride;promptsOverride;themesOverride;agentsFilesOverride;systemPromptOverride;appendSystemPromptOverride;extensionsResult;skills;skillDiagnostics;prompts;promptDiagnostics;themes;themeDiagnostics;agentsFiles;systemPrompt;systemPromptSourcePath;appendSystemPrompt;appendSystemPromptSourcePaths;lastSkillPaths;extensionSkillSourceInfos;extensionPromptSourceInfos;extensionThemeSourceInfos;resourceMetadataByPath;lastPromptPaths;lastThemePaths;loaded;constructor(t){this.cwd=g(t.cwd),this.agentDir=g(t.agentDir),this.settingsManager=t.settingsManager??lt.create(this.cwd,this.agentDir),this.eventBus=t.eventBus??st(),this.packageManager=new at({cwd:this.cwd,agentDir:this.agentDir,settingsManager:this.settingsManager}),this.additionalExtensionPaths=t.additionalExtensionPaths??[],this.additionalSkillPaths=t.additionalSkillPaths??[],this.additionalPromptTemplatePaths=t.additionalPromptTemplatePaths??[],this.additionalThemePaths=t.additionalThemePaths??[],this.extensionFactories=t.extensionFactories??[],this.noExtensions=t.noExtensions??!1,this.noSkills=t.noSkills??!1,this.noPromptTemplates=t.noPromptTemplates??!1,this.noThemes=t.noThemes??!1,this.noContextFiles=t.noContextFiles??!1,this.systemPromptSource=t.systemPrompt,this.appendSystemPromptSource=t.appendSystemPrompt,this.extensionsOverride=t.extensionsOverride,this.skillsOverride=t.skillsOverride,this.promptsOverride=t.promptsOverride,this.themesOverride=t.themesOverride,this.agentsFilesOverride=t.agentsFilesOverride,this.systemPromptOverride=t.systemPromptOverride,this.appendSystemPromptOverride=t.appendSystemPromptOverride,this.extensionsResult={extensions:[],errors:[],runtime:it()},this.skills=[],this.skillDiagnostics=[],this.prompts=[],this.promptDiagnostics=[],this.themes=[],this.themeDiagnostics=[],this.agentsFiles=[],this.appendSystemPrompt=[],this.appendSystemPromptSourcePaths=[],this.lastSkillPaths=[],this.extensionSkillSourceInfos=new Map,this.extensionPromptSourceInfos=new Map,this.extensionThemeSourceInfos=new Map,this.resourceMetadataByPath=new Map,this.lastPromptPaths=[],this.lastThemePaths=[],this.loaded=!1}getExtensions(){return this.extensionsResult}getSkills(){return{skills:this.skills,diagnostics:this.skillDiagnostics}}getPrompts(){return{prompts:this.prompts,diagnostics:this.promptDiagnostics}}getThemes(){return{themes:this.themes,diagnostics:this.themeDiagnostics}}getAgentsFiles(){return{agentsFiles:this.agentsFiles}}getSystemPrompt(){return this.systemPrompt}getSystemPromptSource(){return this.systemPromptSourcePath?{path:this.systemPromptSourcePath}:void 0}getAppendSystemPrompt(){return this.appendSystemPrompt}getAppendSystemPromptSources(){return this.appendSystemPromptSourcePaths.map(t=>({path:t}))}extendResources(t){const o=this.normalizeExtensionPaths(t.skillPaths??[]),s=this.normalizeExtensionPaths(t.promptPaths??[]),i=this.normalizeExtensionPaths(t.themePaths??[]);for(const e of o)this.extensionSkillSourceInfos.set(e.path,E(e.path,e.metadata));for(const e of s)this.extensionPromptSourceInfos.set(e.path,E(e.path,e.metadata));for(const e of i)this.extensionThemeSourceInfos.set(e.path,E(e.path,e.metadata));o.length>0&&(this.lastSkillPaths=this.mergePaths(this.lastSkillPaths,o.map(e=>e.path)),this.updateSkillsFromPaths(this.lastSkillPaths,this.resourceMetadataByPath)),s.length>0&&(this.lastPromptPaths=this.mergePaths(this.lastPromptPaths,s.map(e=>e.path)),this.updatePromptsFromPaths(this.lastPromptPaths,this.resourceMetadataByPath)),i.length>0&&(this.lastThemePaths=this.mergePaths(this.lastThemePaths,i.map(e=>e.path)),this.updateThemesFromPaths(this.lastThemePaths,this.resourceMetadataByPath))}async loadProjectTrustExtensions(){return this.settingsManager.setProjectTrusted(!1),await this.settingsManager.reload(),this.loadCurrentExtensionSet({includeInlineFactories:!0})}async reload(t){mt("extensions"),this.loaded&&ot();let o;if(t?.resolveProjectTrust){o=await this.loadProjectTrustExtensions();const a=await t.resolveProjectTrust({extensionsResult:o});this.settingsManager.setProjectTrusted(a)}await this.settingsManager.reload();const s=await this.packageManager.resolve(),i=await this.packageManager.resolveExtensionSources(this.additionalExtensionPaths,{temporary:!0});this.resourceMetadataByPath=new Map;const e=this.resourceMetadataByPath;this.extensionSkillSourceInfos=new Map,this.extensionPromptSourceInfos=new Map,this.extensionThemeSourceInfos=new Map;const n=P(a=>{for(const c of a)e.has(c.path)||e.set(c.path,c.metadata);return a.filter(c=>c.enabled)},"getEnabledResources"),r=P(a=>n(a).map(c=>c.path),"getEnabledPaths"),d=r(s.extensions),l=n(s.skills),f=r(s.prompts),h=r(s.themes),S=l.map(a=>this.mapSkillPath(a,e));for(const a of i.extensions)e.has(a.path)||e.set(a.path,{source:"cli",scope:"temporary",origin:"top-level"});for(const a of i.skills)e.has(a.path)||e.set(a.path,{source:"cli",scope:"temporary",origin:"top-level"});const C=r(i.extensions),$=r(i.skills),A=r(i.prompts),j=r(i.themes),J=this.noExtensions?C:this.mergePaths(C,d),M=await this.loadFinalExtensionSet(J,o);for(const a of this.additionalExtensionPaths)if(O(a)){const c=this.resolveResourcePath(a);u(c)||M.errors.push({path:c,error:`Extension path does not exist: ${c}`})}this.extensionsResult=this.extensionsOverride?this.extensionsOverride(M):M,this.applyExtensionSourceInfo(this.extensionsResult.extensions,e);const v=m(tt(),"skills"),B=!this.noSkills&&u(v)?[v]:[];B.length>0&&!e.has(v)&&e.set(v,{source:"auto",scope:"user",origin:"top-level",baseDir:v});const W=this.noSkills?this.mergePaths($,this.additionalSkillPaths):this.mergePaths([...B,...$,...S],this.additionalSkillPaths);this.lastSkillPaths=W,this.updateSkillsFromPaths(W,e);for(const a of this.additionalSkillPaths)if(O(a)){const c=this.resolveResourcePath(a);!u(c)&&!this.skillDiagnostics.some(F=>F.path===c)&&this.skillDiagnostics.push({type:"error",message:"Skill path does not exist",path:c})}const z=this.noPromptTemplates?this.mergePaths(A,this.additionalPromptTemplatePaths):this.mergePaths([...A,...f],this.additionalPromptTemplatePaths);this.lastPromptPaths=z,this.updatePromptsFromPaths(z,e);for(const a of this.additionalPromptTemplatePaths)if(O(a)){const c=this.resolveResourcePath(a);!u(c)&&!this.promptDiagnostics.some(F=>F.path===c)&&this.promptDiagnostics.push({type:"error",message:"Prompt template path does not exist",path:c})}const L=this.noThemes?this.mergePaths(j,this.additionalThemePaths):this.mergePaths([...j,...h],this.additionalThemePaths);this.lastThemePaths=L,this.updateThemesFromPaths(L,e);for(const a of this.additionalThemePaths){const c=this.resolveResourcePath(a);!u(c)&&!this.themeDiagnostics.some(F=>F.path===c)&&this.themeDiagnostics.push({type:"error",message:"Theme path does not exist",path:c})}const N={agentsFiles:this.noContextFiles?[]:pt({cwd:this.cwd,agentDir:this.agentDir})},Q=this.agentsFilesOverride?this.agentsFilesOverride(N):N;this.agentsFiles=Q.agentsFiles;const T=this.systemPromptSource??this.discoverSystemPromptFile(),G=H(T,"system prompt");this.systemPrompt=this.systemPromptOverride?this.systemPromptOverride(G):G,this.systemPromptSourcePath=T&&u(T)?g(T):void 0;let I=this.appendSystemPromptSource;if(!I){const a=this.discoverAppendSystemPromptFile();I=a?[a]:[]}const U=I.map(a=>H(a,"append system prompt")).filter(a=>a!==void 0);this.appendSystemPrompt=this.appendSystemPromptOverride?this.appendSystemPromptOverride(U):U,this.appendSystemPromptSourcePaths=I.filter(a=>u(a)).map(a=>g(a)),this.loaded=!0}async loadCurrentExtensionSet(t){const o=await this.packageManager.resolve(),s=await this.packageManager.resolveExtensionSources(this.additionalExtensionPaths,{temporary:!0}),i=o.extensions.filter(l=>l.enabled).map(l=>l.path),e=s.extensions.filter(l=>l.enabled).map(l=>l.path),n=this.noExtensions?e:this.mergePaths(e,i),r=await b(n,this.cwd,this.eventBus);if(!t.includeInlineFactories)return r;const d=await this.loadExtensionFactories(r.runtime);return r.extensions.push(...d.extensions),r.errors.push(...d.errors),r}resolveExtensionLoadPath(t){return g(t,this.cwd,{normalizeUnicodeSpaces:!0})}async loadFinalExtensionSet(t,o){if(!o){const h=await b(t,this.cwd,this.eventBus),S=await this.loadExtensionFactories(h.runtime);return h.extensions.push(...S.extensions),h.errors.push(...S.errors),this.addExtensionConflictDiagnostics(h),h}const s=new Map(o.extensions.filter(h=>!h.path.startsWith("<inline:")).map(h=>[h.resolvedPath,h])),i=new Set(o.errors.map(h=>this.resolveExtensionLoadPath(h.path))),e=t.filter(h=>{const S=this.resolveExtensionLoadPath(h);return!s.has(S)&&!i.has(S)}),n=await b(e,this.cwd,this.eventBus,o.runtime),r=new Map(s);for(const h of n.extensions)r.set(h.resolvedPath,h);const d=o.extensions.filter(h=>h.path.startsWith("<inline:")),l=t.map(h=>r.get(this.resolveExtensionLoadPath(h))).filter(h=>h!==void 0);l.push(...d);const f={extensions:l,errors:[...o.errors,...n.errors],runtime:o.runtime};return this.addExtensionConflictDiagnostics(f),f}addExtensionConflictDiagnostics(t){const o=this.detectExtensionConflicts(t.extensions);for(const s of o)t.errors.push({path:s.path,error:s.message})}mapSkillPath(t,o){if(t.metadata.source!=="auto"&&t.metadata.origin!=="package")return t.path;try{if(!w(t.path).isDirectory())return t.path}catch{return t.path}const s=m(t.path,"SKILL.md");return u(s)?(o.has(s)||o.set(s,t.metadata),s):t.path}normalizeExtensionPaths(t){return t.map(o=>{const s=o.metadata.baseDir?{...o.metadata,baseDir:this.resolveResourcePath(o.metadata.baseDir)}:o.metadata;return{path:this.resolveResourcePath(o.path),metadata:s}})}updateSkillsFromPaths(t,o){let s;this.noSkills&&t.length===0?s={skills:[],diagnostics:[]}:s=ct({cwd:this.cwd,agentDir:this.agentDir,skillPaths:t,includeDefaults:!1});const i=this.skillsOverride?this.skillsOverride(s):s;this.skills=i.skills.map(e=>({...e,sourceInfo:this.findSourceInfoForPath(e.filePath,this.extensionSkillSourceInfos,o)??e.sourceInfo??this.getDefaultSourceInfoForPath(e.filePath)})),this.skillDiagnostics=i.diagnostics}updatePromptsFromPaths(t,o){let s;if(this.noPromptTemplates&&t.length===0)s={prompts:[],diagnostics:[]};else{const e=ht({cwd:this.cwd,agentDir:this.agentDir,promptPaths:t,includeDefaults:!1}),n=this.dedupePrompts(e.templates);s={prompts:n.prompts,diagnostics:[...e.diagnostics,...n.diagnostics]}}const i=this.promptsOverride?this.promptsOverride(s):s;this.prompts=i.prompts.map(e=>({...e,sourceInfo:this.findSourceInfoForPath(e.filePath,this.extensionPromptSourceInfos,o)??e.sourceInfo??this.getDefaultSourceInfoForPath(e.filePath)})),this.promptDiagnostics=i.diagnostics}updateThemesFromPaths(t,o){let s;if(this.noThemes&&t.length===0)s={themes:[],diagnostics:[]};else{const e=this.loadThemes(t,!1),n=this.dedupeThemes(e.themes);s={themes:n.themes,diagnostics:[...e.diagnostics,...n.diagnostics]}}const i=this.themesOverride?this.themesOverride(s):s;this.themes=i.themes.map(e=>{const n=e.sourcePath;return e.sourceInfo=n?this.findSourceInfoForPath(n,this.extensionThemeSourceInfos,o)??e.sourceInfo??this.getDefaultSourceInfoForPath(n):e.sourceInfo,e}),this.themeDiagnostics=i.diagnostics}applyExtensionSourceInfo(t,o){for(const s of t){s.sourceInfo=this.findSourceInfoForPath(s.path,void 0,o)??this.getDefaultSourceInfoForPath(s.path);for(const i of s.commands.values())i.sourceInfo=s.sourceInfo;for(const i of s.tools.values())i.sourceInfo=s.sourceInfo}}findSourceInfoForPath(t,o,s){if(!t)return;if(t.startsWith("<"))return this.getDefaultSourceInfoForPath(t);const i=y(t);if(o)for(const[e,n]of o.entries()){const r=y(e);if(i===r||i.startsWith(`${r}${D}`))return{...n,path:t}}if(s){const e=s.get(i)??s.get(t);if(e)return E(t,e);for(const[n,r]of s.entries()){const d=y(n);if(i===d||i.startsWith(`${d}${D}`))return E(t,r)}}}getDefaultSourceInfoForPath(t){if(t.startsWith("<")&&t.endsWith(">"))return{path:t,source:t.slice(1,-1).split(":")[0]||"temporary",scope:"temporary",origin:"top-level"};const o=y(t),s=[m(this.agentDir,"skills"),m(this.agentDir,"prompts"),m(this.agentDir,"themes"),m(this.agentDir,"extensions")],i=[m(this.cwd,x,"skills"),m(this.cwd,x,"prompts"),m(this.cwd,x,"themes"),m(this.cwd,x,"extensions")];for(const e of s)if(this.isUnderPath(o,e))return{path:t,source:"local",scope:"user",origin:"top-level",baseDir:e};for(const e of i)if(this.isUnderPath(o,e))return{path:t,source:"local",scope:"project",origin:"top-level",baseDir:e};return{path:t,source:"local",scope:"temporary",origin:"top-level",baseDir:w(o).isDirectory()?o:y(o,"..")}}mergePaths(t,o){const s=[],i=new Set;for(const e of[...t,...o]){const n=this.resolveResourcePath(e),r=k(n);i.has(r)||(i.add(r),s.push(n))}return s}resolveResourcePath(t){return g(t,this.cwd,{trim:!0})}loadThemes(t,o=!0){const s=[],i=[];if(o){const e=[m(this.agentDir,"themes"),m(this.cwd,x,"themes")];for(const n of e)this.loadThemesFromDir(n,s,i)}for(const e of t){const n=this.resolveResourcePath(e);if(!u(n)){i.push({type:"warning",message:"theme path does not exist",path:n});continue}try{const r=w(n);r.isDirectory()?this.loadThemesFromDir(n,s,i):r.isFile()&&n.endsWith(".json")?this.loadThemeFromFile(n,s,i):i.push({type:"warning",message:"theme path is not a json file",path:n})}catch(r){const d=r instanceof Error?r.message:"failed to read theme path";i.push({type:"warning",message:d,path:n})}}return{themes:s,diagnostics:i}}loadThemesFromDir(t,o,s){if(u(t))try{const i=X(t,{withFileTypes:!0});for(const e of i){let n=e.isFile();if(e.isSymbolicLink())try{n=w(m(t,e.name)).isFile()}catch{continue}n&&e.name.endsWith(".json")&&this.loadThemeFromFile(m(t,e.name),o,s)}}catch(i){const e=i instanceof Error?i.message:"failed to read theme directory";s.push({type:"warning",message:e,path:t})}}loadThemeFromFile(t,o,s){try{o.push(et(t))}catch(i){const e=i instanceof Error?i.message:"failed to load theme";s.push({type:"warning",message:e,path:t})}}async loadExtensionFactories(t){const o=[],s=[];for(const[i,e]of this.extensionFactories.entries()){const n=typeof e!="function",r=n?e.factory:e,d=`<inline:${n?e.name:i+1}>`;try{const l=await nt(r,this.cwd,this.eventBus,t,d);l.hidden=n&&e.hidden,o.push(l)}catch(l){const f=l instanceof Error?l.message:"failed to load extension";s.push({path:d,error:f})}}return{extensions:o,errors:s}}dedupePrompts(t){const o=new Map,s=[];for(const i of t){const e=o.get(i.name);e?s.push({type:"collision",message:`name "/${i.name}" collision`,path:i.filePath,collision:{resourceType:"prompt",name:i.name,winnerPath:e.filePath,loserPath:i.filePath}}):o.set(i.name,i)}return{prompts:Array.from(o.values()),diagnostics:s}}dedupeThemes(t){const o=new Map,s=[];for(const i of t){const e=i.name??"unnamed",n=o.get(e);n?s.push({type:"collision",message:`name "${e}" collision`,path:i.sourcePath,collision:{resourceType:"theme",name:e,winnerPath:n.sourcePath??"<builtin>",loserPath:i.sourcePath??"<builtin>"}}):o.set(e,i)}return{themes:Array.from(o.values()),diagnostics:s}}discoverSystemPromptFile(){const t=m(this.cwd,x,"SYSTEM.md");if(this.settingsManager.isProjectTrusted()&&u(t))return t;const o=m(this.agentDir,"SYSTEM.md");if(u(o))return o}discoverAppendSystemPromptFile(){const t=m(this.cwd,x,"APPEND_SYSTEM.md");if(this.settingsManager.isProjectTrusted()&&u(t))return t;const o=m(this.agentDir,"APPEND_SYSTEM.md");if(u(o))return o}isUnderPath(t,o){const s=y(o);if(t===s)return!0;const i=s.endsWith(D)?s:`${s}${D}`;return t.startsWith(i)}detectExtensionConflicts(t){const o=[],s=new Map,i=new Map;for(const e of t){for(const n of e.tools.keys()){const r=s.get(n);r&&r!==e.path?o.push({path:e.path,message:`Tool "${n}" conflicts with ${r}`}):s.set(n,e.path)}for(const n of e.flags.keys()){const r=i.get(n);r&&r!==e.path?o.push({path:e.path,message:`Flag "--${n}" conflicts with ${r}`}):i.set(n,e.path)}}return o}}export{bt as DefaultResourceLoader,pt as loadProjectContextFiles};
|
|
1
|
+
var Z=Object.defineProperty;var P=(p,t)=>Z(p,"name",{value:t,configurable:!0});import{existsSync as u,readdirSync as tt,readFileSync as _,statSync as w}from"node:fs";import{basename as et,dirname as K,join as m,resolve as y,sep as D}from"node:path";import q from"chalk";import{CONFIG_DIR_NAME as x,getExamplesPath as st}from"../config.js";import{fill as H,t as M}from"../dal/i18n.js";import{loadThemeFromPath as ot}from"../modes/interactive/theme/theme.js";import{canonicalizePath as k,isLocalPath as b,resolvePath as g}from"../utils/paths.js";import{stripBom as J}from"../utils/text.js";import{createEventBus as it}from"./event-bus.js";import{clearExtensionCache as nt,createExtensionRuntime as rt,loadExtensionFromFactory as at,loadExtensionsCached as R}from"./extensions/loader.js";import{findGitPaths as ht}from"./footer-data-provider.js";import{DefaultPackageManager as lt}from"./package-manager.js";import{loadPromptTemplates as ct}from"./prompt-templates.js";import{SettingsManager as mt}from"./settings-manager.js";import{loadSkills as dt}from"./skills.js";import{createSourceInfo as E}from"./source-info.js";import{resetTimings as pt}from"./timings.js";function Q(p,t){if(p){if(u(p))try{return J(_(p,"utf-8"))}catch(o){return console.error(q.yellow(H(M("\u8B66\u544A\uFF1A\u65E0\u6CD5\u8BFB\u53D6{what}\u6587\u4EF6 {path}\uFF1A{error}"),{what:t,path:p,error:String(o)}))),p}return p}}P(Q,"resolvePromptInput");function C(p){const t=["AGENTS.override.md","AGENTS.md","AGENTS.MD","CLAUDE.md","CLAUDE.MD"];for(const o of t){const s=m(p,o);if(u(s))try{if(!w(s).isFile())continue;return{path:s,content:J(_(s,"utf-8"))}}catch(i){console.error(q.yellow(H(M("\u8B66\u544A\uFF1A\u65E0\u6CD5\u8BFB\u53D6 {path}\uFF1A{error}"),{path:s,error:String(i)})))}}return null}P(C,"loadContextFileFromDir");function ut(p){const t=ht(p);if(!t)return;const o=k(t.commonGitDir),s=k(t.repoDir),i=K(o);if(!s.startsWith(`${i}${D}`)||k(m(i,".git"))!==o)return;const e=C(s);return e?m(i,et(e.path)):void 0}P(ut,"findShadowedContextFile");function ft(p){const t=g(p.cwd),o=g(p.agentDir),s=[],i=new Set,e=C(o);e&&(s.push(e),i.add(e.path));const n=[],r=ut(t);let d=t;for(;;){const l=C(d),f=r!==void 0&&k(l?.path??"")===r;l&&!f&&!i.has(l.path)&&(n.unshift(l),i.add(l.path));const h=K(d);if(h===d)break;d=h}return s.push(...n),s}P(ft,"loadProjectContextFiles");class At{static{P(this,"DefaultResourceLoader")}cwd;agentDir;settingsManager;eventBus;packageManager;additionalExtensionPaths;additionalSkillPaths;additionalPromptTemplatePaths;additionalThemePaths;extensionFactories;noExtensions;noSkills;noPromptTemplates;noThemes;noContextFiles;systemPromptSource;appendSystemPromptSource;extensionsOverride;skillsOverride;promptsOverride;themesOverride;agentsFilesOverride;systemPromptOverride;appendSystemPromptOverride;extensionsResult;skills;skillDiagnostics;prompts;promptDiagnostics;themes;themeDiagnostics;agentsFiles;systemPrompt;systemPromptSourcePath;appendSystemPrompt;appendSystemPromptSourcePaths;lastSkillPaths;extensionSkillSourceInfos;extensionPromptSourceInfos;extensionThemeSourceInfos;resourceMetadataByPath;lastPromptPaths;lastThemePaths;loaded;constructor(t){this.cwd=g(t.cwd),this.agentDir=g(t.agentDir),this.settingsManager=t.settingsManager??mt.create(this.cwd,this.agentDir),this.eventBus=t.eventBus??it(),this.packageManager=new lt({cwd:this.cwd,agentDir:this.agentDir,settingsManager:this.settingsManager}),this.additionalExtensionPaths=t.additionalExtensionPaths??[],this.additionalSkillPaths=t.additionalSkillPaths??[],this.additionalPromptTemplatePaths=t.additionalPromptTemplatePaths??[],this.additionalThemePaths=t.additionalThemePaths??[],this.extensionFactories=t.extensionFactories??[],this.noExtensions=t.noExtensions??!1,this.noSkills=t.noSkills??!1,this.noPromptTemplates=t.noPromptTemplates??!1,this.noThemes=t.noThemes??!1,this.noContextFiles=t.noContextFiles??!1,this.systemPromptSource=t.systemPrompt,this.appendSystemPromptSource=t.appendSystemPrompt,this.extensionsOverride=t.extensionsOverride,this.skillsOverride=t.skillsOverride,this.promptsOverride=t.promptsOverride,this.themesOverride=t.themesOverride,this.agentsFilesOverride=t.agentsFilesOverride,this.systemPromptOverride=t.systemPromptOverride,this.appendSystemPromptOverride=t.appendSystemPromptOverride,this.extensionsResult={extensions:[],errors:[],runtime:rt()},this.skills=[],this.skillDiagnostics=[],this.prompts=[],this.promptDiagnostics=[],this.themes=[],this.themeDiagnostics=[],this.agentsFiles=[],this.appendSystemPrompt=[],this.appendSystemPromptSourcePaths=[],this.lastSkillPaths=[],this.extensionSkillSourceInfos=new Map,this.extensionPromptSourceInfos=new Map,this.extensionThemeSourceInfos=new Map,this.resourceMetadataByPath=new Map,this.lastPromptPaths=[],this.lastThemePaths=[],this.loaded=!1}getExtensions(){return this.extensionsResult}getSkills(){return{skills:this.skills,diagnostics:this.skillDiagnostics}}getPrompts(){return{prompts:this.prompts,diagnostics:this.promptDiagnostics}}getThemes(){return{themes:this.themes,diagnostics:this.themeDiagnostics}}getAgentsFiles(){return{agentsFiles:this.agentsFiles}}getSystemPrompt(){return this.systemPrompt}getSystemPromptSource(){return this.systemPromptSourcePath?{path:this.systemPromptSourcePath}:void 0}getAppendSystemPrompt(){return this.appendSystemPrompt}getAppendSystemPromptSources(){return this.appendSystemPromptSourcePaths.map(t=>({path:t}))}extendResources(t){const o=this.normalizeExtensionPaths(t.skillPaths??[]),s=this.normalizeExtensionPaths(t.promptPaths??[]),i=this.normalizeExtensionPaths(t.themePaths??[]);for(const e of o)this.extensionSkillSourceInfos.set(e.path,E(e.path,e.metadata));for(const e of s)this.extensionPromptSourceInfos.set(e.path,E(e.path,e.metadata));for(const e of i)this.extensionThemeSourceInfos.set(e.path,E(e.path,e.metadata));o.length>0&&(this.lastSkillPaths=this.mergePaths(this.lastSkillPaths,o.map(e=>e.path)),this.updateSkillsFromPaths(this.lastSkillPaths,this.resourceMetadataByPath)),s.length>0&&(this.lastPromptPaths=this.mergePaths(this.lastPromptPaths,s.map(e=>e.path)),this.updatePromptsFromPaths(this.lastPromptPaths,this.resourceMetadataByPath)),i.length>0&&(this.lastThemePaths=this.mergePaths(this.lastThemePaths,i.map(e=>e.path)),this.updateThemesFromPaths(this.lastThemePaths,this.resourceMetadataByPath))}async loadProjectTrustExtensions(){return this.settingsManager.setProjectTrusted(!1),await this.settingsManager.reload(),this.loadCurrentExtensionSet({includeInlineFactories:!0})}async reload(t){pt("extensions"),this.loaded&&nt();let o;if(t?.resolveProjectTrust){o=await this.loadProjectTrustExtensions();const a=await t.resolveProjectTrust({extensionsResult:o});this.settingsManager.setProjectTrusted(a)}await this.settingsManager.reload();const s=await this.packageManager.resolve(),i=await this.packageManager.resolveExtensionSources(this.additionalExtensionPaths,{temporary:!0});this.resourceMetadataByPath=new Map;const e=this.resourceMetadataByPath;this.extensionSkillSourceInfos=new Map,this.extensionPromptSourceInfos=new Map,this.extensionThemeSourceInfos=new Map;const n=P(a=>{for(const c of a)e.has(c.path)||e.set(c.path,c.metadata);return a.filter(c=>c.enabled)},"getEnabledResources"),r=P(a=>n(a).map(c=>c.path),"getEnabledPaths"),d=r(s.extensions),l=n(s.skills),f=r(s.prompts),h=r(s.themes),S=l.map(a=>this.mapSkillPath(a,e));for(const a of i.extensions)e.has(a.path)||e.set(a.path,{source:"cli",scope:"temporary",origin:"top-level"});for(const a of i.skills)e.has(a.path)||e.set(a.path,{source:"cli",scope:"temporary",origin:"top-level"});const A=r(i.extensions),j=r(i.skills),$=r(i.prompts),B=r(i.themes),V=this.noExtensions?A:this.mergePaths(A,d),O=await this.loadFinalExtensionSet(V,o);for(const a of this.additionalExtensionPaths)if(b(a)){const c=this.resolveResourcePath(a);u(c)||O.errors.push({path:c,error:`Extension path does not exist: ${c}`})}this.extensionsResult=this.extensionsOverride?this.extensionsOverride(O):O,this.applyExtensionSourceInfo(this.extensionsResult.extensions,e);const v=m(st(),"skills"),W=!this.noSkills&&u(v)?[v]:[];W.length>0&&!e.has(v)&&e.set(v,{source:"auto",scope:"user",origin:"top-level",baseDir:v});const z=this.noSkills?this.mergePaths(j,this.additionalSkillPaths):this.mergePaths([...W,...j,...S],this.additionalSkillPaths);this.lastSkillPaths=z,this.updateSkillsFromPaths(z,e);for(const a of this.additionalSkillPaths)if(b(a)){const c=this.resolveResourcePath(a);!u(c)&&!this.skillDiagnostics.some(F=>F.path===c)&&this.skillDiagnostics.push({type:"error",message:"Skill path does not exist",path:c})}const L=this.noPromptTemplates?this.mergePaths($,this.additionalPromptTemplatePaths):this.mergePaths([...$,...f],this.additionalPromptTemplatePaths);this.lastPromptPaths=L,this.updatePromptsFromPaths(L,e);for(const a of this.additionalPromptTemplatePaths)if(b(a)){const c=this.resolveResourcePath(a);!u(c)&&!this.promptDiagnostics.some(F=>F.path===c)&&this.promptDiagnostics.push({type:"error",message:"Prompt template path does not exist",path:c})}const N=this.noThemes?this.mergePaths(B,this.additionalThemePaths):this.mergePaths([...B,...h],this.additionalThemePaths);this.lastThemePaths=N,this.updateThemesFromPaths(N,e);for(const a of this.additionalThemePaths){const c=this.resolveResourcePath(a);!u(c)&&!this.themeDiagnostics.some(F=>F.path===c)&&this.themeDiagnostics.push({type:"error",message:"Theme path does not exist",path:c})}const G={agentsFiles:this.noContextFiles?[]:ft({cwd:this.cwd,agentDir:this.agentDir})},X=this.agentsFilesOverride?this.agentsFilesOverride(G):G;this.agentsFiles=X.agentsFiles;const T=this.systemPromptSource??this.discoverSystemPromptFile(),U=Q(T,M("\u7CFB\u7EDF\u63D0\u793A\u8BCD"));this.systemPrompt=this.systemPromptOverride?this.systemPromptOverride(U):U,this.systemPromptSourcePath=T&&u(T)?g(T):void 0;let I=this.appendSystemPromptSource;if(!I){const a=this.discoverAppendSystemPromptFile();I=a?[a]:[]}const Y=I.map(a=>Q(a,M("\u8FFD\u52A0\u7684\u7CFB\u7EDF\u63D0\u793A\u8BCD"))).filter(a=>a!==void 0);this.appendSystemPrompt=this.appendSystemPromptOverride?this.appendSystemPromptOverride(Y):Y,this.appendSystemPromptSourcePaths=I.filter(a=>u(a)).map(a=>g(a)),this.loaded=!0}async loadCurrentExtensionSet(t){const o=await this.packageManager.resolve(),s=await this.packageManager.resolveExtensionSources(this.additionalExtensionPaths,{temporary:!0}),i=o.extensions.filter(l=>l.enabled).map(l=>l.path),e=s.extensions.filter(l=>l.enabled).map(l=>l.path),n=this.noExtensions?e:this.mergePaths(e,i),r=await R(n,this.cwd,this.eventBus);if(!t.includeInlineFactories)return r;const d=await this.loadExtensionFactories(r.runtime);return r.extensions.push(...d.extensions),r.errors.push(...d.errors),r}resolveExtensionLoadPath(t){return g(t,this.cwd,{normalizeUnicodeSpaces:!0})}async loadFinalExtensionSet(t,o){if(!o){const h=await R(t,this.cwd,this.eventBus),S=await this.loadExtensionFactories(h.runtime);return h.extensions.push(...S.extensions),h.errors.push(...S.errors),this.addExtensionConflictDiagnostics(h),h}const s=new Map(o.extensions.filter(h=>!h.path.startsWith("<inline:")).map(h=>[h.resolvedPath,h])),i=new Set(o.errors.map(h=>this.resolveExtensionLoadPath(h.path))),e=t.filter(h=>{const S=this.resolveExtensionLoadPath(h);return!s.has(S)&&!i.has(S)}),n=await R(e,this.cwd,this.eventBus,o.runtime),r=new Map(s);for(const h of n.extensions)r.set(h.resolvedPath,h);const d=o.extensions.filter(h=>h.path.startsWith("<inline:")),l=t.map(h=>r.get(this.resolveExtensionLoadPath(h))).filter(h=>h!==void 0);l.push(...d);const f={extensions:l,errors:[...o.errors,...n.errors],runtime:o.runtime};return this.addExtensionConflictDiagnostics(f),f}addExtensionConflictDiagnostics(t){const o=this.detectExtensionConflicts(t.extensions);for(const s of o)t.errors.push({path:s.path,error:s.message})}mapSkillPath(t,o){if(t.metadata.source!=="auto"&&t.metadata.origin!=="package")return t.path;try{if(!w(t.path).isDirectory())return t.path}catch{return t.path}const s=m(t.path,"SKILL.md");return u(s)?(o.has(s)||o.set(s,t.metadata),s):t.path}normalizeExtensionPaths(t){return t.map(o=>{const s=o.metadata.baseDir?{...o.metadata,baseDir:this.resolveResourcePath(o.metadata.baseDir)}:o.metadata;return{path:this.resolveResourcePath(o.path),metadata:s}})}updateSkillsFromPaths(t,o){let s;this.noSkills&&t.length===0?s={skills:[],diagnostics:[]}:s=dt({cwd:this.cwd,agentDir:this.agentDir,skillPaths:t,includeDefaults:!1});const i=this.skillsOverride?this.skillsOverride(s):s;this.skills=i.skills.map(e=>({...e,sourceInfo:this.findSourceInfoForPath(e.filePath,this.extensionSkillSourceInfos,o)??e.sourceInfo??this.getDefaultSourceInfoForPath(e.filePath)})),this.skillDiagnostics=i.diagnostics}updatePromptsFromPaths(t,o){let s;if(this.noPromptTemplates&&t.length===0)s={prompts:[],diagnostics:[]};else{const e=ct({cwd:this.cwd,agentDir:this.agentDir,promptPaths:t,includeDefaults:!1}),n=this.dedupePrompts(e.templates);s={prompts:n.prompts,diagnostics:[...e.diagnostics,...n.diagnostics]}}const i=this.promptsOverride?this.promptsOverride(s):s;this.prompts=i.prompts.map(e=>({...e,sourceInfo:this.findSourceInfoForPath(e.filePath,this.extensionPromptSourceInfos,o)??e.sourceInfo??this.getDefaultSourceInfoForPath(e.filePath)})),this.promptDiagnostics=i.diagnostics}updateThemesFromPaths(t,o){let s;if(this.noThemes&&t.length===0)s={themes:[],diagnostics:[]};else{const e=this.loadThemes(t,!1),n=this.dedupeThemes(e.themes);s={themes:n.themes,diagnostics:[...e.diagnostics,...n.diagnostics]}}const i=this.themesOverride?this.themesOverride(s):s;this.themes=i.themes.map(e=>{const n=e.sourcePath;return e.sourceInfo=n?this.findSourceInfoForPath(n,this.extensionThemeSourceInfos,o)??e.sourceInfo??this.getDefaultSourceInfoForPath(n):e.sourceInfo,e}),this.themeDiagnostics=i.diagnostics}applyExtensionSourceInfo(t,o){for(const s of t){s.sourceInfo=this.findSourceInfoForPath(s.path,void 0,o)??this.getDefaultSourceInfoForPath(s.path);for(const i of s.commands.values())i.sourceInfo=s.sourceInfo;for(const i of s.tools.values())i.sourceInfo=s.sourceInfo}}findSourceInfoForPath(t,o,s){if(!t)return;if(t.startsWith("<"))return this.getDefaultSourceInfoForPath(t);const i=y(t);if(o)for(const[e,n]of o.entries()){const r=y(e);if(i===r||i.startsWith(`${r}${D}`))return{...n,path:t}}if(s){const e=s.get(i)??s.get(t);if(e)return E(t,e);for(const[n,r]of s.entries()){const d=y(n);if(i===d||i.startsWith(`${d}${D}`))return E(t,r)}}}getDefaultSourceInfoForPath(t){if(t.startsWith("<")&&t.endsWith(">"))return{path:t,source:t.slice(1,-1).split(":")[0]||"temporary",scope:"temporary",origin:"top-level"};const o=y(t),s=[m(this.agentDir,"skills"),m(this.agentDir,"prompts"),m(this.agentDir,"themes"),m(this.agentDir,"extensions")],i=[m(this.cwd,x,"skills"),m(this.cwd,x,"prompts"),m(this.cwd,x,"themes"),m(this.cwd,x,"extensions")];for(const e of s)if(this.isUnderPath(o,e))return{path:t,source:"local",scope:"user",origin:"top-level",baseDir:e};for(const e of i)if(this.isUnderPath(o,e))return{path:t,source:"local",scope:"project",origin:"top-level",baseDir:e};return{path:t,source:"local",scope:"temporary",origin:"top-level",baseDir:w(o).isDirectory()?o:y(o,"..")}}mergePaths(t,o){const s=[],i=new Set;for(const e of[...t,...o]){const n=this.resolveResourcePath(e),r=k(n);i.has(r)||(i.add(r),s.push(n))}return s}resolveResourcePath(t){return g(t,this.cwd,{trim:!0})}loadThemes(t,o=!0){const s=[],i=[];if(o){const e=[m(this.agentDir,"themes"),m(this.cwd,x,"themes")];for(const n of e)this.loadThemesFromDir(n,s,i)}for(const e of t){const n=this.resolveResourcePath(e);if(!u(n)){i.push({type:"warning",message:"theme path does not exist",path:n});continue}try{const r=w(n);r.isDirectory()?this.loadThemesFromDir(n,s,i):r.isFile()&&n.endsWith(".json")?this.loadThemeFromFile(n,s,i):i.push({type:"warning",message:"theme path is not a json file",path:n})}catch(r){const d=r instanceof Error?r.message:"failed to read theme path";i.push({type:"warning",message:d,path:n})}}return{themes:s,diagnostics:i}}loadThemesFromDir(t,o,s){if(u(t))try{const i=tt(t,{withFileTypes:!0});for(const e of i){let n=e.isFile();if(e.isSymbolicLink())try{n=w(m(t,e.name)).isFile()}catch{continue}n&&e.name.endsWith(".json")&&this.loadThemeFromFile(m(t,e.name),o,s)}}catch(i){const e=i instanceof Error?i.message:"failed to read theme directory";s.push({type:"warning",message:e,path:t})}}loadThemeFromFile(t,o,s){try{o.push(ot(t))}catch(i){const e=i instanceof Error?i.message:"failed to load theme";s.push({type:"warning",message:e,path:t})}}async loadExtensionFactories(t){const o=[],s=[];for(const[i,e]of this.extensionFactories.entries()){const n=typeof e!="function",r=n?e.factory:e,d=`<inline:${n?e.name:i+1}>`;try{const l=await at(r,this.cwd,this.eventBus,t,d);l.hidden=n&&e.hidden,o.push(l)}catch(l){const f=l instanceof Error?l.message:"failed to load extension";s.push({path:d,error:f})}}return{extensions:o,errors:s}}dedupePrompts(t){const o=new Map,s=[];for(const i of t){const e=o.get(i.name);e?s.push({type:"collision",message:`name "/${i.name}" collision`,path:i.filePath,collision:{resourceType:"prompt",name:i.name,winnerPath:e.filePath,loserPath:i.filePath}}):o.set(i.name,i)}return{prompts:Array.from(o.values()),diagnostics:s}}dedupeThemes(t){const o=new Map,s=[];for(const i of t){const e=i.name??"unnamed",n=o.get(e);n?s.push({type:"collision",message:`name "${e}" collision`,path:i.sourcePath,collision:{resourceType:"theme",name:e,winnerPath:n.sourcePath??"<builtin>",loserPath:i.sourcePath??"<builtin>"}}):o.set(e,i)}return{themes:Array.from(o.values()),diagnostics:s}}discoverSystemPromptFile(){const t=m(this.cwd,x,"SYSTEM.md");if(this.settingsManager.isProjectTrusted()&&u(t))return t;const o=m(this.agentDir,"SYSTEM.md");if(u(o))return o}discoverAppendSystemPromptFile(){const t=m(this.cwd,x,"APPEND_SYSTEM.md");if(this.settingsManager.isProjectTrusted()&&u(t))return t;const o=m(this.agentDir,"APPEND_SYSTEM.md");if(u(o))return o}isUnderPath(t,o){const s=y(o);if(t===s)return!0;const i=s.endsWith(D)?s:`${s}${D}`;return t.startsWith(i)}detectExtensionConflicts(t){const o=[],s=new Map,i=new Map;for(const e of t){for(const n of e.tools.keys()){const r=s.get(n);r&&r!==e.path?o.push({path:e.path,message:`Tool "${n}" conflicts with ${r}`}):s.set(n,e.path)}for(const n of e.flags.keys()){const r=i.get(n);r&&r!==e.path?o.push({path:e.path,message:`Flag "--${n}" conflicts with ${r}`}):i.set(n,e.path)}}return o}}export{At as DefaultResourceLoader,ft as loadProjectContextFiles};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{APP_NAME as
|
|
1
|
+
var p=Object.defineProperty;var n=(t,r)=>p(t,"name",{value:r,configurable:!0});import{APP_NAME as s}from"../config.js";import{fill as l,t as o}from"../dal/i18n.js";function e(t,r,i){return{name:t,get description(){return r()},...i&&{argumentHint:i}}}n(e,"builtin");const u=[e("settings",()=>o("\u6253\u5F00\u8BBE\u7F6E\u83DC\u5355")),e("extensions",()=>o("\u542F\u7528\u6216\u505C\u7528\u5DF2\u52A0\u8F7D\u7684\u6269\u5C55")),e("model",()=>o("\u9009\u62E9\u6A21\u578B\uFF08\u6253\u5F00\u9009\u62E9\u754C\u9762\uFF09"),"<provider/model>"),e("tree",()=>o("\u6D4F\u89C8\u4F1A\u8BDD\u6811\uFF0C\u5207\u6362\u5206\u652F")),e("thinking",()=>o("\u8BBE\u7F6E\u601D\u8003\u6DF1\u5EA6"),"<level>"),e("scoped-models",()=>o("\u9009\u62E9\u54EA\u4E9B\u6A21\u578B\u53C2\u4E0E Ctrl+P \u8F6E\u6362")),e("export",()=>o("\u5BFC\u51FA\u4F1A\u8BDD\uFF08\u9ED8\u8BA4 HTML\uFF0C\u4E5F\u53EF\u6307\u5B9A\u8DEF\u5F84\uFF1A.html/.jsonl\uFF09")),e("import",()=>o("\u4ECE JSONL \u6587\u4EF6\u5BFC\u5165\u4F1A\u8BDD\u5E76\u7EE7\u7EED")),e("share",()=>o("\u628A\u4F1A\u8BDD\u5206\u4EAB\u4E3A\u79C1\u5BC6 GitHub gist")),e("bug",()=>o("\u5BFC\u51FA\u95EE\u9898\u62A5\u544A\uFF08\u672C\u5730 zip\uFF09\uFF0C\u53D1\u7ED9\u6280\u672F\u652F\u6301"),"<description>"),e("copy",()=>o("\u590D\u5236\u6700\u540E\u4E00\u6761\u56DE\u590D\u5230\u526A\u8D34\u677F")),e("name",()=>o("\u8BBE\u7F6E\u4F1A\u8BDD\u663E\u793A\u540D\u79F0")),e("session",()=>o("\u67E5\u770B\u4F1A\u8BDD\u4FE1\u606F\u548C\u7EDF\u8BA1")),e("map",()=>o("\u67E5\u770B\u7CBE\u7B80\u7684\u9879\u76EE\u7ED3\u6784\u56FE")),e("changelog",()=>o("\u67E5\u770B\u66F4\u65B0\u65E5\u5FD7")),e("hotkeys",()=>o("\u67E5\u770B\u5168\u90E8\u5FEB\u6377\u952E")),e("fork",()=>o("\u4ECE\u4E4B\u524D\u7684\u67D0\u6761\u6D88\u606F\u5206\u53C9\u51FA\u65B0\u4F1A\u8BDD")),e("clone",()=>o("\u5728\u5F53\u524D\u4F4D\u7F6E\u590D\u5236\u4E00\u4EFD\u4F1A\u8BDD")),e("trust",()=>o("\u4FDD\u5B58\u9879\u76EE\u4FE1\u4EFB\u8BBE\u7F6E\uFF0C\u4EE5\u540E\u7684\u4F1A\u8BDD\u6CBF\u7528")),e("login",()=>o("\u914D\u7F6E\u6A21\u578B\u63D0\u4F9B\u65B9\u7684\u767B\u5F55"),"<provider>"),e("logout",()=>o("\u79FB\u9664\u6A21\u578B\u63D0\u4F9B\u65B9\u7684\u767B\u5F55\u4FE1\u606F")),e("new",()=>o("\u5F00\u59CB\u65B0\u4F1A\u8BDD")),e("compact",()=>o("\u624B\u52A8\u538B\u7F29\u4F1A\u8BDD\u4E0A\u4E0B\u6587")),e("resume",()=>o("\u6062\u590D\u4E4B\u524D\u7684\u4F1A\u8BDD")),e("reload",()=>o("\u91CD\u65B0\u52A0\u8F7D\u5FEB\u6377\u952E\u3001\u6269\u5C55\u3001\u6280\u80FD\u3001\u63D0\u793A\u8BCD\u3001\u4E3B\u9898\u548C\u4E0A\u4E0B\u6587\u6587\u4EF6")),e("quit",()=>l(o("\u9000\u51FA {app}"),{app:s}))];export{u as BUILTIN_SLASH_COMMANDS};
|
package/dist/core/tools/bash.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
var
|
|
2
|
-
Cannot execute ${
|
|
3
|
-
${h.fg("muted",` \u23BF ${n} ${d.trim()}`)}`}const s=d===null?
|
|
1
|
+
var J=Object.defineProperty;var l=(e,n)=>J(e,"name",{value:n,configurable:!0});import{constants as Q}from"node:fs";import{access as Z}from"node:fs/promises";import{constants as tt}from"node:os";import{Container as et,Text as I,truncateToWidth as nt}from"@earendil-works/pi-tui";import{spawn as it}from"child_process";import{Type as b}from"typebox";import{fill as _,t as E}from"../../dal/i18n.js";import{keyHint as ot}from"../../modes/interactive/components/keybinding-hints.js";import{truncateToVisualLines as st}from"../../modes/interactive/components/visual-truncate.js";import{theme as h}from"../../modes/interactive/theme/theme.js";import{waitForChildProcess as rt}from"../../utils/child-process.js";import{getShellConfig as at,getShellEnv as G,killProcessTree as H,trackDetachedChildPid as dt,untrackDetachedChildPid as ut}from"../../utils/shell.js";import{OutputAccumulator as lt}from"./output-accumulator.js";import{countOutputLines as ct,formatCollapsedSummary as pt,getTextOutput as U,invalidArgText as mt,str as V,truncateDisplay as ft}from"./render-utils.js";import{wrapToolDefinition as ht}from"./tool-definition-wrapper.js";import{DEFAULT_MAX_BYTES as N,DEFAULT_MAX_LINES as wt,formatSize as D}from"./truncate.js";const j=2147483647,St=j/1e3,X=12e4;function Et(e){if(e===void 0)return X;if(!Number.isFinite(e)||e<=0)throw new Error("Invalid timeout: must be a finite number of seconds");const n=e*1e3;if(n>j)throw new Error(`Invalid timeout: maximum is ${St} seconds`);return n}l(Et,"resolveTimeoutMs");const $t=b.Object({command:b.String({description:"Shell command to execute"}),description:b.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:b.Optional(b.Number({description:"Timeout in seconds. Defaults to 120; raise it for genuinely long-running commands."}))}),z={snippet:"Execute bash commands (ls, grep, find, etc.)",guidelines:["You can inspect PI_* environment variables for current model and session details."]};function Tt(e,n){return{exec:l(async(i,d,{onData:u,signal:o,timeout:S,env:s})=>{const a=Et(S);if(o?.aborted)throw new Error("aborted");const m=n();try{await Z(d,Q.F_OK)}catch{throw new Error(`Working directory does not exist: ${d}
|
|
2
|
+
Cannot execute ${e} commands.`)}const c=m.commandTransport==="stdin",t=it(m.shell,c?m.args:[...m.args,i],{cwd:d,detached:process.platform!=="win32",env:s??G(),stdio:[c?"pipe":"ignore","pipe","pipe"],windowsHide:!0});c&&(t.stdin?.on("error",()=>{}),t.stdin?.end(i)),t.pid&&dt(t.pid);let p=!1,f;const $=l(()=>{t.pid&&H(t.pid)},"onAbort");try{a!==void 0&&(f=setTimeout(()=>{p=!0,t.pid&&H(t.pid)},a)),t.stdout?.on("data",u),t.stderr?.on("data",u),o&&(o.aborted?$():o.addEventListener("abort",$,{once:!0}));const O=await rt(t);if(o?.aborted)throw new Error("aborted");if(p)throw new Error(`timeout:${(a??X)/1e3}`);const P=t.signalCode;return{exitCode:O??(P?128+(tt.signals[P]??0):1)}}finally{t.pid&&ut(t.pid),f&&clearTimeout(f),o&&o.removeEventListener("abort",$)}},"exec")}}l(Tt,"createLocalShellOperations");function Ot(e){return Tt("bash",()=>at(e?.shellPath))}l(Ot,"createLocalBashOperations");function Pt(e,n,i,d,u){const o={...G()};if(delete o.PI_SESSION_ID,delete o.PI_SESSION_FILE,delete o.PI_PROVIDER,delete o.PI_MODEL,delete o.PI_REASONING_LEVEL,d&&u){const s=u.model;o.PI_SESSION_ID=u.sessionManager.getSessionId();const a=u.sessionManager.getSessionFile();a&&(o.PI_SESSION_FILE=a),s&&(o.PI_PROVIDER=s.provider,o.PI_MODEL=s.id),u.thinkingLevel&&(o.PI_REASONING_LEVEL=u.thinkingLevel)}const S={command:e,cwd:n,env:o};return i?i(S):S}l(Pt,"resolveSpawnContext");const Lt=5,gt=100;class xt extends et{static{l(this,"BashResultRenderComponent")}state={cachedWidth:void 0,cachedLines:void 0,cachedSkipped:void 0}}function K(e){const n=e/1e3;if(n<60)return`${n.toFixed(1)}s`;const i=Math.floor(n),d=Math.floor(i/60),u=i%60;return d<60?`${d}m ${u}s`:`${Math.floor(d/60)}h ${d%60}m ${u}s`}l(K,"formatDuration");function _t(e,n,i=!1){const d=V(e?.command),u=V(e?.description)?.trim(),o=e?.timeout,S=o?h.fg("muted",_(E(" (\u8D85\u65F6 {seconds} \u79D2)"),{seconds:o})):"";if(u){const a=h.fg("toolTitle",h.bold(u))+S;return!i||!d?a:`${a}
|
|
3
|
+
${h.fg("muted",` \u23BF ${n} ${d.trim()}`)}`}const s=d===null?mt(h):d?h.fg("dim",ft(d.replace(/\s+/g," ").trim(),42)):h.fg("dim","\u2026");return`${h.fg("toolTitle",h.bold(n))} ${s}${S}`}l(_t,"formatShellCall");function Ct(e,n,i,d,u,o,S){const s=e.state;if(e.clear(),!i.expanded&&!S){const t=U(n,d),p=ct(t),f=[];if(p>0&&f.push(_(E("{count} \u884C"),{count:p})),u!==void 0){const P=(o??Date.now())-u;if(i.isPartial||P>=100){const L=i.isPartial?E("\u5DF2\u8FD0\u884C"):E("\u8017\u65F6");f.push(`${L} ${K(P)}`)}}const $=pt(h,f);$&&e.addChild(new I($,0,0));return}let a=U(n,d).trim();const m=n.details?.truncation,c=n.details?.fullOutputPath;if(!i.isPartial&&m?.truncated&&c&&a.endsWith("]")){const t=a.lastIndexOf(`
|
|
4
4
|
|
|
5
|
-
[`);
|
|
5
|
+
[`);t!==-1&&a.slice(t).includes(c)&&(a=a.slice(0,t).trimEnd())}if(a){const t=a.split(`
|
|
6
6
|
`).map(p=>h.fg("toolOutput",p)).join(`
|
|
7
|
-
`);i.expanded?
|
|
8
|
-
${
|
|
9
|
-
${h.fg("warning",`[${
|
|
10
|
-
${h.fg("muted",`${f} ${
|
|
11
|
-
${a}`:a,$=
|
|
7
|
+
`);i.expanded?e.addChild(new I(`
|
|
8
|
+
${t}`,0,0)):e.addChild({render:l(p=>{if(s.cachedLines===void 0||s.cachedWidth!==p){const f=st(t,Lt,p);s.cachedLines=f.visualLines,s.cachedSkipped=f.skippedCount,s.cachedWidth=p}if(s.cachedSkipped&&s.cachedSkipped>0){const f=h.fg("muted",_(E("... (\u524D\u9762\u8FD8\u6709 {count} \u884C\uFF0C"),{count:s.cachedSkipped}))+` ${ot("app.tools.expand",E("\u5373\u53EF\u5C55\u5F00"))}${h.fg("muted",")")}`;return["",nt(f,p,"..."),...s.cachedLines??[]]}return["",...s.cachedLines??[]]},"render"),invalidate:l(()=>{s.cachedWidth=void 0,s.cachedLines=void 0,s.cachedSkipped=void 0},"invalidate")})}if(m?.truncated||c){const t=[];c&&t.push(_(E("\u5B8C\u6574\u8F93\u51FA\uFF1A{path}"),{path:c})),m?.truncated&&(m.truncatedBy==="lines"?t.push(_(E("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A {shown}/{total} \u884C"),{shown:m.outputLines,total:m.totalLines})):t.push(_(E("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A\u4E86 {shown} \u884C\uFF08\u4E0A\u9650 {limit}\uFF09"),{shown:m.outputLines,limit:D(m.maxBytes??N)}))),e.addChild(new I(`
|
|
9
|
+
${h.fg("warning",`[${t.join(". ")}]`)}`,0,0))}if(u!==void 0){const p=(o??Date.now())-u;if(i.isPartial||p>=100){const f=i.isPartial?E("\u5DF2\u8FD0\u884C"):E("\u8017\u65F6");e.addChild(new I(`
|
|
10
|
+
${h.fg("muted",`${f} ${K(p)}`)}`,0,0))}}}l(Ct,"rebuildBashResultRenderComponent");function It(e,n,i){const d=i?.operations??Ot({shellPath:i?.shellPath}),u=i?.commandPrefix,o=i?.exposeSessionEnvironment??!0,S=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 ${wt} lines or ${N/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:o&&n.promptGuidelines?[...n.promptGuidelines]:void 0,executionMode:"sequential",parameters:$t,constrainedSampling:{type:"json_schema",strict:"prefer"},async execute(s,{command:a,timeout:m},c,t,p){const f=u?`${u}
|
|
11
|
+
${a}`:a,$=Pt(f,p?.cwd||e,S,o,p),O=new lt({tempFilePrefix:n.tempFilePrefix});let P=!0,L,M=!1,B=0;const A=l(()=>{if(!t||!M)return;M=!1,B=Date.now();const r=O.snapshot({persistIfTruncated:!0});t({content:[{type:"text",text:r.content||""}],details:{truncation:r.truncation.truncated?r.truncation:void 0,fullOutputPath:r.fullOutputPath}})},"emitOutputUpdate"),F=l(()=>{L&&(clearTimeout(L),L=void 0)},"clearUpdateTimer"),Y=l(()=>{if(!t)return;M=!0;const r=gt-(Date.now()-B);if(r<=0){F(),A();return}L??=setTimeout(()=>{L=void 0,A()},r)},"scheduleOutputUpdate");t&&t({content:[],details:void 0});const q=l(r=>{P&&(O.append(r),Y())},"handleData"),R=l(async()=>{P=!1,O.finish(),F(),A();const r=O.snapshot({persistIfTruncated:!0});return await O.closeTempFile(),r},"finishOutput"),W=l((r,C="(no output)")=>{const w=r.truncation;let g=r.content||C,T;if(w.truncated){T={truncation:w,fullOutputPath:r.fullOutputPath};const y=w.totalLines-w.outputLines+1,x=w.totalLines;if(w.lastLinePartial){const k=D(O.getLastLineBytes());g+=`
|
|
12
12
|
|
|
13
|
-
[Showing last ${
|
|
13
|
+
[Showing last ${D(w.outputBytes)} of line ${x} (line is ${k}). Full output: ${r.fullOutputPath}]`}else w.truncatedBy==="lines"?g+=`
|
|
14
14
|
|
|
15
|
-
[Showing lines ${
|
|
15
|
+
[Showing lines ${y}-${x} of ${w.totalLines}. Full output: ${r.fullOutputPath}]`:g+=`
|
|
16
16
|
|
|
17
|
-
[Showing lines ${
|
|
17
|
+
[Showing lines ${y}-${x} of ${w.totalLines} (${D(N)} limit). Full output: ${r.fullOutputPath}]`}return{text:g,details:T}},"formatOutput"),v=l((r,C)=>`${r?`${r}
|
|
18
18
|
|
|
19
|
-
`:""}${
|
|
19
|
+
`:""}${C}`,"appendStatus");try{let r;try{r=(await d.exec($.command,$.cwd,{onData:q,signal:c,timeout:m,env:$.env})).exitCode}catch(T){const y=await R(),{text:x}=W(y,"");if(T instanceof Error&&T.message==="aborted")throw new Error(v(x,"Command aborted"));if(T instanceof Error&&T.message.startsWith("timeout:")){const k=T.message.split(":")[1];throw new Error(v(x,`Command timed out after ${k} seconds`))}throw T}const C=await R(),{text:w,details:g}=W(C);if(r===null)throw new Error(v(w,"Command terminated without an exit code"));if(r!==0)throw new Error(v(w,`Command exited with code ${r}`));return{content:[{type:"text",text:w}],details:g}}finally{F()}},renderCall(s,a,m){const c=m.state;m.executionStarted&&c.startedAt===void 0&&(c.startedAt=Date.now(),c.endedAt=void 0);const t=m.lastComponent??new I("",0,0);return t.setText(_t(s,n.prompt,m.expanded===!0)),t},renderResult(s,a,m,c){const t=c.state;t.startedAt!==void 0&&a.isPartial&&!t.interval&&(t.interval=setInterval(()=>c.invalidate(),1e3)),(!a.isPartial||c.isError)&&(t.endedAt??=Date.now(),t.interval&&(clearInterval(t.interval),t.interval=void 0));const p=c.lastComponent??new xt;return Ct(p,s,a,c.showImages,t.startedAt,t.endedAt,c.isError),p.invalidate(),p}}}l(It,"createShellToolDefinition");const bt={name:"bash",label:"bash",shellName:"bash",prompt:"$",promptSnippet:z.snippet,promptGuidelines:z.guidelines,tempFilePrefix:"pi-bash"};function vt(e,n){return It(e,bt,n)}l(vt,"createBashToolDefinition");function Kt(e,n){const i=vt(e,n),d=ht(i);return Object.assign(d,{promptSnippet:i.promptSnippet,promptGuidelines:i.promptGuidelines}),d}l(Kt,"createBashTool");export{z as bashToolSystemPromptContribution,Kt as createBashTool,vt as createBashToolDefinition,Ot as createLocalBashOperations,Tt as createLocalShellOperations,It as createShellToolDefinition};
|
package/dist/core/tools/find.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
var
|
|
2
|
-
`),
|
|
3
|
-
${
|
|
4
|
-
`)}`,
|
|
5
|
-
... (
|
|
6
|
-
${r.fg("warning"
|
|
7
|
-
`),
|
|
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&&($+=`
|
|
8
8
|
|
|
9
|
-
[${h.join(". ")}]`),
|
|
10
|
-
`);if(s!==0){const
|
|
11
|
-
`),$=
|
|
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+=`
|
|
12
12
|
|
|
13
|
-
[${
|
|
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};
|
package/dist/core/tools/grep.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
var
|
|
2
|
-
`),
|
|
3
|
-
${
|
|
4
|
-
`)}`,
|
|
5
|
-
... (
|
|
6
|
-
${f.fg("warning"
|
|
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,`
|
|
7
7
|
`).replace(/\r/g,`
|
|
8
8
|
`).split(`
|
|
9
|
-
`)}catch{t=[]}
|
|
10
|
-
`).replace(/\r/g,"").replace(/\n$/,""),{text:
|
|
11
|
-
`),p=
|
|
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+=`
|
|
12
12
|
|
|
13
|
-
[${
|
|
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};
|
package/dist/core/tools/ls.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var
|
|
2
|
-
`),
|
|
3
|
-
${
|
|
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+=`
|
|
3
|
+
${x.map(p=>o.fg("toolOutput",p)).join(`
|
|
4
4
|
`)}`,s>0&&(t+=`${o.fg("muted",`
|
|
5
|
-
... (
|
|
6
|
-
${o.fg("warning"
|
|
7
|
-
`),
|
|
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+=`
|
|
8
8
|
|
|
9
|
-
[${
|
|
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};
|
package/dist/core/tools/read.js
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
var
|
|
2
|
-
`),L=
|
|
3
|
-
${R.map(
|
|
1
|
+
var q=Object.defineProperty;var r=(e,t)=>q(e,"name",{value:t,configurable:!0});import{basename as j,dirname as G,isAbsolute as Y,relative as J,resolve as W,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=G(te()),n=J(W(t),W(e));if(n===""||n===".."||n.startsWith(`..${K}`)||Y(n))return;const i=we(n);if(i==="README.md"||i.startsWith("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(G(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(`
|
|
4
4
|
`)}`;$>0&&(g+=`${i.fg("muted",`
|
|
5
|
-
... (
|
|
6
|
-
${i.fg("warning"
|
|
7
|
-
${i.fg("warning"
|
|
8
|
-
${i.fg("warning"
|
|
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+=`
|
|
9
9
|
${b.hints.join(`
|
|
10
|
-
`)}`),
|
|
11
|
-
${
|
|
12
|
-
${b.message}`;
|
|
13
|
-
${
|
|
14
|
-
`),
|
|
15
|
-
`),E=p-
|
|
16
|
-
`);const h=
|
|
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}]
|
|
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+=`
|
|
17
17
|
|
|
18
|
-
[Showing lines ${C}-${p} of ${
|
|
18
|
+
[Showing lines ${C}-${p} of ${B}. Use offset=${v} to continue.]`:w+=`
|
|
19
19
|
|
|
20
|
-
[Showing lines ${C}-${p} of ${
|
|
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}
|
|
21
21
|
|
|
22
|
-
[${p} more lines in file. Use offset=${
|
|
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 Ge(e,t){return me(Ce(e,t))}r(Ge,"createReadTool");export{Ge as createReadTool,Ce as createReadToolDefinition,X as readToolSystemPromptContribution};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var a=Object.defineProperty;var r=(t,
|
|
2
|
-
`);const f=c();if(o.length>0&&(!f.images||!
|
|
3
|
-
`);
|
|
4
|
-
${u}`:u}return
|
|
5
|
-
`).length:0}r(
|
|
6
|
-
${t.fg("muted",i.join(" \xB7 "))}`}r(
|
|
1
|
+
var a=Object.defineProperty;var r=(t,e)=>a(t,"name",{value:e,configurable:!0});import*as m from"node:os";import{pathToFileURL as g}from"node:url";import{getCapabilities as c,getImageDimensions as y,hyperlink as h,imageFallback as d}from"@earendil-works/pi-tui";import{t as x}from"../../dal/i18n.js";import{stripAnsi as T}from"../../utils/ansi.js";import{resolvePath as k}from"../../utils/paths.js";import{sanitizeBinaryOutput as _}from"../../utils/shell.js";function $(t){if(typeof t!="string")return"";const e=m.homedir();return t.startsWith(e)?`~${t.slice(e.length)}`:t}r($,"shortenPath");function b(t,e,i){if(!c().hyperlinks)return t;const o=k(e,i);return h(t,g(o).href)}r(b,"linkPath");function z(t){return typeof t=="string"?t:t==null?"":null}r(z,"str");function I(t){return t.replace(/\t/g," ")}r(I,"replaceTabs");function R(t){return t.replace(/\r/g,"")}r(R,"normalizeDisplayText");function S(t,e){if(!t)return"";const i=t.content.filter(u=>u.type==="text"),o=t.content.filter(u=>u.type==="image");let n=i.map(u=>_(T(u.text||"")).replace(/\r/g,"")).join(`
|
|
2
|
+
`);const f=c();if(o.length>0&&(!f.images||!e)){const u=o.map(p=>{const l=p.mimeType??"image/unknown",s=p.data&&p.mimeType?y(p.data,p.mimeType)??void 0:void 0;return d(l,s)}).join(`
|
|
3
|
+
`);n=n?`${n}
|
|
4
|
+
${u}`:u}return n}r(S,"getTextOutput");function P(t){return t.fg("error",x("[\u53C2\u6570\u65E0\u6548]"))}r(P,"invalidArgText");function W(t){const e=t.trim();return e?e.split(`
|
|
5
|
+
`).length:0}r(W,"countOutputLines");function q(t,e){const i=e.filter(o=>o.length>0);return i.length===0?"":`
|
|
6
|
+
${t.fg("muted",i.join(" \xB7 "))}`}r(q,"formatCollapsedSummary");const j=["path","file_path","filePath","command","query","pattern","description","uri","name","file","goal"];function E(t,e=48){if(!t||typeof t!="object")return"";const i=t;for(const o of j){const n=i[o];if(typeof n=="string"&&n.length>0)return n.length>e?`${n.slice(0,e-1)}\u2026`:n}return""}r(E,"compactToolArgHint");function G(t){if(!t.startsWith("mcp__"))return t;const e=t.split("__");return e.length<3?t:`${e[1]}:${e.slice(2).join("__")}`}r(G,"prettyToolLabel");function H(t,e=72){return t.length<=e?t:`${t.slice(0,e-1)}\u2026`}r(H,"truncateDisplay");function K(t,e,i,o){if(t===null)return P(e);const n=t||o?.emptyFallback;return n?b(e.fg("accent",$(n)),n,i):e.fg("toolOutput","...")}r(K,"renderToolPath");export{E as compactToolArgHint,W as countOutputLines,q as formatCollapsedSummary,S as getTextOutput,P as invalidArgText,b as linkPath,R as normalizeDisplayText,G as prettyToolLabel,K as renderToolPath,I as replaceTabs,$ as shortenPath,z as str,H as truncateDisplay};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var
|
|
2
|
-
${r.fg("muted",` \u23BF ${d} ${i??""}`.trimEnd())}`:l}f(
|
|
1
|
+
var L=Object.defineProperty;var f=(n,d)=>L(n,"name",{value:d,configurable:!0});import{Container as g,Text as S,truncateToWidth as v}from"@earendil-works/pi-tui";import{fill as $,t as m}from"../../../dal/i18n.js";import{keyHint as w}from"../../../modes/interactive/components/keybinding-hints.js";import{truncateToVisualLines as A}from"../../../modes/interactive/components/visual-truncate.js";import{theme as r}from"../../../modes/interactive/theme/theme.js";import{getTextOutput as C,invalidArgText as E,str as T}from"../render-utils.js";import{DEFAULT_MAX_BYTES as x,formatSize as P}from"../truncate.js";const _=5,F=100;class k extends g{static{f(this,"BashResultRenderComponent")}state={cachedWidth:void 0,cachedLines:void 0,cachedSkipped:void 0}}function O(n){const d=n/1e3;if(d<60)return`${d.toFixed(1)}s`;const s=Math.floor(d),i=Math.floor(s/60),e=s%60;return i<60?`${i}m ${e}s`:`${Math.floor(i/60)}h ${i%60}m ${e}s`}f(O,"formatDuration");function R(n,d,s){const i=T(n?.command),e=T(n?.description)?.trim(),a=n?.timeout,t=a?r.fg("muted",$(m(" (\u8D85\u65F6 {seconds} \u79D2)"),{seconds:a})):"",c=i===null?E(r):i||r.fg("toolOutput","...");if(!e)return r.fg("toolTitle",r.bold(`${d} ${c}`))+t;const l=r.fg("toolTitle",r.bold(e))+t;return s?`${l}
|
|
2
|
+
${r.fg("muted",` \u23BF ${d} ${i??""}`.trimEnd())}`:l}f(R,"formatShellCall");function B(n,d,s,i,e,a){const t=n.state;n.clear();let c=C(d,i).trim();const l=d.details?.truncation,p=d.details?.fullOutputPath;if(!s.isPartial&&l?.truncated&&p&&c.endsWith("]")){const o=c.lastIndexOf(`
|
|
3
3
|
|
|
4
|
-
[`);o!==-1&&
|
|
5
|
-
`).map(
|
|
6
|
-
`);s.expanded?n.addChild(new
|
|
7
|
-
${o}`,0,0)):n.addChild({render:f(
|
|
8
|
-
${r.fg("warning",`[${o.join(". ")}]`)}`,0,0))}if(
|
|
9
|
-
${r.fg("muted",`${
|
|
4
|
+
[`);o!==-1&&c.slice(o).includes(p)&&(c=c.slice(0,o).trimEnd())}if(c){const o=c.split(`
|
|
5
|
+
`).map(u=>r.fg("toolOutput",u)).join(`
|
|
6
|
+
`);s.expanded?n.addChild(new S(`
|
|
7
|
+
${o}`,0,0)):n.addChild({render:f(u=>{if(t.cachedLines===void 0||t.cachedWidth!==u){const h=A(o,_,u);t.cachedLines=h.visualLines,t.cachedSkipped=h.skippedCount,t.cachedWidth=u}if(t.cachedSkipped&&t.cachedSkipped>0){const h=r.fg("muted",$(m("... (\u524D\u9762\u8FD8\u6709 {count} \u884C\uFF0C"),{count:t.cachedSkipped}))+` ${w("app.tools.expand",m("\u5373\u53EF\u5C55\u5F00"))}${r.fg("muted",")")}`;return["",v(h,u,"..."),...t.cachedLines??[]]}return["",...t.cachedLines??[]]},"render"),invalidate:f(()=>{t.cachedWidth=void 0,t.cachedLines=void 0,t.cachedSkipped=void 0},"invalidate")})}if(l?.truncated||p){const o=[];p&&o.push($(m("\u5B8C\u6574\u8F93\u51FA\uFF1A{path}"),{path:p})),l?.truncated&&(l.truncatedBy==="lines"?o.push($(m("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A {shown}/{total} \u884C"),{shown:l.outputLines,total:l.totalLines})):o.push($(m("\u5DF2\u622A\u65AD\uFF1A\u663E\u793A\u4E86 {shown} \u884C\uFF08\u4E0A\u9650 {limit}\uFF09"),{shown:l.outputLines,limit:P(l.maxBytes??x)}))),n.addChild(new S(`
|
|
8
|
+
${r.fg("warning",`[${o.join(". ")}]`)}`,0,0))}if(e!==void 0){const u=(a??Date.now())-e;if(s.isPartial||u>=100){const h=s.isPartial?m("\u5DF2\u8FD0\u884C"):m("\u8017\u65F6");n.addChild(new S(`
|
|
9
|
+
${r.fg("muted",`${h} ${O(u)}`)}`,0,0))}}}f(B,"rebuildBashResultRenderComponent");function U(n){return{renderCall(d,s,i){const e=i.state;i.executionStarted&&e.startedAt===void 0&&(e.startedAt=Date.now(),e.endedAt=void 0);const a=d,t=i.lastComponent??new S("",0,0);return t.setText(R(a,n,i.expanded===!0)),t},renderResult(d,s,i,e){const a=e.state;a.startedAt!==void 0&&s.isPartial&&!a.interval&&(a.interval=setInterval(()=>e.invalidate(),1e3)),(!s.isPartial||e.isError)&&(a.endedAt??=Date.now(),a.interval&&(clearInterval(a.interval),a.interval=void 0));const t=e.lastComponent??new k;return B(t,d,s,e.showImages,a.startedAt,a.endedAt),t.invalidate(),t}}}f(U,"createShellRenderers");export{F as BASH_UPDATE_THROTTLE_MS,U as createShellRenderers};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var
|
|
2
|
-
`),
|
|
3
|
-
${
|
|
4
|
-
`)}`,
|
|
5
|
-
... (
|
|
6
|
-
${
|
|
1
|
+
var w=Object.defineProperty;var f=(n,t)=>w(n,"name",{value:t,configurable:!0});import{Text as m}from"@earendil-works/pi-tui";import{fill as c,t as l}from"../../../dal/i18n.js";import{keyHint as $}from"../../../modes/interactive/components/keybinding-hints.js";import{getTextOutput as h,invalidArgText as L,shortenPath as A,str as g}from"../render-utils.js";import{DEFAULT_MAX_BYTES as C,formatSize as O}from"../truncate.js";function R(n,t){const o=g(n?.pattern),i=g(n?.path),e=i!==null?A(i||"."):null,s=n?.limit,a=L(t);let u=t.fg("toolTitle",t.bold("find"))+" "+(o===null?a:t.fg("accent",o||""))+t.fg("toolOutput",c(l(" \u4F4D\u4E8E {path}"),{path:e===null?a:e}));return s!==void 0&&(u+=t.fg("toolOutput",c(l(" (\u4E0A\u9650 {limit})"),{limit:s}))),u}f(R,"formatFindCall");function y(n,t,o,i){const e=h(n,i).trim();let s="";if(e){const r=e.split(`
|
|
2
|
+
`),p=t.expanded?r.length:20,x=r.slice(0,p),d=r.length-p;s+=`
|
|
3
|
+
${x.map(T=>o.fg("toolOutput",T)).join(`
|
|
4
|
+
`)}`,d>0&&(s+=`${o.fg("muted",`
|
|
5
|
+
${c(l("... (\u8FD8\u6709 {count} \u884C\uFF0C"),{count:d})}`)} ${$("app.tools.expand",l("\u5373\u53EF\u5C55\u5F00"))}${o.fg("muted",")")}`)}const a=n.details?.resultLimitReached,u=n.details?.truncation;if(a||u?.truncated){const r=[];a&&r.push(c(l("\u4E0A\u9650 {count} \u4E2A\u7ED3\u679C"),{count:a})),u?.truncated&&r.push(c(l("\u4E0A\u9650 {size}"),{size:O(u.maxBytes??C)})),s+=`
|
|
6
|
+
${o.fg("warning",c(l("[\u5DF2\u622A\u65AD\uFF1A{reasons}]"),{reasons:r.join(", ")}))}`}return s}f(y,"formatFindResult");const P={renderCall(n,t,o){const i=o.lastComponent??new m("",0,0);return i.setText(R(n,t)),i},renderResult(n,t,o,i){const e=i.lastComponent??new m("",0,0);return e.setText(y(n,t,o,i.showImages)),e}};export{P as findRenderers};
|