dal-code 1.0.18 → 1.0.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/CHANGELOG.md +8 -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,6 +1,6 @@
1
- var $=Object.defineProperty;var c=(t,n)=>$(t,"name",{value:n,configurable:!0});import{Text as m}from"@earendil-works/pi-tui";import{keyHint as T}from"../../../modes/interactive/components/keybinding-hints.js";import{getTextOutput as h,invalidArgText as w,shortenPath as L,str as p}from"../render-utils.js";import{DEFAULT_MAX_BYTES as O,formatSize as A}from"../truncate.js";function C(t,n){const o=p(t?.pattern),i=p(t?.path),e=i!==null?L(i||"."):null,r=p(t?.glob),s=t?.limit,a=w(n);let u=n.fg("toolTitle",n.bold("grep"))+" "+(o===null?a:n.fg("accent",`/${o||""}/`))+n.fg("toolOutput",` in ${e===null?a:e}`);return r&&(u+=n.fg("toolOutput",` (${r})`)),s!==void 0&&(u+=n.fg("toolOutput",` limit ${s}`)),u}c(C,"formatGrepCall");function R(t,n,o,i){const e=h(t,i).trim();let r="";if(e){const l=e.split(`
2
- `),f=n.expanded?l.length:15,g=l.slice(0,f),d=l.length-f;r+=`
3
- ${g.map(x=>o.fg("toolOutput",x)).join(`
4
- `)}`,d>0&&(r+=`${o.fg("muted",`
5
- ... (${d} more lines,`)} ${T("app.tools.expand","to expand")}${o.fg("muted",")")}`)}const s=t.details?.matchLimitReached,a=t.details?.truncation,u=t.details?.linesTruncated;if(s||a?.truncated||u){const l=[];s&&l.push(`${s} matches limit`),a?.truncated&&l.push(`${A(a.maxBytes??O)} limit`),u&&l.push("some lines truncated"),r+=`
6
- ${o.fg("warning",`[Truncated: ${l.join(", ")}]`)}`}return r}c(R,"formatGrepResult");const E={renderCall(t,n,o){const i=o.lastComponent??new m("",0,0);return i.setText(C(t,n)),i},renderResult(t,n,o,i){const e=i.lastComponent??new m("",0,0);return e.setText(R(t,n,o,i.showImages)),e}};export{E as grepRenderers};
1
+ var h=Object.defineProperty;var f=(t,n)=>h(t,"name",{value:n,configurable:!0});import{Text as x}from"@earendil-works/pi-tui";import{fill as p,t as l}from"../../../dal/i18n.js";import{keyHint as w}from"../../../modes/interactive/components/keybinding-hints.js";import{getTextOutput as L,invalidArgText as O,shortenPath as A,str as d}from"../render-utils.js";import{DEFAULT_MAX_BYTES as C,formatSize as R}from"../truncate.js";function b(t,n){const o=d(t?.pattern),i=d(t?.path),e=i!==null?A(i||"."):null,r=d(t?.glob),a=t?.limit,u=O(n);let c=n.fg("toolTitle",n.bold("grep"))+" "+(o===null?u:n.fg("accent",`/${o||""}/`))+n.fg("toolOutput",p(l(" \u4F4D\u4E8E {path}"),{path:e===null?u:e}));return r&&(c+=n.fg("toolOutput",` (${r})`)),a!==void 0&&(c+=n.fg("toolOutput",` limit ${a}`)),c}f(b,"formatGrepCall");function y(t,n,o,i){const e=L(t,i).trim();let r="";if(e){const s=e.split(`
2
+ `),m=n.expanded?s.length:15,T=s.slice(0,m),g=s.length-m;r+=`
3
+ ${T.map($=>o.fg("toolOutput",$)).join(`
4
+ `)}`,g>0&&(r+=`${o.fg("muted",`
5
+ ${p(l("... (\u8FD8\u6709 {count} \u884C\uFF0C"),{count:g})}`)} ${w("app.tools.expand",l("\u5373\u53EF\u5C55\u5F00"))}${o.fg("muted",")")}`)}const a=t.details?.matchLimitReached,u=t.details?.truncation,c=t.details?.linesTruncated;if(a||u?.truncated||c){const s=[];a&&s.push(p(l("\u4E0A\u9650 {count} \u5904\u5339\u914D"),{count:a})),u?.truncated&&s.push(p(l("\u4E0A\u9650 {size}"),{size:R(u.maxBytes??C)})),c&&s.push(l("\u90E8\u5206\u884C\u88AB\u622A\u65AD")),r+=`
6
+ ${o.fg("warning",p(l("[\u5DF2\u622A\u65AD\uFF1A{reasons}]"),{reasons:s.join(", ")}))}`}return r}f(y,"formatGrepResult");const P={renderCall(t,n,o){const i=o.lastComponent??new x("",0,0);return i.setText(b(t,n)),i},renderResult(t,n,o,i){const e=i.lastComponent??new x("",0,0);return e.setText(y(t,n,o,i.showImages)),e}};export{P as grepRenderers};
@@ -1,6 +1,6 @@
1
- var g=Object.defineProperty;var p=(t,n)=>g(t,"name",{value:n,configurable:!0});import{Text as c}from"@earendil-works/pi-tui";import{keyHint as x}from"../../../modes/interactive/components/keybinding-hints.js";import{getTextOutput as $,renderToolPath as T,str as y}from"../render-utils.js";import{DEFAULT_MAX_BYTES as L,formatSize as w}from"../truncate.js";function C(t,n,e){const i=t?.limit,o=T(y(t?.path),n,e,{emptyFallback:"."});let s=`${n.fg("toolTitle",n.bold("ls"))} ${o}`;return i!==void 0&&(s+=n.fg("toolOutput",` (limit ${i})`)),s}p(C,"formatLsCall");function R(t,n,e,i){const o=$(t,i).trim();let s="";if(o){const r=o.split(`
2
- `),m=n.expanded?r.length:20,f=r.slice(0,m),u=r.length-m;s+=`
3
- ${f.map(d=>e.fg("toolOutput",d)).join(`
4
- `)}`,u>0&&(s+=`${e.fg("muted",`
5
- ... (${u} more lines,`)} ${x("app.tools.expand","to expand")}${e.fg("muted",")")}`)}const l=t.details?.entryLimitReached,a=t.details?.truncation;if(l||a?.truncated){const r=[];l&&r.push(`${l} entries limit`),a?.truncated&&r.push(`${w(a.maxBytes??L)} limit`),s+=`
6
- ${e.fg("warning",`[Truncated: ${r.join(", ")}]`)}`}return s}p(R,"formatLsResult");const A={renderCall(t,n,e){const i=e.lastComponent??new c("",0,0);return i.setText(C(t,n,e.cwd)),i},renderResult(t,n,e,i){const o=i.lastComponent??new c("",0,0);return o.setText(R(t,n,e,i.showImages)),o}};export{A as lsRenderers};
1
+ var T=Object.defineProperty;var p=(t,n)=>T(t,"name",{value:n,configurable:!0});import{Text as d}from"@earendil-works/pi-tui";import{fill as a,t as l}from"../../../dal/i18n.js";import{keyHint as $}from"../../../modes/interactive/components/keybinding-hints.js";import{getTextOutput as y,renderToolPath as L,str as w}from"../render-utils.js";import{DEFAULT_MAX_BYTES as C,formatSize as R}from"../truncate.js";function h(t,n,o){const e=t?.limit,i=L(w(t?.path),n,o,{emptyFallback:"."});let s=`${n.fg("toolTitle",n.bold("ls"))} ${i}`;return e!==void 0&&(s+=n.fg("toolOutput",a(l(" (\u4E0A\u9650 {limit})"),{limit:e}))),s}p(h,"formatLsCall");function z(t,n,o,e){const i=y(t,e).trim();let s="";if(i){const r=i.split(`
2
+ `),f=n.expanded?r.length:20,g=r.slice(0,f),m=r.length-f;s+=`
3
+ ${g.map(x=>o.fg("toolOutput",x)).join(`
4
+ `)}`,m>0&&(s+=`${o.fg("muted",`
5
+ ${a(l("... (\u8FD8\u6709 {count} \u884C\uFF0C"),{count:m})}`)} ${$("app.tools.expand",l("\u5373\u53EF\u5C55\u5F00"))}${o.fg("muted",")")}`)}const u=t.details?.entryLimitReached,c=t.details?.truncation;if(u||c?.truncated){const r=[];u&&r.push(a(l("\u4E0A\u9650 {count} \u4E2A\u6761\u76EE"),{count:u})),c?.truncated&&r.push(a(l("\u4E0A\u9650 {size}"),{size:R(c.maxBytes??C)})),s+=`
6
+ ${o.fg("warning",a(l("[\u5DF2\u622A\u65AD\uFF1A{reasons}]"),{reasons:r.join(", ")}))}`}return s}p(z,"formatLsResult");const D={renderCall(t,n,o){const e=o.lastComponent??new d("",0,0);return e.setText(h(t,n,o.cwd)),e},renderResult(t,n,o,e){const i=e.lastComponent??new d("",0,0);return i.setText(z(t,n,o,e.showImages)),i}};export{D as lsRenderers};
@@ -1,8 +1,8 @@
1
- var _=Object.defineProperty;var a=(t,i)=>_(t,"name",{value:i,configurable:!0});import{basename as w,dirname as C,isAbsolute as S,relative as D,resolve as E,sep as b}from"node:path";import{Text as h}from"@earendil-works/pi-tui";import{getReadmePath as M}from"../../../config.js";import{keyHint as y,keyText as v}from"../../../modes/interactive/components/keybinding-hints.js";import{getLanguageFromPath as N,highlightCode as F}from"../../../modes/interactive/theme/theme.js";import{formatPathRelativeToCwdOrAbsolute as O}from"../../../utils/paths.js";import{resolveToCwd as U}from"../path-utils.js";import{getTextOutput as B,renderToolPath as I,replaceTabs as u,str as c}from"../render-utils.js";import{DEFAULT_MAX_BYTES as R,DEFAULT_MAX_LINES as G,formatSize as A}from"../truncate.js";const W=new Set(["AGENTS.override.md","AGENTS.md","AGENTS.MD","CLAUDE.md","CLAUDE.MD"]);function m(t,i){if(t?.offset===void 0&&t?.limit===void 0)return"";const n=t.offset??1,e=t.limit!==void 0?n+t.limit-1:"";return i.fg("warning",`:${n}${e?`-${e}`:""}`)}a(m,"formatReadLineRange");function j(t,i,n){const e=I(c(t?.file_path??t?.path),i,n);return`${i.fg("toolTitle",i.bold("read"))} ${e}${m(t,i)}`}a(j,"formatReadCall");function H(t){let i=t.length;for(;i>0&&t[i-1]==="";)i--;return t.slice(0,i)}a(H,"trimTrailingEmptyLines");function X(t){return t.split(b).join("/")}a(X,"toPosixPath");function z(t){const i=C(M()),n=D(E(i),E(t));if(n===""||n===".."||n.startsWith(`..${b}`)||S(n))return;const e=X(n);if(e==="README.md"||e.startsWith("docs/")||e.startsWith("examples/"))return{kind:"docs",label:e}}a(z,"getPiDocsClassification");function K(t,i){const n=c(t?.file_path??t?.path);if(!n)return;const e=U(n,i),o=w(e);if(o==="SKILL.md")return{kind:"skill",label:w(C(e))||o};const s=z(e);if(s)return s;if(W.has(o))return{kind:"resource",label:O(e,i)}}a(K,"getCompactReadClassification");function Y(t,i,n){const e=n.fg("dim",` (${v("app.tools.expand")} to expand)`);return t.kind==="skill"?n.fg("customMessageLabel","\x1B[1m[skill]\x1B[22m ")+n.fg("customMessageText",t.label)+m(i,n)+e:n.fg("toolTitle",n.bold(`read ${t.kind}`))+" "+n.fg("accent",t.label)+m(i,n)+e}a(Y,"formatCompactReadCall");function q(t,i,n,e,o,s,p){if(!n.expanded&&!p)return"";const g=c(t?.file_path??t?.path),L=B(i,o),d=!p&&g?N(g):void 0,P=d?F(u(L),d):L.split(`
2
- `),f=H(P),$=n.expanded?f.length:10,k=f.slice(0,$),T=f.length-$;let l=`
3
- ${k.map(x=>d?u(x):e.fg("toolOutput",u(x))).join(`
4
- `)}`;T>0&&(l+=`${e.fg("muted",`
5
- ... (${T} more lines,`)} ${y("app.tools.expand","to expand")}${e.fg("muted",")")}`);const r=i.details?.truncation;return r?.truncated&&(r.firstLineExceedsLimit?l+=`
6
- ${e.fg("warning",`[First line exceeds ${A(r.maxBytes??R)} limit]`)}`:r.truncatedBy==="lines"?l+=`
7
- ${e.fg("warning",`[Truncated: showing ${r.outputLines} of ${r.totalLines} lines (${r.maxLines??G} line limit)]`)}`:l+=`
8
- ${e.fg("warning",`[Truncated: ${r.outputLines} lines shown (${A(r.maxBytes??R)} limit)]`)}`),l}a(q,"formatReadResult");const at={renderCall(t,i,n){const e=t,o=n.lastComponent??new h("",0,0),s=n.expanded?void 0:K(e,n.cwd);return o.setText(s?Y(s,e,i):j(e,i,n.cwd)),o},renderResult(t,i,n,e){const o=e.lastComponent??new h("",0,0);return o.setText(q(e.args,t,i,n,e.showImages,e.cwd,e.isError)),o}};export{at as readRenderers};
1
+ var S=Object.defineProperty;var a=(t,i)=>S(t,"name",{value:i,configurable:!0});import{basename as E,dirname as $,isAbsolute as D,relative as M,resolve as b,sep as R}from"node:path";import{Text as A}from"@earendil-works/pi-tui";import{getReadmePath as v}from"../../../config.js";import{fill as f,t as l}from"../../../dal/i18n.js";import{keyHint as N,keyText as O}from"../../../modes/interactive/components/keybinding-hints.js";import{getLanguageFromPath as U,highlightCode as B}from"../../../modes/interactive/theme/theme.js";import{formatPathRelativeToCwdOrAbsolute as F}from"../../../utils/paths.js";import{resolveToCwd as I}from"../path-utils.js";import{getTextOutput as G,renderToolPath as W,replaceTabs as m,str as p}from"../render-utils.js";import{DEFAULT_MAX_BYTES as k,DEFAULT_MAX_LINES as j,formatSize as P}from"../truncate.js";const H=new Set(["AGENTS.override.md","AGENTS.md","AGENTS.MD","CLAUDE.md","CLAUDE.MD"]);function g(t,i){if(t?.offset===void 0&&t?.limit===void 0)return"";const e=t.offset??1,n=t.limit!==void 0?e+t.limit-1:"";return i.fg("warning",`:${e}${n?`-${n}`:""}`)}a(g,"formatReadLineRange");function X(t,i,e){const n=W(p(t?.file_path??t?.path),i,e);return`${i.fg("toolTitle",i.bold("read"))} ${n}${g(t,i)}`}a(X,"formatReadCall");function z(t){let i=t.length;for(;i>0&&t[i-1]==="";)i--;return t.slice(0,i)}a(z,"trimTrailingEmptyLines");function K(t){return t.split(R).join("/")}a(K,"toPosixPath");function Y(t){const i=$(v()),e=M(b(i),b(t));if(e===""||e===".."||e.startsWith(`..${R}`)||D(e))return;const n=K(e);if(n==="README.md"||n.startsWith("docs/")||n.startsWith("examples/"))return{kind:"docs",label:n}}a(Y,"getPiDocsClassification");function q(t,i){const e=p(t?.file_path??t?.path);if(!e)return;const n=I(e,i),o=E(n);if(o==="SKILL.md")return{kind:"skill",label:E($(n))||o};const s=Y(n);if(s)return s;if(H.has(o))return{kind:"resource",label:F(n,i)}}a(q,"getCompactReadClassification");function J(t,i,e){const n=e.fg("dim",f(l(" ({key} \u5373\u53EF\u5C55\u5F00)"),{key:O("app.tools.expand")}));return t.kind==="skill"?e.fg("customMessageLabel","\x1B[1m[skill]\x1B[22m ")+e.fg("customMessageText",t.label)+g(i,e)+n:e.fg("toolTitle",e.bold(`read ${t.kind}`))+" "+e.fg("accent",t.label)+g(i,e)+n}a(J,"formatCompactReadCall");function Q(t,i,e,n,o,s,L){if(!e.expanded&&!L)return"";const w=p(t?.file_path??t?.path),x=G(i,o),u=!L&&w?U(w):void 0,_=u?B(m(x),u):x.split(`
2
+ `),c=z(_),T=e.expanded?c.length:10,y=c.slice(0,T),C=c.length-T;let d=`
3
+ ${y.map(h=>u?m(h):n.fg("toolOutput",m(h))).join(`
4
+ `)}`;C>0&&(d+=`${n.fg("muted",`
5
+ ${f(l("... (\u8FD8\u6709 {count} \u884C\uFF0C"),{count:C})}`)} ${N("app.tools.expand",l("\u5373\u53EF\u5C55\u5F00"))}${n.fg("muted",")")}`);const r=i.details?.truncation;return r?.truncated&&(r.firstLineExceedsLimit?d+=`
6
+ ${n.fg("warning",f(l("[\u9996\u884C\u8D85\u51FA {limit} \u4E0A\u9650]"),{limit:P(r.maxBytes??k)}))}`:r.truncatedBy==="lines"?d+=`
7
+ ${n.fg("warning",f(l("[\u5DF2\u622A\u65AD\uFF1A\u663E\u793A {shown}/{total} \u884C\uFF08\u4E0A\u9650 {max} \u884C\uFF09]"),{shown:r.outputLines,total:r.totalLines,max:r.maxLines??j}))}`:d+=`
8
+ ${n.fg("warning",f(l("[\u5DF2\u622A\u65AD\uFF1A\u663E\u793A\u4E86 {shown} \u884C\uFF08\u4E0A\u9650 {limit}\uFF09]"),{shown:r.outputLines,limit:P(r.maxBytes??k)}))}`),d}a(Q,"formatReadResult");const dt={renderCall(t,i,e){const n=t,o=e.lastComponent??new A("",0,0),s=e.expanded?void 0:q(n,e.cwd);return o.setText(s?J(s,n,i):X(n,i,e.cwd)),o},renderResult(t,i,e,n){const o=n.lastComponent??new A("",0,0);return o.setText(Q(n.args,t,i,e,n.showImages,n.cwd,n.isError)),o}};export{dt as readRenderers};
@@ -1,13 +1,13 @@
1
- var W=Object.defineProperty;var s=(n,e)=>W(n,"name",{value:e,configurable:!0});import{Container as I,Text as $}from"@earendil-works/pi-tui";import{keyHint as R}from"../../../modes/interactive/components/keybinding-hints.js";import{getLanguageFromPath as x,highlightCode as p}from"../../../modes/interactive/theme/theme.js";import{normalizeDisplayText as f,renderToolPath as _,replaceTabs as m,str as h}from"../render-utils.js";class E extends ${static{s(this,"WriteCallRenderComponent")}cache;constructor(){super("",0,0)}}const b=50;function c(n,e){return p(n,e)[0]??""}s(c,"highlightSingleLine");function j(n){const e=Math.min(b,n.normalizedLines.length);if(e===0)return;const t=n.normalizedLines.slice(0,e).join(`
2
- `),i=p(t,n.lang);for(let r=0;r<e;r++)n.highlightedLines[r]=i[r]??c(n.normalizedLines[r]??"",n.lang)}s(j,"refreshWriteHighlightPrefix");function L(n,e){const t=n?x(n):void 0;if(!t)return;const i=f(e),r=m(i);return{rawPath:n,lang:t,rawContent:e,normalizedLines:r.split(`
3
- `),highlightedLines:p(r,t)}}s(L,"rebuildWriteHighlightCacheFull");function A(n,e,t){const i=e?x(e):void 0;if(!i)return;if(!n||n.lang!==i||n.rawPath!==e||!t.startsWith(n.rawContent))return L(e,t);if(t.length===n.rawContent.length)return n;const r=t.slice(n.rawContent.length),l=f(r),o=m(l);n.rawContent=t,n.normalizedLines.length===0&&(n.normalizedLines.push(""),n.highlightedLines.push(""));const u=o.split(`
4
- `),d=n.normalizedLines.length-1;n.normalizedLines[d]+=u[0],n.highlightedLines[d]=c(n.normalizedLines[d],n.lang);for(let g=1;g<u.length;g++)n.normalizedLines.push(u[g]),n.highlightedLines.push(c(u[g],n.lang));return j(n),n}s(A,"updateWriteHighlightCacheIncremental");function D(n){let e=n.length;for(;e>0&&n[e-1]==="";)e--;return n.slice(0,e)}s(D,"trimTrailingEmptyLines");function F(n,e,t,i,r){const l=h(n?.file_path??n?.path),o=h(n?.content),u=_(l,t,r);let d=`${t.fg("toolTitle",t.bold("write"))} ${u}`;if(o===null)d+=`
1
+ var I=Object.defineProperty;var s=(n,e)=>I(n,"name",{value:e,configurable:!0});import{Container as R,Text as $}from"@earendil-works/pi-tui";import{fill as _,t as c}from"../../../dal/i18n.js";import{keyHint as E}from"../../../modes/interactive/components/keybinding-hints.js";import{getLanguageFromPath as x,highlightCode as p}from"../../../modes/interactive/theme/theme.js";import{normalizeDisplayText as f,renderToolPath as b,replaceTabs as m,str as h}from"../render-utils.js";class j extends ${static{s(this,"WriteCallRenderComponent")}cache;constructor(){super("",0,0)}}const A=50;function C(n,e){return p(n,e)[0]??""}s(C,"highlightSingleLine");function D(n){const e=Math.min(A,n.normalizedLines.length);if(e===0)return;const t=n.normalizedLines.slice(0,e).join(`
2
+ `),i=p(t,n.lang);for(let r=0;r<e;r++)n.highlightedLines[r]=i[r]??C(n.normalizedLines[r]??"",n.lang)}s(D,"refreshWriteHighlightPrefix");function L(n,e){const t=n?x(n):void 0;if(!t)return;const i=f(e),r=m(i);return{rawPath:n,lang:t,rawContent:e,normalizedLines:r.split(`
3
+ `),highlightedLines:p(r,t)}}s(L,"rebuildWriteHighlightCacheFull");function F(n,e,t){const i=e?x(e):void 0;if(!i)return;if(!n||n.lang!==i||n.rawPath!==e||!t.startsWith(n.rawContent))return L(e,t);if(t.length===n.rawContent.length)return n;const r=t.slice(n.rawContent.length),l=f(r),o=m(l);n.rawContent=t,n.normalizedLines.length===0&&(n.normalizedLines.push(""),n.highlightedLines.push(""));const u=o.split(`
4
+ `),d=n.normalizedLines.length-1;n.normalizedLines[d]+=u[0],n.highlightedLines[d]=C(n.normalizedLines[d],n.lang);for(let g=1;g<u.length;g++)n.normalizedLines.push(u[g]),n.highlightedLines.push(C(u[g],n.lang));return D(n),n}s(F,"updateWriteHighlightCacheIncremental");function S(n){let e=n.length;for(;e>0&&n[e-1]==="";)e--;return n.slice(0,e)}s(S,"trimTrailingEmptyLines");function G(n,e,t,i,r){const l=h(n?.file_path??n?.path),o=h(n?.content),u=b(l,t,r);let d=`${t.fg("toolTitle",t.bold("write"))} ${u}`;if(o===null)d+=`
5
5
 
6
- ${t.fg("error","[invalid content arg - expected string]")}`;else if(o){const g=l?x(l):void 0,w=g?i?.highlightedLines??p(m(f(o)),g):f(o).split(`
7
- `),a=D(w),y=a.length,C=e.expanded?a.length:10,H=a.slice(0,C),z=a.length-C;d+=`
6
+ ${t.fg("error",c("[content \u53C2\u6570\u65E0\u6548\uFF1A\u5E94\u4E3A\u5B57\u7B26\u4E32]"))}`;else if(o){const g=l?x(l):void 0,y=g?i?.highlightedLines??p(m(f(o)),g):f(o).split(`
7
+ `),a=S(y),H=a.length,z=e.expanded?a.length:10,W=a.slice(0,z),T=a.length-z;d+=`
8
8
 
9
- ${H.map(T=>g?T:t.fg("toolOutput",m(T))).join(`
10
- `)}`,z>0&&(d+=`${t.fg("muted",`
11
- ... (${z} more lines, ${y} total,`)} ${R("app.tools.expand","to expand")}${t.fg("muted",")")}`)}return d}s(F,"formatWriteCall");function S(n,e){if(!n.isError)return;const t=n.content.filter(i=>i.type==="text").map(i=>i.text||"").join(`
9
+ ${W.map(w=>g?w:t.fg("toolOutput",m(w))).join(`
10
+ `)}`,T>0&&(d+=`${t.fg("muted",`
11
+ ${_(c("... (\u8FD8\u6709 {count} \u884C\uFF0C\u5171 {total} \u884C\uFF0C"),{count:T,total:H})}`)} ${E("app.tools.expand",c("\u5373\u53EF\u5C55\u5F00"))}${t.fg("muted",")")}`)}return d}s(G,"formatWriteCall");function N(n,e){if(!n.isError)return;const t=n.content.filter(i=>i.type==="text").map(i=>i.text||"").join(`
12
12
  `);if(t)return`
13
- ${e.fg("error",t)}`}s(S,"formatWriteResult");const M={renderCall(n,e,t){const i=n,r=h(i?.file_path??i?.path),l=h(i?.content),o=t.lastComponent??new E;return l!==null?o.cache=t.argsComplete?L(r,l):A(o.cache,r,l):o.cache=void 0,o.setText(F(i,{expanded:t.expanded,isPartial:t.isPartial},e,o.cache,t.cwd)),o},renderResult(n,e,t,i){const r=S({...n,isError:i.isError},t);if(!r){const o=i.lastComponent??new I;return o.clear(),o}const l=i.lastComponent??new $("",0,0);return l.setText(r),l}};export{M as writeRenderers};
13
+ ${e.fg("error",t)}`}s(N,"formatWriteResult");const v={renderCall(n,e,t){const i=n,r=h(i?.file_path??i?.path),l=h(i?.content),o=t.lastComponent??new j;return l!==null?o.cache=t.argsComplete?L(r,l):F(o.cache,r,l):o.cache=void 0,o.setText(G(i,{expanded:t.expanded,isPartial:t.isPartial},e,o.cache,t.cwd)),o},renderResult(n,e,t,i){const r=N({...n,isError:i.isError},t);if(!r){const o=i.lastComponent??new R;return o.clear(),o}const l=i.lastComponent??new $("",0,0);return l.setText(r),l}};export{v as writeRenderers};
@@ -1,14 +1,14 @@
1
- var I=Object.defineProperty;var a=(t,e)=>I(t,"name",{value:e,configurable:!0});import{Container as F,Text as W}from"@earendil-works/pi-tui";import{mkdir as H,writeFile as E}from"fs/promises";import{dirname as v}from"path";import{Type as L}from"typebox";import{keyHint as R}from"../../modes/interactive/components/keybinding-hints.js";import{getLanguageFromPath as x,highlightCode as g}from"../../modes/interactive/theme/theme.js";import{withFileMutationQueue as j}from"./file-mutation-queue.js";import{resolveToCwd as k}from"./path-utils.js";import{normalizeDisplayText as f,renderToolPath as A,replaceTabs as m,str as c}from"./render-utils.js";import{wrapToolDefinition as D}from"./tool-definition-wrapper.js";const P=L.Object({path:L.String({description:"Path to the file to write (relative or absolute)"}),content:L.String({description:"Content to write to the file"})}),$={snippet:"Create or overwrite files",guidelines:["Use write only for new files or complete rewrites."]},O={writeFile:a((t,e)=>E(t,e,"utf-8"),"writeFile"),mkdir:a(t=>H(t,{recursive:!0}).then(()=>{}),"mkdir")};class G extends W{static{a(this,"WriteCallRenderComponent")}cache;constructor(){super("",0,0)}}const M=50;function C(t,e){return g(t,e)[0]??""}a(C,"highlightSingleLine");function U(t){const e=Math.min(M,t.normalizedLines.length);if(e===0)return;const n=t.normalizedLines.slice(0,e).join(`
2
- `),l=g(n,t.lang);for(let o=0;o<e;o++)t.highlightedLines[o]=l[o]??C(t.normalizedLines[o]??"",t.lang)}a(U,"refreshWriteHighlightPrefix");function h(t,e){const n=t?x(t):void 0;if(!n)return;const l=f(e),o=m(l);return{rawPath:t,lang:n,rawContent:e,normalizedLines:o.split(`
3
- `),highlightedLines:g(o,n)}}a(h,"rebuildWriteHighlightCacheFull");function N(t,e,n){const l=e?x(e):void 0;if(!l)return;if(!t||t.lang!==l||t.rawPath!==e||!n.startsWith(t.rawContent))return h(e,n);if(n.length===t.rawContent.length)return t;const o=n.slice(t.rawContent.length),d=f(o),r=m(d);t.rawContent=n,t.normalizedLines.length===0&&(t.normalizedLines.push(""),t.highlightedLines.push(""));const p=r.split(`
4
- `),s=t.normalizedLines.length-1;t.normalizedLines[s]+=p[0],t.highlightedLines[s]=C(t.normalizedLines[s],t.lang);for(let i=1;i<p.length;i++)t.normalizedLines.push(p[i]),t.highlightedLines.push(C(p[i],t.lang));return U(t),t}a(N,"updateWriteHighlightCacheIncremental");function b(t){let e=t.length;for(;e>0&&t[e-1]==="";)e--;return t.slice(0,e)}a(b,"trimTrailingEmptyLines");function Q(t,e,n,l,o){const d=c(t?.file_path??t?.path),r=c(t?.content),p=A(d,n,o);let s=`${n.fg("toolTitle",n.bold("write"))} ${p}`;if(r===null)s+=`
1
+ var H=Object.defineProperty;var a=(t,e)=>H(t,"name",{value:e,configurable:!0});import{Container as E,Text as b}from"@earendil-works/pi-tui";import{mkdir as R,writeFile as j}from"fs/promises";import{dirname as k}from"path";import{Type as x}from"typebox";import{fill as S,t as g}from"../../dal/i18n.js";import{keyHint as v}from"../../modes/interactive/components/keybinding-hints.js";import{getLanguageFromPath as C,highlightCode as m}from"../../modes/interactive/theme/theme.js";import{withFileMutationQueue as A}from"./file-mutation-queue.js";import{resolveToCwd as D}from"./path-utils.js";import{normalizeDisplayText as f,renderToolPath as P,replaceTabs as c,str as h}from"./render-utils.js";import{wrapToolDefinition as O}from"./tool-definition-wrapper.js";const G=x.Object({path:x.String({description:"Path to the file to write (relative or absolute)"}),content:x.String({description:"Content to write to the file"})}),_={snippet:"Create or overwrite files",guidelines:["Use write only for new files or complete rewrites."]},M={writeFile:a((t,e)=>j(t,e,"utf-8"),"writeFile"),mkdir:a(t=>R(t,{recursive:!0}).then(()=>{}),"mkdir")};class U extends b{static{a(this,"WriteCallRenderComponent")}cache;constructor(){super("",0,0)}}const N=50;function y(t,e){return m(t,e)[0]??""}a(y,"highlightSingleLine");function Q(t){const e=Math.min(N,t.normalizedLines.length);if(e===0)return;const n=t.normalizedLines.slice(0,e).join(`
2
+ `),l=m(n,t.lang);for(let o=0;o<e;o++)t.highlightedLines[o]=l[o]??y(t.normalizedLines[o]??"",t.lang)}a(Q,"refreshWriteHighlightPrefix");function w(t,e){const n=t?C(t):void 0;if(!n)return;const l=f(e),o=c(l);return{rawPath:t,lang:n,rawContent:e,normalizedLines:o.split(`
3
+ `),highlightedLines:m(o,n)}}a(w,"rebuildWriteHighlightCacheFull");function q(t,e,n){const l=e?C(e):void 0;if(!l)return;if(!t||t.lang!==l||t.rawPath!==e||!n.startsWith(t.rawContent))return w(e,n);if(n.length===t.rawContent.length)return t;const o=n.slice(t.rawContent.length),d=f(o),r=c(d);t.rawContent=n,t.normalizedLines.length===0&&(t.normalizedLines.push(""),t.highlightedLines.push(""));const p=r.split(`
4
+ `),s=t.normalizedLines.length-1;t.normalizedLines[s]+=p[0],t.highlightedLines[s]=y(t.normalizedLines[s],t.lang);for(let i=1;i<p.length;i++)t.normalizedLines.push(p[i]),t.highlightedLines.push(y(p[i],t.lang));return Q(t),t}a(q,"updateWriteHighlightCacheIncremental");function $(t){let e=t.length;for(;e>0&&t[e-1]==="";)e--;return t.slice(0,e)}a($,"trimTrailingEmptyLines");function B(t,e,n,l,o){const d=h(t?.file_path??t?.path),r=h(t?.content),p=P(d,n,o);let s=`${n.fg("toolTitle",n.bold("write"))} ${p}`;if(r===null)s+=`
5
5
 
6
- ${n.fg("error","[invalid content arg - expected string]")}`;else if(r&&!e.expanded){const i=b(f(r).split(`
7
- `)).length;i>0&&(s+=n.fg("muted",` (${i} lines)`))}else if(r&&e.expanded){const i=d?x(d):void 0,w=i?l?.highlightedLines??g(m(f(r)),i):f(r).split(`
8
- `),u=b(w),S=u.length,y=e.expanded?u.length:10,_=u.slice(0,y),T=u.length-y;s+=`
6
+ ${n.fg("error",g("[content \u53C2\u6570\u65E0\u6548\uFF1A\u5E94\u4E3A\u5B57\u7B26\u4E32]"))}`;else if(r&&!e.expanded){const i=$(f(r).split(`
7
+ `)).length;i>0&&(s+=n.fg("muted",S(g(" ({count} \u884C)"),{count:i})))}else if(r&&e.expanded){const i=d?C(d):void 0,L=i?l?.highlightedLines??m(c(f(r)),i):f(r).split(`
8
+ `),u=$(L),I=u.length,T=e.expanded?u.length:10,F=u.slice(0,T),z=u.length-T;s+=`
9
9
 
10
- ${_.map(z=>i?z:n.fg("toolOutput",m(z))).join(`
11
- `)}`,T>0&&(s+=`${n.fg("muted",`
12
- ... (${T} more lines, ${S} total,`)} ${R("app.tools.expand","to expand")}${n.fg("muted",")")}`)}return s}a(Q,"formatWriteCall");function q(t,e){if(!t.isError)return;const n=t.content.filter(l=>l.type==="text").map(l=>l.text||"").join(`
10
+ ${F.map(W=>i?W:n.fg("toolOutput",c(W))).join(`
11
+ `)}`,z>0&&(s+=`${n.fg("muted",`
12
+ ${S(g("... (\u8FD8\u6709 {count} \u884C\uFF0C\u5171 {total} \u884C\uFF0C"),{count:z,total:I})}`)} ${v("app.tools.expand",g("\u5373\u53EF\u5C55\u5F00"))}${n.fg("muted",")")}`)}return s}a(B,"formatWriteCall");function J(t,e){if(!t.isError)return;const n=t.content.filter(l=>l.type==="text").map(l=>l.text||"").join(`
13
13
  `);if(n)return`
14
- ${e.fg("error",n)}`}a(q,"formatWriteResult");function B(t,e){const n=e?.operations??O;return{name:"write",label:"write",description:"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.",promptSnippet:$.snippet,promptGuidelines:[...$.guidelines],parameters:P,constrainedSampling:{type:"json_schema",strict:"prefer"},async execute(l,{path:o,content:d},r,p,s){const i=k(o,s?.cwd||t),w=v(i);return j(i,async()=>{const u=a(()=>{if(r?.aborted)throw new Error("Operation aborted")},"throwIfAborted");return u(),await n.mkdir(w),u(),await n.writeFile(i,d),u(),{content:[{type:"text",text:`Successfully wrote to ${o}`}],details:void 0}})},renderCall(l,o,d){const r=l,p=c(r?.file_path??r?.path),s=c(r?.content),i=d.lastComponent??new G;return s!==null?i.cache=d.argsComplete?h(p,s):N(i.cache,p,s):i.cache=void 0,i.setText(Q(r,{expanded:d.expanded,isPartial:d.isPartial},o,i.cache,d.cwd)),i},renderResult(l,o,d,r){const p=q({...l,isError:r.isError},d);if(!p){const i=r.lastComponent??new F;return i.clear(),i}const s=r.lastComponent??new W("",0,0);return s.setText(p),s}}}a(B,"createWriteToolDefinition");function ot(t,e){return D(B(t,e))}a(ot,"createWriteTool");export{ot as createWriteTool,B as createWriteToolDefinition,$ as writeToolSystemPromptContribution};
14
+ ${e.fg("error",n)}`}a(J,"formatWriteResult");function K(t,e){const n=e?.operations??M;return{name:"write",label:"write",description:"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.",promptSnippet:_.snippet,promptGuidelines:[..._.guidelines],parameters:G,constrainedSampling:{type:"json_schema",strict:"prefer"},async execute(l,{path:o,content:d},r,p,s){const i=D(o,s?.cwd||t),L=k(i);return A(i,async()=>{const u=a(()=>{if(r?.aborted)throw new Error("Operation aborted")},"throwIfAborted");return u(),await n.mkdir(L),u(),await n.writeFile(i,d),u(),{content:[{type:"text",text:`Successfully wrote to ${o}`}],details:void 0}})},renderCall(l,o,d){const r=l,p=h(r?.file_path??r?.path),s=h(r?.content),i=d.lastComponent??new U;return s!==null?i.cache=d.argsComplete?w(p,s):q(i.cache,p,s):i.cache=void 0,i.setText(B(r,{expanded:d.expanded,isPartial:d.isPartial},o,i.cache,d.cwd)),i},renderResult(l,o,d,r){const p=J({...l,isError:r.isError},d);if(!p){const i=r.lastComponent??new E;return i.clear(),i}const s=r.lastComponent??new b("",0,0);return s.setText(p),s}}}a(K,"createWriteToolDefinition");function dt(t,e){return O(K(t,e))}a(dt,"createWriteTool");export{dt as createWriteTool,K as createWriteToolDefinition,_ as writeToolSystemPromptContribution};
@@ -1,3 +1,3 @@
1
- var c=Object.defineProperty;var r=(a,e)=>c(a,"name",{value:e,configurable:!0});import{execFileSync as s}from"node:child_process";import{readFileSync as i}from"node:fs";import{createRequire as p}from"node:module";import{dirname as f,join as P}from"node:path";import{setAmbientAuthPolicy as u,setEnvApiKeyPolicy as y}from"@earendil-works/pi-ai";import{houseProvidersEnforced as m,isProviderConfigurable as T}from"../core/house-providers.js";function b(){if(!m())return;const a=r(e=>T(e),"allowed");y(a),u(a)}r(b,"applyDalEnvApiKeyPolicy");const g=["@dalcode/dal-plugins","@dalcode/deepailab","@dalcode/dal-gateway","@dalcode/dal-guard","@dalcode/dal-lsp","@dalcode/dal-subagent","@dalcode/dal-router","@dalcode/dal-mcp","@dalcode/dal-skills","@dalcode/dal-office","@dalcode/dal-web","@dalcode/dal-workflow","@dalcode/dal-tool-catalog","@dalcode/dal-halo","@dalcode/dal-lang","@dalcode/dal-bridge","@dalcode/dal-telemetry","cc-safety-net","pi-rewind"],x=new Set(["@dalcode/dal-guard","cc-safety-net"]);function h(){const a=p(import.meta.url),e=[];for(const o of g)try{const t=a.resolve(`${o}/package.json`),n=JSON.parse(i(t,"utf8"));for(const l of n.pi?.extensions??[])e.push(P(f(t),l))}catch(t){x.has(o)&&process.stderr.write(`dal: \u5B89\u5168\u6269\u5C55 ${o} \u52A0\u8F7D\u5931\u8D25\uFF0C\u5371\u9669\u547D\u4EE4\u7684\u5BA1\u6279\u95E8\u5DF2\u5931\u6548 \u2014 ${t instanceof Error?t.message:String(t)}
1
+ var c=Object.defineProperty;var r=(a,e)=>c(a,"name",{value:e,configurable:!0});import{execFileSync as s}from"node:child_process";import{readFileSync as i}from"node:fs";import{createRequire as p}from"node:module";import{dirname as f,join as P}from"node:path";import{setAmbientAuthPolicy as u,setEnvApiKeyPolicy as y}from"@earendil-works/pi-ai";import{houseProvidersEnforced as m,isProviderConfigurable as T}from"../core/house-providers.js";function b(){if(!m())return;const a=r(e=>T(e),"allowed");y(a),u(a)}r(b,"applyDalEnvApiKeyPolicy");const g=["@dalcode/dal-plugins","@dalcode/deepailab","@dalcode/dal-gateway","@dalcode/dal-guard","@dalcode/dal-lsp","@dalcode/dal-subagent","@dalcode/dal-router","@dalcode/dal-mcp","@dalcode/dal-skills","@dalcode/dal-office","@dalcode/dal-web","@dalcode/dal-workflow","@dalcode/dal-tool-catalog","@dalcode/dal-halo","@dalcode/dal-lang","@dalcode/dal-bridge","@dalcode/dal-telemetry","@dalcode/dal-rewind","cc-safety-net"],x=new Set(["@dalcode/dal-guard","cc-safety-net"]);function h(){const a=p(import.meta.url),e=[];for(const o of g)try{const t=a.resolve(`${o}/package.json`),n=JSON.parse(i(t,"utf8"));for(const l of n.pi?.extensions??[])e.push(P(f(t),l))}catch(t){x.has(o)&&process.stderr.write(`dal: \u5B89\u5168\u6269\u5C55 ${o} \u52A0\u8F7D\u5931\u8D25\uFF0C\u5371\u9669\u547D\u4EE4\u7684\u5BA1\u6279\u95E8\u5DF2\u5931\u6548 \u2014 ${t instanceof Error?t.message:String(t)}
2
2
  \u91CD\u65B0\u5B89\u88C5\u53EF\u6062\u590D\uFF1Anpm i -g dal-code@latest
3
3
  `)}return e}r(h,"bundledPackageExtensionPaths");function H(){return h()}r(H,"dalBuiltinExtensionPaths");function R(){if(!(process.platform!=="darwin"||["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy","ALL_PROXY","all_proxy"].some(e=>process.env[e])))try{const e=s("scutil",["--proxy"],{encoding:"utf8",timeout:2e3}),o=r(d=>e.match(new RegExp(`${d}\\s*:\\s*(\\S+)`))?.[1],"get"),t=r(d=>o(`${d}Enable`)==="1","enabled"),n=t("HTTPS")?`http://${o("HTTPSProxy")}:${o("HTTPSPort")}`:t("HTTP")?`http://${o("HTTPProxy")}:${o("HTTPPort")}`:void 0;if(!n||n.includes("undefined"))return;process.env.HTTPS_PROXY=n,process.env.HTTP_PROXY=n;const l=new Set((process.env.NO_PROXY??process.env.no_proxy??"").split(",").filter(Boolean));for(const d of["localhost","127.0.0.1","::1"])l.add(d);process.env.NO_PROXY=[...l].join(",")}catch{}}r(R,"applyDalSystemProxyFallback");export{g as BUNDLED_EXTENSION_PACKAGES,b as applyDalEnvApiKeyPolicy,R as applyDalSystemProxyFallback,H as dalBuiltinExtensionPaths};
package/dist/dal/i18n.js CHANGED
@@ -1 +1 @@
1
- import{getLanguage as g,hasChosenLanguage as n,setLanguage as t,t as o}from"@dalcode/dal-pi-kit";export{g as getLanguage,n as hasChosenLanguage,t as setLanguage,o as t};
1
+ var r=Object.defineProperty;var t=(g,e)=>r(g,"name",{value:e,configurable:!0});import{getLanguage as l,hasChosenLanguage as p,setLanguage as L,t as c}from"@dalcode/dal-pi-kit";function u(g,e){return g.replace(/\{(\w+)\}/g,(a,n)=>n in e?String(e[n]):a)}t(u,"fill");export{u as fill,l as getLanguage,p as hasChosenLanguage,L as setLanguage,c as t};
@@ -1,9 +1,9 @@
1
- var v=Object.defineProperty;var c=(o,e)=>v(o,"name",{value:e,configurable:!0});function w(o,e){if(typeof o!="object"||o===null)return e;const t=o.error;if(typeof t!="object"||t===null)return e;const r=t.message;return typeof r=="string"&&r?r:e}c(w,"errorMessage");function $(o){if(typeof o!="object"||o===null)return!1;const e=o;return typeof e.id=="string"&&typeof e.status?.value=="string"}c($,"isModelInfo");function y(o,e){if(!o)return()=>{};if(o.aborted)return e.abort(o.reason),()=>{};const t=c(()=>e.abort(o.reason),"abort");return o.addEventListener("abort",t,{once:!0}),()=>o.removeEventListener("abort",t)}c(y,"linkSignal");function p(o,e){return new Promise((t,r)=>{if(e?.aborted){r(e.reason??new Error("Cancelled"));return}const n=c(()=>{clearTimeout(s),r(e?.reason??new Error("Cancelled"))},"abort"),s=setTimeout(()=>{e?.removeEventListener("abort",n),t()},o);e?.addEventListener("abort",n,{once:!0})})}c(p,"sleep");function S(o){if(typeof o!="object"||o===null)return;const e=o.progress;if(typeof e!="object"||e===null)return;const t=e,r=typeof t.current=="string"?t.current:typeof t.stage=="string"?t.stage:void 0,n=Array.isArray(t.stages)?t.stages.filter(a=>typeof a=="string"):[],s=typeof t.value=="number"?Math.max(0,Math.min(1,t.value)):void 0;let i=s;if(r&&n.length>0){const a=n.indexOf(r);a>=0&&(i=(a+(s??0))/n.length)}return{message:r?`Loading ${r.replaceAll("_"," ")}`:"Loading model",ratio:i}}c(S,"parseLoadProgress");function m(o){if(typeof o!="object"||o===null)return;const e=o.progress,t=typeof e=="object"&&e!==null?e:o;let r=0,n=0;for(const s of Object.values(t)){if(typeof s!="object"||s===null)continue;const i=s;typeof i.done!="number"||typeof i.total!="number"||(r+=i.done,n+=i.total)}if(!(n<=0))return{message:"Downloading model",ratio:r/n,detail:`${g(r)} / ${g(n)}`}}c(m,"parseDownloadProgress");function g(o){if(o<1024)return`${o} B`;const e=["KiB","MiB","GiB","TiB"];let t=o/1024,r=e[0];for(let n=1;n<e.length&&t>=1024;n++)t/=1024,r=e[n];return`${t>=10?t.toFixed(1):t.toFixed(2)} ${r}`}c(g,"formatBytes");function b(o){const e=new URL(o.trim());if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error("Server URL must use http or https");return e.hash="",e.search="",e.pathname=e.pathname.replace(/\/+$/u,"").replace(/\/v1$/u,"")||"/",e.toString().replace(/\/$/u,"")}c(b,"normalizeLlamaServerUrl");function x(o){return`${b(o)}/v1`}c(x,"llamaInferenceUrl");class A{static{c(this,"LlamaClient")}serverUrl;apiKey;constructor(e,t){this.serverUrl=b(e),this.apiKey=t}async request(e,t={}){const r=new Headers(t.headers);t.body!==void 0&&r.set("Content-Type","application/json"),this.apiKey&&r.set("Authorization",`Bearer ${this.apiKey}`);const n=AbortSignal.timeout(15e3),s=t.signal?AbortSignal.any([t.signal,n]):n,i=await fetch(`${this.serverUrl}${e}`,{...t,headers:r,signal:s});let a;try{a=await i.json()}catch{a=void 0}if(!i.ok)throw new Error(w(a,`llama.cpp returned HTTP ${i.status}`));return a}async list(e={}){const t=await this.request(`/models${e.reload?"?reload=1":""}`,{signal:e.signal});if(typeof t!="object"||t===null||!Array.isArray(t.data))throw new Error("llama.cpp returned an invalid model catalog");const r=t.data;if(!r.every($))throw new Error("Server is not running in llama.cpp router mode");return r}async props(e={}){const t=e.model?`?${new URLSearchParams({model:e.model,autoload:"false"})}`:"",r=await this.request(`/props${t}`,{signal:e.signal});if(typeof r!="object"||r===null)return{};const{models_autoload:n,chat_template:s}=r;return{...typeof n=="boolean"?{models_autoload:n}:{},...typeof s=="string"?{chat_template:s}:{}}}async load(e,t){await this.request("/models/load",{method:"POST",body:JSON.stringify({model:e}),signal:t})}async unload(e,t){await this.request("/models/unload",{method:"POST",body:JSON.stringify({model:e}),signal:t})}async unloadAndWait(e,t){for(await this.unload(e,t);;){const r=(await this.list({signal:t})).find(n=>n.id===e);if(!r||r.status.value==="unloaded")return;await p(100,t)}}async download(e,t){await this.request("/models",{method:"POST",body:JSON.stringify({model:e}),signal:t})}async watch(e,t){const r=new Headers;this.apiKey&&r.set("Authorization",`Bearer ${this.apiKey}`);const n=await fetch(`${this.serverUrl}/models/sse`,{headers:r,signal:t});if(!n.ok||!n.body)throw new Error(`llama.cpp SSE returned HTTP ${n.status}`);const s=n.body.getReader(),i=new TextDecoder;let a="";for(;;){const l=await s.read();if(l.done)break;a+=i.decode(l.value,{stream:!0}).replaceAll(`\r
1
+ var S=Object.defineProperty;var c=(o,e)=>S(o,"name",{value:e,configurable:!0});import{fill as w,t as h}from"../../dal/i18n.js";function m(o,e){if(typeof o!="object"||o===null)return e;const t=o.error;if(typeof t!="object"||t===null)return e;const r=t.message;return typeof r=="string"&&r?r:e}c(m,"errorMessage");function E(o){if(typeof o!="object"||o===null)return!1;const e=o;return typeof e.id=="string"&&typeof e.status?.value=="string"}c(E,"isModelInfo");function g(o,e){if(!o)return()=>{};if(o.aborted)return e.abort(o.reason),()=>{};const t=c(()=>e.abort(o.reason),"abort");return o.addEventListener("abort",t,{once:!0}),()=>o.removeEventListener("abort",t)}c(g,"linkSignal");function y(o,e){return new Promise((t,r)=>{if(e?.aborted){r(e.reason??new Error("Cancelled"));return}const n=c(()=>{clearTimeout(s),r(e?.reason??new Error("Cancelled"))},"abort"),s=setTimeout(()=>{e?.removeEventListener("abort",n),t()},o);e?.addEventListener("abort",n,{once:!0})})}c(y,"sleep");function A(o){if(typeof o!="object"||o===null)return;const e=o.progress;if(typeof e!="object"||e===null)return;const t=e,r=typeof t.current=="string"?t.current:typeof t.stage=="string"?t.stage:void 0,n=Array.isArray(t.stages)?t.stages.filter(a=>typeof a=="string"):[],s=typeof t.value=="number"?Math.max(0,Math.min(1,t.value)):void 0;let i=s;if(r&&n.length>0){const a=n.indexOf(r);a>=0&&(i=(a+(s??0))/n.length)}return{message:r?w(h("\u6B63\u5728\u52A0\u8F7D {stage}"),{stage:r.replaceAll("_"," ")}):h("\u6B63\u5728\u52A0\u8F7D\u6A21\u578B"),ratio:i}}c(A,"parseLoadProgress");function b(o){if(typeof o!="object"||o===null)return;const e=o.progress,t=typeof e=="object"&&e!==null?e:o;let r=0,n=0;for(const s of Object.values(t)){if(typeof s!="object"||s===null)continue;const i=s;typeof i.done!="number"||typeof i.total!="number"||(r+=i.done,n+=i.total)}if(!(n<=0))return{message:h("\u6B63\u5728\u4E0B\u8F7D\u6A21\u578B"),ratio:r/n,detail:`${v(r)} / ${v(n)}`}}c(b,"parseDownloadProgress");function v(o){if(o<1024)return`${o} B`;const e=["KiB","MiB","GiB","TiB"];let t=o/1024,r=e[0];for(let n=1;n<e.length&&t>=1024;n++)t/=1024,r=e[n];return`${t>=10?t.toFixed(1):t.toFixed(2)} ${r}`}c(v,"formatBytes");function $(o){const e=new URL(o.trim());if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error("Server URL must use http or https");return e.hash="",e.search="",e.pathname=e.pathname.replace(/\/+$/u,"").replace(/\/v1$/u,"")||"/",e.toString().replace(/\/$/u,"")}c($,"normalizeLlamaServerUrl");function T(o){return`${$(o)}/v1`}c(T,"llamaInferenceUrl");class _{static{c(this,"LlamaClient")}serverUrl;apiKey;constructor(e,t){this.serverUrl=$(e),this.apiKey=t}async request(e,t={}){const r=new Headers(t.headers);t.body!==void 0&&r.set("Content-Type","application/json"),this.apiKey&&r.set("Authorization",`Bearer ${this.apiKey}`);const n=AbortSignal.timeout(15e3),s=t.signal?AbortSignal.any([t.signal,n]):n,i=await fetch(`${this.serverUrl}${e}`,{...t,headers:r,signal:s});let a;try{a=await i.json()}catch{a=void 0}if(!i.ok)throw new Error(m(a,`llama.cpp returned HTTP ${i.status}`));return a}async list(e={}){const t=await this.request(`/models${e.reload?"?reload=1":""}`,{signal:e.signal});if(typeof t!="object"||t===null||!Array.isArray(t.data))throw new Error("llama.cpp returned an invalid model catalog");const r=t.data;if(!r.every(E))throw new Error("Server is not running in llama.cpp router mode");return r}async props(e={}){const t=e.model?`?${new URLSearchParams({model:e.model,autoload:"false"})}`:"",r=await this.request(`/props${t}`,{signal:e.signal});if(typeof r!="object"||r===null)return{};const{models_autoload:n,chat_template:s}=r;return{...typeof n=="boolean"?{models_autoload:n}:{},...typeof s=="string"?{chat_template:s}:{}}}async load(e,t){await this.request("/models/load",{method:"POST",body:JSON.stringify({model:e}),signal:t})}async unload(e,t){await this.request("/models/unload",{method:"POST",body:JSON.stringify({model:e}),signal:t})}async unloadAndWait(e,t){for(await this.unload(e,t);;){const r=(await this.list({signal:t})).find(n=>n.id===e);if(!r||r.status.value==="unloaded")return;await y(100,t)}}async download(e,t){await this.request("/models",{method:"POST",body:JSON.stringify({model:e}),signal:t})}async watch(e,t){const r=new Headers;this.apiKey&&r.set("Authorization",`Bearer ${this.apiKey}`);const n=await fetch(`${this.serverUrl}/models/sse`,{headers:r,signal:t});if(!n.ok||!n.body)throw new Error(`llama.cpp SSE returned HTTP ${n.status}`);const s=n.body.getReader(),i=new TextDecoder;let a="";for(;;){const l=await s.read();if(l.done)break;a+=i.decode(l.value,{stream:!0}).replaceAll(`\r
2
2
  `,`
3
3
  `);let f=a.indexOf(`
4
4
 
5
- `);for(;f>=0;){const d=a.slice(0,f);a=a.slice(f+2);const h=d.split(`
5
+ `);for(;f>=0;){const d=a.slice(0,f);a=a.slice(f+2);const p=d.split(`
6
6
  `).filter(u=>u.startsWith("data:")).map(u=>u.slice(5).trimStart()).join(`
7
- `);if(h)try{const u=JSON.parse(h);u&&typeof u.model=="string"&&typeof u.event=="string"&&e(u)}catch{}f=a.indexOf(`
7
+ `);if(p)try{const u=JSON.parse(p);u&&typeof u.model=="string"&&typeof u.event=="string"&&e(u)}catch{}f=a.indexOf(`
8
8
 
9
- `)}}}async loadAndWait(e,t,r){const n=new AbortController,s=y(r,n);let i=!1,a;this.watch(l=>{if(l.model!==e||l.event!=="model_status"&&l.event!=="status_change")return;const f=l.data;f?.status==="loaded"&&(i=!0),f?.status==="unloaded"&&(a="Model failed to load");const d=S(l.data);d&&t(d)},n.signal).catch(()=>{});try{for(await this.load(e,r),t({message:"Loading model"});;){if(r?.aborted)throw r.reason??new Error("Cancelled");const l=(await this.list({signal:r})).find(f=>f.id===e);if(l?.status.value==="loaded")return l;if(i&&!l)return{id:e,status:{value:"loaded"}};if(l?.status.failed||a)throw new Error(l?.status.exit_code===void 0?a??"Model failed to load":`Model exited with code ${l.status.exit_code}`);await p(250,r)}}finally{s(),n.abort()}}async downloadAndWait(e,t,r){const n=new AbortController,s=y(r,n);let i=!1,a,l=!1,f=0;this.watch(d=>{if(d.model===e&&(d.event==="download_finished"&&(i=!0),d.event==="download_failed"&&(a=w(d.data,"Download failed")),d.event==="download_progress")){l=!0;const h=m(d.data);h&&t(h)}},n.signal).catch(()=>{});try{for(await this.download(e,r),t({message:"Downloading model"});;){if(r?.aborted)throw r.reason??new Error("Cancelled");if(a)throw new Error(a);const d=await this.list({signal:r});f++;const h=d.find(u=>u.id===e);if(h?.status.value==="downloading"){l=!0;const u=m(h.status.progress);u&&t(u)}else if(i||h&&(l||f>=2))return this.list({reload:!0,signal:r});await p(500,r)}}finally{s(),n.abort()}}}export{A as LlamaClient,g as formatBytes,x as llamaInferenceUrl,b as normalizeLlamaServerUrl};
9
+ `)}}}async loadAndWait(e,t,r){const n=new AbortController,s=g(r,n);let i=!1,a;this.watch(l=>{if(l.model!==e||l.event!=="model_status"&&l.event!=="status_change")return;const f=l.data;f?.status==="loaded"&&(i=!0),f?.status==="unloaded"&&(a=h("\u6A21\u578B\u52A0\u8F7D\u5931\u8D25"));const d=A(l.data);d&&t(d)},n.signal).catch(()=>{});try{for(await this.load(e,r),t({message:h("\u6B63\u5728\u52A0\u8F7D\u6A21\u578B")});;){if(r?.aborted)throw r.reason??new Error("Cancelled");const l=(await this.list({signal:r})).find(f=>f.id===e);if(l?.status.value==="loaded")return l;if(i&&!l)return{id:e,status:{value:"loaded"}};if(l?.status.failed||a)throw new Error(l?.status.exit_code===void 0?a??h("\u6A21\u578B\u52A0\u8F7D\u5931\u8D25"):w(h("\u6A21\u578B\u8FDB\u7A0B\u5DF2\u9000\u51FA\uFF0C\u9000\u51FA\u7801 {code}"),{code:l.status.exit_code}));await y(250,r)}}finally{s(),n.abort()}}async downloadAndWait(e,t,r){const n=new AbortController,s=g(r,n);let i=!1,a,l=!1,f=0;this.watch(d=>{if(d.model===e&&(d.event==="download_finished"&&(i=!0),d.event==="download_failed"&&(a=m(d.data,h("\u4E0B\u8F7D\u5931\u8D25"))),d.event==="download_progress")){l=!0;const p=b(d.data);p&&t(p)}},n.signal).catch(()=>{});try{for(await this.download(e,r),t({message:h("\u6B63\u5728\u4E0B\u8F7D\u6A21\u578B")});;){if(r?.aborted)throw r.reason??new Error("Cancelled");if(a)throw new Error(a);const d=await this.list({signal:r});f++;const p=d.find(u=>u.id===e);if(p?.status.value==="downloading"){l=!0;const u=b(p.status.progress);u&&t(u)}else if(i||p&&(l||f>=2))return this.list({reload:!0,signal:r});await y(500,r)}}finally{s(),n.abort()}}}export{_ as LlamaClient,v as formatBytes,T as llamaInferenceUrl,$ as normalizeLlamaServerUrl};
@@ -1,8 +1,8 @@
1
- var U=Object.defineProperty;var i=(a,r)=>U(a,"name",{value:r,configurable:!0});import{formatBytes as S,LlamaClient as z,normalizeLlamaServerUrl as q}from"./client.js";import{findHuggingFaceToken as _,HuggingFaceClient as F}from"./huggingface.js";import{createLlamaProvider as R,LLAMA_PROVIDER_ID as p}from"./provider.js";import{runWithProgress as $,showLlamaUi as W}from"./ui.js";function M(a){return a.status.value==="loaded"||a.status.value==="sleeping"}i(M,"modelIsLoaded");function L(a){if(!(a instanceof Error))return!1;const r=`${a.name} ${a.message}`.toLowerCase();return r.includes("fetch failed")||r.includes("timeout")||r.includes("network")}i(L,"isConnectionError");function H(a){return L(a)?"Could not connect to the server.":a instanceof Error?a.message:String(a)}i(H,"connectionErrorMessage");function O(a){const r=a.indexOf(":",a.indexOf("/")+1);return r<0?{repository:a}:{repository:a.slice(0,r),quantization:a.slice(r+1)}}i(O,"parseHuggingFaceModel");async function P(a){const r=await a.modelRegistry.getProviderAuth(p);if(!r){a.ui.notify(`Configure llama.cpp with /login ${p}`,"warning");return}const m=r.env?.LLAMA_BASE_URL,y=q(typeof m=="string"&&m?m:r.auth.baseUrl??"");return new z(y,r.auth.apiKey)}i(P,"configuredClient");function T(a){const r=R();a.registerProvider(r.provider);const m=i(async(u,n,o)=>{const s=AbortSignal.timeout(15e3),d=o??await n.list({signal:s});r.setCatalog(d,n.serverUrl);const l=await u.modelRegistry.refresh({providers:[p],allowNetwork:!0,signal:s});if(l.aborted)throw new Error("Model catalog refresh timed out.");const e=l.errors.get(p);if(e)throw e;return d},"syncCatalog"),y=i(async(u,n,o,s,d)=>{const l=s.filter(t=>t.id!==d.id&&M(t));let e=!1;if(l.length>0){const t=await n.select(`${l.length} model${l.length===1?" is":"s are"} loaded`,["Unload all and load","Keep loaded and load","Cancel"]);if(!t||t==="Cancel")return;e=t==="Unload all and load"}const c=i(async()=>{u.ui.notify("Restoring previously loaded models");for(const t of l)await o.loadAndWait(t.id,()=>{});await m(u,o)},"restoreLoaded");if(e)for(const t of l)await o.unloadAndWait(t.id);try{if((await $(n,{title:"Loading model",model:d.id,initialMessage:"Starting\u2026",cancelTitle:"Stop loading?",cancelMessage:d.id,run:i((f,w)=>o.loadAndWait(d.id,w,f),"run"),cancel:i(()=>o.unload(d.id),"cancel")})).cancelled){e&&await c();return}const g=(await m(u,o)).find(f=>f.id===d.id);u.ui.notify(g?.status.value==="loaded"?`Loaded ${d.id}`:`Load started for ${d.id}`)}catch(t){if(e)try{await c()}catch{}throw t}},"loadModel"),C=i(async(u,n,o,s)=>{await n.confirm("Unload model?",s.id)&&(await o.unloadAndWait(s.id),await m(u,o),u.ui.notify(`Unloaded ${s.id}`))},"unloadModel"),A=i(async(u,n,o)=>{const s=new F(await _()),d=await n.searchModels((g,f)=>s.search(g,f));if(!d)return;const l=O(d);n.showStatus("Loading model details",l.repository);const e=await s.details(l.repository);if(e.gated){const g=e.gated==="manual"?"Manual approval is required":"Accept the access terms";if(await n.select(`Hugging Face access required
2
- ${e.id}
1
+ var _=Object.defineProperty;var r=(t,s)=>_(t,"name",{value:s,configurable:!0});import{fill as y,t as e}from"../../dal/i18n.js";import{formatBytes as q,LlamaClient as F,normalizeLlamaServerUrl as O}from"./client.js";import{findHuggingFaceToken as S,HuggingFaceClient as W}from"./huggingface.js";import{createLlamaProvider as H,LLAMA_PROVIDER_ID as v}from"./provider.js";import{runWithProgress as E,showLlamaUi as P}from"./ui.js";function L(t){return t.status.value==="loaded"||t.status.value==="sleeping"}r(L,"modelIsLoaded");function $(t){if(!(t instanceof Error))return!1;const s=`${t.name} ${t.message}`.toLowerCase();return s.includes("fetch failed")||s.includes("timeout")||s.includes("network")}r($,"isConnectionError");function R(t){return $(t)?e("\u65E0\u6CD5\u8FDE\u63A5\u5230\u670D\u52A1\u5668\u3002"):t instanceof Error?t.message:String(t)}r(R,"connectionErrorMessage");function k(t){const s=t.indexOf(":",t.indexOf("/")+1);return s<0?{repository:t}:{repository:t.slice(0,s),quantization:t.slice(s+1)}}r(k,"parseHuggingFaceModel");async function T(t){const s=await t.modelRegistry.getProviderAuth(v);if(!s){t.ui.notify(y(e("\u8BF7\u5148\u7528 /login {provider} \u914D\u7F6E llama.cpp"),{provider:v}),"warning");return}const g=s.env?.LLAMA_BASE_URL,M=O(typeof g=="string"&&g?g:s.auth.baseUrl??"");return new F(M,s.auth.apiKey)}r(T,"configuredClient");function b(t){const s=H();t.registerProvider(s.provider);const g=r(async(m,a,o)=>{const l=AbortSignal.timeout(15e3),d=o??await a.list({signal:l});s.setCatalog(d,a.serverUrl);const c=await m.modelRegistry.refresh({providers:[v],allowNetwork:!0,signal:l});if(c.aborted)throw new Error(e("\u6A21\u578B\u76EE\u5F55\u5237\u65B0\u8D85\u65F6\u3002"));const n=c.errors.get(v);if(n)throw n;return d},"syncCatalog"),M=r(async(m,a,o,l,d)=>{const c=l.filter(i=>i.id!==d.id&&L(i));let n=!1;if(c.length>0){const i=e("\u5168\u90E8\u5378\u8F7D\u540E\u518D\u52A0\u8F7D"),p=e("\u4FDD\u7559\u5DF2\u52A0\u8F7D\u7684\uFF0C\u540C\u65F6\u52A0\u8F7D"),w=e("\u53D6\u6D88"),u=await a.select(c.length===1?e("\u5DF2\u52A0\u8F7D 1 \u4E2A\u6A21\u578B"):y(e("\u5DF2\u52A0\u8F7D {count} \u4E2A\u6A21\u578B"),{count:c.length}),[i,p,w]);if(!u||u===w)return;n=u===i}const f=r(async()=>{m.ui.notify(e("\u6B63\u5728\u6062\u590D\u4E4B\u524D\u52A0\u8F7D\u7684\u6A21\u578B"));for(const i of c)await o.loadAndWait(i.id,()=>{});await g(m,o)},"restoreLoaded");if(n)for(const i of c)await o.unloadAndWait(i.id);try{if((await E(a,{title:e("\u6B63\u5728\u52A0\u8F7D\u6A21\u578B"),model:d.id,initialMessage:e("\u6B63\u5728\u542F\u52A8\u2026"),cancelTitle:e("\u505C\u6B62\u52A0\u8F7D\uFF1F"),cancelMessage:d.id,run:r((u,h)=>o.loadAndWait(d.id,h,u),"run"),cancel:r(()=>o.unload(d.id),"cancel")})).cancelled){n&&await f();return}const w=(await g(m,o)).find(u=>u.id===d.id);m.ui.notify(w?.status.value==="loaded"?y(e("\u5DF2\u52A0\u8F7D {model}"),{model:d.id}):y(e("\u5DF2\u5F00\u59CB\u52A0\u8F7D {model}"),{model:d.id}))}catch(i){if(n)try{await f()}catch{}throw i}},"loadModel"),z=r(async(m,a,o,l)=>{await a.confirm(e("\u5378\u8F7D\u8FD9\u4E2A\u6A21\u578B\uFF1F"),l.id)&&(await o.unloadAndWait(l.id),await g(m,o),m.ui.notify(y(e("\u5DF2\u5378\u8F7D {model}"),{model:l.id})))},"unloadModel"),C=r(async(m,a,o)=>{const l=new W(await S()),d=await a.searchModels((w,u)=>l.search(w,u));if(!d)return;const c=k(d);a.showStatus(e("\u6B63\u5728\u8BFB\u53D6\u6A21\u578B\u8BE6\u60C5"),c.repository);const n=await l.details(c.repository);if(n.gated){const w=n.gated==="manual"?e("\u9700\u8981\u4EBA\u5DE5\u5BA1\u6279\uFF0C\u8BF7\u524D\u5F80"):e("\u8BF7\u5148\u63A5\u53D7\u8BBF\u95EE\u6761\u6B3E\uFF0C\u5730\u5740"),u=e("\u7EE7\u7EED\u4E0B\u8F7D");if(await a.select(`${e("\u9700\u8981 Hugging Face \u8BBF\u95EE\u6743\u9650")}
2
+ ${n.id}
3
3
 
4
- ${g} at:
5
- https://huggingface.co/${e.id}
4
+ ${w}
5
+ https://huggingface.co/${n.id}
6
6
 
7
- The llama.cpp server needs HF_TOKEN with access.`,["Continue","Back"])!=="Continue")return}let c=l.quantization;if(!c&&e.quantizations.length>0){const g=e.quantizations.map(w=>{const v=[w.size===void 0?void 0:S(w.size),w.name==="Q4_K_M"?"recommended":void 0].filter(E=>!!E).join(" \xB7 ");return v?`${w.name} \xB7 ${v}`:w.name}),f=await n.select(`Select quantization
8
- ${e.id}`,g);if(!f||(c=e.quantizations[g.indexOf(f)]?.name,!c))return}const t=c?`${e.id}:${c}`:e.id,h=await $(n,{title:"Downloading model",model:t,initialMessage:"Starting\u2026",cancelTitle:"Stop download?",cancelMessage:t,run:i((g,f)=>o.downloadAndWait(t,f,g),"run"),cancel:i(()=>o.unload(t),"cancel")});h.cancelled||(await m(u,o,h.value),u.ui.notify(`Downloaded ${t}`))},"downloadModel");a.registerCommand("llama",{description:"Manage llama.cpp router models",handler:i(async(u,n)=>{if(n.mode!=="tui"){n.ui.notify("/llama is available in interactive mode","warning");return}const o=await P(n);o&&await W(n,async s=>{const d=i(async()=>{for(;;)try{return await m(n,o)}catch(e){if(await s.connectionError(o.serverUrl,H(e))==="close")return}},"readCatalog");let l=await d();if(l)for(;;){const e=await s.showModels(o.serverUrl,l);if(e.type==="close")return;let c;try{e.type==="download"?await A(n,s,o):M(e.model)?await C(n,s,o,e.model):e.model.status.value==="unloaded"?await y(n,s,o,l,e.model):n.ui.notify(`${e.model.id} is ${e.model.status.value}`,"warning")}catch(h){c=h}const t=await d();if(!t)return;l=t,c&&!L(c)&&n.ui.notify(c instanceof Error?c.message:String(c),"error")}})},"handler")})}i(T,"llamaExtension");export{T as default};
7
+ ${e("llama.cpp \u670D\u52A1\u5668\u9700\u8981\u4E00\u4E2A\u6709\u8BBF\u95EE\u6743\u9650\u7684 HF_TOKEN\u3002")}`,[u,e("\u8FD4\u56DE")])!==u)return}let f=c.quantization;if(!f&&n.quantizations.length>0){const w=n.quantizations.map(h=>{const A=[h.size===void 0?void 0:q(h.size),h.name==="Q4_K_M"?e("\u63A8\u8350"):void 0].filter(U=>!!U).join(" \xB7 ");return A?`${h.name} \xB7 ${A}`:h.name}),u=await a.select(`${e("\u9009\u62E9\u91CF\u5316\u7248\u672C")}
8
+ ${n.id}`,w);if(!u||(f=n.quantizations[w.indexOf(u)]?.name,!f))return}const i=f?`${n.id}:${f}`:n.id,p=await E(a,{title:e("\u6B63\u5728\u4E0B\u8F7D\u6A21\u578B"),model:i,initialMessage:e("\u6B63\u5728\u542F\u52A8\u2026"),cancelTitle:e("\u505C\u6B62\u4E0B\u8F7D\uFF1F"),cancelMessage:i,run:r((w,u)=>o.downloadAndWait(i,u,w),"run"),cancel:r(()=>o.unload(i),"cancel")});p.cancelled||(await g(m,o,p.value),m.ui.notify(y(e("\u5DF2\u4E0B\u8F7D {model}"),{model:i})))},"downloadModel");t.registerCommand("llama",{description:e("\u7BA1\u7406 llama.cpp \u8DEF\u7531\u4E0A\u7684\u6A21\u578B"),handler:r(async(m,a)=>{if(a.mode!=="tui"){a.ui.notify(e("/llama \u53EA\u80FD\u5728\u4EA4\u4E92\u6A21\u5F0F\u4E0B\u4F7F\u7528"),"warning");return}const o=await T(a);o&&await P(a,async l=>{const d=r(async()=>{for(;;)try{return await g(a,o)}catch(n){if(await l.connectionError(o.serverUrl,R(n))==="close")return}},"readCatalog");let c=await d();if(c)for(;;){const n=await l.showModels(o.serverUrl,c);if(n.type==="close")return;let f;try{n.type==="download"?await C(a,l,o):L(n.model)?await z(a,l,o,n.model):n.model.status.value==="unloaded"?await M(a,l,o,c,n.model):a.ui.notify(y(e("{model} \u5F53\u524D\u72B6\u6001\uFF1A{status}"),{model:n.model.id,status:n.model.status.value}),"warning")}catch(p){f=p}const i=await d();if(!i)return;c=i,f&&!$(f)&&a.ui.notify(f instanceof Error?f.message:String(f),"error")}})},"handler")})}r(b,"llamaExtension");export{b as default};
@@ -1 +1 @@
1
- var U=Object.defineProperty;var s=(r,n)=>U(r,"name",{value:n,configurable:!0});import{stream as h,streamSimple as w}from"@earendil-works/pi-ai/compat";import{LlamaClient as L,llamaInferenceUrl as p,normalizeLlamaServerUrl as c}from"./client.js";const d="llama.cpp",m="http://127.0.0.1:8080";function _(r){const n=r?.env?.LLAMA_BASE_URL;return typeof n=="string"&&n.trim()?c(n):void 0}s(_,"credentialServerUrl");async function v(r,n){const o=_(n)??(await r.env("LLAMA_BASE_URL"))?.trim();return o?c(o):void 0}s(v,"resolveServerUrl");function g(r,n){return r.status.value==="loaded"||r.status.value==="sleeping"?!0:n&&r.status.value==="unloaded"&&!r.status.failed&&r.source==="preset"}s(g,"modelIsSelectable");async function S(r,n,o){if(!n.some(e=>e.status.value==="unloaded"&&e.source==="preset"))return!1;try{return(await r.props({signal:o})).models_autoload===!0}catch{return!1}}s(S,"routerAutoloadEnabled");function f(r,n,o){const e=r.meta?.n_ctx??r.meta?.n_ctx_train,t=e&&e>0?e:128e3,a=o?.chat_template?.includes("enable_thinking")===!0;return{id:r.id,name:r.id,api:"openai-completions",provider:d,baseUrl:p(n),reasoning:a,...a&&{thinkingLevelMap:{off:"off",minimal:null,low:null,medium:"medium",high:null,xhigh:null}},input:r.architecture?.input_modalities?.includes("image")?["text","image"]:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:t,maxTokens:t,compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,supportsUsageInStreaming:!0,supportsStrictMode:!1,maxTokensField:"max_tokens",...a&&{thinkingFormat:"qwen-chat-template"}}}}s(f,"toPiModel");function E(){let r=[];const n=s((e,t,a={})=>{r=e.filter(i=>g(i,a.routerAutoload===!0)).map(i=>f(i,t))},"setCatalog");return{provider:{id:d,name:"llama.cpp",baseUrl:p(m),auth:{apiKey:{name:"llama.cpp server",login:s(async e=>{const t=await e.prompt({type:"text",message:"llama.cpp server URL",placeholder:process.env.LLAMA_BASE_URL??m}),a=c(t.trim()||process.env.LLAMA_BASE_URL||m),i=(await e.prompt({type:"secret",message:"API key (optional)"})).trim();return await new L(a,i||void 0).list({signal:e.signal}),{type:"api_key",key:i||void 0,env:{LLAMA_BASE_URL:a}}},"login"),check:s(async({ctx:e,credential:t})=>await v(e,t)?{type:"api_key",source:t?"stored credential":"LLAMA_BASE_URL"}:void 0,"check"),resolve:s(async({ctx:e,credential:t})=>{const a=await v(e,t);return a?{auth:{apiKey:t?.key??await e.env("LLAMA_API_KEY")??"local",baseUrl:p(a)},env:{...t?.env,LLAMA_BASE_URL:a},source:t?"stored credential":"LLAMA_BASE_URL"}:void 0},"resolve")}},getModels:s(()=>r,"getModels"),refreshModels:s(async e=>{if(e.stored){const l=e.stored.models.filter(u=>u.provider===d&&u.api==="openai-completions");if(!await e.publish({update:s(()=>{r=l},"update")}))return}if(!e.allowNetwork||e.signal.aborted||e.credential?.type!=="api_key")return;const t=_(e.credential);if(!t)return;const a=new L(t,e.credential.key),i=await a.list({signal:e.signal});if(e.signal.aborted)return;const y=await S(a,i,e.signal);if(e.signal.aborted)return;const A=await Promise.all(i.filter(l=>g(l,y)).map(async l=>{if(l.status.value!=="loaded")return f(l,t);const u=await a.props({model:l.id,signal:e.signal});return f(l,t,u)}));e.signal.aborted||await e.publish({persist:{models:A,checkedAt:Date.now()},update:s(()=>{r=A},"update")})},"refreshModels"),stream:s((e,t,a)=>h(e,t,a),"stream"),streamSimple:s((e,t,a)=>w(e,t,a),"streamSimple")},setCatalog:n}}s(E,"createLlamaProvider");export{m as DEFAULT_LLAMA_SERVER_URL,d as LLAMA_PROVIDER_ID,E as createLlamaProvider};
1
+ var h=Object.defineProperty;var s=(r,n)=>h(r,"name",{value:n,configurable:!0});import{stream as w,streamSimple as S}from"@earendil-works/pi-ai/compat";import{t as L}from"../../dal/i18n.js";import{LlamaClient as _,llamaInferenceUrl as p,normalizeLlamaServerUrl as c}from"./client.js";const d="llama.cpp",m="http://127.0.0.1:8080";function v(r){const n=r?.env?.LLAMA_BASE_URL;return typeof n=="string"&&n.trim()?c(n):void 0}s(v,"credentialServerUrl");async function g(r,n){const o=v(n)??(await r.env("LLAMA_BASE_URL"))?.trim();return o?c(o):void 0}s(g,"resolveServerUrl");function y(r,n){return r.status.value==="loaded"||r.status.value==="sleeping"?!0:n&&r.status.value==="unloaded"&&!r.status.failed&&r.source==="preset"}s(y,"modelIsSelectable");async function k(r,n,o){if(!n.some(e=>e.status.value==="unloaded"&&e.source==="preset"))return!1;try{return(await r.props({signal:o})).models_autoload===!0}catch{return!1}}s(k,"routerAutoloadEnabled");function f(r,n,o){const e=r.meta?.n_ctx??r.meta?.n_ctx_train,t=e&&e>0?e:128e3,a=o?.chat_template?.includes("enable_thinking")===!0;return{id:r.id,name:r.id,api:"openai-completions",provider:d,baseUrl:p(n),reasoning:a,...a&&{thinkingLevelMap:{off:"off",minimal:null,low:null,medium:"medium",high:null,xhigh:null}},input:r.architecture?.input_modalities?.includes("image")?["text","image"]:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:t,maxTokens:t,compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,supportsUsageInStreaming:!0,supportsStrictMode:!1,maxTokensField:"max_tokens",...a&&{thinkingFormat:"qwen-chat-template"}}}}s(f,"toPiModel");function B(){let r=[];const n=s((e,t,a={})=>{r=e.filter(i=>y(i,a.routerAutoload===!0)).map(i=>f(i,t))},"setCatalog");return{provider:{id:d,name:"llama.cpp",baseUrl:p(m),auth:{apiKey:{name:"llama.cpp server",login:s(async e=>{const t=await e.prompt({type:"text",message:L("llama.cpp \u670D\u52A1\u5668\u5730\u5740"),placeholder:process.env.LLAMA_BASE_URL??m}),a=c(t.trim()||process.env.LLAMA_BASE_URL||m),i=(await e.prompt({type:"secret",message:L("API key\uFF08\u53EF\u9009\uFF09")})).trim();return await new _(a,i||void 0).list({signal:e.signal}),{type:"api_key",key:i||void 0,env:{LLAMA_BASE_URL:a}}},"login"),check:s(async({ctx:e,credential:t})=>await g(e,t)?{type:"api_key",source:t?"stored credential":"LLAMA_BASE_URL"}:void 0,"check"),resolve:s(async({ctx:e,credential:t})=>{const a=await g(e,t);return a?{auth:{apiKey:t?.key??await e.env("LLAMA_API_KEY")??"local",baseUrl:p(a)},env:{...t?.env,LLAMA_BASE_URL:a},source:t?"stored credential":"LLAMA_BASE_URL"}:void 0},"resolve")}},getModels:s(()=>r,"getModels"),refreshModels:s(async e=>{if(e.stored){const l=e.stored.models.filter(u=>u.provider===d&&u.api==="openai-completions");if(!await e.publish({update:s(()=>{r=l},"update")}))return}if(!e.allowNetwork||e.signal.aborted||e.credential?.type!=="api_key")return;const t=v(e.credential);if(!t)return;const a=new _(t,e.credential.key),i=await a.list({signal:e.signal});if(e.signal.aborted)return;const U=await k(a,i,e.signal);if(e.signal.aborted)return;const A=await Promise.all(i.filter(l=>y(l,U)).map(async l=>{if(l.status.value!=="loaded")return f(l,t);const u=await a.props({model:l.id,signal:e.signal});return f(l,t,u)}));e.signal.aborted||await e.publish({persist:{models:A,checkedAt:Date.now()},update:s(()=>{r=A},"update")})},"refreshModels"),stream:s((e,t,a)=>w(e,t,a),"stream"),streamSimple:s((e,t,a)=>S(e,t,a),"streamSimple")},setCatalog:n}}s(B,"createLlamaProvider");export{m as DEFAULT_LLAMA_SERVER_URL,d as LLAMA_PROVIDER_ID,B as createLlamaProvider};
@@ -1,5 +1,5 @@
1
- var x=Object.defineProperty;var o=(n,e)=>x(n,"name",{value:e,configurable:!0});import{Container as g,fuzzyFilter as C,Input as R,SelectList as p,Spacer as c,Text as a,truncateToWidth as $,visibleWidth as M}from"@earendil-works/pi-tui";import{DynamicBorder as w}from"../../modes/interactive/components/dynamic-border.js";import{keyHint as d}from"../../modes/interactive/components/keybinding-hints.js";const y="\0download";function q(n){const e=n.meta?.n_ctx??n.meta?.n_ctx_train;if(e)return e>=1e3?`${Math.round(e/1e3)}k`:String(e);const t=n.status.args??[];for(let s=0;s<t.length-1;s++){if(t[s]!=="--ctx-size"&&t[s]!=="-c"&&t[s]!=="-ctx")continue;const i=Number(t[s+1]);if(Number.isFinite(i)&&i>0)return i>=1e3?`${Math.round(i/1e3)}k`:String(i)}}o(q,"contextLabel");function I(n){const e=[],t=n.status.value==="loaded"||n.status.value==="sleeping";t?e.push("loaded"):n.status.value!=="unloaded"&&e.push(n.status.value);const s=t?q(n):void 0;return s&&e.push(`${s} context`),e.join(" \xB7 ")}o(I,"modelDescription");function b(n){return{selectedPrefix:o(e=>n.fg("accent",e),"selectedPrefix"),selectedText:o(e=>n.fg("accent",e),"selectedText"),description:o(e=>n.fg("muted",e),"description"),scrollInfo:o(e=>n.fg("dim",e),"scrollInfo"),noMatch:o(e=>n.fg("warning",e),"noMatch")}}o(b,"selectTheme");function u(n,e,t,s){const i=new g;i.addChild(new w(r=>n.fg("accent",r))),i.addChild(new a(n.fg("accent",n.bold(e)),1,0));for(const r of t)i.addChild(r);return s&&(i.addChild(new c(1)),i.addChild(new a(n.fg("dim",s),1,0))),i.addChild(new w(r=>n.fg("accent",r))),i}o(u,"frame");function P(n){return n>=1e6?`${(n/1e6).toFixed(n>=1e7?0:1)}M`:n>=1e3?`${(n/1e3).toFixed(n>=1e5?0:1)}k`:String(n)}o(P,"compactCount");class v extends g{static{o(this,"HuggingFaceSearch")}tui;theme;keybindings;search;cache;onSelectModel;input=new R;resultsContainer=new g;results=[];filteredResults=[];selectedIndex=0;query="";status="Type at least 2 characters";debounce;request;closed=!1;_focused=!1;constructor(e,t,s,i,r,l){super(),this.tui=e,this.theme=t,this.keybindings=s,this.search=i,this.cache=r,this.onSelectModel=l,this.addChild(new a(t.fg("dim","Model name or owner/repository[:quant]"),1,0)),this.addChild(this.input),this.addChild(new c(1)),this.addChild(this.resultsContainer),this.updateResults()}get focused(){return this._focused}set focused(e){this._focused=e,this.input.focused=e}updateResults(){this.resultsContainer.clear();const e=10,t=Math.max(0,Math.min(this.selectedIndex-Math.floor(e/2),this.filteredResults.length-e)),s=Math.min(t+e,this.filteredResults.length);for(let i=t;i<s;i++){const r=this.filteredResults[i];if(!r)continue;const l=i===this.selectedIndex?"\u2192 ":" ",h=`${P(r.downloads)} downloads`;this.resultsContainer.addChild(new a(i===this.selectedIndex?this.theme.fg("accent",`${l}${r.id} ${h}`):`${l}${r.id}${this.theme.fg("muted",` ${h}`)}`,0,0))}(t>0||s<this.filteredResults.length)&&this.resultsContainer.addChild(new a(this.theme.fg("dim",` (${this.selectedIndex+1}/${this.filteredResults.length})`),0,0)),this.filteredResults.length===0?this.resultsContainer.addChild(new a(this.theme.fg("dim",` ${this.status}`),0,0)):this.status==="Searching Hugging Face\u2026"&&this.resultsContainer.addChild(new a(this.theme.fg("dim",` ${this.status}`),0,0)),this.tui.requestRender()}filterResults(){if(this.query){const e=new Set(C(this.results,this.query,t=>t.id).map(t=>t.id));this.filteredResults=this.results.filter(t=>e.has(t.id))}else this.filteredResults=this.results;this.selectedIndex=Math.min(this.selectedIndex,Math.max(0,this.filteredResults.length-1)),this.updateResults()}scheduleSearch(){if(this.debounce&&clearTimeout(this.debounce),this.request?.abort(),this.request=void 0,this.query.length<2){this.status="Type at least 2 characters",this.filterResults();return}const e=this.cache.get(this.query.toLowerCase());if(e){this.results=e,this.status=e.length===0?"No GGUF models found":"",this.filterResults();return}this.status="Searching Hugging Face\u2026",this.filterResults(),this.debounce=setTimeout(()=>{this.runSearch(this.query)},500)}async runSearch(e){const t=new AbortController;this.request=t;try{const s=await this.search(e,t.signal);if(this.cache.set(e.toLowerCase(),s),this.closed||t.signal.aborted||this.query!==e)return;this.results=s,this.selectedIndex=0,this.status=s.length===0?"No GGUF models found":"",this.filterResults()}catch(s){if(this.closed||t.signal.aborted||this.query!==e)return;this.results=[],this.status=s instanceof Error?s.message:String(s),this.filterResults()}finally{this.request===t&&(this.request=void 0)}}close(e){this.closed||(this.closed=!0,this.debounce&&clearTimeout(this.debounce),this.request?.abort(),this.onSelectModel(e))}handleInput(e){if(this.keybindings.matches(e,"tui.select.up")){this.filteredResults.length>0&&(this.selectedIndex=this.selectedIndex===0?this.filteredResults.length-1:this.selectedIndex-1,this.updateResults());return}if(this.keybindings.matches(e,"tui.select.down")){this.filteredResults.length>0&&(this.selectedIndex=this.selectedIndex===this.filteredResults.length-1?0:this.selectedIndex+1,this.updateResults());return}if(this.keybindings.matches(e,"tui.select.confirm")){const i=(/^[^/\s]+\/[^:\s]+(?::[^\s:]+)?$/u.test(this.query)?this.query:void 0)??this.filteredResults[this.selectedIndex]?.id;i&&this.close(i);return}if(this.keybindings.matches(e,"tui.select.cancel")){this.close(void 0);return}this.input.handleInput(e);const t=this.input.getValue().trim();t!==this.query&&(this.query=t,this.scheduleSearch())}}class S{static{o(this,"LlamaView")}tui;theme;keybindings;searchCache=new Map;content;inputHandler;inputTarget;progressPromise;progressResolver;showingProgress=!1;_focused=!1;constructor(e,t,s){this.tui=e,this.theme=t,this.keybindings=s,this.content=u(t,"llama.cpp models",[new a(t.fg("muted","Loading\u2026"),1,1)])}get focused(){return this._focused}set focused(e){this._focused=e,this.inputTarget&&(this.inputTarget.focused=e)}setContent(e,t,s){this.inputTarget&&(this.inputTarget.focused=!1),this.progressPromise=void 0,this.progressResolver=void 0,this.showingProgress=!1,this.content=e,this.inputHandler=t,this.inputTarget=s,this.inputTarget&&(this.inputTarget.focused=this._focused),this.tui.requestRender()}showModels(e,t){const s=[...t].sort((l,h)=>+(h.status.value==="loaded")-+(l.status.value==="loaded")||l.id.localeCompare(h.id)),i=new Map(s.map(l=>[l.id,l])),r=[...s.map(l=>({value:l.id,label:l.id,description:I(l)})),{value:y,label:"Download model\u2026",description:"Hugging Face owner/repository[:quant]"}];return new Promise(l=>{const h=new p(r,Math.min(r.length,12),b(this.theme),{minPrimaryColumnWidth:36,maxPrimaryColumnWidth:56});h.onSelect=f=>{if(f.value===y)l({type:"download"});else{const m=i.get(f.value);m&&l({type:"model",model:m})}},h.onCancel=()=>l({type:"close"}),this.setContent(u(this.theme,"llama.cpp models",[new a(this.theme.fg("dim",e),1,0),new c(1),h],`${d("tui.select.confirm","load/unload/download")} \u2022 ${d("tui.select.cancel","close")}`),h)})}select(e,t){return new Promise(s=>{const i=new p(t.map(r=>({value:r,label:r})),Math.min(t.length,12),b(this.theme));i.onSelect=r=>s(r.value),i.onCancel=()=>s(void 0),this.setContent(u(this.theme,e,[new c(1),i],`${d("tui.select.confirm","select")} \u2022 ${d("tui.select.cancel","cancel")}`),i)})}async confirm(e,t){return await this.select(`${e}
2
- ${t}`,["Yes","No"])==="Yes"}async connectionError(e,t){return await this.select(`llama.cpp unavailable
1
+ var R=Object.defineProperty;var c=(n,e)=>R(n,"name",{value:e,configurable:!0});import{Container as m,fuzzyFilter as $,Input as M,SelectList as w,Spacer as a,Text as u,truncateToWidth as q,visibleWidth as I}from"@earendil-works/pi-tui";import{fill as y,t as h}from"../../dal/i18n.js";import{DynamicBorder as C}from"../../modes/interactive/components/dynamic-border.js";import{keyHint as d}from"../../modes/interactive/components/keybinding-hints.js";const b="\0download";function P(n){const e=n.meta?.n_ctx??n.meta?.n_ctx_train;if(e)return e>=1e3?`${Math.round(e/1e3)}k`:String(e);const t=n.status.args??[];for(let s=0;s<t.length-1;s++){if(t[s]!=="--ctx-size"&&t[s]!=="-c"&&t[s]!=="-ctx")continue;const i=Number(t[s+1]);if(Number.isFinite(i)&&i>0)return i>=1e3?`${Math.round(i/1e3)}k`:String(i)}}c(P,"contextLabel");function v(n){const e=[],t=n.status.value==="loaded"||n.status.value==="sleeping";t?e.push(h("\u5DF2\u52A0\u8F7D")):n.status.value!=="unloaded"&&e.push(n.status.value);const s=t?P(n):void 0;return s&&e.push(y(h("{context} \u4E0A\u4E0B\u6587"),{context:s})),e.join(" \xB7 ")}c(v,"modelDescription");function x(n){return{selectedPrefix:c(e=>n.fg("accent",e),"selectedPrefix"),selectedText:c(e=>n.fg("accent",e),"selectedText"),description:c(e=>n.fg("muted",e),"description"),scrollInfo:c(e=>n.fg("dim",e),"scrollInfo"),noMatch:c(e=>n.fg("warning",e),"noMatch")}}c(x,"selectTheme");function f(n,e,t,s){const i=new m;i.addChild(new C(r=>n.fg("accent",r))),i.addChild(new u(n.fg("accent",n.bold(e)),1,0));for(const r of t)i.addChild(r);return s&&(i.addChild(new a(1)),i.addChild(new u(n.fg("dim",s),1,0))),i.addChild(new C(r=>n.fg("accent",r))),i}c(f,"frame");function _(n){return n>=1e6?`${(n/1e6).toFixed(n>=1e7?0:1)}M`:n>=1e3?`${(n/1e3).toFixed(n>=1e5?0:1)}k`:String(n)}c(_,"compactCount");class S extends m{static{c(this,"HuggingFaceSearch")}tui;theme;keybindings;search;cache;onSelectModel;input=new M;resultsContainer=new m;results=[];filteredResults=[];selectedIndex=0;query="";status=h("\u81F3\u5C11\u8F93\u5165 2 \u4E2A\u5B57\u7B26");debounce;request;closed=!1;_focused=!1;constructor(e,t,s,i,r,l){super(),this.tui=e,this.theme=t,this.keybindings=s,this.search=i,this.cache=r,this.onSelectModel=l,this.addChild(new u(t.fg("dim",h("\u6A21\u578B\u540D\u79F0\u6216 owner/repository[:quant]")),1,0)),this.addChild(this.input),this.addChild(new a(1)),this.addChild(this.resultsContainer),this.updateResults()}get focused(){return this._focused}set focused(e){this._focused=e,this.input.focused=e}updateResults(){this.resultsContainer.clear();const e=10,t=Math.max(0,Math.min(this.selectedIndex-Math.floor(e/2),this.filteredResults.length-e)),s=Math.min(t+e,this.filteredResults.length);for(let i=t;i<s;i++){const r=this.filteredResults[i];if(!r)continue;const l=i===this.selectedIndex?"\u2192 ":" ",o=y(h("{count} \u6B21\u4E0B\u8F7D"),{count:_(r.downloads)});this.resultsContainer.addChild(new u(i===this.selectedIndex?this.theme.fg("accent",`${l}${r.id} ${o}`):`${l}${r.id}${this.theme.fg("muted",` ${o}`)}`,0,0))}(t>0||s<this.filteredResults.length)&&this.resultsContainer.addChild(new u(this.theme.fg("dim",` (${this.selectedIndex+1}/${this.filteredResults.length})`),0,0)),this.filteredResults.length===0?this.resultsContainer.addChild(new u(this.theme.fg("dim",` ${this.status}`),0,0)):this.status===h("\u6B63\u5728\u641C\u7D22 Hugging Face\u2026")&&this.resultsContainer.addChild(new u(this.theme.fg("dim",` ${this.status}`),0,0)),this.tui.requestRender()}filterResults(){if(this.query){const e=new Set($(this.results,this.query,t=>t.id).map(t=>t.id));this.filteredResults=this.results.filter(t=>e.has(t.id))}else this.filteredResults=this.results;this.selectedIndex=Math.min(this.selectedIndex,Math.max(0,this.filteredResults.length-1)),this.updateResults()}scheduleSearch(){if(this.debounce&&clearTimeout(this.debounce),this.request?.abort(),this.request=void 0,this.query.length<2){this.status=h("\u81F3\u5C11\u8F93\u5165 2 \u4E2A\u5B57\u7B26"),this.filterResults();return}const e=this.cache.get(this.query.toLowerCase());if(e){this.results=e,this.status=e.length===0?h("\u6CA1\u6709\u627E\u5230 GGUF \u6A21\u578B"):"",this.filterResults();return}this.status=h("\u6B63\u5728\u641C\u7D22 Hugging Face\u2026"),this.filterResults(),this.debounce=setTimeout(()=>{this.runSearch(this.query)},500)}async runSearch(e){const t=new AbortController;this.request=t;try{const s=await this.search(e,t.signal);if(this.cache.set(e.toLowerCase(),s),this.closed||t.signal.aborted||this.query!==e)return;this.results=s,this.selectedIndex=0,this.status=s.length===0?h("\u6CA1\u6709\u627E\u5230 GGUF \u6A21\u578B"):"",this.filterResults()}catch(s){if(this.closed||t.signal.aborted||this.query!==e)return;this.results=[],this.status=s instanceof Error?s.message:String(s),this.filterResults()}finally{this.request===t&&(this.request=void 0)}}close(e){this.closed||(this.closed=!0,this.debounce&&clearTimeout(this.debounce),this.request?.abort(),this.onSelectModel(e))}handleInput(e){if(this.keybindings.matches(e,"tui.select.up")){this.filteredResults.length>0&&(this.selectedIndex=this.selectedIndex===0?this.filteredResults.length-1:this.selectedIndex-1,this.updateResults());return}if(this.keybindings.matches(e,"tui.select.down")){this.filteredResults.length>0&&(this.selectedIndex=this.selectedIndex===this.filteredResults.length-1?0:this.selectedIndex+1,this.updateResults());return}if(this.keybindings.matches(e,"tui.select.confirm")){const i=(/^[^/\s]+\/[^:\s]+(?::[^\s:]+)?$/u.test(this.query)?this.query:void 0)??this.filteredResults[this.selectedIndex]?.id;i&&this.close(i);return}if(this.keybindings.matches(e,"tui.select.cancel")){this.close(void 0);return}this.input.handleInput(e);const t=this.input.getValue().trim();t!==this.query&&(this.query=t,this.scheduleSearch())}}class k{static{c(this,"LlamaView")}tui;theme;keybindings;searchCache=new Map;content;inputHandler;inputTarget;progressPromise;progressResolver;showingProgress=!1;_focused=!1;constructor(e,t,s){this.tui=e,this.theme=t,this.keybindings=s,this.content=f(t,h("llama.cpp \u6A21\u578B"),[new u(t.fg("muted",h("\u52A0\u8F7D\u4E2D\u2026")),1,1)])}get focused(){return this._focused}set focused(e){this._focused=e,this.inputTarget&&(this.inputTarget.focused=e)}setContent(e,t,s){this.inputTarget&&(this.inputTarget.focused=!1),this.progressPromise=void 0,this.progressResolver=void 0,this.showingProgress=!1,this.content=e,this.inputHandler=t,this.inputTarget=s,this.inputTarget&&(this.inputTarget.focused=this._focused),this.tui.requestRender()}showModels(e,t){const s=[...t].sort((l,o)=>+(o.status.value==="loaded")-+(l.status.value==="loaded")||l.id.localeCompare(o.id)),i=new Map(s.map(l=>[l.id,l])),r=[...s.map(l=>({value:l.id,label:l.id,description:v(l)})),{value:b,label:h("\u4E0B\u8F7D\u6A21\u578B\u2026"),description:"Hugging Face owner/repository[:quant]"}];return new Promise(l=>{const o=new w(r,Math.min(r.length,12),x(this.theme),{minPrimaryColumnWidth:36,maxPrimaryColumnWidth:56});o.onSelect=g=>{if(g.value===b)l({type:"download"});else{const p=i.get(g.value);p&&l({type:"model",model:p})}},o.onCancel=()=>l({type:"close"}),this.setContent(f(this.theme,h("llama.cpp \u6A21\u578B"),[new u(this.theme.fg("dim",e),1,0),new a(1),o],`${d("tui.select.confirm",h("\u52A0\u8F7D/\u5378\u8F7D/\u4E0B\u8F7D"))} \u2022 ${d("tui.select.cancel",h("\u5173\u95ED"))}`),o)})}select(e,t){return new Promise(s=>{const i=new w(t.map(r=>({value:r,label:r})),Math.min(t.length,12),x(this.theme));i.onSelect=r=>s(r.value),i.onCancel=()=>s(void 0),this.setContent(f(this.theme,e,[new a(1),i],`${d("tui.select.confirm",h("\u9009\u62E9").toLowerCase())} \u2022 ${d("tui.select.cancel",h("\u53D6\u6D88").toLowerCase())}`),i)})}async confirm(e,t){const s=h("\u662F");return await this.select(`${e}
2
+ ${t}`,[s,h("\u5426")])===s}async connectionError(e,t){const s=h("\u91CD\u8BD5");return await this.select(`${h("llama.cpp \u4E0D\u53EF\u7528")}
3
3
  ${e}
4
4
 
5
- ${t}`,["Retry","Close"])==="Retry"?"retry":"close"}searchModels(e){return new Promise(t=>{const s=new v(this.tui,this.theme,this.keybindings,e,this.searchCache,t);this.setContent(u(this.theme,"Download model",[new c(1),s],`${d("tui.select.confirm","select")} \u2022 ${d("tui.select.cancel","back")}`),s,s)})}showStatus(e,t){this.setContent(u(this.theme,e,[new c(1),new a(this.theme.fg("muted",t),1,0)]))}progress(e){return this.progressPromise||(this.progressPromise=new Promise(t=>{this.progressResolver=t})),this.showingProgress=!0,this.updateProgress(e),this.progressPromise}updateProgress(e){if(!this.showingProgress)return;const t=[new a(this.theme.fg("text",e.model),1,0),new c(1),new a(this.theme.fg("muted",e.message),1,0)];if(e.ratio!==void 0){const i=Math.round(Math.max(0,Math.min(1,e.ratio))*40);t.push(new a(this.theme.fg("accent",`${"\u2588".repeat(i)}${"\u2500".repeat(40-i)} ${Math.round(e.ratio*100)}%`),1,0))}e.detail&&t.push(new a(this.theme.fg("dim",e.detail),1,0)),this.content=u(this.theme,e.title,t,d("tui.select.cancel","stop")),this.inputHandler=void 0,this.tui.requestRender()}handleInput(e){if(this.progressResolver&&this.keybindings.matches(e,"tui.select.cancel")){const t=this.progressResolver;this.progressPromise=void 0,this.progressResolver=void 0,t();return}this.inputHandler?.handleInput?.(e),this.tui.requestRender()}render(e){return this.content.render(e).map(t=>M(t)>e?$(t,e,""):t)}invalidate(){this.content.invalidate()}}async function H(n,e){await n.ui.custom((t,s,i,r)=>{const l=new S(t,s,i);return e(l).then(()=>r(),h=>{n.ui.notify(h instanceof Error?h.message:String(h),"error"),r()}),l})}o(H,"showLlamaUi");async function L(n,e){const t=new AbortController,s={title:e.title,model:e.model,message:e.initialMessage},i=e.run(t.signal,h=>{Object.assign(s,h),n.updateProgress(s)}).then(h=>({ok:!0,value:h}),h=>({ok:!1,error:h}));let r=!1;for(i.finally(()=>{r=!0});!r&&await Promise.race([i.then(()=>"settled"),n.progress(s).then(()=>"stop")])!=="settled";)if(!(!await n.confirm(e.cancelTitle,e.cancelMessage)||r)){try{await e.cancel()}finally{t.abort(new Error("Cancelled"))}return await i,{cancelled:!0}}const l=await i;if(!l.ok)throw l.error;return{cancelled:!1,value:l.value}}o(L,"runWithProgress");export{L as runWithProgress,H as showLlamaUi};
5
+ ${t}`,[s,h("\u5173\u95ED\u9762\u677F")])===s?"retry":"close"}searchModels(e){return new Promise(t=>{const s=new S(this.tui,this.theme,this.keybindings,e,this.searchCache,t);this.setContent(f(this.theme,h("\u4E0B\u8F7D\u6A21\u578B"),[new a(1),s],`${d("tui.select.confirm",h("\u9009\u62E9").toLowerCase())} \u2022 ${d("tui.select.cancel",h("\u8FD4\u56DE").toLowerCase())}`),s,s)})}showStatus(e,t){this.setContent(f(this.theme,e,[new a(1),new u(this.theme.fg("muted",t),1,0)]))}progress(e){return this.progressPromise||(this.progressPromise=new Promise(t=>{this.progressResolver=t})),this.showingProgress=!0,this.updateProgress(e),this.progressPromise}updateProgress(e){if(!this.showingProgress)return;const t=[new u(this.theme.fg("text",e.model),1,0),new a(1),new u(this.theme.fg("muted",e.message),1,0)];if(e.ratio!==void 0){const i=Math.round(Math.max(0,Math.min(1,e.ratio))*40);t.push(new u(this.theme.fg("accent",`${"\u2588".repeat(i)}${"\u2500".repeat(40-i)} ${Math.round(e.ratio*100)}%`),1,0))}e.detail&&t.push(new u(this.theme.fg("dim",e.detail),1,0)),this.content=f(this.theme,e.title,t,d("tui.select.cancel",h("\u505C\u6B62").toLowerCase())),this.inputHandler=void 0,this.tui.requestRender()}handleInput(e){if(this.progressResolver&&this.keybindings.matches(e,"tui.select.cancel")){const t=this.progressResolver;this.progressPromise=void 0,this.progressResolver=void 0,t();return}this.inputHandler?.handleInput?.(e),this.tui.requestRender()}render(e){return this.content.render(e).map(t=>I(t)>e?q(t,e,""):t)}invalidate(){this.content.invalidate()}}async function E(n,e){await n.ui.custom((t,s,i,r)=>{const l=new k(t,s,i);return e(l).then(()=>r(),o=>{n.ui.notify(o instanceof Error?o.message:String(o),"error"),r()}),l})}c(E,"showLlamaUi");async function N(n,e){const t=new AbortController,s={title:e.title,model:e.model,message:e.initialMessage},i=e.run(t.signal,o=>{Object.assign(s,o),n.updateProgress(s)}).then(o=>({ok:!0,value:o}),o=>({ok:!1,error:o}));let r=!1;for(i.finally(()=>{r=!0});!r&&await Promise.race([i.then(()=>"settled"),n.progress(s).then(()=>"stop")])!=="settled";)if(!(!await n.confirm(e.cancelTitle,e.cancelMessage)||r)){try{await e.cancel()}finally{t.abort(new Error("Cancelled"))}return await i,{cancelled:!0}}const l=await i;if(!l.ok)throw l.error;return{cancelled:!1,value:l.value}}c(N,"runWithProgress");export{N as runWithProgress,E as showLlamaUi};
package/dist/main.js CHANGED
@@ -1,4 +1,4 @@
1
- var _e=Object.defineProperty;var d=(e,t)=>_e(e,"name",{value:t,configurable:!0});import{createInterface as Ne}from"node:readline";import{modelsAreEqual as He}from"@earendil-works/pi-ai";import l from"chalk";import{normalizeSessionName as We,parseArgs as re,printHelp as De}from"./cli/args.js";import{checkProviderAuth as Ue,createAuthCheckModelRuntime as Be,getProviderCredential as Ke}from"./cli/auth-check.js";import{AuthCommandError as _,getAuthCommandName as qe,getAuthCommandUsage as Ve,isAuthCommandHelp as ze,parseAuthCommand as Ye,printAuthCommandHelp as Ge,validateAuthCommandArgs as Je}from"./cli/auth-command.js";import{resolveCredentialForPrint as Qe}from"./cli/credential-print.js";import{processFileArguments as Xe}from"./cli/file-processor.js";import{buildInitialMessage as ae}from"./cli/initial-message.js";import{listModels as Ze}from"./cli/list-models.js";import{createProjectTrustContext as et}from"./cli/project-trust.js";import{selectSession as tt}from"./cli/session-picker.js";import{shouldRunFirstTimeSetup as ot,showFirstTimeSetup as nt,showStartupSelector as it}from"./cli/startup-ui.js";import{APP_NAME as ce,ENV_SESSION_DIR as st,expandTildePath as rt,getAgentDir as at,getPackageDir as ct,VERSION as lt}from"./config.js";import{createAgentSessionRuntime as dt}from"./core/agent-session-runtime.js";import{createAgentSessionFromServices as ut,createAgentSessionServices as mt}from"./core/agent-session-services.js";import{formatNoModelsAvailableMessage as ft}from"./core/auth-guidance.js";import{AuthStorage as pt,ReadOnlyAuthStorage as gt}from"./core/auth-storage.js";import{exportFromFile as ht}from"./core/export-html/index.js";import{applyHttpProxySettings as le,configureHttpDispatcher as de}from"./core/http-dispatcher.js";import{resolveCliModel as vt,resolveModelScope as St}from"./core/model-resolver.js";import{ModelRuntime as wt}from"./core/model-runtime.js";import{restoreStdout as xt,takeOverStdout as yt}from"./core/output-guard.js";import{resolveProjectTrusted as Tt}from"./core/project-trust.js";import{formatMissingSessionCwdPrompt as Pt,getMissingSessionCwdIssue as Mt,MissingSessionCwdError as kt}from"./core/session-cwd.js";import{assertValidSessionId as Ct,SessionManager as f}from"./core/session-manager.js";import{collectSettingsDiagnostics as ue,deduplicateDiagnostics as me}from"./core/settings-diagnostics.js";import{SettingsManager as N}from"./core/settings-manager.js";import{printTimings as y,resetTimings as Et,time as p}from"./core/timings.js";import{hasTrustRequiringProjectResources as fe,ProjectTrustStore as It}from"./core/trust-manager.js";import{applyDalEnvApiKeyPolicy as At,applyDalSystemProxyFallback as Ft,dalBuiltinExtensionPaths as Rt}from"./dal/builtins.js";import{builtInExtensions as bt}from"./extensions/index.js";import{runMigrations as Lt,showDeprecationWarnings as jt}from"./migrations.js";import{InteractiveMode as $t,runAcpMode as Ot,runPrintMode as _t,runRpcMode as Nt}from"./modes/index.js";import{initTheme as Ht,stopThemeWatcher as H}from"./modes/interactive/theme/theme.js";import{cleanupManagedInstall as Wt,handleConfigCommand as Dt,handlePackageCommand as Ut}from"./package-manager-cli.js";import{isTruthyEnvFlag as pe}from"./utils/offline.js";import{isLocalPath as Bt,normalizePath as Kt,resolvePath as ge}from"./utils/paths.js";import{cleanupWindowsSelfUpdateQuarantine as qt}from"./utils/windows-self-update.js";const Vt=`Hint: Start without extensions using "${ce} -ne".`;async function zt(){if(!process.stdin.isTTY)return new Promise(e=>{let t="";process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{t+=n}),process.stdin.on("end",()=>{e(t.trim()||void 0)}),process.stdin.resume()})}d(zt,"readPipedStdin");function W(e){for(const t of e){const n=t.type==="error"?l.red:t.type==="warning"?l.yellow:l.dim,a=t.type==="error"?"Error: ":t.type==="warning"?"Warning: ":"";console.error(n(`${a}${t.message}`))}}d(W,"reportDiagnostics");function Yt(e,t,n){return e.mode==="rpc"?"rpc":e.mode==="acp"?"acp":e.mode==="json"?"json":e.print||!t||!n?"print":"interactive"}d(Yt,"resolveAppMode");function Gt(e){return e==="json"?"json":"text"}d(Gt,"toPrintOutputMode");function Jt(e){return!e.print&&e.mode===void 0&&(e.help===!0||e.listModels!==void 0)}d(Jt,"isPlainRuntimeMetadataCommand");async function Qt(e){if(ze(e))return Ge(),!0;let t;try{t=Ye(e)}catch(a){const i=a instanceof _?a.message:"Failed to parse auth command";return console.error(l.red(`Error: ${i}`)),process.exitCode=1,!0}if(!t)return!1;const n=re(t.args);if(n.unknownFlags.size>0){const a=n.unknownFlags.keys().next().value;return console.error(l.red(`Unknown option --${a} for "${qe(t.kind)}".`)),console.error(l.dim(`Use "${ce} --help" or "${Ve(t.kind)}".`)),process.exitCode=1,!0}try{if(n.diagnostics.length>0)throw new _(n.diagnostics.map(o=>o.message).join(`
2
- `));if(t.kind!=="check"){const o=AbortSignal.timeout(15e3),s=await wt.create({allowModelNetwork:!1,signal:o}),x=await Qe(n,s,t.kind,t.minExpiryMs,o);return process.stdout.write(`${x}
3
- `),!0}const a=Je(n,t.kind);let i,c;try{const o=t.noRefresh?new gt:pt.create(),s=await Be(o);i=await Ue(n,s,{refresh:!t.noRefresh}),t.credentials&&i.status==="ready"&&(c=await Ke(i.provider,s,o,{refresh:!t.noRefresh}),c||(i={status:"not_ready",provider:i.provider,reason:"credential_not_available"}))}catch{i={status:"invalid",provider:a.provider??a.model,reason:"invalid_state"}}const m=t.json?JSON.stringify({...i,...c?{credentials:c}:{}}):c??i.status;process.stdout.write(`${m}
4
- `),process.exitCode=i.status==="ready"?0:i.status==="not_ready"?1:2}catch(a){const i=a instanceof _?a.message:"Failed to resolve credential";console.error(l.red(`Error: ${i}`)),process.exitCode=t.kind==="check"?2:1}return!0}d(Qt,"runAuthCommand");async function Xt(e,t){if(e.fileArgs.length===0)return ae({parsed:e,stdinContent:t});const{text:n,images:a}=await Xe(e.fileArgs,{autoResizeImages:!1});return ae({parsed:e,fileText:n,fileImages:a,stdinContent:t})}d(Xt,"prepareInitialMessage");function D(e,t,n){const a=f.findById(t,e,n);return a?{type:"local",path:a}:void 0}d(D,"findLocalSessionByExactId");async function he(e,t,n){if(e.includes("/")||e.includes("\\")||e.endsWith(".jsonl"))return{type:"path",path:ge(e,t)};const a=D(e,t,n);if(a)return a;const c=(await f.list(t,n)).find(s=>s.id.startsWith(e));if(c)return{type:"local",path:c.path};const m=await f.listAll(n),o=m.find(s=>s.id===e)??m.find(s=>s.id.startsWith(e));return o?{type:"global",path:o.path,cwd:o.cwd}:{type:"not_found",arg:e}}d(he,"resolveSessionPath");async function Zt(e){return new Promise(t=>{const n=Ne({input:process.stdin,output:process.stdout});n.question(`${e} [y/N] `,a=>{n.close(),t(a.toLowerCase()==="y"||a.toLowerCase()==="yes")})})}d(Zt,"promptConfirm");function eo(e){if(!e.fork)return;const t=[e.session?"--session":void 0,e.continue?"--continue":void 0,e.resume?"--resume":void 0,e.noSession?"--no-session":void 0].filter(n=>n!==void 0);t.length>0&&(console.error(l.red(`Error: --fork cannot be combined with ${t.join(", ")}`)),process.exit(1))}d(eo,"validateForkFlags");function to(e){if(e.sessionId===void 0)return;const t=[e.session?"--session":void 0,e.continue?"--continue":void 0,e.resume?"--resume":void 0].filter(n=>n!==void 0);t.length>0&&(console.error(l.red(`Error: --session-id cannot be combined with ${t.join(", ")}`)),process.exit(1));try{Ct(e.sessionId)}catch(n){const a=n instanceof Error?n.message:String(n);console.error(l.red(`Error: ${a}`)),process.exit(1)}}d(to,"validateSessionIdFlags");function oo(e,t){try{return f.open(e,t)}catch(n){const a=n instanceof Error?n.message:String(n);console.error(l.red(`Error: ${a}`)),process.exit(1)}}d(oo,"openSessionOrExit");function ve(e,t,n,a){try{return f.forkFrom(e,t,n,{id:a})}catch(i){const c=i instanceof Error?i.message:String(i);console.error(l.red(`Error: ${c}`)),process.exit(1)}}d(ve,"forkSessionOrExit");async function no(e,t,n,a){if(e.noSession||e.help||e.listModels!==void 0)return f.inMemory(t,e.sessionId!==void 0?{id:e.sessionId}:void 0);if(e.fork){e.sessionId&&D(e.sessionId,t,n)&&(console.error(l.red(`Session already exists with id '${e.sessionId}'`)),process.exit(1));const i=await he(e.fork,t,n);switch(i.type){case"path":case"local":case"global":return ve(i.path,t,n,e.sessionId);case"not_found":console.error(l.red(`No session found matching '${i.arg}'`)),process.exit(1)}}if(e.session){const i=await he(e.session,t,n);switch(i.type){case"path":case"local":return oo(i.path,n);case"global":return console.log(l.yellow(`Session found in different project: ${i.cwd}`)),await Zt("Fork this session into current directory?")||(console.log(l.dim("Aborted.")),process.exit(0)),ve(i.path,t,n);case"not_found":console.error(l.red(`No session found matching '${i.arg}'`)),process.exit(1)}}if(e.resume)try{const i=await tt((c,m)=>f.list(t,n,c,m),(c,m)=>f.listAll(n,c,m),a);return i||(console.log(l.dim("No session selected")),process.exit(0)),f.open(i,n)}finally{H()}if(e.continue)return f.continueRecent(t,n);if(e.sessionId){const i=D(e.sessionId,t,n);if(i)return f.open(i.path,n);console.error(l.yellow(`Warning: No project session found with id '${e.sessionId}'; creating a new session with that id.`))}return f.create(t,n,{id:e.sessionId})}d(no,"createSessionManager");function io(e,t,n,a,i){const c={},m=[];let o=!1;if(e.model){const s=vt({cliProvider:e.provider,cliModel:e.model,cliThinking:e.thinking,modelRuntime:a});s.warning&&m.push({type:"warning",message:s.warning}),s.error&&m.push({type:"error",message:s.error}),s.model&&(c.model=s.model,!e.thinking&&s.thinkingLevel&&(c.thinkingLevel=s.thinkingLevel,o=!0))}if(!c.model&&t.length>0&&!n){const s=i.getDefaultProvider(),x=i.getDefaultModel(),T=s&&x?a.getModel(s,x):void 0,S=T?t.find(g=>He(g.model,T)):void 0;S?(c.model=S.model,!e.thinking&&S.thinkingLevel&&(c.thinkingLevel=S.thinkingLevel)):(c.model=t[0].model,!e.thinking&&t[0].thinkingLevel&&(c.thinkingLevel=t[0].thinkingLevel))}return e.thinking&&(c.thinkingLevel=e.thinking),t.length>0&&(c.scopedModels=t.map(s=>({model:s.model,thinkingLevel:s.thinkingLevel}))),e.noTools?c.noTools="all":e.noBuiltinTools&&(c.noTools="builtin"),e.tools&&(c.tools=[...e.tools]),e.excludeTools&&(c.excludeTools=[...e.excludeTools]),{options:c,cliThinkingFromModel:o,diagnostics:m}}d(io,"buildSessionOptions");function I(e,t){return t?.map(n=>Bt(n)?ge(n,e):n)}d(I,"resolveCliPaths");async function so(e,t){return it(t,Pt(e),[{label:"Continue",value:e.fallbackCwd},{label:"Cancel",value:void 0}])}d(so,"promptForMissingSessionCwd");async function zo(e,t){Et();const n=[...bt,...t?.extensionFactories??[]],a=e.includes("--offline")||pe(process.env.PI_OFFLINE);if(a&&(process.env.PI_OFFLINE="1",process.env.PI_SKIP_VERSION_CHECK="1"),await Qt(e))return;process.platform==="win32"&&qt(ct()),Wt();const i=process.cwd(),c=at(),m=N.create(i,c,{projectTrusted:!1});if(le(m.getGlobalSettings().httpProxy),Ft(),At(),de(),await Ut(e,{extensionFactories:n})){const r=process.exitCode??0;if(process.platform==="win32"&&r===0&&e[0]==="update")return;process.exit(r);return}if(await Dt(e,{extensionFactories:n}))return;const o=re(e);if(o.diagnostics.length>0){for(const r of o.diagnostics){const u=r.type==="error"?l.red:l.yellow;console.error(u(`${r.type==="error"?"Error":"Warning"}: ${r.message}`))}o.diagnostics.some(r=>r.type==="error")&&process.exit(1)}if(p("parseArgs"),o.version&&(console.log(lt),process.exit(0)),o.export){let r;try{const u=o.messages.length>0?o.messages[0]:void 0;r=await ht(o.export,u)}catch(u){const M=u instanceof Error?u.message:"Failed to export session";console.error(l.red(`Error: ${M}`)),process.exit(1)}console.log(`Exported to: ${r}`),process.exit(0)}let s=Yt(o,process.stdin.isTTY,process.stdout.isTTY);s!=="interactive"&&!Jt(o)&&yt(),(o.mode==="rpc"||o.mode==="acp")&&o.fileArgs.length>0&&(console.error(l.red(`Error: @file arguments are not supported in ${o.mode.toUpperCase()} mode`)),process.exit(1)),eo(o),to(o);const{migratedAuthProviders:T,deprecationWarnings:S}=Lt(i);p("runMigrations");const g=N.create(i,c),A=ue(g);s==="interactive"&&!o.help&&o.listModels===void 0&&ot()&&(await nt(g),p("firstTimeSetup")),s==="interactive"&&o.useTheme!==void 0&&g.applyOverrides({theme:o.useTheme});const U=process.env[st],B=(o.sessionDir?Kt(o.sessionDir):void 0)??(U?rt(U):void 0)??g.getSessionDir();let w=await no(o,i,B,g);const P=Mt(w,i);if(P)if(s==="interactive"){const r=await so(P,g);r||process.exit(0),w=f.open(P.sessionFile,B,r)}else console.error(l.red(new kt(P).message)),process.exit(1);if(o.name!==void 0){const r=We(o.name);r===void 0&&(console.error(l.red("Error: --name requires a non-empty value")),process.exit(1)),w.appendSessionInfo(r)}p("createSessionManager");const K=new It(c),q=w.getCwd(),Se=o.projectTrustOverride===void 0&&!fe(q)?q:void 0,V=o.help||o.listModels!==void 0?"print":s,z=new Map,we=[...Rt(),...I(i,o.extensions)??[]],xe=I(i,o.skills),ye=I(i,o.promptTemplates),Te=I(i,o.themes),Pe=d(async({cwd:r,agentDir:u,sessionManager:M,sessionStartEvent:ee,projectTrustContext:Ie})=>{const te=ee===void 0,oe=[],ne=z.get(r),ie=fe(r),se=o.projectTrustOverride===void 0&&ne===void 0&&ie,Ae=se?!1:ne??o.projectTrustOverride??(!ie||K.get(r)===!0),Fe=N.create(r,u,{projectTrusted:Ae}),k=await mt({cwd:r,agentDir:u,settingsManager:Fe,modelRuntimeSignal:AbortSignal.timeout(15e3),extensionFlagValues:o.unknownFlags,resourceLoaderReloadOptions:se?{resolveProjectTrust:d(async({extensionsResult:O})=>{const E=await Tt({cwd:r,trustStore:K,trustOverride:o.projectTrustOverride,defaultProjectTrust:g.getDefaultProjectTrust(),extensionsResult:O,projectTrustContext:Ie??et({cwd:r,mode:te?V:s,settingsManager:g,hasUI:te&&V==="interactive"}),onExtensionError:d(Oe=>oe.push({type:"warning",message:Oe}),"onExtensionError")});return z.set(r,E),E},"resolveProjectTrust")}:void 0,resourceLoaderOptions:{additionalExtensionPaths:we,additionalSkillPaths:xe,additionalPromptTemplatePaths:ye,additionalThemePaths:Te,noExtensions:o.noExtensions,noSkills:o.noSkills,noPromptTemplates:o.noPromptTemplates,noThemes:o.noThemes,noContextFiles:o.noContextFiles,systemPrompt:o.systemPrompt,appendSystemPrompt:o.appendSystemPrompt,extensionFactories:n}}),{settingsManager:b,modelRuntime:L,resourceLoader:Re}=k,j=[...oe,...k.diagnostics,...ue(b),...Re.getExtensions().errors.map(({path:O,error:E})=>({type:"error",message:`Failed to load extension "${O}": ${E}`}))],$=o.models??b.getEnabledModels(),be=$&&$.length>0?await St($,L,{signal:AbortSignal.timeout(15e3)}):[],{options:v,cliThinkingFromModel:Le,diagnostics:je}=io(o,be,M.buildSessionContext().messages.length>0,L,b);j.push(...je),o.apiKey&&(v.model?await L.setRuntimeApiKey(v.model.provider,o.apiKey):j.push({type:"error",message:"--api-key requires a model to be specified via --model, --provider/--model, or --models"}));const C=await ut({services:k,sessionManager:M,sessionStartEvent:ee,model:v.model,thinkingLevel:v.thinkingLevel,scopedModels:v.scopedModels,tools:v.tools,excludeTools:v.excludeTools,noTools:v.noTools,customTools:v.customTools}),$e=o.thinking!==void 0||Le;return C.session.model&&$e&&C.session.setThinkingLevel(C.session.thinkingLevel),{...C,services:k,diagnostics:j}},"createRuntime");p("createRuntime");const h=await dt(Pe,{cwd:w.getCwd(),agentDir:c,sessionManager:w});p("createAgentSessionRuntime");const{services:Me,session:ke,modelFallbackMessage:Ce}=h,{settingsManager:F,modelRuntime:Y,resourceLoader:Ee}=Me;if(le(F.getGlobalSettings().httpProxy),de(F.getHttpIdleTimeoutMs()),o.help){W(A);const r=Ee.getExtensions().extensions.flatMap(u=>Array.from(u.flags.values()));De(r),process.exit(0)}if(o.listModels!==void 0){W(me([...A,...h.diagnostics]));const r=typeof o.listModels=="string"?o.listModels:void 0;await Ze(Y,r,AbortSignal.timeout(15e3)),process.exit(0)}let R;s!=="rpc"&&s!=="acp"&&(R=await zt(),R!==void 0&&s==="interactive"&&(s="print")),p("readPipedStdin");const{initialMessage:G,initialImages:J}=await Xt(o,R);p("prepareInitialMessage"),Ht(F.getTheme(),s==="interactive"),p("initTheme"),s==="interactive"&&S.length>0&&await jt(S),p("resolveModelScope");const Q=me([...A,...h.diagnostics]),X=h.diagnostics.some(r=>r.type==="error");(s!=="interactive"||X)&&W(Q),X&&(h.diagnostics.some(r=>r.message.includes("Failed to load extension"))&&console.error(l.yellow(Vt)),process.exit(1)),p("createAgentSession"),s!=="interactive"&&!ke.model&&(console.error(l.red(ft())),process.exit(1));const Z=pe(process.env.PI_STARTUP_BENCHMARK);if(Z&&s!=="interactive"&&(console.error(l.red("Error: PI_STARTUP_BENCHMARK only supports interactive mode")),process.exit(1)),!a&&(s==="rpc"||s==="acp")){const r=new AbortController,u=setTimeout(()=>r.abort(),15e3);Y.refresh({signal:r.signal}).catch(()=>{}).finally(()=>clearTimeout(u))}if(s==="rpc")y(),await Nt(h);else if(s==="acp")y(),await Ot(h);else if(s==="interactive"){const r=new $t(h,{migratedProviders:T,startupDiagnostics:Q,modelFallbackMessage:Ce,autoTrustOnReloadCwd:Se,initialMessage:G,initialImages:J,initialMessages:o.messages,verbose:o.verbose,tuiMode:o.tuiMode,initialThemeSetting:o.useTheme});if(Z){await r.init(),p("interactiveMode.init"),await new Promise(u=>setTimeout(u,150)),r.stop(),H(),y(),process.stdout.writableLength>0&&await new Promise(u=>process.stdout.once("drain",u)),process.stderr.writableLength>0&&await new Promise(u=>process.stderr.once("drain",u));return}y(),await r.run()}else{y();const r=await _t(h,{mode:Gt(s),messages:o.messages,initialMessage:G,initialImages:J});H(),xt(),r!==0&&(process.exitCode=r);return}}d(zo,"main");export{no as createSessionManager,zo as main};
1
+ var He=Object.defineProperty;var m=(e,t)=>He(e,"name",{value:t,configurable:!0});import{createInterface as Be}from"node:readline";import{modelsAreEqual as Ke}from"@earendil-works/pi-ai";import d from"chalk";import{normalizeSessionName as We,parseArgs as le,printHelp as Ue}from"./cli/args.js";import{checkProviderAuth as qe,createAuthCheckModelRuntime as Ve,getProviderCredential as $e}from"./cli/auth-check.js";import{AuthCommandError as H,getAuthCommandName as ze,getAuthCommandUsage as Ye,isAuthCommandHelp as Ge,parseAuthCommand as Je,printAuthCommandHelp as Qe,validateAuthCommandArgs as Xe}from"./cli/auth-command.js";import{resolveCredentialForPrint as Ze}from"./cli/credential-print.js";import{processFileArguments as et}from"./cli/file-processor.js";import{buildInitialMessage as ce}from"./cli/initial-message.js";import{listModels as tt}from"./cli/list-models.js";import{createProjectTrustContext as ot}from"./cli/project-trust.js";import{selectSession as st}from"./cli/session-picker.js";import{shouldRunFirstTimeSetup as nt,showFirstTimeSetup as it,showStartupSelector as rt}from"./cli/startup-ui.js";import{APP_NAME as de,ENV_SESSION_DIR as at,expandTildePath as lt,getAgentDir as ct,getPackageDir as dt,VERSION as mt}from"./config.js";import{createAgentSessionRuntime as ut}from"./core/agent-session-runtime.js";import{createAgentSessionFromServices as ft,createAgentSessionServices as pt}from"./core/agent-session-services.js";import{formatNoModelsAvailableMessage as gt}from"./core/auth-guidance.js";import{AuthStorage as ht,ReadOnlyAuthStorage as vt}from"./core/auth-storage.js";import{exportFromFile as St}from"./core/export-html/index.js";import{applyHttpProxySettings as me,configureHttpDispatcher as ue}from"./core/http-dispatcher.js";import{resolveCliModel as xt,resolveModelScope as yt}from"./core/model-resolver.js";import{ModelRuntime as wt}from"./core/model-runtime.js";import{restoreStdout as Tt,takeOverStdout as Pt}from"./core/output-guard.js";import{resolveProjectTrusted as Mt}from"./core/project-trust.js";import{formatMissingSessionCwdPrompt as kt,getMissingSessionCwdIssue as Ct,MissingSessionCwdError as It}from"./core/session-cwd.js";import{assertValidSessionId as At,SessionManager as g}from"./core/session-manager.js";import{collectSettingsDiagnostics as fe,deduplicateDiagnostics as pe}from"./core/settings-diagnostics.js";import{SettingsManager as B}from"./core/settings-manager.js";import{printTimings as P,resetTimings as Ft,time as h}from"./core/timings.js";import{hasTrustRequiringProjectResources as ge,ProjectTrustStore as Rt}from"./core/trust-manager.js";import{applyDalEnvApiKeyPolicy as Et,applyDalSystemProxyFallback as bt,dalBuiltinExtensionPaths as Lt}from"./dal/builtins.js";import{fill as u,t as c}from"./dal/i18n.js";import{builtInExtensions as jt}from"./extensions/index.js";import{runMigrations as Ot,showDeprecationWarnings as _t}from"./migrations.js";import{InteractiveMode as Nt,runAcpMode as Dt,runPrintMode as Ht,runRpcMode as Bt}from"./modes/index.js";import{initTheme as Kt,stopThemeWatcher as K}from"./modes/interactive/theme/theme.js";import{cleanupManagedInstall as Wt,handleConfigCommand as Ut,handlePackageCommand as qt}from"./package-manager-cli.js";import{isTruthyEnvFlag as he}from"./utils/offline.js";import{isLocalPath as Vt,normalizePath as $t,resolvePath as ve}from"./utils/paths.js";import{cleanupWindowsSelfUpdateQuarantine as zt}from"./utils/windows-self-update.js";const Yt=m(()=>u(c("\u63D0\u793A\uFF1A\u53EF\u4EE5\u7528\u300C{app} -ne\u300D\u5728\u4E0D\u52A0\u8F7D\u6269\u5C55\u7684\u60C5\u51B5\u4E0B\u542F\u52A8\u3002"),{app:de}),"extensionLoadFailureHint");async function Gt(){if(!process.stdin.isTTY)return new Promise(e=>{let t="";process.stdin.setEncoding("utf8"),process.stdin.on("data",s=>{t+=s}),process.stdin.on("end",()=>{e(t.trim()||void 0)}),process.stdin.resume()})}m(Gt,"readPipedStdin");function W(e){for(const t of e){const s=t.type==="error"?d.red:t.type==="warning"?d.yellow:d.dim,a=t.type==="error"?u(c("\u9519\u8BEF\uFF1A{message}"),{message:t.message}):t.type==="warning"?u(c("\u8B66\u544A\uFF1A{message}"),{message:t.message}):t.message;console.error(s(a))}}m(W,"reportDiagnostics");function Jt(e,t,s){return e.mode==="rpc"?"rpc":e.mode==="acp"?"acp":e.mode==="json"?"json":e.print||!t||!s?"print":"interactive"}m(Jt,"resolveAppMode");function Qt(e){return e==="json"?"json":"text"}m(Qt,"toPrintOutputMode");function Xt(e){return!e.print&&e.mode===void 0&&(e.help===!0||e.listModels!==void 0)}m(Xt,"isPlainRuntimeMetadataCommand");async function Zt(e){if(Ge(e))return Qe(),!0;let t;try{t=Je(e)}catch(a){const n=a instanceof H?a.message:c("\u65E0\u6CD5\u89E3\u6790 auth \u547D\u4EE4");return console.error(d.red(u(c("\u9519\u8BEF\uFF1A{message}"),{message:n}))),process.exitCode=1,!0}if(!t)return!1;const s=le(t.args);if(s.unknownFlags.size>0){const a=s.unknownFlags.keys().next().value;return console.error(d.red(u(c("\u300C{command}\u300D\u4E0D\u652F\u6301\u9009\u9879 --{option}\u3002"),{option:String(a),command:ze(t.kind)}))),console.error(d.dim(u(c("\u8BF7\u67E5\u770B\u300C{app} --help\u300D\u6216\u300C{usage}\u300D\u3002"),{app:de,usage:Ye(t.kind)}))),process.exitCode=1,!0}try{if(s.diagnostics.length>0)throw new H(s.diagnostics.map(o=>o.message).join(`
2
+ `));if(t.kind!=="check"){const o=AbortSignal.timeout(15e3),i=await wt.create({allowModelNetwork:!1,signal:o}),T=await Ze(s,i,t.kind,t.minExpiryMs,o);return process.stdout.write(`${T}
3
+ `),!0}const a=Xe(s,t.kind);let n,l;try{const o=t.noRefresh?new vt:ht.create(),i=await Ve(o);n=await qe(s,i,{refresh:!t.noRefresh}),t.credentials&&n.status==="ready"&&(l=await $e(n.provider,i,o,{refresh:!t.noRefresh}),l||(n={status:"not_ready",provider:n.provider,reason:"credential_not_available"}))}catch{n={status:"invalid",provider:a.provider??a.model,reason:"invalid_state"}}const p=t.json?JSON.stringify({...n,...l?{credentials:l}:{}}):l??n.status;process.stdout.write(`${p}
4
+ `),process.exitCode=n.status==="ready"?0:n.status==="not_ready"?1:2}catch(a){const n=a instanceof H?a.message:c("\u65E0\u6CD5\u83B7\u53D6\u51ED\u636E");console.error(d.red(u(c("\u9519\u8BEF\uFF1A{message}"),{message:n}))),process.exitCode=t.kind==="check"?2:1}return!0}m(Zt,"runAuthCommand");async function eo(e,t){if(e.fileArgs.length===0)return ce({parsed:e,stdinContent:t});const{text:s,images:a}=await et(e.fileArgs,{autoResizeImages:!1});return ce({parsed:e,fileText:s,fileImages:a,stdinContent:t})}m(eo,"prepareInitialMessage");function U(e,t,s){const a=g.findById(t,e,s);return a?{type:"local",path:a}:void 0}m(U,"findLocalSessionByExactId");async function Se(e,t,s){if(e.includes("/")||e.includes("\\")||e.endsWith(".jsonl"))return{type:"path",path:ve(e,t)};const a=U(e,t,s);if(a)return a;const l=(await g.list(t,s)).find(i=>i.id.startsWith(e));if(l)return{type:"local",path:l.path};const p=await g.listAll(s),o=p.find(i=>i.id===e)??p.find(i=>i.id.startsWith(e));return o?{type:"global",path:o.path,cwd:o.cwd}:{type:"not_found",arg:e}}m(Se,"resolveSessionPath");async function to(e){return new Promise(t=>{const s=Be({input:process.stdin,output:process.stdout});s.question(`${e} [y/N] `,a=>{s.close(),t(a.toLowerCase()==="y"||a.toLowerCase()==="yes")})})}m(to,"promptConfirm");function oo(e){if(!e.fork)return;const t=[e.session?"--session":void 0,e.continue?"--continue":void 0,e.resume?"--resume":void 0,e.noSession?"--no-session":void 0].filter(s=>s!==void 0);t.length>0&&(console.error(d.red(u(c("\u9519\u8BEF\uFF1A--fork \u4E0D\u80FD\u548C {flags} \u540C\u65F6\u4F7F\u7528"),{flags:t.join(", ")}))),process.exit(1))}m(oo,"validateForkFlags");function so(e){if(e.sessionId===void 0)return;const t=[e.session?"--session":void 0,e.continue?"--continue":void 0,e.resume?"--resume":void 0].filter(s=>s!==void 0);t.length>0&&(console.error(d.red(u(c("\u9519\u8BEF\uFF1A--session-id \u4E0D\u80FD\u548C {flags} \u540C\u65F6\u4F7F\u7528"),{flags:t.join(", ")}))),process.exit(1));try{At(e.sessionId)}catch(s){const a=s instanceof Error?s.message:String(s);console.error(d.red(u(c("\u9519\u8BEF\uFF1A{message}"),{message:a}))),process.exit(1)}}m(so,"validateSessionIdFlags");function no(e,t){try{return g.open(e,t)}catch(s){const a=s instanceof Error?s.message:String(s);console.error(d.red(u(c("\u9519\u8BEF\uFF1A{message}"),{message:a}))),process.exit(1)}}m(no,"openSessionOrExit");function xe(e,t,s,a){try{return g.forkFrom(e,t,s,{id:a})}catch(n){const l=n instanceof Error?n.message:String(n);console.error(d.red(u(c("\u9519\u8BEF\uFF1A{message}"),{message:l}))),process.exit(1)}}m(xe,"forkSessionOrExit");async function io(e,t,s,a){if(e.noSession||e.help||e.listModels!==void 0)return g.inMemory(t,e.sessionId!==void 0?{id:e.sessionId}:void 0);if(e.fork){e.sessionId&&U(e.sessionId,t,s)&&(console.error(d.red(u(c("ID \u4E3A\u300C{id}\u300D\u7684\u4F1A\u8BDD\u5DF2\u7ECF\u5B58\u5728"),{id:e.sessionId}))),process.exit(1));const n=await Se(e.fork,t,s);switch(n.type){case"path":case"local":case"global":return xe(n.path,t,s,e.sessionId);case"not_found":console.error(d.red(u(c("\u6CA1\u6709\u627E\u5230\u5339\u914D\u300C{session}\u300D\u7684\u4F1A\u8BDD"),{session:n.arg}))),process.exit(1)}}if(e.session){const n=await Se(e.session,t,s);switch(n.type){case"path":case"local":return no(n.path,s);case"global":return console.log(d.yellow(u(c("\u5728\u53E6\u4E00\u4E2A\u9879\u76EE\u91CC\u627E\u5230\u4E86\u8FD9\u4E2A\u4F1A\u8BDD\uFF1A{cwd}"),{cwd:n.cwd}))),await to(c("\u8981\u628A\u8FD9\u4E2A\u4F1A\u8BDD\u5206\u53C9\u5230\u5F53\u524D\u76EE\u5F55\u5417\uFF1F"))||(console.log(d.dim(c("\u5DF2\u53D6\u6D88\u3002"))),process.exit(0)),xe(n.path,t,s);case"not_found":console.error(d.red(u(c("\u6CA1\u6709\u627E\u5230\u5339\u914D\u300C{session}\u300D\u7684\u4F1A\u8BDD"),{session:n.arg}))),process.exit(1)}}if(e.resume)try{const n=await st((l,p)=>g.list(t,s,l,p),(l,p)=>g.listAll(s,l,p),a);return n||(console.log(d.dim(c("\u6CA1\u6709\u9009\u62E9\u4F1A\u8BDD"))),process.exit(0)),g.open(n,s)}finally{K()}if(e.continue)return g.continueRecent(t,s);if(e.sessionId){const n=U(e.sessionId,t,s);if(n)return g.open(n.path,s);console.error(d.yellow(u(c("\u8B66\u544A\uFF1A\u5F53\u524D\u9879\u76EE\u91CC\u6CA1\u6709 ID \u4E3A\u300C{id}\u300D\u7684\u4F1A\u8BDD\uFF0C\u5C06\u7528\u8FD9\u4E2A ID \u65B0\u5EFA\u4E00\u4E2A\u4F1A\u8BDD\u3002"),{id:e.sessionId})))}return g.create(t,s,{id:e.sessionId})}m(io,"createSessionManager");function ro(e,t,s,a,n){const l={},p=[];let o=!1;if(e.model){const i=xt({cliProvider:e.provider,cliModel:e.model,cliThinking:e.thinking,modelRuntime:a});i.warning&&p.push({type:"warning",message:i.warning}),i.error&&p.push({type:"error",message:i.error}),i.model&&(l.model=i.model,!e.thinking&&i.thinkingLevel&&(l.thinkingLevel=i.thinkingLevel,o=!0))}if(!l.model&&t.length>0&&!s){const i=n.getDefaultProvider(),T=n.getDefaultModel(),M=i&&T?a.getModel(i,T):void 0,y=M?t.find(v=>Ke(v.model,M)):void 0;y?(l.model=y.model,!e.thinking&&y.thinkingLevel&&(l.thinkingLevel=y.thinkingLevel)):(l.model=t[0].model,!e.thinking&&t[0].thinkingLevel&&(l.thinkingLevel=t[0].thinkingLevel))}return e.thinking&&(l.thinkingLevel=e.thinking),t.length>0&&(l.scopedModels=t.map(i=>({model:i.model,thinkingLevel:i.thinkingLevel}))),e.noTools?l.noTools="all":e.noBuiltinTools&&(l.noTools="builtin"),e.tools&&(l.tools=[...e.tools]),e.excludeTools&&(l.excludeTools=[...e.excludeTools]),{options:l,cliThinkingFromModel:o,diagnostics:p}}m(ro,"buildSessionOptions");function R(e,t){return t?.map(s=>Vt(s)?ve(s,e):s)}m(R,"resolveCliPaths");async function ao(e,t){return rt(t,kt(e),[{label:"Continue",value:e.fallbackCwd},{label:"Cancel",value:void 0}])}m(ao,"promptForMissingSessionCwd");async function Jo(e,t){Ft();const s=[...jt,...t?.extensionFactories??[]],a=e.includes("--offline")||he(process.env.PI_OFFLINE);if(a&&(process.env.PI_OFFLINE="1",process.env.PI_SKIP_VERSION_CHECK="1"),await Zt(e))return;process.platform==="win32"&&zt(dt()),Wt();const n=process.cwd(),l=ct(),p=B.create(n,l,{projectTrusted:!1});if(me(p.getGlobalSettings().httpProxy),bt(),Et(),ue(),await qt(e,{extensionFactories:s})){const r=process.exitCode??0;if(process.platform==="win32"&&r===0&&e[0]==="update")return;process.exit(r);return}if(await Ut(e,{extensionFactories:s}))return;const o=le(e);if(o.diagnostics.length>0){for(const r of o.diagnostics){const f=r.type==="error"?d.red:d.yellow;console.error(f(u(r.type==="error"?c("\u9519\u8BEF\uFF1A{message}"):c("\u8B66\u544A\uFF1A{message}"),{message:r.message})))}o.diagnostics.some(r=>r.type==="error")&&process.exit(1)}if(h("parseArgs"),o.version&&(console.log(mt),process.exit(0)),o.export){let r;try{const f=o.messages.length>0?o.messages[0]:void 0;r=await St(o.export,f)}catch(f){const C=f instanceof Error?f.message:c("\u5BFC\u51FA\u4F1A\u8BDD\u5931\u8D25");console.error(d.red(u(c("\u9519\u8BEF\uFF1A{message}"),{message:C}))),process.exit(1)}console.log(u(c("\u5DF2\u5BFC\u51FA\u5230\uFF1A{path}"),{path:r})),process.exit(0)}let i=Jt(o,process.stdin.isTTY,process.stdout.isTTY);i!=="interactive"&&!Xt(o)&&Pt(),(o.mode==="rpc"||o.mode==="acp")&&o.fileArgs.length>0&&(console.error(d.red(u(c("\u9519\u8BEF\uFF1A{mode} \u6A21\u5F0F\u4E0D\u652F\u6301 @\u6587\u4EF6 \u53C2\u6570"),{mode:o.mode.toUpperCase()}))),process.exit(1)),oo(o),so(o);const{migratedAuthProviders:M,deprecationWarnings:y}=Ot(n);h("runMigrations");const v=B.create(n,l),E=fe(v);i==="interactive"&&!o.help&&o.listModels===void 0&&nt()&&(await it(v),h("firstTimeSetup")),i==="interactive"&&o.useTheme!==void 0&&v.applyOverrides({theme:o.useTheme});const q=process.env[at],V=(o.sessionDir?$t(o.sessionDir):void 0)??(q?lt(q):void 0)??v.getSessionDir();let w=await io(o,n,V,v);const k=Ct(w,n);if(k)if(i==="interactive"){const r=await ao(k,v);r||process.exit(0),w=g.open(k.sessionFile,V,r)}else console.error(d.red(new It(k).message)),process.exit(1);if(o.name!==void 0){const r=We(o.name);r===void 0&&(console.error(d.red(c("\u9519\u8BEF\uFF1A--name \u7684\u503C\u4E0D\u80FD\u4E3A\u7A7A"))),process.exit(1)),w.appendSessionInfo(r)}h("createSessionManager");const $=new Rt(l),z=w.getCwd(),ye=o.projectTrustOverride===void 0&&!ge(z)?z:void 0,Y=o.help||o.listModels!==void 0?"print":i,G=new Map,we=[...Lt(),...R(n,o.extensions)??[]],Te=R(n,o.skills),Pe=R(n,o.promptTemplates),Me=R(n,o.themes),ke=m(async({cwd:r,agentDir:f,sessionManager:C,sessionStartEvent:oe,projectTrustContext:Re})=>{const se=oe===void 0,ne=[],ie=G.get(r),re=ge(r),ae=o.projectTrustOverride===void 0&&ie===void 0&&re,Ee=ae?!1:ie??o.projectTrustOverride??(!re||$.get(r)===!0),be=B.create(r,f,{projectTrusted:Ee}),I=await pt({cwd:r,agentDir:f,settingsManager:be,modelRuntimeSignal:AbortSignal.timeout(15e3),extensionFlagValues:o.unknownFlags,resourceLoaderReloadOptions:ae?{resolveProjectTrust:m(async({extensionsResult:D})=>{const F=await Mt({cwd:r,trustStore:$,trustOverride:o.projectTrustOverride,defaultProjectTrust:v.getDefaultProjectTrust(),extensionsResult:D,projectTrustContext:Re??ot({cwd:r,mode:se?Y:i,settingsManager:v,hasUI:se&&Y==="interactive"}),onExtensionError:m(De=>ne.push({type:"warning",message:De}),"onExtensionError")});return G.set(r,F),F},"resolveProjectTrust")}:void 0,resourceLoaderOptions:{additionalExtensionPaths:we,additionalSkillPaths:Te,additionalPromptTemplatePaths:Pe,additionalThemePaths:Me,noExtensions:o.noExtensions,noSkills:o.noSkills,noPromptTemplates:o.noPromptTemplates,noThemes:o.noThemes,noContextFiles:o.noContextFiles,systemPrompt:o.systemPrompt,appendSystemPrompt:o.appendSystemPrompt,extensionFactories:s}}),{settingsManager:j,modelRuntime:O,resourceLoader:Le}=I,_=[...ne,...I.diagnostics,...fe(j),...Le.getExtensions().errors.map(({path:D,error:F})=>({type:"error",message:`Failed to load extension "${D}": ${F}`}))],N=o.models??j.getEnabledModels(),je=N&&N.length>0?await yt(N,O,{signal:AbortSignal.timeout(15e3)}):[],{options:x,cliThinkingFromModel:Oe,diagnostics:_e}=ro(o,je,C.buildSessionContext().messages.length>0,O,j);_.push(..._e),o.apiKey&&(x.model?await O.setRuntimeApiKey(x.model.provider,o.apiKey):_.push({type:"error",message:c("\u4F7F\u7528 --api-key \u65F6\u9700\u8981\u901A\u8FC7 --model\u3001--provider/--model \u6216 --models \u6307\u5B9A\u6A21\u578B")}));const A=await ft({services:I,sessionManager:C,sessionStartEvent:oe,model:x.model,thinkingLevel:x.thinkingLevel,scopedModels:x.scopedModels,tools:x.tools,excludeTools:x.excludeTools,noTools:x.noTools,customTools:x.customTools}),Ne=o.thinking!==void 0||Oe;return A.session.model&&Ne&&A.session.setThinkingLevel(A.session.thinkingLevel),{...A,services:I,diagnostics:_}},"createRuntime");h("createRuntime");const S=await ut(ke,{cwd:w.getCwd(),agentDir:l,sessionManager:w});h("createAgentSessionRuntime");const{services:Ce,session:Ie,modelFallbackMessage:Ae}=S,{settingsManager:b,modelRuntime:J,resourceLoader:Fe}=Ce;if(me(b.getGlobalSettings().httpProxy),ue(b.getHttpIdleTimeoutMs()),o.help){W(E);const r=Fe.getExtensions().extensions.flatMap(f=>Array.from(f.flags.values()));Ue(r),process.exit(0)}if(o.listModels!==void 0){W(pe([...E,...S.diagnostics]));const r=typeof o.listModels=="string"?o.listModels:void 0;await tt(J,r,AbortSignal.timeout(15e3)),process.exit(0)}let L;i!=="rpc"&&i!=="acp"&&(L=await Gt(),L!==void 0&&i==="interactive"&&(i="print")),h("readPipedStdin");const{initialMessage:Q,initialImages:X}=await eo(o,L);h("prepareInitialMessage"),Kt(b.getTheme(),i==="interactive"),h("initTheme"),i==="interactive"&&y.length>0&&await _t(y),h("resolveModelScope");const Z=pe([...E,...S.diagnostics]),ee=S.diagnostics.some(r=>r.type==="error");(i!=="interactive"||ee)&&W(Z),ee&&(S.diagnostics.some(r=>r.message.includes("Failed to load extension"))&&console.error(d.yellow(Yt())),process.exit(1)),h("createAgentSession"),i!=="interactive"&&!Ie.model&&(console.error(d.red(gt())),process.exit(1));const te=he(process.env.PI_STARTUP_BENCHMARK);if(te&&i!=="interactive"&&(console.error(d.red(c("\u9519\u8BEF\uFF1API_STARTUP_BENCHMARK \u53EA\u652F\u6301\u4EA4\u4E92\u6A21\u5F0F"))),process.exit(1)),!a&&(i==="rpc"||i==="acp")){const r=new AbortController,f=setTimeout(()=>r.abort(),15e3);J.refresh({signal:r.signal}).catch(()=>{}).finally(()=>clearTimeout(f))}if(i==="rpc")P(),await Bt(S);else if(i==="acp")P(),await Dt(S);else if(i==="interactive"){const r=new Nt(S,{migratedProviders:M,startupDiagnostics:Z,modelFallbackMessage:Ae,autoTrustOnReloadCwd:ye,initialMessage:Q,initialImages:X,initialMessages:o.messages,verbose:o.verbose,tuiMode:o.tuiMode,initialThemeSetting:o.useTheme});if(te){await r.init(),h("interactiveMode.init"),await new Promise(f=>setTimeout(f,150)),r.stop(),K(),P(),process.stdout.writableLength>0&&await new Promise(f=>process.stdout.once("drain",f)),process.stderr.writableLength>0&&await new Promise(f=>process.stderr.once("drain",f));return}P(),await r.run()}else{P();const r=await Ht(S,{mode:Qt(i),messages:o.messages,initialMessage:Q,initialImages:X});K(),Tt(),r!==0&&(process.exitCode=r);return}}m(Jo,"main");export{io as createSessionManager,Jo as main};
@@ -1,5 +1,5 @@
1
- var O=Object.defineProperty;var l=(e,t)=>O(e,"name",{value:t,configurable:!0});import u from"chalk";import{existsSync as a,mkdirSync as h,readdirSync as S,readFileSync as d,renameSync as y,rmSync as j,writeFileSync as w}from"fs";import{dirname as N,join as i}from"path";import{CONFIG_DIR_NAME as P,getAgentDir as m,getBinDir as v}from"./config.js";import{migrateKeybindingsConfig as A}from"./core/keybindings.js";import{stripBom as b}from"./utils/text.js";const $="https://github.com/earendil-works/pi/blob/main/packages/coding-agent/CHANGELOG.md#extensions-migration",C="https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/extensions.md";function M(){const e=m(),t=i(e,"auth.json"),o=i(e,"oauth.json"),r=i(e,"settings.json");if(a(t))return[];const n={},f=[];if(a(o))try{const g=JSON.parse(b(d(o,"utf-8")));for(const[s,c]of Object.entries(g))n[s]={type:"oauth",...c},f.push(s);y(o,`${o}.migrated`)}catch{}if(a(r))try{const g=d(r,"utf-8"),s=JSON.parse(b(g));if(s.apiKeys&&typeof s.apiKeys=="object"){for(const[c,p]of Object.entries(s.apiKeys))!n[c]&&typeof p=="string"&&(n[c]={type:"api_key",key:p},f.push(c));delete s.apiKeys,w(r,JSON.stringify(s,null,2))}}catch{}return Object.keys(n).length>0&&(h(N(t),{recursive:!0}),w(t,JSON.stringify(n,null,2),{mode:384})),f}l(M,"migrateAuthToAuthJson");function E(){const e=m();let t;try{t=S(e).filter(o=>o.endsWith(".jsonl")).map(o=>i(e,o))}catch{return}if(t.length!==0)for(const o of t)try{const n=d(o,"utf8").split(`
2
- `)[0];if(!n?.trim())continue;const f=JSON.parse(n);if(f.type!=="session"||!f.cwd)continue;const s=`--${f.cwd.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`,c=i(e,"sessions",s);a(c)||h(c,{recursive:!0});const p=o.split("/").pop()||o.split("\\").pop(),D=i(c,p);if(a(D))continue;y(o,D)}catch{}}l(E,"migrateSessionsFromAgentRoot");function x(e,t){const o=i(e,"commands"),r=i(e,"prompts");if(a(o)&&!a(r))try{return y(o,r),console.log(u.green(`Migrated ${t} commands/ \u2192 prompts/`)),!0}catch(n){console.log(u.yellow(`Warning: Could not migrate ${t} commands/ to prompts/: ${n instanceof Error?n.message:n}`))}return!1}l(x,"migrateCommandsToPrompts");function J(){const e=i(m(),"keybindings.json");if(a(e))try{const t=JSON.parse(b(d(e,"utf-8")));if(typeof t!="object"||t===null||Array.isArray(t))return;const{config:o,migrated:r}=A(t);if(!r)return;w(e,`${JSON.stringify(o,null,2)}
3
- `,"utf-8")}catch{}}l(J,"migrateKeybindingsConfigFile");function T(){const e=m(),t=i(e,"tools"),o=v();if(!a(t))return;const r=["fd","rg","fd.exe","rg.exe"];let n=!1;for(const f of r){const g=i(t,f),s=i(o,f);if(a(g))if(a(o)||h(o,{recursive:!0}),a(s))try{j?.(g,{force:!0})}catch{}else try{y(g,s),n=!0}catch{}}n&&console.log(u.green("Migrated managed binaries tools/ \u2192 bin/"))}l(T,"migrateToolsToBin");function k(e,t){const o=i(e,"hooks"),r=i(e,"tools"),n=[];if(a(o)&&n.push(`${t} hooks/ directory found. Hooks have been renamed to extensions.`),a(r))try{S(r).filter(s=>{const c=s.toLowerCase();return c!=="fd"&&c!=="rg"&&c!=="fd.exe"&&c!=="rg.exe"&&!s.startsWith(".")}).length>0&&n.push(`${t} tools/ directory contains custom tools. Custom tools have been merged into extensions.`)}catch{}return n}l(k,"checkDeprecatedExtensionDirs");function G(e){const t=m(),o=i(e,P);return x(t,"Global"),x(o,"Project"),[...k(t,"Global"),...k(o,"Project")]}l(G,"migrateExtensionSystem");async function B(e){if(e.length!==0){for(const t of e)console.log(u.yellow(`Warning: ${t}`));console.log(u.yellow(`
4
- Move your extensions to the extensions/ directory.`)),console.log(u.yellow(`Migration guide: ${$}`)),console.log(u.yellow(`Documentation: ${C}`)),console.log(u.dim(`
5
- Press any key to continue...`)),await new Promise(t=>{process.stdin.setRawMode?.(!0),process.stdin.resume(),process.stdin.once("data",()=>{process.stdin.setRawMode?.(!1),process.stdin.pause(),t()})}),console.log()}}l(B,"showDeprecationWarnings");function U(e){const t=M();E(),T(),J();const o=G(e);return{migratedAuthProviders:t,deprecationWarnings:o}}l(U,"runMigrations");export{M as migrateAuthToAuthJson,E as migrateSessionsFromAgentRoot,U as runMigrations,B as showDeprecationWarnings};
1
+ var j=Object.defineProperty;var p=(e,t)=>j(e,"name",{value:t,configurable:!0});import u from"chalk";import{existsSync as a,mkdirSync as S,readdirSync as O,readFileSync as y,renameSync as w,rmSync as A,writeFileSync as D}from"fs";import{dirname as P,join as i}from"path";import{CONFIG_DIR_NAME as v,getAgentDir as d,getBinDir as E}from"./config.js";import{migrateKeybindingsConfig as J}from"./core/keybindings.js";import{fill as m,t as f}from"./dal/i18n.js";import{stripBom as x}from"./utils/text.js";const T="https://github.com/earendil-works/pi/blob/main/packages/coding-agent/CHANGELOG.md#extensions-migration",C="https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/extensions.md";function R(){const e=d(),t=i(e,"auth.json"),o=i(e,"oauth.json"),r=i(e,"settings.json");if(a(t))return[];const n={},l=[];if(a(o))try{const g=JSON.parse(x(y(o,"utf-8")));for(const[s,c]of Object.entries(g))n[s]={type:"oauth",...c},l.push(s);w(o,`${o}.migrated`)}catch{}if(a(r))try{const g=y(r,"utf-8"),s=JSON.parse(x(g));if(s.apiKeys&&typeof s.apiKeys=="object"){for(const[c,h]of Object.entries(s.apiKeys))!n[c]&&typeof h=="string"&&(n[c]={type:"api_key",key:h},l.push(c));delete s.apiKeys,D(r,JSON.stringify(s,null,2))}}catch{}return Object.keys(n).length>0&&(S(P(t),{recursive:!0}),D(t,JSON.stringify(n,null,2),{mode:384})),l}p(R,"migrateAuthToAuthJson");function _(){const e=d();let t;try{t=O(e).filter(o=>o.endsWith(".jsonl")).map(o=>i(e,o))}catch{return}if(t.length!==0)for(const o of t)try{const n=y(o,"utf8").split(`
2
+ `)[0];if(!n?.trim())continue;const l=JSON.parse(n);if(l.type!=="session"||!l.cwd)continue;const s=`--${l.cwd.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`,c=i(e,"sessions",s);a(c)||S(c,{recursive:!0});const h=o.split("/").pop()||o.split("\\").pop(),k=i(c,h);if(a(k))continue;w(o,k)}catch{}}p(_,"migrateSessionsFromAgentRoot");function b(e,t){const o=i(e,"commands"),r=i(e,"prompts");if(a(o)&&!a(r))try{return w(o,r),console.log(u.green(m(f("\u5DF2\u628A{scope}\u7684 commands/ \u8FC1\u79FB\u5230 prompts/"),{scope:t}))),!0}catch(n){console.log(u.yellow(m(f("\u8B66\u544A\uFF1A\u65E0\u6CD5\u628A{scope}\u7684 commands/ \u8FC1\u79FB\u5230 prompts/\uFF1A{error}"),{scope:t,error:n instanceof Error?n.message:String(n)})))}return!1}p(b,"migrateCommandsToPrompts");function I(){const e=i(d(),"keybindings.json");if(a(e))try{const t=JSON.parse(x(y(e,"utf-8")));if(typeof t!="object"||t===null||Array.isArray(t))return;const{config:o,migrated:r}=J(t);if(!r)return;D(e,`${JSON.stringify(o,null,2)}
3
+ `,"utf-8")}catch{}}p(I,"migrateKeybindingsConfigFile");function K(){const e=d(),t=i(e,"tools"),o=E();if(!a(t))return;const r=["fd","rg","fd.exe","rg.exe"];let n=!1;for(const l of r){const g=i(t,l),s=i(o,l);if(a(g))if(a(o)||S(o,{recursive:!0}),a(s))try{A?.(g,{force:!0})}catch{}else try{w(g,s),n=!0}catch{}}n&&console.log(u.green(f("\u5DF2\u628A\u6258\u7BA1\u7684\u53EF\u6267\u884C\u6587\u4EF6\u4ECE tools/ \u8FC1\u79FB\u5230 bin/")))}p(K,"migrateToolsToBin");function N(e,t){const o=i(e,"hooks"),r=i(e,"tools"),n=[];if(a(o)&&n.push(m(f("\u53D1\u73B0{scope}\u7684 hooks/ \u76EE\u5F55\u3002Hooks \u5DF2\u66F4\u540D\u4E3A\u6269\u5C55\uFF08extensions\uFF09\u3002"),{scope:t})),a(r))try{O(r).filter(s=>{const c=s.toLowerCase();return c!=="fd"&&c!=="rg"&&c!=="fd.exe"&&c!=="rg.exe"&&!s.startsWith(".")}).length>0&&n.push(m(f("{scope}\u7684 tools/ \u76EE\u5F55\u91CC\u6709\u81EA\u5B9A\u4E49\u5DE5\u5177\u3002\u81EA\u5B9A\u4E49\u5DE5\u5177\u5DF2\u5E76\u5165\u6269\u5C55\uFF08extensions\uFF09\u3002"),{scope:t}))}catch{}return n}p(N,"checkDeprecatedExtensionDirs");function F(e){const t=d(),o=i(e,v);return b(t,f("\u5168\u5C40")),b(o,f("\u9879\u76EE\u5185")),[...N(t,f("\u5168\u5C40")),...N(o,f("\u9879\u76EE\u5185"))]}p(F,"migrateExtensionSystem");async function X(e){if(e.length!==0){for(const t of e)console.log(u.yellow(m(f("\u8B66\u544A\uFF1A{message}"),{message:t})));console.log(u.yellow(`
4
+ ${f("\u8BF7\u628A\u6269\u5C55\u79FB\u5230 extensions/ \u76EE\u5F55\u3002")}`)),console.log(u.yellow(m(f("\u8FC1\u79FB\u6307\u5357\uFF1A{url}"),{url:T}))),console.log(u.yellow(m(f("\u6587\u6863\uFF1A{url}"),{url:C}))),console.log(u.dim(`
5
+ ${f("\u6309\u4EFB\u610F\u952E\u7EE7\u7EED\u2026")}`)),await new Promise(t=>{process.stdin.setRawMode?.(!0),process.stdin.resume(),process.stdin.once("data",()=>{process.stdin.setRawMode?.(!1),process.stdin.pause(),t()})}),console.log()}}p(X,"showDeprecationWarnings");function q(e){const t=R();_(),K(),I();const o=F(e);return{migratedAuthProviders:t,deprecationWarnings:o}}p(q,"runMigrations");export{R as migrateAuthToAuthJson,_ as migrateSessionsFromAgentRoot,q as runMigrations,X as showDeprecationWarnings};