dal-code 1.0.18 → 1.0.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/NOTICE +13 -3
  3. package/dist/cli/args.js +21 -182
  4. package/dist/cli/auth-check.js +1 -1
  5. package/dist/cli/auth-command.js +5 -5
  6. package/dist/cli/credential-print.js +1 -1
  7. package/dist/cli/file-processor.js +5 -5
  8. package/dist/cli/list-models.js +2 -2
  9. package/dist/cli/project-trust.js +2 -2
  10. package/dist/core/event-bus.js +1 -1
  11. package/dist/core/keybindings.js +1 -1
  12. package/dist/core/model-resolver.js +1 -1
  13. package/dist/core/resource-loader.js +1 -1
  14. package/dist/core/slash-commands.js +1 -1
  15. package/dist/core/tools/bash.js +13 -13
  16. package/dist/core/tools/find.js +11 -11
  17. package/dist/core/tools/grep.js +10 -10
  18. package/dist/core/tools/ls.js +7 -7
  19. package/dist/core/tools/read.js +17 -17
  20. package/dist/core/tools/render-utils.js +6 -6
  21. package/dist/core/tools/renderers/bash.js +8 -8
  22. package/dist/core/tools/renderers/find.js +6 -6
  23. package/dist/core/tools/renderers/grep.js +6 -6
  24. package/dist/core/tools/renderers/ls.js +6 -6
  25. package/dist/core/tools/renderers/read.js +8 -8
  26. package/dist/core/tools/renderers/write.js +10 -10
  27. package/dist/core/tools/write.js +11 -11
  28. package/dist/dal/builtins.js +1 -1
  29. package/dist/dal/i18n.js +1 -1
  30. package/dist/extensions/llama/client.js +4 -4
  31. package/dist/extensions/llama/index.js +6 -6
  32. package/dist/extensions/llama/provider.js +1 -1
  33. package/dist/extensions/llama/ui.js +3 -3
  34. package/dist/main.js +4 -4
  35. package/dist/migrations.js +5 -5
  36. package/dist/modes/interactive/bug-report.js +4 -7
  37. package/dist/modes/interactive/components/assistant-message.js +2 -2
  38. package/dist/modes/interactive/components/bash-execution.js +6 -6
  39. package/dist/modes/interactive/components/bordered-loader.js +1 -1
  40. package/dist/modes/interactive/components/branch-summary-message.js +2 -2
  41. package/dist/modes/interactive/components/compaction-summary-message.js +2 -2
  42. package/dist/modes/interactive/components/config-selector.js +1 -1
  43. package/dist/modes/interactive/components/custom-entry.js +1 -1
  44. package/dist/modes/interactive/components/extension-editor.js +1 -1
  45. package/dist/modes/interactive/components/extension-input.js +2 -2
  46. package/dist/modes/interactive/components/extension-selector.js +2 -2
  47. package/dist/modes/interactive/components/first-time-setup.js +4 -6
  48. package/dist/modes/interactive/components/login-dialog.js +1 -1
  49. package/dist/modes/interactive/components/model-selector.js +2 -2
  50. package/dist/modes/interactive/components/oauth-selector.js +1 -1
  51. package/dist/modes/interactive/components/scoped-models-selector.js +1 -1
  52. package/dist/modes/interactive/components/session-selector.js +2 -2
  53. package/dist/modes/interactive/components/settings-selector.js +1 -1
  54. package/dist/modes/interactive/components/settings-submenu.js +1 -1
  55. package/dist/modes/interactive/components/show-images-selector.js +1 -1
  56. package/dist/modes/interactive/components/skill-invocation-message.js +2 -2
  57. package/dist/modes/interactive/components/status-indicator.js +1 -1
  58. package/dist/modes/interactive/components/theme-selector.js +1 -1
  59. package/dist/modes/interactive/components/thinking-selector.js +1 -1
  60. package/dist/modes/interactive/components/tool-execution.js +4 -4
  61. package/dist/modes/interactive/components/tree-selector.js +1 -1
  62. package/dist/modes/interactive/components/trust-selector.js +2 -2
  63. package/dist/modes/interactive/components/user-message-selector.js +1 -1
  64. package/dist/modes/interactive/external-editor.js +3 -3
  65. package/dist/modes/interactive/interactive-mode.js +58 -105
  66. package/dist/modes/interactive/session-share.js +2 -2
  67. package/dist/modes/interactive/theme/theme-controller.js +2 -2
  68. package/dist/modes/print-mode.js +4 -4
  69. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  70. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  71. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  72. package/dist/node_modules/@dalcode/dal-guard/src/index.js +1 -1
  73. package/dist/node_modules/@dalcode/dal-guard/src/review.js +3 -0
  74. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  75. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  76. package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
  77. package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
  78. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  79. package/dist/node_modules/@dalcode/dal-office/src/extract/pdf.js +4 -4
  80. package/dist/node_modules/@dalcode/dal-office/src/index.js +1 -1
  81. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +15 -1
  82. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  83. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +15 -1
  84. package/dist/node_modules/@dalcode/dal-plugins/package.json +3 -2
  85. package/dist/node_modules/@dalcode/dal-plugins/src/index.js +8 -8
  86. package/dist/node_modules/@dalcode/dal-plugins/src/rank.js +4 -0
  87. package/dist/node_modules/@dalcode/dal-rewind/LICENSE +21 -0
  88. package/dist/node_modules/@dalcode/dal-rewind/package.json +34 -0
  89. package/dist/node_modules/@dalcode/dal-rewind/src/commands.js +3 -0
  90. package/dist/node_modules/@dalcode/dal-rewind/src/core.js +4 -0
  91. package/dist/node_modules/@dalcode/dal-rewind/src/index.js +1 -0
  92. package/dist/node_modules/@dalcode/dal-rewind/src/state.js +1 -0
  93. package/dist/node_modules/@dalcode/dal-rewind/src/ui.js +1 -0
  94. package/dist/node_modules/@dalcode/dal-router/package.json +6 -4
  95. package/dist/node_modules/@dalcode/dal-router/src/compact-defer.js +3 -0
  96. package/dist/node_modules/@dalcode/dal-router/src/config.js +2 -2
  97. package/dist/node_modules/@dalcode/dal-router/src/index.js +4 -3
  98. package/dist/node_modules/@dalcode/dal-router/src/services.js +1 -0
  99. package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
  100. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  101. package/dist/node_modules/@dalcode/dal-subagent/src/index.js +8 -7
  102. package/dist/node_modules/@dalcode/dal-subagent/src/role-pick.js +2 -0
  103. package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
  104. package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
  105. package/dist/node_modules/@dalcode/dal-web/package.json +3 -2
  106. package/dist/node_modules/@dalcode/dal-web/src/config.js +2 -2
  107. package/dist/node_modules/@dalcode/dal-web/src/index.js +4 -4
  108. package/dist/node_modules/@dalcode/dal-web/src/providers.js +1 -1
  109. package/dist/node_modules/@dalcode/dal-web/src/search.js +5 -7
  110. package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
  111. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  112. package/dist/node_modules/@dalcode/deepailab/src/index.js +3 -3
  113. package/dist/node_modules/@earendil-works/chord/package.json +1 -1
  114. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +4 -4
  115. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  116. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  117. package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
  118. package/dist/node_modules/@earendil-works/pi-client/package.json +3 -3
  119. package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
  120. package/dist/node_modules/@earendil-works/pi-server/package.json +5 -5
  121. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/package.json +3 -3
  122. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  123. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  124. package/dist/package-manager-cli.js +72 -74
  125. package/dist/utils/changelog.js +3 -3
  126. package/dist/utils/deprecation.js +1 -1
  127. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  128. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  129. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  130. package/examples/extensions/gondolin/package-lock.json +2 -2
  131. package/examples/extensions/gondolin/package.json +1 -1
  132. package/examples/extensions/sandbox/package-lock.json +2 -2
  133. package/examples/extensions/sandbox/package.json +1 -1
  134. package/examples/extensions/with-deps/package-lock.json +2 -2
  135. package/examples/extensions/with-deps/package.json +1 -1
  136. package/examples/sdk/03-custom-prompt.ts +1 -1
  137. package/npm-shrinkwrap.json +2 -9
  138. 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 e}from"../config.js";const s=[{name:"settings",description:"Open settings menu"},{name:"extensions",description:"Enable or disable loaded extensions"},{name:"model",description:"Select model (opens selector UI)",argumentHint:"<provider/model>"},{name:"tree",description:"Navigate session tree (switch branches)"},{name:"thinking",description:"Set thinking level",argumentHint:"<level>"},{name:"scoped-models",description:"Enable/disable models for Ctrl+P cycling"},{name:"export",description:"Export session (HTML default, or specify path: .html/.jsonl)"},{name:"import",description:"Import and resume a session from a JSONL file"},{name:"share",description:"Share session as a secret GitHub gist"},{name:"bug",description:"Export a bug report (local zip) to send to support",argumentHint:"<description>"},{name:"copy",description:"Copy last agent message to clipboard"},{name:"name",description:"Set session display name"},{name:"session",description:"Show session info and stats"},{name:"map",description:"Show a compact project map"},{name:"changelog",description:"Show changelog entries"},{name:"hotkeys",description:"Show all keyboard shortcuts"},{name:"fork",description:"Create a new fork from a previous user message"},{name:"clone",description:"Duplicate the current session at the current position"},{name:"trust",description:"Save project trust decision for future sessions"},{name:"login",description:"Configure provider authentication",argumentHint:"<provider>"},{name:"logout",description:"Remove provider authentication"},{name:"new",description:"Start a new session"},{name:"compact",description:"Manually compact the session context"},{name:"resume",description:"Resume a different session"},{name:"reload",description:"Reload keybindings, extensions, skills, prompts, themes, and context files"},{name:"quit",description:`Quit ${e}`}];export{s as BUILTIN_SLASH_COMMANDS};
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};
@@ -1,19 +1,19 @@
1
- var Y=Object.defineProperty;var u=(t,n)=>Y(t,"name",{value:n,configurable:!0});import{constants as q}from"node:fs";import{access as J}from"node:fs/promises";import{constants as Q}from"node:os";import{Container as Z,Text as _,truncateToWidth as ee}from"@earendil-works/pi-tui";import{spawn as te}from"child_process";import{Type as C}from"typebox";import{keyHint as ne}from"../../modes/interactive/components/keybinding-hints.js";import{truncateToVisualLines as ie}from"../../modes/interactive/components/visual-truncate.js";import{theme as h}from"../../modes/interactive/theme/theme.js";import{waitForChildProcess as oe}from"../../utils/child-process.js";import{getShellConfig as se,getShellEnv as R,killProcessTree as W,trackDetachedChildPid as re,untrackDetachedChildPid as ae}from"../../utils/shell.js";import{OutputAccumulator as de}from"./output-accumulator.js";import{countOutputLines as le,formatCollapsedSummary as ue,getTextOutput as G,invalidArgText as ce,str as H,truncateDisplay as pe}from"./render-utils.js";import{wrapToolDefinition as me}from"./tool-definition-wrapper.js";import{DEFAULT_MAX_BYTES as A,DEFAULT_MAX_LINES as fe,formatSize as v}from"./truncate.js";const U=2147483647,he=U/1e3,V=12e4;function Se(t){if(t===void 0)return V;if(!Number.isFinite(t)||t<=0)throw new Error("Invalid timeout: must be a finite number of seconds");const n=t*1e3;if(n>U)throw new Error(`Invalid timeout: maximum is ${he} seconds`);return n}u(Se,"resolveTimeoutMs");const we=C.Object({command:C.String({description:"Shell command to execute"}),description:C.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:C.Optional(C.Number({description:"Timeout in seconds. Defaults to 120; raise it for genuinely long-running commands."}))}),j={snippet:"Execute bash commands (ls, grep, find, etc.)",guidelines:["You can inspect PI_* environment variables for current model and session details."]};function $e(t,n){return{exec:u(async(i,d,{onData:l,signal:o,timeout:w,env:s})=>{const a=Se(w);if(o?.aborted)throw new Error("aborted");const m=n();try{await J(d,q.F_OK)}catch{throw new Error(`Working directory does not exist: ${d}
2
- Cannot execute ${t} commands.`)}const c=m.commandTransport==="stdin",e=te(m.shell,c?m.args:[...m.args,i],{cwd:d,detached:process.platform!=="win32",env:s??R(),stdio:[c?"pipe":"ignore","pipe","pipe"],windowsHide:!0});c&&(e.stdin?.on("error",()=>{}),e.stdin?.end(i)),e.pid&&re(e.pid);let p=!1,f;const $=u(()=>{e.pid&&W(e.pid)},"onAbort");try{a!==void 0&&(f=setTimeout(()=>{p=!0,e.pid&&W(e.pid)},a)),e.stdout?.on("data",l),e.stderr?.on("data",l),o&&(o.aborted?$():o.addEventListener("abort",$,{once:!0}));const T=await oe(e);if(o?.aborted)throw new Error("aborted");if(p)throw new Error(`timeout:${(a??V)/1e3}`);const O=e.signalCode;return{exitCode:T??(O?128+(Q.signals[O]??0):1)}}finally{e.pid&&ae(e.pid),f&&clearTimeout(f),o&&o.removeEventListener("abort",$)}},"exec")}}u($e,"createLocalShellOperations");function Ee(t){return $e("bash",()=>se(t?.shellPath))}u(Ee,"createLocalBashOperations");function Te(t,n,i,d,l){const o={...R()};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&&l){const s=l.model;o.PI_SESSION_ID=l.sessionManager.getSessionId();const a=l.sessionManager.getSessionFile();a&&(o.PI_SESSION_FILE=a),s&&(o.PI_PROVIDER=s.provider,o.PI_MODEL=s.id),l.thinkingLevel&&(o.PI_REASONING_LEVEL=l.thinkingLevel)}const w={command:t,cwd:n,env:o};return i?i(w):w}u(Te,"resolveSpawnContext");const Oe=5,Pe=100;class ge extends Z{static{u(this,"BashResultRenderComponent")}state={cachedWidth:void 0,cachedLines:void 0,cachedSkipped:void 0}}function X(t){const n=t/1e3;if(n<60)return`${n.toFixed(1)}s`;const i=Math.floor(n),d=Math.floor(i/60),l=i%60;return d<60?`${d}m ${l}s`:`${Math.floor(d/60)}h ${d%60}m ${l}s`}u(X,"formatDuration");function xe(t,n,i=!1){const d=H(t?.command),l=H(t?.description)?.trim(),o=t?.timeout,w=o?h.fg("muted",` (timeout ${o}s)`):"";if(l){const a=h.fg("toolTitle",h.bold(l))+w;return!i||!d?a:`${a}
3
- ${h.fg("muted",` \u23BF ${n} ${d.trim()}`)}`}const s=d===null?ce(h):d?h.fg("dim",pe(d.replace(/\s+/g," ").trim(),42)):h.fg("dim","\u2026");return`${h.fg("toolTitle",h.bold(n))} ${s}${w}`}u(xe,"formatShellCall");function Le(t,n,i,d,l,o,w){const s=t.state;if(t.clear(),!i.expanded&&!w){const e=G(n,d),p=le(e),f=[];if(p>0&&f.push(`${p} lines`),l!==void 0){const O=(o??Date.now())-l;if(i.isPartial||O>=100){const P=i.isPartial?"Elapsed":"Took";f.push(`${P} ${X(O)}`)}}const $=ue(h,f);$&&t.addChild(new _($,0,0));return}let a=G(n,d).trim();const m=n.details?.truncation,c=n.details?.fullOutputPath;if(!i.isPartial&&m?.truncated&&c&&a.endsWith("]")){const e=a.lastIndexOf(`
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
- [`);e!==-1&&a.slice(e).includes(c)&&(a=a.slice(0,e).trimEnd())}if(a){const e=a.split(`
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?t.addChild(new _(`
8
- ${e}`,0,0)):t.addChild({render:u(p=>{if(s.cachedLines===void 0||s.cachedWidth!==p){const f=ie(e,Oe,p);s.cachedLines=f.visualLines,s.cachedSkipped=f.skippedCount,s.cachedWidth=p}if(s.cachedSkipped&&s.cachedSkipped>0){const f=h.fg("muted",`... (${s.cachedSkipped} earlier lines,`)+` ${ne("app.tools.expand","to expand")}${h.fg("muted",")")}`;return["",ee(f,p,"..."),...s.cachedLines??[]]}return["",...s.cachedLines??[]]},"render"),invalidate:u(()=>{s.cachedWidth=void 0,s.cachedLines=void 0,s.cachedSkipped=void 0},"invalidate")})}if(m?.truncated||c){const e=[];c&&e.push(`Full output: ${c}`),m?.truncated&&(m.truncatedBy==="lines"?e.push(`Truncated: showing ${m.outputLines} of ${m.totalLines} lines`):e.push(`Truncated: ${m.outputLines} lines shown (${v(m.maxBytes??A)} limit)`)),t.addChild(new _(`
9
- ${h.fg("warning",`[${e.join(". ")}]`)}`,0,0))}if(l!==void 0){const p=(o??Date.now())-l;if(i.isPartial||p>=100){const f=i.isPartial?"Elapsed":"Took";t.addChild(new _(`
10
- ${h.fg("muted",`${f} ${X(p)}`)}`,0,0))}}}u(Le,"rebuildBashResultRenderComponent");function _e(t,n,i){const d=i?.operations??Ee({shellPath:i?.shellPath}),l=i?.commandPrefix,o=i?.exposeSessionEnvironment??!0,w=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 ${fe} lines or ${A/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:we,constrainedSampling:{type:"json_schema",strict:"prefer"},async execute(s,{command:a,timeout:m},c,e,p){const f=l?`${l}
11
- ${a}`:a,$=Te(f,p?.cwd||t,w,o,p),T=new de({tempFilePrefix:n.tempFilePrefix});let O=!0,P,y=!1,k=0;const D=u(()=>{if(!e||!y)return;y=!1,k=Date.now();const r=T.snapshot({persistIfTruncated:!0});e({content:[{type:"text",text:r.content||""}],details:{truncation:r.truncation.truncated?r.truncation:void 0,fullOutputPath:r.fullOutputPath}})},"emitOutputUpdate"),F=u(()=>{P&&(clearTimeout(P),P=void 0)},"clearUpdateTimer"),z=u(()=>{if(!e)return;y=!0;const r=Pe-(Date.now()-k);if(r<=0){F(),D();return}P??=setTimeout(()=>{P=void 0,D()},r)},"scheduleOutputUpdate");e&&e({content:[],details:void 0});const K=u(r=>{O&&(T.append(r),z())},"handleData"),N=u(async()=>{O=!1,T.finish(),F(),D();const r=T.snapshot({persistIfTruncated:!0});return await T.closeTempFile(),r},"finishOutput"),B=u((r,L="(no output)")=>{const S=r.truncation;let g=r.content||L,E;if(S.truncated){E={truncation:S,fullOutputPath:r.fullOutputPath};const b=S.totalLines-S.outputLines+1,x=S.totalLines;if(S.lastLinePartial){const M=v(T.getLastLineBytes());g+=`
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 ${v(S.outputBytes)} of line ${x} (line is ${M}). Full output: ${r.fullOutputPath}]`}else S.truncatedBy==="lines"?g+=`
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 ${b}-${x} of ${S.totalLines}. Full output: ${r.fullOutputPath}]`:g+=`
15
+ [Showing lines ${y}-${x} of ${w.totalLines}. Full output: ${r.fullOutputPath}]`:g+=`
16
16
 
17
- [Showing lines ${b}-${x} of ${S.totalLines} (${v(A)} limit). Full output: ${r.fullOutputPath}]`}return{text:g,details:E}},"formatOutput"),I=u((r,L)=>`${r?`${r}
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
- `:""}${L}`,"appendStatus");try{let r;try{r=(await d.exec($.command,$.cwd,{onData:K,signal:c,timeout:m,env:$.env})).exitCode}catch(E){const b=await N(),{text:x}=B(b,"");if(E instanceof Error&&E.message==="aborted")throw new Error(I(x,"Command aborted"));if(E instanceof Error&&E.message.startsWith("timeout:")){const M=E.message.split(":")[1];throw new Error(I(x,`Command timed out after ${M} seconds`))}throw E}const L=await N(),{text:S,details:g}=B(L);if(r===null)throw new Error(I(S,"Command terminated without an exit code"));if(r!==0)throw new Error(I(S,`Command exited with code ${r}`));return{content:[{type:"text",text:S}],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 e=m.lastComponent??new _("",0,0);return e.setText(xe(s,n.prompt,m.expanded===!0)),e},renderResult(s,a,m,c){const e=c.state;e.startedAt!==void 0&&a.isPartial&&!e.interval&&(e.interval=setInterval(()=>c.invalidate(),1e3)),(!a.isPartial||c.isError)&&(e.endedAt??=Date.now(),e.interval&&(clearInterval(e.interval),e.interval=void 0));const p=c.lastComponent??new ge;return Le(p,s,a,c.showImages,e.startedAt,e.endedAt,c.isError),p.invalidate(),p}}}u(_e,"createShellToolDefinition");const Ce={name:"bash",label:"bash",shellName:"bash",prompt:"$",promptSnippet:j.snippet,promptGuidelines:j.guidelines,tempFilePrefix:"pi-bash"};function Ie(t,n){return _e(t,Ce,n)}u(Ie,"createBashToolDefinition");function je(t,n){const i=Ie(t,n),d=me(i);return Object.assign(d,{promptSnippet:i.promptSnippet,promptGuidelines:i.promptGuidelines}),d}u(je,"createBashTool");export{j as bashToolSystemPromptContribution,je as createBashTool,Ie as createBashToolDefinition,Ee as createLocalBashOperations,$e as createLocalShellOperations,_e as createShellToolDefinition};
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};
@@ -1,13 +1,13 @@
1
- var Q=Object.defineProperty;var m=(t,n)=>Q(t,"name",{value:n,configurable:!0});import{createInterface as V}from"node:readline";import{Text as j}from"@earendil-works/pi-tui";import{spawn as Z}from"child_process";import k from"path";import{Type as O}from"typebox";import{keyHint as tt}from"../../modes/interactive/components/keybinding-hints.js";import{ensureTool as et}from"../../utils/tools-manager.js";import{pathExists as H,resolveToCwd as nt}from"./path-utils.js";import{countOutputLines as rt,formatCollapsedSummary as it,getTextOutput as M,invalidArgText as ot,shortenPath as st,str as q}from"./render-utils.js";import{wrapToolDefinition as at}from"./tool-definition-wrapper.js";import{DEFAULT_MAX_BYTES as F,formatSize as N,truncateHead as K}from"./truncate.js";function Y(t,n,r=k){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(Y,"relativizeFindResultPath");const lt=O.Object({pattern:O.String({description:"Glob pattern to match files, e.g. '*.ts', '**/*.json', or 'src/**/*.spec.ts'"}),path:O.Optional(O.String({description:"Directory to search in (default: current directory)"})),limit:O.Optional(O.Number({description:"Maximum number of results (default: 1000)"}))}),ct={snippet:"Find files by glob pattern (respects .gitignore)",guidelines:[]},J=1e3,ut={exists:H,glob:m(()=>[],"glob")};function dt(t,n){const r=q(t?.pattern),d=q(t?.path),i=d!==null?st(d||"."):null,a=t?.limit,o=ot(n);let e=n.fg("toolTitle",n.bold("find"))+" "+(r===null?o:n.fg("accent",r||""))+n.fg("toolOutput",` in ${i===null?o:i}`);return a!==void 0&&(e+=n.fg("toolOutput",` (limit ${a})`)),e}m(dt,"formatFindCall");function pt(t,n,r,d,i){if(!n.expanded&&!i){const p=rt(M(t,d));return it(r,p>0?[`${p} lines`]:[])}const a=M(t,d).trim();let o="";if(a){const p=a.split(`
2
- `),b=n.expanded?p.length:20,c=p.slice(0,b),T=p.length-b;o+=`
3
- ${c.map(y=>r.fg("toolOutput",y)).join(`
4
- `)}`,T>0&&(o+=`${r.fg("muted",`
5
- ... (${T} more lines,`)} ${tt("app.tools.expand","to expand")}${r.fg("muted",")")}`)}const e=t.details?.resultLimitReached,R=t.details?.truncation;if(e||R?.truncated){const p=[];e&&p.push(`${e} results limit`),R?.truncated&&p.push(`${N(R.maxBytes??F)} limit`),o+=`
6
- ${r.fg("warning",`[Truncated: ${p.join(", ")}]`)}`}return o}m(pt,"formatFindResult");function ft(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 ${J} results or ${F/1024}KB (whichever is hit first).`,promptSnippet:ct.snippet,parameters:lt,async execute(d,{pattern:i,path:a,limit:o},e,R,p){return new Promise((b,c)=>{if(e?.aborted){c(new Error("Operation aborted"));return}let T=!1,y;const l=m(u=>{T||(T=!0,e?.removeEventListener("abort",I),y=void 0,u())},"settle"),I=m(()=>{y?.(),l(()=>c(new Error("Operation aborted")))},"onAbort");e?.addEventListener("abort",I,{once:!0}),(async()=>{try{const u=nt(a||".",p?.cwd||t),f=o??J,D=r??ut;if(r?.glob){if(!await D.exists(u)){l(()=>c(new Error(`Path not found: ${u}`)));return}if(e?.aborted){l(()=>c(new Error("Operation aborted")));return}const s=await D.glob(i,u,{ignore:["**/node_modules/**","**/.git/**"],limit:f});if(e?.aborted){l(()=>c(new Error("Operation aborted")));return}if(s.length===0){l(()=>b({content:[{type:"text",text:"No files found matching pattern"}],details:void 0}));return}const g=s.map(E=>Y(E,u)),S=g.length>=f,C=g.join(`
7
- `),v=K(C,{maxLines:Number.MAX_SAFE_INTEGER});let $=v.content;const x={},h=[];S&&(h.push(`${f} results limit reached`),x.resultLimitReached=f),v.truncated&&(h.push(`${N(F)} limit reached`),x.truncation=v),h.length>0&&($+=`
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(". ")}]`),l(()=>b({content:[{type:"text",text:$}],details:Object.keys(x).length>0?x:void 0}));return}const W=await et("fd");if(e?.aborted){l(()=>c(new Error("Operation aborted")));return}if(!W){l(()=>c(new Error("fd is not available and could not be downloaded")));return}const L=["--glob","--color=never","--hidden"];let z=!1;for(let s=u;;){if(await H(k.join(s,".git"))){z=!0;break}const g=k.dirname(s);if(g===s)break;s=g}z||L.push("--no-require-git"),L.push("--max-results",String(f));let A=i;i.includes("/")&&(L.push("--full-path"),!i.startsWith("/")&&!i.startsWith("**/")&&i!=="**"&&(A=`**/${i}`),process.platform==="win32"&&(A=A.replaceAll("/",String.raw`[/\\]`))),L.push("--",A,u);const w=Z(W,L,{stdio:["ignore","pipe","pipe"]}),G=V({input:w.stdout});let U="";const _=[];y=m(()=>{w.killed||w.kill()},"stopChild");const B=m(()=>{G.close()},"cleanup");w.stderr?.on("data",s=>{U+=s.toString()}),G.on("line",s=>{_.push(s)}),w.on("error",s=>{B(),l(()=>c(new Error(`Failed to run fd: ${s.message}`)))}),w.on("close",s=>{if(B(),e?.aborted){l(()=>c(new Error("Operation aborted")));return}const g=_.join(`
10
- `);if(s!==0){const P=U.trim()||`fd exited with code ${s}`;if(!g){l(()=>c(new Error(P)));return}}if(!g){l(()=>b({content:[{type:"text",text:"No files found matching pattern"}],details:void 0}));return}const S=[];for(const P of _){const X=P.replace(/\r$/,"").trim();X&&S.push(Y(X,u))}const C=S.length>=f,v=S.join(`
11
- `),$=K(v,{maxLines:Number.MAX_SAFE_INTEGER});let x=$.content;const h={},E=[];C&&(E.push(`${f} results limit reached. Use limit=${f*2} for more, or refine pattern`),h.resultLimitReached=f),$.truncated&&(E.push(`${N(F)} limit reached`),h.truncation=$),E.length>0&&(x+=`
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
- [${E.join(". ")}]`),l(()=>b({content:[{type:"text",text:x}],details:Object.keys(h).length>0?h:void 0}))})}catch(u){if(e?.aborted){l(()=>c(new Error("Operation aborted")));return}const f=u instanceof Error?u:new Error(String(u));l(()=>c(f))}})()})},renderCall(d,i,a){const o=a.lastComponent??new j("",0,0);return o.setText(dt(d,i)),o},renderResult(d,i,a,o){const e=o.lastComponent??new j("",0,0);return e.setText(pt(d,i,a,o.showImages,o.isError)),e}}}m(ft,"createFindToolDefinition");function St(t,n){return at(ft(t,n))}m(St,"createFindTool");export{St as createFindTool,ft as createFindToolDefinition,ct as findToolSystemPromptContribution,Y as relativizeFindResultPath};
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};
@@ -1,13 +1,13 @@
1
- var ft=Object.defineProperty;var o=(n,i)=>ft(n,"name",{value:i,configurable:!0});import{readFile as dt,stat as mt}from"node:fs/promises";import{createInterface as ht}from"node:readline";import{Text as nt}from"@earendil-works/pi-tui";import{spawn as gt}from"child_process";import rt from"path";import{Type as a}from"typebox";import{keyHint as xt}from"../../modes/interactive/components/keybinding-hints.js";import{ensureTool as $t}from"../../utils/tools-manager.js";import{resolveToCwd as Tt}from"./path-utils.js";import{countOutputLines as bt,formatCollapsedSummary as wt,getTextOutput as it,invalidArgText as yt,shortenPath as Lt,str as G}from"./render-utils.js";import{wrapToolDefinition as Ot}from"./tool-definition-wrapper.js";import{DEFAULT_MAX_BYTES as N,formatSize as ot,GREP_MAX_LINE_LENGTH as at,truncateHead as Et,truncateLine as st}from"./truncate.js";const St=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)"}))}),vt={snippet:"Search file contents for patterns (respects .gitignore)",guidelines:[]},ct=100,Ct={isDirectory:o(async n=>(await mt(n)).isDirectory(),"isDirectory"),readFile:o(n=>dt(n,"utf-8"),"readFile")};function Mt(n,i){const f=G(n?.pattern),d=G(n?.path),m=d!==null?Lt(d||"."):null,c=G(n?.glob),r=n?.limit,l=yt(i);let x=i.fg("toolTitle",i.bold("grep"))+" "+(f===null?l:i.fg("accent",`/${f||""}/`))+i.fg("toolOutput",` in ${m===null?l:m}`);return c&&(x+=i.fg("toolOutput",` (${c})`)),r!==void 0&&(x+=i.fg("toolOutput",` limit ${r}`)),x}o(Mt,"formatGrepCall");function _t(n,i,f,d,m){if(!i.expanded&&!m){const s=bt(it(n,d));return wt(f,s>0?[`${s} lines`]:[])}const c=it(n,d).trim();let r="";if(c){const s=c.split(`
2
- `),L=i.expanded?s.length:15,B=s.slice(0,L),M=s.length-L;r+=`
3
- ${B.map(_=>f.fg("toolOutput",_)).join(`
4
- `)}`,M>0&&(r+=`${f.fg("muted",`
5
- ... (${M} more lines,`)} ${xt("app.tools.expand","to expand")}${f.fg("muted",")")}`)}const l=n.details?.matchLimitReached,x=n.details?.truncation,y=n.details?.linesTruncated;if(l||x?.truncated||y){const s=[];l&&s.push(`${l} matches limit`),x?.truncated&&s.push(`${ot(x.maxBytes??N)} limit`),y&&s.push("some lines truncated"),r+=`
6
- ${f.fg("warning",`[Truncated: ${s.join(", ")}]`)}`}return r}o(_t,"formatGrepResult");function Dt(n,i){const f=i?.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 ${ct} matches or ${N/1024}KB (whichever is hit first). Long lines are truncated to ${at} chars.`,promptSnippet:vt.snippet,parameters:St,async execute(d,{pattern:m,path:c,glob:r,ignoreCase:l,literal:x,context:y,limit:s},L,B,M){return new Promise((_,b)=>{if(L?.aborted){b(new Error("Operation aborted"));return}let I=!1;const T=o(O=>{I||(I=!0,O())},"settle");(async()=>{try{const O=await $t("rg");if(!O){T(()=>b(new Error("ripgrep (rg) is not available and could not be downloaded")));return}const D=Tt(c||".",M?.cwd||n),U=f??Ct;let z;try{z=await U.isDirectory(D)}catch{T(()=>b(new Error(`Path not found: ${D}`)));return}const S=y&&y>0?y:0,v=Math.max(1,s??ct),H=o(e=>{if(z){const t=rt.relative(D,e);if(t&&!t.startsWith(".."))return t.replace(/\\/g,"/")}return rt.basename(e)},"formatPath"),X=new Map,lt=o(async e=>{let t=X.get(e);if(!t){try{t=(await U.readFile(e)).replace(/\r\n/g,`
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=[]}X.set(e,t)}return t},"getFileLines"),C=["--json","--line-number","--color=never","--hidden"];l&&C.push("--ignore-case"),x&&C.push("--fixed-strings"),r&&C.push("--glob",r),C.push("--",m,D);const E=gt(O,C,{stdio:["ignore","pipe","pipe"]}),j=ht({input:E.stdout});let J="",F=0,K=!1,P=!1,V=!1,W=!1;const R=[],Y=o(()=>{j.close(),L?.removeEventListener("abort",Q)},"cleanup"),q=o((e=!1)=>{E.killed||(W=e,E.kill())},"stopChild"),Q=o(()=>{V=!0,q()},"onAbort");L?.addEventListener("abort",Q,{once:!0}),E.stderr?.on("data",e=>{J+=e.toString()});const pt=o(async(e,t)=>{const p=H(e),$=await lt(e);if(!$.length)return[`${p}:${t}: (unable to read file)`];const u=[],w=S>0?Math.max(1,t-S):t,h=S>0?Math.min($.length,t+S):t;for(let g=w;g<=h;g++){const A=($[g-1]??"").replace(/\r/g,""),k=g===t,{text:et,wasTruncated:ut}=st(A);ut&&(P=!0),k?u.push(`${p}:${g}: ${et}`):u.push(`${p}-${g}- ${et}`)}return u},"formatBlock"),Z=[];j.on("line",e=>{if(!e.trim()||F>=v)return;let t;try{t=JSON.parse(e)}catch{return}if(t.type==="match"){F++;const p=t.data?.path?.text,$=t.data?.line_number,u=t.data?.lines?.text;p&&typeof $=="number"&&Z.push({filePath:p,lineNumber:$,lineText:u}),F>=v&&(K=!0,q(!0))}}),E.on("error",e=>{Y(),T(()=>b(new Error(`Failed to run ripgrep: ${e.message}`)))}),E.on("close",async e=>{if(Y(),V){T(()=>b(new Error("Operation aborted")));return}if(!W&&e!==0&&e!==1){const h=J.trim()||`ripgrep exited with code ${e}`;T(()=>b(new Error(h)));return}if(F===0){T(()=>_({content:[{type:"text",text:"No matches found"}],details:void 0}));return}for(const h of Z)if(S===0&&h.lineText!==void 0){const g=H(h.filePath),tt=h.lineText.replace(/\r\n/g,`
10
- `).replace(/\r/g,"").replace(/\n$/,""),{text:A,wasTruncated:k}=st(tt);k&&(P=!0),R.push(`${g}:${h.lineNumber}: ${A}`)}else{const g=await pt(h.filePath,h.lineNumber);R.push(...g)}const t=R.join(`
11
- `),p=Et(t,{maxLines:Number.MAX_SAFE_INTEGER});let $=p.content;const u={},w=[];K&&(w.push(`${v} matches limit reached. Use limit=${v*2} for more, or refine pattern`),u.matchLimitReached=v),p.truncated&&(w.push(`${ot(N)} limit reached`),u.truncation=p),P&&(w.push(`Some lines truncated to ${at} chars. Use read tool to see full lines`),u.linesTruncated=!0),w.length>0&&($+=`
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
- [${w.join(". ")}]`),T(()=>_({content:[{type:"text",text:$}],details:Object.keys(u).length>0?u:void 0}))})}catch(O){T(()=>b(O))}})()})},renderCall(d,m,c){const r=c.lastComponent??new nt("",0,0);return r.setText(Mt(d,m)),r},renderResult(d,m,c,r){const l=r.lastComponent??new nt("",0,0);return l.setText(_t(d,m,c,r.showImages,r.isError)),l}}}o(Dt,"createGrepToolDefinition");function jt(n,i){return Ot(Dt(n,i))}o(jt,"createGrepTool");export{jt as createGrepTool,Dt as createGrepToolDefinition,vt as grepToolSystemPromptContribution};
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};
@@ -1,9 +1,9 @@
1
- var _=Object.defineProperty;var f=(e,n)=>_(e,"name",{value:n,configurable:!0});import{readdir as A,stat as I}from"node:fs/promises";import{Text as S}from"@earendil-works/pi-tui";import k from"path";import{Type as h}from"typebox";import{keyHint as F}from"../../modes/interactive/components/keybinding-hints.js";import{pathExists as M,resolveToCwd as N}from"./path-utils.js";import{countOutputLines as U,formatCollapsedSummary as B,getTextOutput as D,renderToolPath as j,str as H}from"./render-utils.js";import{wrapToolDefinition as X}from"./tool-definition-wrapper.js";import{DEFAULT_MAX_BYTES as E,formatSize as R,truncateHead as z}from"./truncate.js";const G=h.Object({path:h.Optional(h.String({description:"Directory to list (default: current directory)"})),limit:h.Optional(h.Number({description:"Maximum number of entries to return (default: 500)"}))}),K={snippet:"List directory contents",guidelines:[]},v=500,Y={exists:M,stat:I,readdir:A};function q(e,n,o){const a=e?.limit,c=j(H(e?.path),n,o,{emptyFallback:"."});let i=`${n.fg("toolTitle",n.bold("ls"))} ${c}`;return a!==void 0&&(i+=n.fg("toolOutput",` (limit ${a})`)),i}f(q,"formatLsCall");function J(e,n,o,a,c){if(!n.expanded&&!c){const r=U(D(e,a));return B(o,r>0?[`${r} lines`]:[])}const i=D(e,a).trim();let t="";if(i){const r=i.split(`
2
- `),l=n.expanded?r.length:20,y=r.slice(0,l),s=r.length-l;t+=`
3
- ${y.map(d=>o.fg("toolOutput",d)).join(`
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
- ... (${s} more lines,`)} ${F("app.tools.expand","to expand")}${o.fg("muted",")")}`)}const u=e.details?.entryLimitReached,m=e.details?.truncation;if(u||m?.truncated){const r=[];u&&r.push(`${u} entries limit`),m?.truncated&&r.push(`${R(m.maxBytes??E)} limit`),t+=`
6
- ${o.fg("warning",`[Truncated: ${r.join(", ")}]`)}`}return t}f(J,"formatLsResult");function Q(e,n){const o=n?.operations??Y;return{name:"ls",label:"ls",description:`List directory contents. Returns entries sorted alphabetically, with '/' suffix for directories. Includes dotfiles. Output is truncated to ${v} entries or ${E/1024}KB (whichever is hit first).`,promptSnippet:K.snippet,parameters:G,async execute(a,{path:c,limit:i},t,u,m){return new Promise((r,l)=>{if(t?.aborted){l(new Error("Operation aborted"));return}const y=f(()=>l(new Error("Operation aborted")),"onAbort");t?.addEventListener("abort",y,{once:!0}),(async()=>{try{const s=N(c||".",m?.cwd||e),d=i??v;if(!await o.exists(s)){l(new Error(`Path not found: ${s}`));return}if(!(await o.stat(s)).isDirectory()){l(new Error(`Not a directory: ${s}`));return}let $;try{$=await o.readdir(s)}catch(p){l(new Error(`Cannot read directory: ${p.message}`));return}$.sort((p,T)=>p.toLowerCase().localeCompare(T.toLowerCase()));const x=[];let g=!1;for(const p of $){if(x.length>=d){g=!0;break}const T=k.join(s,p);let C="";try{(await o.stat(T)).isDirectory()&&(C="/")}catch{continue}x.push(p+C)}if(t?.removeEventListener("abort",y),x.length===0){r({content:[{type:"text",text:"(empty directory)"}],details:void 0});return}const P=x.join(`
7
- `),b=z(P,{maxLines:Number.MAX_SAFE_INTEGER});let O=b.content;const L={},w=[];g&&(w.push(`${d} entries limit reached. Use limit=${d*2} for more`),L.entryLimitReached=d),b.truncated&&(w.push(`${R(E)} limit reached`),L.truncation=b),w.length>0&&(O+=`
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
- [${w.join(". ")}]`),r({content:[{type:"text",text:O}],details:Object.keys(L).length>0?L:void 0})}catch(s){t?.removeEventListener("abort",y),l(s)}})()})},renderCall(a,c,i){const t=i.lastComponent??new S("",0,0);return t.setText(q(a,c,i.cwd)),t},renderResult(a,c,i,t){const u=t.lastComponent??new S("",0,0);return u.setText(J(a,c,i,t.showImages,t.isError)),u}}}f(Q,"createLsToolDefinition");function lt(e,n){return X(Q(e,n))}f(lt,"createLsTool");export{lt as createLsTool,Q as createLsToolDefinition,K as lsToolSystemPromptContribution};
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};
@@ -1,22 +1,22 @@
1
- var V=Object.defineProperty;var r=(e,t)=>V(e,"name",{value:t,configurable:!0});import{basename as z,dirname as B,isAbsolute as X,relative as q,resolve as j,sep as G}from"node:path";import{Text as W}from"@earendil-works/pi-tui";import{constants as Y}from"fs";import{access as J,readFile as Q}from"fs/promises";import{Type as T}from"typebox";import{getReadmePath as Z}from"../../config.js";import{keyHint as ee}from"../../modes/interactive/components/keybinding-hints.js";import{getLanguageFromPath as te,highlightCode as ne}from"../../modes/interactive/theme/theme.js";import{processImage as ie}from"../../utils/image-process.js";import{detectSupportedImageMimeTypeFromFile as oe}from"../../utils/mime.js";import{formatPathRelativeToCwdOrAbsolute as se}from"../../utils/paths.js";import{resolveReadPathAsync as re,resolveToCwd as ae}from"./path-utils.js";import{getTextOutput as le,renderToolPath as fe,replaceTabs as _,str as F}from"./render-utils.js";import{wrapToolDefinition as de}from"./tool-definition-wrapper.js";import{DEFAULT_MAX_BYTES as y,DEFAULT_MAX_LINES as K,formatSize as S,truncateHead as ce}from"./truncate.js";const ue=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"}))}),H={snippet:"Read file contents",guidelines:["Use read to examine files instead of cat or sed."]},me=new Set(["AGENTS.override.md","AGENTS.md","AGENTS.MD","CLAUDE.md","CLAUDE.MD"]),pe={readFile:r(e=>Q(e),"readFile"),access:r(e=>J(e,Y.R_OK),"access"),detectImageMimeType:oe};function D(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(D,"formatReadLineRange");function ge(e,t,n){const i=fe(F(e?.file_path??e?.path),t,n);return`${t.fg("toolTitle",t.bold("read"))} ${i}${D(e,t)}`}r(ge,"formatReadCall");function he(e){let t=e.length;for(;t>0&&e[t-1]==="";)t--;return e.slice(0,t)}r(he,"trimTrailingEmptyLines");function $e(e){if(!(!e||e.input.includes("image")))return"[Current model does not support images. The image will be omitted from this request.]"}r($e,"getNonVisionImageNote");function be(e){return e.split(G).join("/")}r(be,"toPosixPath");function Le(e){const t=B(Z()),n=q(j(t),j(e));if(n===""||n===".."||n.startsWith(`..${G}`)||X(n))return;const i=be(n);if(i==="README.md"||i.startsWith("docs/")||i.startsWith("examples/"))return{kind:"docs",label:i}}r(Le,"getPiDocsClassification");function xe(e,t){const n=F(e?.file_path??e?.path);if(!n)return;const i=ae(n,t),d=z(i);if(d==="SKILL.md")return{kind:"skill",label:z(B(i))||d};const c=Le(i);if(c)return c;if(me.has(d))return{kind:"resource",label:se(i,t)}}r(xe,"getCompactReadClassification");function we(e,t,n){return e.kind==="skill"?n.fg("customMessageLabel","\x1B[1m[skill]\x1B[22m ")+n.fg("customMessageText",e.label)+D(t,n):n.fg("toolTitle",n.bold(`read ${e.kind}`))+" "+n.fg("accent",e.label)+D(t,n)}r(we,"formatCompactReadCall");function Te(e,t,n,i,d,c,u){if(!n.expanded&&!u)return"";const f=F(e?.file_path??e?.path),a=le(t,d),l=!u&&f?te(f):void 0,N=l?ne(_(a),l):a.split(`
2
- `),L=he(N),O=n.expanded?L.length:10,R=L.slice(0,O),$=L.length-O;let g=`
3
- ${R.map(w=>l?_(w):i.fg("toolOutput",_(w))).join(`
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
- ... (${$} more lines,`)} ${ee("app.tools.expand","to expand")}${i.fg("muted",")")}`);const o=t.details?.truncation;return o?.truncated&&(o.firstLineExceedsLimit?g+=`
6
- ${i.fg("warning",`[First line exceeds ${S(o.maxBytes??y)} limit]`)}`:o.truncatedBy==="lines"?g+=`
7
- ${i.fg("warning",`[Truncated: showing ${o.outputLines} of ${o.totalLines} lines (${o.maxLines??K} line limit)]`)}`:g+=`
8
- ${i.fg("warning",`[Truncated: ${o.outputLines} lines shown (${S(o.maxBytes??y)} limit)]`)}`),g}r(Te,"formatReadResult");function ye(e,t){const n=t?.autoResizeImages??!0,i=t?.resizeOptions,d=t?.operations??pe;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 ${K} 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:H.snippet,promptGuidelines:[...H.guidelines],parameters:ue,constrainedSampling:{type:"json_schema",strict:"prefer"},async execute(c,{path:u,offset:f,limit:a},l,N,L){return new Promise((O,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 re(u,L?.cwd||e);if($||(await d.access(o),$))return;const w=d.detectImageMimeType?await d.detectImageMimeType(o):void 0;let P,v;const A=$e(L?.model);if(w){const k=await d.readFile(o),b=await ie(k,w,{autoResizeImages:n,resizeOptions:L?.model?.inputLimits?.images?.resize??i});if(b.ok){let s=`Read image file [${b.mimeType}]`;b.hints.length>0&&(s+=`
5
+ ${I(S("... (\u8FD8\u6709 {count} \u884C\uFF0C"),{count:$})}`)} ${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
- `)}`),A&&(s+=`
11
- ${A}`),P=[{type:"text",text:s},{type:"image",data:b.data,mimeType:b.mimeType}]}else{let s=`Read image file [${w}]
12
- ${b.message}`;A&&(s+=`
13
- ${A}`),P=[{type:"text",text:s}]}}else{const s=(await d.readFile(o)).toString("utf-8").split(`
14
- `),U=s.length,m=f?Math.max(0,f-1):0,C=m+1;if(m>=s.length)throw new Error(`Offset ${f} is beyond end of file (${s.length} lines total)`);let I,E;if(a!==void 0){const p=Math.min(m+a,s.length);I=s.slice(m,p).join(`
15
- `),E=p-m}else I=s.slice(m).join(`
16
- `);const h=ce(I);let x;if(h.firstLineExceedsLimit){const p=S(Buffer.byteLength(s[m],"utf-8"));x=`[Line ${C} is ${p}, exceeds ${S(y)} limit. Use bash: sed -n '${C}p' ${u} | head -c ${y}]`,v={truncation:h}}else if(h.truncated){const p=C+h.outputLines-1,M=p+1;x=h.content,h.truncatedBy==="lines"?x+=`
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 ${U}. Use offset=${M} to continue.]`:x+=`
18
+ [Showing lines ${C}-${p} of ${B}. Use offset=${v} to continue.]`:w+=`
19
19
 
20
- [Showing lines ${C}-${p} of ${U} (${S(y)} limit). Use offset=${M} to continue.]`,v={truncation:h}}else if(E!==void 0&&m+E<s.length){const p=s.length-(m+E),M=m+E+1;x=`${h.content}
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=${M} to continue.]`}else x=h.content;P=[{type:"text",text:x}]}if($)return;l?.removeEventListener("abort",g),O({content:P,details:v})}catch(o){l?.removeEventListener("abort",g),$||R(o)}})()})},renderCall(c,u,f){const a=f.lastComponent??new W("",0,0),l=f.expanded?void 0:xe(c,f.cwd);return a.setText(l?we(l,c,u):ge(c,u,f.cwd)),a},renderResult(c,u,f,a){const l=a.lastComponent??new W("",0,0);return l.setText(Te(a.args,c,u,f,a.showImages,a.cwd,a.isError)),l}}}r(ye,"createReadToolDefinition");function ze(e,t){return de(ye(e,t))}r(ze,"createReadTool");export{ze as createReadTool,ye as createReadToolDefinition,H as readToolSystemPromptContribution};
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,n)=>a(t,"name",{value:n,configurable:!0});import*as m from"node:os";import{pathToFileURL as g}from"node:url";import{getCapabilities as c,getImageDimensions as y,hyperlink as d,imageFallback as h}from"@earendil-works/pi-tui";import{stripAnsi as x}from"../../utils/ansi.js";import{resolvePath as T}from"../../utils/paths.js";import{sanitizeBinaryOutput as k}from"../../utils/shell.js";function _(t){if(typeof t!="string")return"";const n=m.homedir();return t.startsWith(n)?`~${t.slice(n.length)}`:t}r(_,"shortenPath");function $(t,n,i){if(!c().hyperlinks)return t;const o=T(n,i);return d(t,g(o).href)}r($,"linkPath");function D(t){return typeof t=="string"?t:t==null?"":null}r(D,"str");function F(t){return t.replace(/\t/g," ")}r(F,"replaceTabs");function z(t){return t.replace(/\r/g,"")}r(z,"normalizeDisplayText");function I(t,n){if(!t)return"";const i=t.content.filter(u=>u.type==="text"),o=t.content.filter(u=>u.type==="image");let e=i.map(u=>k(x(u.text||"")).replace(/\r/g,"")).join(`
2
- `);const f=c();if(o.length>0&&(!f.images||!n)){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 h(l,s)}).join(`
3
- `);e=e?`${e}
4
- ${u}`:u}return e}r(I,"getTextOutput");function b(t){return t.fg("error","[invalid arg]")}r(b,"invalidArgText");function R(t){const n=t.trim();return n?n.split(`
5
- `).length:0}r(R,"countOutputLines");function S(t,n){const i=n.filter(o=>o.length>0);return i.length===0?"":`
6
- ${t.fg("muted",i.join(" \xB7 "))}`}r(S,"formatCollapsedSummary");const P=["path","file_path","filePath","command","query","pattern","description","uri","name","file","goal"];function W(t,n=48){if(!t||typeof t!="object")return"";const i=t;for(const o of P){const e=i[o];if(typeof e=="string"&&e.length>0)return e.length>n?`${e.slice(0,n-1)}\u2026`:e}return""}r(W,"compactToolArgHint");function q(t){if(!t.startsWith("mcp__"))return t;const n=t.split("__");return n.length<3?t:`${n[1]}:${n.slice(2).join("__")}`}r(q,"prettyToolLabel");function E(t,n=72){return t.length<=n?t:`${t.slice(0,n-1)}\u2026`}r(E,"truncateDisplay");function G(t,n,i,o){if(t===null)return b(n);const e=t||o?.emptyFallback;return e?$(n.fg("accent",_(e)),e,i):n.fg("toolOutput","...")}r(G,"renderToolPath");export{W as compactToolArgHint,R as countOutputLines,S as formatCollapsedSummary,I as getTextOutput,b as invalidArgText,$ as linkPath,z as normalizeDisplayText,q as prettyToolLabel,G as renderToolPath,F as replaceTabs,_ as shortenPath,D as str,E as truncateDisplay};
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 T=Object.defineProperty;var f=(n,d)=>T(n,"name",{value:d,configurable:!0});import{Container as S,Text as p,truncateToWidth as g}from"@earendil-works/pi-tui";import{keyHint as L}from"../../../modes/interactive/components/keybinding-hints.js";import{truncateToVisualLines as v}from"../../../modes/interactive/components/visual-truncate.js";import{theme as r}from"../../../modes/interactive/theme/theme.js";import{getTextOutput as A,invalidArgText as C,str as $}from"../render-utils.js";import{DEFAULT_MAX_BYTES as w,formatSize as E}from"../truncate.js";const x=5,M=100;class k extends S{static{f(this,"BashResultRenderComponent")}state={cachedWidth:void 0,cachedLines:void 0,cachedSkipped:void 0}}function P(n){const d=n/1e3;if(d<60)return`${d.toFixed(1)}s`;const s=Math.floor(d),i=Math.floor(s/60),t=s%60;return i<60?`${i}m ${t}s`:`${Math.floor(i/60)}h ${i%60}m ${t}s`}f(P,"formatDuration");function _(n,d,s){const i=$(n?.command),t=$(n?.description)?.trim(),a=n?.timeout,e=a?r.fg("muted",` (timeout ${a}s)`):"",u=i===null?C(r):i||r.fg("toolOutput","...");if(!t)return r.fg("toolTitle",r.bold(`${d} ${u}`))+e;const l=r.fg("toolTitle",r.bold(t))+e;return s?`${l}
2
- ${r.fg("muted",` \u23BF ${d} ${i??""}`.trimEnd())}`:l}f(_,"formatShellCall");function O(n,d,s,i,t,a){const e=n.state;n.clear();let u=A(d,i).trim();const l=d.details?.truncation,h=d.details?.fullOutputPath;if(!s.isPartial&&l?.truncated&&h&&u.endsWith("]")){const o=u.lastIndexOf(`
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&&u.slice(o).includes(h)&&(u=u.slice(0,o).trimEnd())}if(u){const o=u.split(`
5
- `).map(c=>r.fg("toolOutput",c)).join(`
6
- `);s.expanded?n.addChild(new p(`
7
- ${o}`,0,0)):n.addChild({render:f(c=>{if(e.cachedLines===void 0||e.cachedWidth!==c){const m=v(o,x,c);e.cachedLines=m.visualLines,e.cachedSkipped=m.skippedCount,e.cachedWidth=c}if(e.cachedSkipped&&e.cachedSkipped>0){const m=r.fg("muted",`... (${e.cachedSkipped} earlier lines,`)+` ${L("app.tools.expand","to expand")}${r.fg("muted",")")}`;return["",g(m,c,"..."),...e.cachedLines??[]]}return["",...e.cachedLines??[]]},"render"),invalidate:f(()=>{e.cachedWidth=void 0,e.cachedLines=void 0,e.cachedSkipped=void 0},"invalidate")})}if(l?.truncated||h){const o=[];h&&o.push(`Full output: ${h}`),l?.truncated&&(l.truncatedBy==="lines"?o.push(`Truncated: showing ${l.outputLines} of ${l.totalLines} lines`):o.push(`Truncated: ${l.outputLines} lines shown (${E(l.maxBytes??w)} limit)`)),n.addChild(new p(`
8
- ${r.fg("warning",`[${o.join(". ")}]`)}`,0,0))}if(t!==void 0){const c=(a??Date.now())-t;if(s.isPartial||c>=100){const m=s.isPartial?"Elapsed":"Took";n.addChild(new p(`
9
- ${r.fg("muted",`${m} ${P(c)}`)}`,0,0))}}}f(O,"rebuildBashResultRenderComponent");function H(n){return{renderCall(d,s,i){const t=i.state;i.executionStarted&&t.startedAt===void 0&&(t.startedAt=Date.now(),t.endedAt=void 0);const a=d,e=i.lastComponent??new p("",0,0);return e.setText(_(a,n,i.expanded===!0)),e},renderResult(d,s,i,t){const a=t.state;a.startedAt!==void 0&&s.isPartial&&!a.interval&&(a.interval=setInterval(()=>t.invalidate(),1e3)),(!s.isPartial||t.isError)&&(a.endedAt??=Date.now(),a.interval&&(clearInterval(a.interval),a.interval=void 0));const e=t.lastComponent??new k;return O(e,d,s,t.showImages,a.startedAt,a.endedAt),e.invalidate(),e}}}f(H,"createShellRenderers");export{M as BASH_UPDATE_THROTTLE_MS,H as createShellRenderers};
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 x=Object.defineProperty;var u=(n,t)=>x(n,"name",{value:t,configurable:!0});import{Text as p}from"@earendil-works/pi-tui";import{keyHint as $}from"../../../modes/interactive/components/keybinding-hints.js";import{getTextOutput as T,invalidArgText as w,shortenPath as L,str as d}from"../render-utils.js";import{DEFAULT_MAX_BYTES as A,formatSize as C}from"../truncate.js";function O(n,t){const i=d(n?.pattern),o=d(n?.path),e=o!==null?L(o||"."):null,l=n?.limit,s=w(t);let a=t.fg("toolTitle",t.bold("find"))+" "+(i===null?s:t.fg("accent",i||""))+t.fg("toolOutput",` in ${e===null?s:e}`);return l!==void 0&&(a+=t.fg("toolOutput",` (limit ${l})`)),a}u(O,"formatFindCall");function R(n,t,i,o){const e=T(n,o).trim();let l="";if(e){const r=e.split(`
2
- `),c=t.expanded?r.length:20,m=r.slice(0,c),f=r.length-c;l+=`
3
- ${m.map(g=>i.fg("toolOutput",g)).join(`
4
- `)}`,f>0&&(l+=`${i.fg("muted",`
5
- ... (${f} more lines,`)} ${$("app.tools.expand","to expand")}${i.fg("muted",")")}`)}const s=n.details?.resultLimitReached,a=n.details?.truncation;if(s||a?.truncated){const r=[];s&&r.push(`${s} results limit`),a?.truncated&&r.push(`${C(a.maxBytes??A)} limit`),l+=`
6
- ${i.fg("warning",`[Truncated: ${r.join(", ")}]`)}`}return l}u(R,"formatFindResult");const B={renderCall(n,t,i){const o=i.lastComponent??new p("",0,0);return o.setText(O(n,t)),o},renderResult(n,t,i,o){const e=o.lastComponent??new p("",0,0);return e.setText(R(n,t,i,o.showImages)),e}};export{B as findRenderers};
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};