min-agent 0.5.1 → 0.6.1

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 (169) hide show
  1. package/README.md +20 -20
  2. package/dist/cli.js +538 -12
  3. package/docs/API.md +8 -6
  4. package/package.json +6 -6
  5. package/skills/self-config/SKILL.md +6 -4
  6. package/skills/self-config/reference.md +4 -1
  7. package/dist/agent.js +0 -1388
  8. package/dist/assistant-stream.js +0 -131
  9. package/dist/cli/commands/chat.js +0 -13
  10. package/dist/cli/commands/ctx.js +0 -7
  11. package/dist/cli/commands/exec.js +0 -35
  12. package/dist/cli/commands/history.js +0 -58
  13. package/dist/cli/commands/index.js +0 -249
  14. package/dist/cli/commands/init.js +0 -18
  15. package/dist/cli/commands/mcp.js +0 -173
  16. package/dist/cli/commands/memory.js +0 -87
  17. package/dist/cli/commands/models.js +0 -21
  18. package/dist/cli/commands/permission.js +0 -12
  19. package/dist/cli/commands/rules.js +0 -33
  20. package/dist/cli/commands/sandbox.js +0 -13
  21. package/dist/cli/commands/serve.js +0 -9
  22. package/dist/cli/commands/setup.js +0 -56
  23. package/dist/cli/commands/shared.js +0 -25
  24. package/dist/cli/commands/skills.js +0 -119
  25. package/dist/cli/commands/think.js +0 -12
  26. package/dist/cli/commands/update.js +0 -7
  27. package/dist/cli/commands/write-config.js +0 -52
  28. package/dist/cli/errors.js +0 -36
  29. package/dist/cli/exec-prompt.js +0 -26
  30. package/dist/cli/option-helpers.js +0 -65
  31. package/dist/cli/program.js +0 -223
  32. package/dist/cli/setup/detect.js +0 -17
  33. package/dist/cli/setup/flags.js +0 -12
  34. package/dist/cli/setup/flow.js +0 -108
  35. package/dist/cli/setup/provider-form.js +0 -102
  36. package/dist/cli/setup/ui.js +0 -534
  37. package/dist/clipboard.js +0 -142
  38. package/dist/code-mode.js +0 -184
  39. package/dist/compaction.js +0 -644
  40. package/dist/config.js +0 -363
  41. package/dist/confirm.js +0 -172
  42. package/dist/context-window.js +0 -256
  43. package/dist/ctx-cli.js +0 -30
  44. package/dist/ctx.js +0 -80
  45. package/dist/doom-loop.js +0 -278
  46. package/dist/fetch-timeout.js +0 -152
  47. package/dist/http-approvals.js +0 -60
  48. package/dist/http.js +0 -119
  49. package/dist/instructions.js +0 -196
  50. package/dist/logger.js +0 -95
  51. package/dist/markdown.js +0 -259
  52. package/dist/mcp.js +0 -1036
  53. package/dist/memory-cli.js +0 -33
  54. package/dist/memory.js +0 -295
  55. package/dist/model-catalog.js +0 -285
  56. package/dist/ollama-model.js +0 -234
  57. package/dist/ollama-openai-bridge.js +0 -383
  58. package/dist/output.js +0 -76
  59. package/dist/paste-handler.js +0 -41
  60. package/dist/permission-cli.js +0 -40
  61. package/dist/plugins.js +0 -131
  62. package/dist/pricing.js +0 -119
  63. package/dist/provider.js +0 -63
  64. package/dist/question-format.js +0 -60
  65. package/dist/reasoning-stream.js +0 -158
  66. package/dist/sandbox-cli.js +0 -79
  67. package/dist/sandbox.js +0 -403
  68. package/dist/save-throttle.js +0 -45
  69. package/dist/scope.js +0 -23
  70. package/dist/serve/common.js +0 -425
  71. package/dist/serve/routes-chat.js +0 -367
  72. package/dist/serve/routes-mcp.js +0 -212
  73. package/dist/serve/routes-memory.js +0 -95
  74. package/dist/serve/routes-meta.js +0 -268
  75. package/dist/serve/routes-sessions.js +0 -61
  76. package/dist/serve/routes-skills.js +0 -70
  77. package/dist/serve.js +0 -138
  78. package/dist/sessions.js +0 -265
  79. package/dist/skills.js +0 -599
  80. package/dist/structured-output.js +0 -29
  81. package/dist/synthetic.js +0 -7
  82. package/dist/think-cli.js +0 -36
  83. package/dist/thinking-wire.js +0 -239
  84. package/dist/thinking.js +0 -166
  85. package/dist/title-gen.js +0 -55
  86. package/dist/token-display.js +0 -39
  87. package/dist/tool-display.js +0 -178
  88. package/dist/tool-output.js +0 -126
  89. package/dist/tools/apply_patch.js +0 -265
  90. package/dist/tools/atomic-file.js +0 -35
  91. package/dist/tools/backend.js +0 -61
  92. package/dist/tools/bash.js +0 -231
  93. package/dist/tools/code_search.js +0 -98
  94. package/dist/tools/edit.js +0 -68
  95. package/dist/tools/explore.js +0 -232
  96. package/dist/tools/glob.js +0 -40
  97. package/dist/tools/grep.js +0 -174
  98. package/dist/tools/index.js +0 -34
  99. package/dist/tools/question.js +0 -54
  100. package/dist/tools/read.js +0 -109
  101. package/dist/tools/search-searxng.js +0 -223
  102. package/dist/tools/search-serper.js +0 -189
  103. package/dist/tools/task.js +0 -165
  104. package/dist/tools/todo.js +0 -213
  105. package/dist/tools/web_fetch.js +0 -195
  106. package/dist/tools/web_search.js +0 -228
  107. package/dist/tools/write.js +0 -55
  108. package/dist/tui/App.js +0 -138
  109. package/dist/tui/ConfirmBar.js +0 -66
  110. package/dist/tui/CtxPicker.js +0 -68
  111. package/dist/tui/InputBar.js +0 -618
  112. package/dist/tui/MessageList.js +0 -718
  113. package/dist/tui/ModelPicker.js +0 -113
  114. package/dist/tui/QuestionBar.js +0 -136
  115. package/dist/tui/SessionPicker.js +0 -79
  116. package/dist/tui/Spinner.js +0 -6
  117. package/dist/tui/StatusBar.js +0 -22
  118. package/dist/tui/ThinkPicker.js +0 -75
  119. package/dist/tui/agent-runner.js +0 -223
  120. package/dist/tui/bracketed-paste.js +0 -37
  121. package/dist/tui/caret-pos.js +0 -179
  122. package/dist/tui/caret.js +0 -69
  123. package/dist/tui/click-count.js +0 -13
  124. package/dist/tui/diff-view.js +0 -61
  125. package/dist/tui/drag-state.js +0 -49
  126. package/dist/tui/hydrate.js +0 -129
  127. package/dist/tui/index.js +0 -264
  128. package/dist/tui/input-history.js +0 -125
  129. package/dist/tui/layout.js +0 -105
  130. package/dist/tui/mouse.js +0 -46
  131. package/dist/tui/overlay-input.js +0 -12
  132. package/dist/tui/paste-draft.js +0 -173
  133. package/dist/tui/prompt-queue.js +0 -24
  134. package/dist/tui/selection.js +0 -232
  135. package/dist/tui/session-switch.js +0 -28
  136. package/dist/tui/slash-commands.js +0 -129
  137. package/dist/tui/slash-handler.js +0 -615
  138. package/dist/tui/text-width.js +0 -113
  139. package/dist/tui/theme.js +0 -12
  140. package/dist/tui/token-info.js +0 -7
  141. package/dist/tui/tool-children.js +0 -19
  142. package/dist/tui/types.js +0 -1
  143. package/dist/tui/undo-stack.js +0 -14
  144. package/dist/tui/use-sgr-mouse.js +0 -29
  145. package/dist/tui-chat.js +0 -478
  146. package/dist/updater.js +0 -116
  147. package/dist/xml-search.js +0 -194
  148. package/docs/superpowers/plans/2026-08-16-batch1-tui-improvements.md +0 -1510
  149. package/docs/superpowers/plans/2026-08-16-batch2-cli-tools-api.md +0 -2105
  150. package/docs/superpowers/plans/2026-08-16-batch3-config-engineering.md +0 -1595
  151. package/docs/superpowers/plans/2026-08-16-input-caret.md +0 -782
  152. package/docs/superpowers/plans/2026-08-20-tui-completeness.md +0 -873
  153. package/docs/superpowers/plans/2026-08-20-unified-tui-default.md +0 -631
  154. package/docs/superpowers/plans/2026-08-23-cli-setup.md +0 -501
  155. package/docs/superpowers/plans/2026-08-23-input-paste-attachments.md +0 -475
  156. package/docs/superpowers/plans/2026-08-23-thinking-wire-profile.md +0 -450
  157. package/docs/superpowers/specs/2026-08-16-batch1-tui-improvements-design.md +0 -183
  158. package/docs/superpowers/specs/2026-08-16-batch2-cli-tools-api-design.md +0 -220
  159. package/docs/superpowers/specs/2026-08-16-batch3-config-engineering-design.md +0 -196
  160. package/docs/superpowers/specs/2026-08-16-input-caret-design.md +0 -63
  161. package/docs/superpowers/specs/2026-08-17-mouse-selection-design.md +0 -116
  162. package/docs/superpowers/specs/2026-08-20-config-http-alignment-design.md +0 -47
  163. package/docs/superpowers/specs/2026-08-20-mcp-plugins-alignment-design.md +0 -37
  164. package/docs/superpowers/specs/2026-08-20-sandbox-permissions-design.md +0 -68
  165. package/docs/superpowers/specs/2026-08-20-tui-completeness-design.md +0 -273
  166. package/docs/superpowers/specs/2026-08-20-unified-tui-default-design.md +0 -165
  167. package/docs/superpowers/specs/2026-08-23-cli-setup-design.md +0 -282
  168. package/docs/superpowers/specs/2026-08-23-input-paste-attachments-design.md +0 -174
  169. package/docs/superpowers/specs/2026-08-23-thinking-wire-profile-design.md +0 -140
package/dist/cli.js CHANGED
@@ -1,12 +1,538 @@
1
- import { runProgram } from "./cli/program.js";
2
- import { registerCommands } from "./cli/commands/index.js";
3
- import { initLogger, log } from "./logger.js";
4
- async function main() {
5
- initLogger();
6
- log("info", "min-agent started");
7
- await runProgram(process.argv.slice(2), registerCommands);
8
- }
9
- main().catch((err) => {
10
- console.error(`\x1b[31mFatal error: ${err.message}\x1b[0m`);
11
- process.exitCode = 1;
12
- });
1
+ import{createRequire as lW}from"node:module";var pW=Object.defineProperty;var dW=($)=>$;function iW($,f){this[$]=dW.bind(null,f)}var U0=($,f)=>{for(var Z in f)pW($,Z,{get:f[Z],enumerable:!0,configurable:!0,set:iW.bind(f,Z)})};var O=($,f)=>()=>($&&(f=$($=0)),f);var tW=lW(import.meta.url);import{writeFile as aW,rename as sW,unlink as eW}from"fs/promises";import{writeFileSync as $H,renameSync as fH,unlinkSync as ZH}from"fs";import{randomBytes as zH}from"crypto";import S3 from"path";function P8($){return S3.join(S3.dirname($),`.${S3.basename($)}.${process.pid}.${zH(4).toString("hex")}.tmp`)}async function of($,f){let Z=P8($);try{await aW(Z,f,"utf-8"),await sW(Z,$)}catch(z){throw await eW(Z).catch(()=>{}),z}}function T0($,f){let Z=P8($);try{$H(Z,f,"utf-8"),fH(Z,$)}catch(z){try{ZH(Z)}catch{}throw z}}var F$=()=>{};var p3={};U0(p3,{writeRoots:()=>g4,workspaceRoot:()=>c3,tightenSandbox:()=>Yz,setSandboxOverride:()=>E4,sandboxStatusLabel:()=>c4,sandboxNetworkLabel:()=>Nz,sandboxModeLabel:()=>h4,sandboxLaunchSource:()=>x3,sandboxEnforcementCaveat:()=>x4,runWithSandboxPolicy:()=>h3,resolveCheckedPath:()=>Pz,resetSandboxBackendCache:()=>XH,readRoots:()=>Hz,planSandboxedSpawn:()=>o3,pathAccessError:()=>q$,parseSandboxMode:()=>O$,parseSandboxConfig:()=>q1,parseNetworkPolicy:()=>g$,networkDeniedMessage:()=>n1,mergeSandboxConfig:()=>g3,isNetworkCommand:()=>Uz,isInsideRoot:()=>X8,getSandboxOverride:()=>QH,getEffectiveSandboxPolicy:()=>i0,detectSandboxBackend:()=>r3,clearSandboxOverride:()=>KH,checkPathAccess:()=>m3,bwrapBin:()=>Fz,buildSeatbeltProfile:()=>Mz,buildBwrapArgs:()=>qz,DEFAULT_SANDBOX_MODE:()=>u3,DEFAULT_NETWORK_POLICY:()=>E3});import{AsyncLocalStorage as JH}from"async_hooks";import{existsSync as pf,realpathSync as W8}from"fs";import v3 from"os";import L0 from"path";function O$($){if($==="off"||$==="workspace"||$==="strict")return $;return}function g$($){if($==="allow"||$==="deny")return $;return}function q1($){if($==null)return;if(typeof $==="string"){let Q=O$($);return Q?{mode:Q}:void 0}if(typeof $!=="object")return;let f=$,Z=O$(f.mode),z=g$(f.network),J=Array.isArray(f.extraWriteRoots)?f.extraWriteRoots.filter((Q)=>typeof Q==="string"&&Q.length>0):void 0,K=Array.isArray(f.extraReadRoots)?f.extraReadRoots.filter((Q)=>typeof Q==="string"&&Q.length>0):void 0;if(!Z&&!z&&!J&&!K)return;return{mode:Z,network:z,extraWriteRoots:J,extraReadRoots:K}}function g3($,f){if(!$&&!f)return;let Z=f?.extraWriteRoots??$?.extraWriteRoots,z=f?.extraReadRoots??$?.extraReadRoots;return{mode:f?.mode??$?.mode,network:f?.network??$?.network,...Z?{extraWriteRoots:Z}:{},...z?{extraReadRoots:z}:{}}}function E4($){t$={...t$,...$}}function KH(){t$={}}function QH(){return{...t$}}function x3(){if(t$.mode!=null||t$.network!=null)return"cli";if(Qz()!=null||Gz()!=null)return"env";return null}function h3($,f){return Kz.run($,f)}function c3(){try{return W8(process.cwd())}catch{return L0.resolve(process.cwd())}}function Qz(){return O$(process.env.MIN_AGENT_SANDBOX)}function Gz(){return g$(process.env.MIN_AGENT_SANDBOX_NETWORK)}function GH(){let $=q1(J0().sandbox);return{mode:t$.mode??Qz()??$?.mode??u3,network:t$.network??Gz()??$?.network??E3,extraWriteRoots:t$.extraWriteRoots??$?.extraWriteRoots??[],extraReadRoots:t$.extraReadRoots??$?.extraReadRoots??[],workspaceRoot:c3()}}function Yz($,f){let Z=f.mode&&$z[f.mode]>$z[$.mode]?f.mode:$.mode,z=f.network==="deny"||$.network==="deny"?"deny":"allow";return{...$,mode:Z,network:z}}function i0(){let $=GH(),f=Kz.getStore();if(!f)return $;if(f.replace)return{mode:f.mode??u3,network:f.network??E3,extraWriteRoots:f.extraWriteRoots??[],extraReadRoots:f.extraReadRoots??[],workspaceRoot:f.workspaceRoot??c3()};return Yz($,f)}function X8($,f){let Z=(Q)=>{let G=L0.resolve(Q);return process.platform==="win32"?G.toLowerCase():G},z=Z($),J=Z(f);if(z===J)return!0;let K=J.endsWith(L0.sep)?J:J+L0.sep;return z.startsWith(K)}function Pz($,f=process.cwd()){let Z=L0.resolve(f,$),z=[],J=Z;for(;;)try{let K=W8(J);return{lexical:Z,real:z.length===0?K:L0.resolve(K,...z)}}catch{let K=L0.dirname(J);if(K===J)return{lexical:Z,real:Z};z.unshift(L0.basename(J)),J=K}}function l$(...$){return L0.join(v3.homedir(),...$)}function Xz(){return[l$(".ssh"),l$(".gnupg"),l$(".aws"),L0.join(l$(".min-agent"),"config.json"),l$(".netrc"),l$(".npmrc"),l$(".pypirc"),l$(".git-credentials"),L0.join(l$(".config"),"gh"),L0.join(l$(".config"),"git","credentials"),"/etc/shadow","/etc/sudoers","/etc/master.passwd"]}function YH($){return Xz().some((f)=>{try{let Z=pf(f)?W8(f):L0.resolve(f);return X8($,Z)||L0.resolve($)===L0.resolve(f)}catch{return X8($,f)}})}function Wz($){let f=[],Z=new Set;for(let z of $){let J=L0.resolve(z),K=[J];try{K.push(W8(J))}catch{}for(let Q of K){let G=process.platform==="win32"?Q.toLowerCase():Q;if(Z.has(G))continue;Z.add(G),f.push(Q)}}return f}function PH(){let $=v3.homedir();return[L0.join($,".npm"),L0.join($,".bun"),L0.join($,".cache"),L0.join($,".local"),L0.join($,".yarn"),L0.join($,"Library","Caches"),L0.join($,"AppData","Local"),L0.join($,"AppData","Roaming")]}function g4($=i0()){return Wz([$.workspaceRoot,v3.tmpdir(),"/tmp","/var/tmp","/private/tmp","/private/var/tmp",...PH(),...$.extraWriteRoots.map((f)=>L0.resolve($.workspaceRoot,f))])}function Hz($=i0()){return Wz([$.workspaceRoot,...g4($),...$.extraReadRoots.map((f)=>L0.resolve($.workspaceRoot,f))])}function fz($,f){return f.some((Z)=>X8($,Z))}function m3($,f,Z=process.cwd(),z=i0()){let{real:J}=Pz($,Z);if(YH(J))return{ok:!1,message:"该路径受保护,无法访问。"};if(z.mode==="off")return{ok:!0,real:J};if(f==="write"){if(!fz(J,g4(z)))return{ok:!1,message:`无法写入工作区以外的路径: ${$}`};return{ok:!0,real:J}}if(z.mode==="strict"&&!fz(J,Hz(z)))return{ok:!1,message:`当前隔离级别不允许读取工作区以外的文件: ${$}`};return{ok:!0,real:J}}function q$($,f,Z){let z=m3($,f,Z);return z.ok?null:z.message}function Uz($){return/\b(curl|wget|nc|ncat|netcat|ssh|scp|sftp|ftp|telnet|nmap|ping|nslookup|dig|traceroute|rsync)\b/i.test($)||/\bgit\s+(clone|fetch|pull|push|ls-remote)\b/i.test($)||/\b(npm|pnpm|yarn|bun)\s+(install|add|publish|update|upgrade)\b/i.test($)}function n1(){return"当前设置不允许访问网络。"}function r3(){if(F1)return F1;let $=process.env.MIN_AGENT_SANDBOX_BACKEND;if($==="seatbelt"||$==="bwrap"||$==="none")return F1=$,F1;if(process.platform==="darwin"&&pf("/usr/bin/sandbox-exec"))F1="seatbelt";else if(process.platform==="linux"&&(pf("/usr/bin/bwrap")||pf("/usr/local/bin/bwrap")))F1="bwrap";else F1="none";return F1}function XH(){F1=void 0}function Zz($){return`"${$.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function Mz($){let f=g4($).map((J)=>`(subpath ${Zz(J)})`).join(`
2
+ `),Z=Xz().map((J)=>`(subpath ${Zz(L0.resolve(J))})`).join(`
3
+ `),z=$.network==="deny"?"(deny network*)":"";return`(version 1)
4
+ (allow default)
5
+ (deny file-write*)
6
+ (allow file-write-data (literal "/dev/null"))
7
+ (allow file-write*
8
+ ${f}
9
+ )
10
+ (deny file-read*
11
+ ${Z}
12
+ )
13
+ ${z}
14
+ `}function Fz(){if(pf("/usr/bin/bwrap"))return"/usr/bin/bwrap";return"/usr/local/bin/bwrap"}function qz($,f,Z){let z=["--die-with-parent","--ro-bind","/","/","--dev","/dev","--proc","/proc"],J=new Set;for(let K of g4($)){let Q=process.platform==="win32"?K.toLowerCase():K;if(J.has(Q))continue;if(J.add(Q),pf(K))z.push("--bind",K,K)}if($.network==="deny")z.push("--unshare-net");return z.push("--chdir",f,"/bin/sh","-c",Z),z}function x4($){if($==="off"||r3()!=="none")return null;return $==="strict"?"⚠ Command-level sandboxing isn't supported on this platform (requires macOS sandbox-exec or Linux bwrap); bash commands will be rejected in strict mode.":"⚠ Command-level sandboxing isn't supported on this platform (requires macOS sandbox-exec or Linux bwrap); bash commands won't be restricted to the workspace (file tools still validate paths)."}function o3($,f,Z,z=i0()){if(z.mode!=="off"){if(!m3(f,"write",process.cwd(),z).ok)return{error:`无法在工作区以外的目录执行命令: ${f}`}}let J=r3();if(z.network==="deny"&&J==="none"&&Uz($))return{error:n1()};let K=process.platform==="win32",Q=K?`chcp 65001 >nul && ${$}`:$,G={...Z,...K?{PYTHONIOENCODING:"utf-8"}:{}},Y=()=>({file:Q,args:[],shell:!0,cwd:f,env:G});if(z.mode==="off"){let X=Y();if(z.network==="deny"&&J==="none")X.warning=Jz;return X}if(J==="seatbelt")return{file:"/usr/bin/sandbox-exec",args:["-p",Mz(z),"/bin/sh","-c",Q],shell:!1,cwd:f,env:G};if(J==="bwrap")return{file:Fz(),args:qz(z,f,Q),shell:!1,cwd:f,env:G};if(z.mode==="strict")return{error:WH};let P=Y();return P.warning=z.network==="deny"?`${zz}
15
+ ${Jz}`:zz,P}function h4($){return $==="off"?"off":$==="strict"?"strict":"workspace"}function Nz($){return $==="deny"?"network denied":"network allowed"}function c4($=i0()){return`${h4($.mode)}, ${Nz($.network)}`}var u3="off",E3="allow",$z,Kz,t$,F1,zz="⚠ 当前平台不支持命令级隔离(需要 macOS 的 sandbox-exec 或 Linux 的 bwrap),bash 命令未在隔离环境中执行,工作区写入限制对它不生效(read/write/edit 等文件工具仍会校验路径)。",Jz="⚠ 当前平台不支持系统级网络隔离,禁止联网仅按命令名拦截,脚本或解释器仍可能访问网络。",WH="当前平台不支持命令级隔离(需要 macOS 的 sandbox-exec 或 Linux 的 bwrap),严格隔离模式下无法安全执行 bash 命令,已拒绝执行。可将隔离级别设为 workspace(文件工具仍会校验路径)或 off。";var E0=O(()=>{d();$z={off:0,workspace:1,strict:2},Kz=new JH,t$={}});var B1={};U0(B1,{withBuiltinProvider:()=>bz,setSandboxConfig:()=>Uf,setPermissionMode:()=>lf,setBudgetMaxCost:()=>a3,saveProjectConfig:()=>Q$,saveConfig:()=>I0,permissionModeLabel:()=>Hf,parseThinkingEffort:()=>R0,parsePermissionMode:()=>N$,parseMemoryMode:()=>g0,normalizeOllamaBaseURL:()=>N1,migrateLegacyConfig:()=>Az,mergeProjectOverGlobal:()=>t3,loadStoredConfig:()=>v1,loadProjectConfig:()=>y0,loadConfigFile:()=>Dz,loadConfig:()=>$0,isConfigured:()=>a$,getSandboxSnapshot:()=>r4,getRulesFile:()=>df,getProjectConfigFile:()=>H8,getProjectConfigDir:()=>S1,getPermissionSnapshot:()=>m4,getEffectiveConfig:()=>J0,getConfigDir:()=>X0,getBudgetSnapshot:()=>M8,getActiveProvider:()=>e,fetchModelsLive:()=>Mf,fetchModels:()=>Ff,DEFAULT_PERMISSION_MODE:()=>U8,BUILTIN_PROVIDER:()=>R1});import{readFileSync as i3,mkdirSync as Vz,existsSync as Lz,statSync as _z}from"fs";import Wf from"path";import HH from"os";function X0(){return process.env.MIN_AGENT_CONFIG_DIR??MH}function df(){return Wf.join(X0(),FH)}function S1(){return Wf.join(process.cwd(),".min-agent")}function H8(){return Wf.join(S1(),l3)}function y0(){let $=H8(),f;try{f=_z($)}catch{return{}}let Z=d3.get($);if(Z&&Z.mtimeMs===f.mtimeMs&&Z.size===f.size)return Z.config;let z;try{z=JSON.parse(i3($,"utf-8"))}catch{return console.warn(`\x1B[33m ⚠ Project config ${$} is not valid JSON; ignoring\x1B[0m`),{}}return d3.set($,{mtimeMs:f.mtimeMs,size:f.size,config:z}),z}function Q$($){let f=S1();if(!Lz(f)){console.warn(`\x1B[33m ⚠ Project write skipped: no .min-agent/ in ${process.cwd()}. Run "min-agent init" to create it first.\x1B[0m`);return}let{disabledSkills:Z,enabledSkills:z,...J}=$;T0(H8(),JSON.stringify({...J,...Z?.length?{disabledSkills:Z}:{},...z?.length?{enabledSkills:z}:{}},null,2)),d3.delete(H8())}function Dz($){let f;try{f=_z($)}catch{return{}}if(Xf&&Xf.file===$&&Xf.mtimeMs===f.mtimeMs&&Xf.size===f.size)return Xf.config;let Z;try{Z=JSON.parse(i3($,"utf-8"))}catch{return console.warn(`\x1B[33m ⚠ Config file ${$} is not valid JSON; using defaults\x1B[0m`),{}}return Xf={file:$,mtimeMs:f.mtimeMs,size:f.size,config:Z},Z}function qH(){let $=process.env[UH]?.trim().toLowerCase();return $!=="1"&&$!=="true"}function NH($){return($.providers??[]).some((f)=>Boolean(f.baseURL?.trim()&&f.apiKey?.trim()))}function bz($){if(!qH())return $;if(NH($))return $;if(($.providers??[]).length>0)return $;return{...$,providers:[{...R1}],activeProvider:$.activeProvider??R1.name}}function BH($){let f=$.providers??[];if(f.length!==1)return!1;let Z=f[0];if(!Z)return!1;return Z.name===R1.name&&Z.type===R1.type&&Z.baseURL===R1.baseURL&&Z.apiKey===R1.apiKey&&Z.defaultModel===R1.defaultModel&&Z.contextWindow==null}function VH($){if(!BH($))return $;let{providers:f,activeProvider:Z,...z}=$;return z}function v1(){let $=Dz(Wf.join(X0(),l3)),{config:f,migrated:Z}=Az($);if(Z)try{I0(f)}catch{}return f}function $0(){return bz(v1())}function Az($){if(!$.provider)return{config:$,migrated:!1};let{provider:Z,...z}=$;return{config:{...z,providers:[{name:"default",...Z}],activeProvider:"default"},migrated:!0}}function t3($,f){let Z=f.activeProvider??$.activeProvider,z=f.sampling?{...$.sampling,...f.sampling}:$.sampling,J=f.budget?{...$.budget,...f.budget}:$.budget,K=N$(f.permission)??N$($.permission),Q=R0(f.thinking)??R0($.thinking),G=g0(f.memory)??g0($.memory),Y=g3(q1($.sandbox),q1(f.sandbox)),P=f.compaction?{...$.compaction,...f.compaction}:$.compaction,X=f.agent?{...$.agent,...f.agent}:$.agent,W=$.providers;if(f.defaultModel&&W&&W.length>0){let H=Z?W.findIndex((F)=>F.name===Z):0,M=H>=0?H:0;W=W.map((F,q)=>q===M?{...F,defaultModel:f.defaultModel}:F)}return{...$,activeProvider:Z,sampling:z,budget:J,permission:K,...Q?{thinking:Q}:{},...G?{memory:G}:{},...Y?{sandbox:Y}:{},compaction:P,agent:X,...W?{providers:W}:{}}}function J0(){return t3($0(),y0())}function M8(){let $=$0(),f=y0(),Z=t3($,f).budget?.maxCostUSD,z=f.budget?.maxCostUSD!=null?"project":$.budget?.maxCostUSD!=null?"global":null;return{maxCostUSD:Z,source:z}}function N$($){if($==="ask"||$==="accept-edits"||$==="allow-all")return $;return}function R0($){if(typeof $!=="string")return;return LH[$.trim().toLowerCase()]}function g0($){if($===!0)return"on";if($===!1)return"off";if(typeof $!=="string")return;return _H[$.trim().toLowerCase()]}function Hf($){if($==="allow-all")return"allow all";if($==="accept-edits")return"accept edits";return"ask"}function m4(){let $=$0(),f=y0(),Z=N$(f.permission)??N$($.permission)??U8,z=N$(f.permission)!=null?"project":N$($.permission)!=null?"global":null;return{permission:Z,source:z}}function lf($,f){if(f==="project"){let Z=y0();Q$({...Z,permission:$});return}I0({...$0(),permission:$})}function Uf($,f){if(f==="project"){let J=y0(),K=q1(J.sandbox)??{};Q$({...J,sandbox:{...K,...$}});return}let Z=$0(),z=q1(Z.sandbox)??{};I0({...Z,sandbox:{...z,...$}})}function r4(){let $=i0(),f=x3(),Z=q1(y0().sandbox),z=q1($0().sandbox),J=Boolean(Z?.mode||Z?.network||Z?.extraWriteRoots?.length||Z?.extraReadRoots?.length),K=Boolean(z?.mode||z?.network||z?.extraWriteRoots?.length||z?.extraReadRoots?.length),Q=f??(J?"project":K?"global":null);return{mode:$.mode,network:$.network,extraWriteRoots:$.extraWriteRoots,extraReadRoots:$.extraReadRoots,source:Q,label:c4($)}}function a3($,f){if(f==="project"){let z=y0();Q$({...z,budget:{...z.budget,maxCostUSD:$}});return}let Z=$0();I0({...Z,budget:{...Z.budget,maxCostUSD:$}})}function e($){if(!$.providers||$.providers.length===0)return;if($.activeProvider){let f=$.providers.find((Z)=>Z.name===$.activeProvider);if(f)return f}return $.providers[0]}function N1($){let f=$.replace(/\/$/,"");return f.endsWith("/v1")?f:`${f}/v1`}function I0($){let f=X0();Vz(f,{recursive:!0}),T0(Wf.join(f,l3),JSON.stringify(VH($),null,2)),Xf=null}function a$(){let $=$0(),f=e($);return!!(f?.baseURL&&f?.apiKey)}async function Bz($,f){let Z=new URL($);Z.searchParams.set("_t",Date.now().toString());let z=await fetch(Z.toString(),{headers:{Authorization:`Bearer ${f}`,"Cache-Control":"no-cache, no-store, must-revalidate",Pragma:"no-cache",Expires:"0"},cache:"no-store",signal:AbortSignal.timeout(1e4)});if(!z.ok)return{models:[],ok:!1,status:z.status};let J=await z.json();return{models:DH(J),ok:!0,status:z.status}}function DH($){return(Array.isArray($)?$:$!==null&&typeof $==="object"&&("data"in $)&&Array.isArray($.data)?$.data:[]).map((Z)=>Z!==null&&typeof Z==="object"&&("id"in Z)&&typeof Z.id==="string"?Z.id:null).filter((Z)=>Z!=null).sort()}function jz(){return Wf.join(X0(),bH)}function s3($){return $.replace(/\/$/,"")}function Cz(){let $=jz();if(!Lz($))return{};try{let f=JSON.parse(i3($,"utf-8"));if(!f||typeof f!=="object"||Array.isArray(f))return{};return Object.fromEntries(Object.entries(f).filter((Z)=>Array.isArray(Z[1])&&Z[1].every((z)=>typeof z==="string")))}catch{return{}}}function AH($){return Cz()[s3($)]??[]}function jH($,f){let Z=Cz();Z[s3($)]=f,Vz(X0(),{recursive:!0}),T0(jz(),JSON.stringify(Z))}async function Mf($,f){try{let Z=s3($),z=await Bz(`${Z}/models`,f);if(z.models.length===0&&!Z.endsWith("/v1"))z=await Bz(`${Z}/v1/models`,f);if(z.ok&&z.models.length>0)return jH(Z,z.models),{models:z.models,ok:!0,status:z.status};if(!z.ok)return{models:[],ok:!1,status:z.status};return{models:[],ok:!0,status:z.status}}catch{return{models:[],ok:!1}}}async function Ff($,f){let Z=await Mf($,f);if(Z.models.length>0)return Z.models;let z=AH($);if(z.length>0){let J=Z.status==null&&!Z.ok?" — network unavailable":"";console.log(`\x1B[90m (using cached model list${J})\x1B[0m`)}return z}var U8="accept-edits",R1,UH="MIN_AGENT_NO_BUILTIN_PROVIDER",MH,l3="config.json",FH="rules.md",Xf=null,d3,LH,_H,bH="models-cache.json";var d=O(()=>{F$();E0();R1={name:"openrouter",type:"openai-compatible",baseURL:"https://openrouter.ai/api/v1",apiKey:"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",defaultModel:"openrouter/free"},MH=Wf.join(HH.homedir(),".min-agent");d3=new Map;LH={off:"off",none:"off",low:"low",minimal:"low",medium:"medium",high:"high",max:"max",xhigh:"max","extra-high":"max",extra_high:"max",extrahigh:"max"};_H={on:"on",true:"on",enable:"on",enabled:"on",off:"off",false:"off",disable:"off",disabled:"off"}});function OH($,f){let Z=[],z=new Set;for(let J of f){let K=$[J];if(typeof K!=="string")continue;let Q=K.trim();if(!Q||z.has(Q))continue;z.add(Q),Z.push(Q)}return Z}function wz($){if($==null)return null;if(typeof $==="string"){let J=$.trim();return J.length>0?J:null}if(typeof $==="number"||typeof $==="boolean")return String($);if(typeof $!=="object"||Array.isArray($))return null;let f=$,Z=OH(f,CH);if(Z.length>0)return Z.join(" — ");let z=f.key;return typeof z==="string"&&z.trim()?z.trim():null}function u1($){if(typeof $==="string")return $;return wz($)??""}function E1($){if($==null)return[];let f=Array.isArray($)?$:[$],Z=[],z=new Set;for(let J of f){let K=wz(J);if(!K||z.has(K))continue;z.add(K),Z.push(K)}return Z}function o4($){let f=$.trim().toLowerCase();return f==="其他"||f==="其它"||f==="other"}function g1($){if($.length===0)return[];let f=$.filter((z)=>!o4(z));if(f.length===0)return[Oz];let Z=$.find((z)=>o4(z));return[...f,Z??Oz]}function yz($){let{multiple:f,choices:Z,index:z,checked:J,otherText:K}=$;if(Z.length===0){let X=K.trim();return X?[X]:null}let Q=Z.findIndex((X)=>o4(X)),G=K.trim();if(!f){if(z<0||z>=Z.length)return null;if(z===Q)return G?[G]:null;return[Z[z]]}let Y=[],P=[...J].sort((X,W)=>X-W);for(let X of P){if(X<0||X>=Z.length)continue;if(X===Q){if(!G)return null;Y.push(G);continue}Y.push(Z[X])}return Y.length>0?Y:null}function Tz($){let f=$.trim();if(f.startsWith("["))try{let Z=JSON.parse(f);if(Array.isArray(Z)&&Z.length>0&&Z.every((z)=>typeof z==="string")){let z=Z.map((J)=>J.trim()).filter(Boolean);if(z.length>0)return z}}catch{}return f?[f]:[]}function Iz($){if($.length===0)return"User cancelled the question";if($.length===1)return`User chose: ${$[0]}`;return`User chose: ${$.join("; ")}`}var CH,Oz="其他";var p4=O(()=>{CH=["label","description","title","text","value","content","prompt"]});var Q9={};U0(Q9,{setTuiQuestion:()=>V8,setTuiConfirm:()=>B8,setPermissionOverride:()=>q8,setConfirmReadline:()=>TH,setAutoApprove:()=>d4,runWithConfirmContext:()=>z9,isEditAutoApprove:()=>Nf,isDangerousCommand:()=>K9,isAutoApprove:()=>qf,getPermissionOverride:()=>i4,getPermissionMode:()=>Z9,confirm:()=>x$,askQuestion:()=>J9});import{AsyncLocalStorage as wH}from"async_hooks";import yH from"readline";function d4($){kz=$}function qf(){let $=N8.getStore();if($)return $.autoApprove;if(kz)return!0;return Z9()==="allow-all"}function q8($){F8=$}function i4(){return F8}function Z9(){if(F8)return F8;let $=J0();return $.permission==="allow-all"||$.permission==="accept-edits"||$.permission==="ask"?$.permission:U8}function Nf(){if(qf())return!0;return Z9()==="accept-edits"}function z9($,f){return N8.run($,f)}function TH($){e3=$}function B8($){$9=$}function V8($){f9=$}async function J9($,f,Z=!1){let z=u1($),J=g1(E1(f)),K=J.length>0?J:void 0,Q=N8.getStore();if(Q){if(Q.autoApprove)return null;if(Q.onQuestion)return Q.onQuestion(z,K,Z);return null}if(f9)return f9(z,K,Z);if(!process.stdin.isTTY)return console.log(`
16
+ \x1B[33m❓ ${z} (no interactive terminal — skipped)\x1B[0m`),null;if(console.log(),console.log(`\x1B[33m❓ ${z}\x1B[0m`),K){for(let G=0;G<K.length;G++)console.log(`\x1B[90m ${G+1}. ${K[G]}\x1B[0m`);if(Z)console.log("\x1B[90m (可勾选多项;最后一项可自己输入)\x1B[0m")}return new Promise((G)=>{let Y=yH.createInterface({input:process.stdin,output:process.stdout});Y.question("\x1B[36m → \x1B[0m",(P)=>{Y.close(),G(P.trim()||"(no answer)")})})}async function x$($){let f=N8.getStore();if(f){if(f.autoApprove)return!0;if(f.onConfirm)return f.onConfirm($);return!1}if(qf())return!0;if($9)return $9($);if(!process.stdin.isTTY)return console.log(`
17
+ \x1B[33m⚠ Rejected (no interactive terminal): ${$}\x1B[0m`),!1;return e3?.pause(),process.stdout.write(`
18
+ \x1B[90m┌─ 即将执行 ─────────────────────────────────\x1B[0m
19
+ `),process.stdout.write(`\x1B[90m│\x1B[0m ${$}
20
+ `),process.stdout.write(`\x1B[90m└────────────────────────────────────────────\x1B[0m
21
+ `),process.stdout.write(`
22
+ `),new Promise((Z)=>{let z=process.stdin.isRaw,J=process.stdin.readableEncoding;if(process.stdin.isTTY)process.stdin.setRawMode(!0);process.stdin.resume(),process.stdin.setEncoding("utf8");let K=1,Q="",G=!1,Y=setTimeout(()=>{G=!0},0);Y.unref?.();let P=(M)=>{if(M==="A"||M==="D")K=0;else if(M==="B"||M==="C")K=1;else return;X()},X=()=>{let M=K===0,F=K===1;process.stdout.write("\r\x1B[K"),process.stdout.write(M?"\x1B[1;32m▸ 允许\x1B[0m":"\x1B[90m 允许\x1B[0m"),process.stdout.write(" "),process.stdout.write(F?"\x1B[1;31m▸ 拒绝\x1B[0m":"\x1B[90m 拒绝\x1B[0m"),process.stdout.write(" \x1B[90m←→/↑↓ 选择 · Enter 确认 · y/n 快捷 · Esc 拒绝\x1B[0m")},W=(M)=>{if(clearTimeout(Y),process.stdin.removeListener("data",H),process.stdin.isTTY)process.stdin.setRawMode(z??!1);if(J)process.stdin.setEncoding(J);process.stdout.write(`
23
+
24
+ `),e3?.resume(),Z(M)};X();let H=(M)=>{Q+=M;while(Q.length>0){if(Q[0]==="\x1B"){if(Q[1]==="["){let q=Q.slice(2).search(/[A-Za-z~]/);if(q===-1)return;let U=Q[2+q];Q=Q.slice(3+q),P(U);continue}if(Q[1]==="O"){if(Q.length<3)return;let q=Q[2];Q=Q.slice(3),P(q);continue}if(Q.length===1){setTimeout(()=>{if(Q==="\x1B")Q="",W(!1)},50).unref?.();return}Q=Q.slice(1),W(!1);return}let F=Q[0];if(Q=Q.slice(1),F===`
25
+ `&&!G)continue;if(F==="\r"||F===`
26
+ `){if(!G)continue;W(K===0);return}if(F==="y"||F==="Y"){W(!0);return}if(F==="n"||F==="N"){W(!1);return}}};process.stdin.on("data",H)})}function K9($){return[/\brm\s+(-[a-z]*[rf][a-z]*|--recursive)\s/,/\bsudo\b/,/\bmkfs\b/,/\bdd\s+/,/\b(shutdown|reboot|halt|poweroff)\b/,/\bgit\s+(push|reset\s+--hard|clean\s+-[a-z]*f|rebase)/,/\bnpm\s+(publish|unpublish)\b/,/\b(drop|truncate)\s+(table|database)\b/i,/\bformat\b.*\b[a-z]:\b/i,/\bfind\b[^|;&]*\s+-delete\b/,/\|\s*(ba|z|fi)?sh\b/,/\bchmod\s+(-[a-zA-Z]+\s+)?[0-7]{3,4}\b/,/\bchown\s+-R\b/,/\bkill(all)?\s+(-9|-[a-z]*9)/,/\b(pkill|killall)\b/,/\bgit\s+checkout\s+\./,/\bgit\s+stash\b/,/\b(docker|podman)\s+(rm|prune|system)\b/,/\b(shred|wipefs)\b/,/\b(cp|mv)\s+-[a-z]*f\b/,/[^<>=!&]\s*>>?\s*[^<>=&]|^\s*>>?\s*[^<>=&]/,/:\(\)\s*\{/,/>+\s*\/dev\/(sd[a-z]+|nvme\d|disk\d)/].some((Z)=>Z.test($))}var kz=!1,F8,N8,e3=null,$9=null,f9=null;var G$=O(()=>{d();p4();N8=new wH});var nz={};U0(nz,{userError:()=>s$,runtimeError:()=>G9,formatCliError:()=>L8,exitCodeFor:()=>Y9,CliError:()=>a});function s$($,f){return new a($,{exitCode:1,hint:f})}function G9($,f){return new a($,{exitCode:2,hint:f})}function L8($){if($ instanceof a)return $.hint?`✖ ${$.message}
27
+ → ${$.hint}`:`✖ ${$.message}`;return`✖ ${$ instanceof Error?$.message:String($)}`}function Y9($){if($ instanceof a)return $.exitCode;return 2}var a;var Y$=O(()=>{a=class a extends Error{exitCode;hint;constructor($,f){super($);this.name="CliError",this.exitCode=f?.exitCode??1,this.hint=f?.hint}}});import{Option as OA}from"commander";function P9($,f="global"){if($.project)return"project";if($.global)return"global";return f}function Rz($){let f=O$($);if(!f)throw s$(`Invalid --sandbox value: "${$}"`,"use one of: off, workspace, strict");return f}function Sz($){let f=g$($);if(!f)throw s$(`Invalid --network value: "${$}"`,"use one of: allow, deny");return f}function vz($){let f=N$($);if(!f)throw s$(`Invalid --permission value: "${$}"`,"use one of: ask, accept-edits, allow-all");return f}function uz($){let f=R0($);if(!f)throw s$(`Invalid --think value: "${$}"`,"use one of: off, low, medium, high, max");return f}function Ez($){let f=g0($);if(!f)throw s$(`Invalid --memory value: "${$}"`,"use one of: on, off");return f}function l4($){return(f)=>{let Z=Number.parseInt(f,10);if(!Number.isFinite(Z)||Z<=0)throw s$(`Invalid ${$} value: "${f}"`,"use a positive integer");return Z}}var _8=O(()=>{E0();d();Y$()});import{existsSync as IH,readFileSync as kH}from"fs";import D8 from"path";import{fileURLToPath as nH}from"url";function b8(){let $=D8.dirname(nH(import.meta.url)),f=$;for(;;){let Z=D8.join(f,"package.json");if(IH(Z))try{if(JSON.parse(kH(Z,"utf-8")).name===RH)return f}catch{}let z=D8.dirname(f);if(z===f)return D8.resolve($,"..");f=z}}var RH="min-agent";var X9=()=>{};import{readFileSync as SH}from"fs";import vH from"path";import{spawnSync as uH}from"child_process";function hH(){return[xz,...hz].join(" ")}function Bf(){try{let $=vH.join(b8(),"package.json"),f=JSON.parse(SH($,"utf-8"));return typeof f.version==="string"&&f.version.length>0?f.version:"0.0.0"}catch{return"0.0.0"}}function cz($,f){let Z=$.split("-")[0].split(".").map(Number),z=f.split("-")[0].split(".").map(Number);for(let J=0;J<Math.max(Z.length,z.length);J++){let K=Z[J]??0,Q=z[J]??0,G=Number.isFinite(K)?K:0,Y=Number.isFinite(Q)?Q:0;if(G!==Y)return G-Y}return 0}function cH($){if(typeof $!=="string"||!gH.test($))return null;return $}async function mz($=fetch){let f;try{f=await $(EH,{signal:AbortSignal.timeout(xH),headers:{Accept:"application/json"}})}catch{return null}if(!f.ok)return null;let Z;try{Z=await f.json()}catch{return null}if(!Z||typeof Z!=="object"||!("version"in Z))return null;return cH(Z.version)}async function rz($){let f=$?.currentVersion??Bf(),Z=await mz($?.fetchFn);return{current:f,latest:Z,updateAvailable:Z!==null&&cz(f,Z)<0}}function mH(){let $=uH(xz,[...hz],{stdio:"inherit",shell:process.platform==="win32",env:process.env});if($.error)return{ok:!1,missing:$.error.code==="ENOENT"};return{ok:$.status===0}}async function oz($={}){let f=$.log??((G)=>console.log(G)),Z=$.error??((G)=>console.error(G)),z=$.currentVersion?.()??Bf(),J=hH();f(`当前版本: ${z}`);let K=$.fetchLatest?await $.fetchLatest():await mz();if(!K)return Z(`无法检查新版本(网络不可用)。请稍后重试,或手动执行: ${J}`),{status:"check-failed",current:z,latest:null};if(cz(z,K)>=0)return f(`已是最新版本 (${K})`),{status:"up-to-date",current:z,latest:K};f(`发现新版本: ${K}`),f(`正在执行 ${J} ...`);let Q=($.install??mH)();if(!Q.ok){if(Q.missing)Z(`未找到 npm。请先安装 Node.js,然后执行: ${J}`);else Z(`自动升级失败。请手动执行: ${J}`);return{status:"install-failed",current:z,latest:K}}return f(`✓ 已升级到 ${K}`),{status:"updated",current:z,latest:K}}var gz="min-agent",EH,xz="npm",hz,gH,xH=1e4;var t4=O(()=>{X9();EH=`https://registry.npmjs.org/${gz}/latest`,hz=["install","-g",gz],gH=/^\d+\.\d+\.\d+/});import{readFileSync as rH,mkdirSync as oH,existsSync as pH}from"fs";import az from"path";function tH(){let $=process.env.MIN_AGENT_MODELS_API_URL?.trim();if(!$)return dH;return $.replace(/\/$/,"")}function sz(){return az.join(X0(),"model-catalog-cache.json")}function ez(){let $=sz();if(!pH($))return{};try{return JSON.parse(rH($,"utf-8"))}catch{return{}}}function aH($){let f=sz();oH(az.dirname(f),{recursive:!0}),T0(f,JSON.stringify($))}function tf($){let f=M9.get($);if(f&&f.version===U9&&Date.now()-f.timestamp<=pz)return f;let Z=ez()[$];if(!Z||Z.version!==U9||Date.now()-Z.timestamp>pz)return null;return M9.set($,Z),Z}function sH($,f){M9.set($,f);let Z=ez();Z[$]=f,aH(Z)}function x1($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function $J($){if(!Array.isArray($))return{toggle:!1,efforts:[]};let f=!1,Z=new Set;for(let z of $){if(!x1(z))continue;if(z.type==="toggle")f=!0;if(z.type==="effort"&&Array.isArray(z.values)){for(let J of z.values)if(typeof J==="string"&&J&&J!=="default")Z.add(J)}}if(Z.has("none"))f=!0;return{toggle:f,efforts:[...Z]}}function eH($,f){let Z=f.toLowerCase(),z=$.find((K)=>K.id.toLowerCase()===Z);if(z)return z;let J=$.find((K)=>{let Q=K.id.toLowerCase();return Q.endsWith(`/${Z}`)||Z.endsWith(`/${Q}`)});if(J)return J;return $.find((K)=>K.name?.toLowerCase()===Z)}function $U($,f){if(!f||$.length===0)return;let Z="";try{Z=new URL(f).hostname.toLowerCase()}catch{return}return $.find((z)=>{let J=String(z.providerId??"").toLowerCase().replace(/_/g,"-");if(!J)return!1;if(Z.includes(J))return!0;let K=J.split("-")[0]??"";return K.length>=4&&Z.includes(K)})}function ZU($){return $.efforts.some((f)=>{let Z=R0(f);return Boolean(Z&&Z!=="off")})}function zU($){let f=$.map((X)=>$J(X.reasoningOptions)).filter((X)=>X.toggle||X.efforts.length>0);if(f.length===0)return{toggle:!1,efforts:[]};let Z=f.filter(ZU),z=f.length/2,J=Z.length===0?Number.POSITIVE_INFINITY:Z.length/2,K=0,Q=0,G=new Map;for(let X of f)if(X.toggle||X.efforts.includes("none"))K++;for(let X of Z){let W=new Set;for(let H of X.efforts){if(H==="xhigh"||H==="extra-high")Q++;let M=R0(H);if(!M||M==="off"||W.has(M))continue;W.add(M),G.set(M,(G.get(M)??0)+1)}}let Y=K>=z,P=[];if(Y)P.push("none");for(let X of fU)if((G.get(X)??0)>=J)P.push(X);if(P.includes("max")&&Q>0)P.push("xhigh");return{toggle:Y,efforts:P}}function iz($){let f=$?.context;if(typeof f==="number"&&Number.isFinite(f)&&f>=4096)return Math.floor(f);return}function JU($,f,Z){let z=$.offerings??[],J=$U(z,Z),K=J?$J(J.reasoningOptions):zU(z),Q=iz(J?.limit)??iz($.limit);return{version:U9,modelId:f,lonaeId:$.id,...Q!=null?{contextWindow:Q}:{},reasoning:K,timestamp:Date.now()}}async function H9($){try{let f=await fetch($,{signal:AbortSignal.timeout(lH)});if(!f.ok)return null;return await f.json()}catch{return null}}function lz($){let f=x1($)?$:null,Z=f&&x1(f.data)?f.data:f;if(!Z||typeof Z.id!=="string")return null;let z=x1(Z.limit)?{context:typeof Z.limit.context==="number"?Z.limit.context:void 0}:void 0,J=Array.isArray(Z.offerings)?Z.offerings.filter(x1).map((K)=>({providerId:typeof K.providerId==="string"?K.providerId:void 0,limit:x1(K.limit)?{context:typeof K.limit.context==="number"?K.limit.context:void 0}:void 0,reasoningOptions:K.reasoningOptions})):[];return{id:Z.id,limit:z,reasoning:Z.reasoning===!0,offerings:J}}function KU($){let f=x1($)?$:null;return(f&&Array.isArray(f.data)?f.data:Array.isArray($)?$:[]).flatMap((z)=>{if(!x1(z)||typeof z.id!=="string")return[];return[{id:z.id,name:typeof z.name==="string"?z.name:void 0,context:typeof z.context==="number"?z.context:void 0}]})}function tz($){return $.split("/").map((f)=>encodeURIComponent(f)).join("/")}async function QU($){let f=tH();if($.includes("/")){let J=lz(await H9(`${f}/api/v1/models/${tz($)}`));if(J)return J}let Z=KU(await H9(`${f}/api/v1/models?q=${encodeURIComponent($)}&page_size=20`)),z=eH(Z,$);if(!z)return null;return lz(await H9(`${f}/api/v1/models/${tz(z.id)}`))}async function A8($,f){let Z=tf($);if(Z)return Z;let z=dz.get($);if(z!==void 0&&Date.now()-z<=iH)return null;let J=W9.get($);if(J)return J;let K=QU($).then((Q)=>{if(!Q)return dz.set($,Date.now()),null;let G=JU(Q,$,f);return sH($,G),G});W9.set($,K);try{return await K}finally{W9.delete($)}}var dH="https://models.lonae.com",pz=604800000,U9=3,iH=3600000,lH=1e4,M9,W9,dz,fU;var F9=O(()=>{F$();d();M9=new Map,W9=new Map,dz=new Map;fU=["low","medium","high","max"]});import{readFileSync as GU,mkdirSync as YU,existsSync as PU}from"fs";import zJ from"path";function sf($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function C8($){return $.replace(/\/$/,"").replace(/\/v1$/i,"")}function KJ($,f){let Z="";try{Z=new URL($).hostname.toLowerCase()}catch{Z=C8($).toLowerCase()}let z=f.trim().toLowerCase();return Z?`${Z}::${z}`:z}function af($){let f=typeof $==="string"&&$.trim()!==""?Number($):$;if(typeof f!=="number"||!Number.isFinite(f)||f<JJ)return;return Math.floor(f)}function HU($){let f=[];for(let[Z,z]of Object.entries($))if(Z==="context_length"||Z.endsWith(".context_length")){let J=af(z);if(J!=null)f.push(J)}if(f.length===0)return;return Math.max(...f)}function UU($){if(typeof $==="number")return af($);if(sf($))return af($.num_ctx);if(typeof $!=="string")return;let f=$.match(/(?:^|\n)\s*num_ctx\s+(\d+)/);if(f?.[1])return af(Number(f[1]));return af($)}function MU($){if(!Array.isArray($))return null;return $.some((f)=>String(f).toLowerCase()==="thinking")}function FU($,f){if($!=null)return $;if(f!=null)return Math.min(f,B9);return}function QJ($,f){let Z=sf($.options)?$.options:{};return{...$,options:{...Z,num_ctx:f}}}function GJ($,f){if(f===!1)return!1;if(!$)return;if(!$.thinkingEnabled)return!1;let Z=$.reasoningEffort;if(Z==="low"||Z==="medium"||Z==="high")return Z;if(Z==="none")return!1;return"high"}function YJ($,f){let Z=e(J0());if(typeof Z?.contextWindow==="number"&&Number.isFinite(Z.contextWindow)&&Z.contextWindow>=JJ)return Math.floor(Z.contextWindow);return h1($,f??Z?.baseURL)?.contextWindow??j8}function qU($,f){let Z=sf($)?$:{},z=sf(Z.model_info)?Z.model_info:{},J=FU(UU(Z.parameters),HU(z));return{version:a4,modelId:f,...J!=null?{contextWindow:J}:{},thinking:MU(Z.capabilities),timestamp:Date.now()}}function PJ($){if($.thinking===!1)return["off"];return["off","low","medium","high","max"]}function XJ(){return zJ.join(X0(),"ollama-model-cache.json")}function WJ(){let $=XJ();if(!PU($))return{};try{let f=JSON.parse(GU($,"utf-8"));if(!sf(f))return{};let Z={};for(let[z,J]of Object.entries(f)){if(!sf(J)||J.version!==a4)continue;if(typeof J.modelId!=="string")continue;let K=J.thinking===!0||J.thinking===!1?J.thinking:null,Q=af(J.contextWindow),G=typeof J.timestamp==="number"?J.timestamp:0;Z[z]={version:a4,modelId:J.modelId,...Q!=null?{contextWindow:Q}:{},thinking:K,timestamp:G}}return Z}catch{return{}}}function NU($){let f=XJ();YU(zJ.dirname(f),{recursive:!0}),T0(f,JSON.stringify($))}function h1($,f){let Z=KJ(f??"",$),z=N9.get(Z);if(z&&z.version===a4&&Date.now()-z.timestamp<=fJ)return z;let J=WJ()[Z];if(!J||J.version!==a4||Date.now()-J.timestamp>fJ)return null;return N9.set(Z,J),J}function BU($,f){N9.set($,f);let Z=WJ();Z[$]=f,NU(Z)}async function VU($,f){try{let Z=await fetch(`${C8($)}/api/show`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:f}),signal:AbortSignal.timeout(WU)});if(!Z.ok)return null;return await Z.json()}catch{return null}}async function s4($,f){let Z=f??"",z=KJ(Z,$),J=h1($,Z);if(J)return J;let K=ZJ.get(z);if(K!==void 0&&Date.now()-K<=XU)return null;let Q=q9.get(z);if(Q)return Q;let G=VU(Z,$).then((Y)=>{if(!Y)return ZJ.set(z,Date.now()),null;let P=qU(Y,$);return BU(z,P),P});q9.set(z,G);try{return await G}finally{q9.delete(z)}}var a4=2,fJ=604800000,XU=3600000,WU=8000,JJ=512,j8=2048,B9=32768,N9,q9,ZJ;var O8=O(()=>{d();F$();N9=new Map,q9=new Map,ZJ=new Map});function s0($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function LU($){return typeof $==="string"?$:$ instanceof URL?$.href:$.url}function _U($){try{return/\/chat\/completions\/?$/i.test(new URL($).pathname)}catch{return/\/chat\/completions\/?$/i.test($)}}function DU($){let f=$.replace(/\/v1\/chat\/completions\/?$/i,"").replace(/\/chat\/completions\/?$/i,"");return`${C8(f)}/api/chat`}async function FJ($){if($==null)return null;if(typeof $==="string")return $;if($ instanceof Uint8Array)return new TextDecoder().decode($);if($ instanceof ArrayBuffer)return new TextDecoder().decode($);if(Buffer?.isBuffer($))return $.toString("utf8");if(typeof Blob<"u"&&$ instanceof Blob)return await $.text();if(typeof ReadableStream<"u"&&$ instanceof ReadableStream){let f=$.getReader(),Z=[];for(;;){let{done:Q,value:G}=await f.read();if(Q)break;if(G)Z.push(G)}let z=Z.reduce((Q,G)=>Q+G.length,0),J=new Uint8Array(z),K=0;for(let Q of Z)J.set(Q,K),K+=Q.length;return new TextDecoder().decode(J)}return null}function bU($){return $.match(/^data:[^;]+;base64,(.+)$/s)?.[1]??null}function AU($){if(typeof $==="string")return{text:$,images:[]};if(!Array.isArray($))return{text:$==null?"":JSON.stringify($),images:[]};let f=[],Z=[];for(let z of $){if(!s0(z))continue;if(z.type==="text"&&typeof z.text==="string")f.push(z.text);else if(z.type==="image_url"){let J=s0(z.image_url)?z.image_url.url:void 0;if(typeof J==="string"){let K=bU(J);if(K)Z.push(K)}}else if(typeof z.text==="string")f.push(z.text)}return{text:f.join(`
28
+ `),images:Z}}function jU($){if(s0($))return $;if(typeof $!=="string"||!$.trim())return{};try{let f=JSON.parse($);return s0(f)?f:{value:f}}catch{return{value:$}}}function CU($){if(typeof $==="string")return $;try{return JSON.stringify($??{})}catch{return"{}"}}function OU($){if(!Array.isArray($)||$.length===0)return;return $.map((f)=>{let Z=s0(f)?f:{},z=s0(Z.function)?Z.function:Z;return{function:{name:typeof z.name==="string"?z.name:"",arguments:jU(z.arguments)}}})}function wU($){if(!Array.isArray($))return[];return $.map((f)=>{let Z=s0(f)?f:{},{text:z,images:J}=AU(Z.content),K={role:typeof Z.role==="string"?Z.role:"user",content:z};if(J.length>0)K.images=J;let Q=OU(Z.tool_calls);if(Q)K.tool_calls=Q;return K})}function yU($){let f=s0($.options)?{...$.options}:{};if(typeof $.temperature==="number")f.temperature=$.temperature;if(typeof $.top_p==="number")f.top_p=$.top_p;if(typeof $.seed==="number")f.seed=$.seed;if(typeof $.max_tokens==="number")f.num_predict=$.max_tokens;if(typeof $.max_completion_tokens==="number")f.num_predict=$.max_completion_tokens;if(Array.isArray($.stop)||typeof $.stop==="string")f.stop=$.stop;return f}function TU($,f){let Z={model:$.model,messages:wU($.messages),stream:$.stream!==!1,options:yU($)};if(Array.isArray($.tools)&&$.tools.length>0)Z.tools=$.tools;if($.format!=null)Z.format=$.format;if(f.think!==void 0)Z.think=f.think;return QJ(Z,f.numCtx)}function qJ($,f){if(Array.isArray(f)&&f.length>0)return"tool_calls";if($==="length"||$==="max_tokens")return"length";return"stop"}function NJ($){let f=typeof $.prompt_eval_count==="number"?$.prompt_eval_count:void 0,Z=typeof $.eval_count==="number"?$.eval_count:void 0;if(f==null&&Z==null)return;let z=f??0,J=Z??0;return{prompt_tokens:z,completion_tokens:J,total_tokens:z+J}}function BJ($){if(!Array.isArray($)||$.length===0)return;return $.map((f,Z)=>{let z=s0(f)?f:{},J=s0(z.function)?z.function:z,K=typeof z.id==="string"&&z.id?z.id:`ollama_call_${Z}`;return{index:Z,id:K,type:"function",function:{name:typeof J.name==="string"?J.name:"",arguments:CU(J.arguments)}}})}function HJ($,f){let Z=s0($.message)?$.message:{},z=typeof Z.content==="string"?Z.content:"",J=typeof Z.thinking==="string"?Z.thinking:"",K=BJ(Z.tool_calls),Q=$.done===!0,G={};if(!f.sentRole)G.role="assistant",f.sentRole=!0;if(J)G.reasoning=J;if(z)G.content=z;if(K)G.tool_calls=K;let Y={id:"chatcmpl-ollama",object:"chat.completion.chunk",created:Math.floor(Date.now()/1000),model:typeof $.model==="string"?$.model:"",choices:[{index:0,delta:G,finish_reason:Q?qJ($.done_reason,Z.tool_calls):null}]},P=NJ($);if(P)Y.usage=P;return Y}function UJ($){let f=s0($.message)?$.message:{},Z=typeof f.content==="string"?f.content:"",z=typeof f.thinking==="string"?f.thinking:"",J=BJ(f.tool_calls),K={role:"assistant",content:Z};if(z)K.reasoning=z;if(J)K.tool_calls=J;let Q={id:"chatcmpl-ollama",object:"chat.completion",created:Math.floor(Date.now()/1000),model:typeof $.model==="string"?$.model:"",choices:[{index:0,message:K,finish_reason:qJ($.done_reason,f.tool_calls)}]},G=NJ($);if(G)Q.usage=G;return Q}function MJ($){return`data: ${JSON.stringify($)}
29
+
30
+ `}function IU($){let f=new TextDecoder,Z=new TextEncoder,z=$.getReader(),J={sentRole:!1},K="";return new ReadableStream({async pull(Q){for(;;){let{done:G,value:Y}=await z.read();if(G){K+=f.decode();let H=K.trim();if(H)try{let M=JSON.parse(H);if(s0(M))Q.enqueue(Z.encode(MJ(HJ(M,J))))}catch{}Q.enqueue(Z.encode(`data: [DONE]
31
+
32
+ `)),Q.close();return}K+=f.decode(Y,{stream:!0});let P=K.lastIndexOf(`
33
+ `);if(P<0)continue;let X=K.slice(0,P+1);K=K.slice(P+1);let W=[];for(let H of X.split(`
34
+ `)){let M=H.trim();if(!M)continue;try{let F=JSON.parse(M);if(s0(F))W.push(MJ(HJ(F,J)))}catch{}}if(W.length>0){Q.enqueue(Z.encode(W.join("")));return}}},cancel(Q){return z.cancel(Q)}})}function kU($){let f=new Headers($);return f.set("content-type","application/json"),f}function nU($){let f=new Headers($);return f.set("content-type","text/event-stream"),f.delete("content-length"),f}async function VJ($,f,Z,z,J){let K=LU(f);if(!_U(K))return $(f,{...Z,body:JSON.stringify(z)});let Q=typeof z.model==="string"?z.model:"",G=h1(Q,K),Y=TU(z,{numCtx:YJ(Q,K),think:GJ(J,G?.thinking??null)}),P=await $(DU(K),{...Z,method:Z.method??"POST",headers:{...Object.fromEntries(new Headers(Z.headers).entries()),"Content-Type":"application/json"},body:JSON.stringify(Y)});if(P.status>=400)return P;if(z.stream===!1)try{let W=await P.json(),H=s0(W)?UJ(W):UJ({});return new Response(JSON.stringify(H),{status:P.status,statusText:P.statusText,headers:kU(P.headers)})}catch{return P}if(!P.body)return P;return new Response(IU(P.body),{status:P.status,statusText:P.statusText,headers:nU(P.headers)})}var LJ=O(()=>{O8()});import{AsyncLocalStorage as RU}from"async_hooks";import{readFileSync as SU,mkdirSync as vU,existsSync as uU}from"fs";import bJ from"path";function AJ($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function gU($){return $==="enabled-disabled"||$==="adaptive-disabled"||$==="omit"}function xU($){return $==="reasoning_effort"||$==="omit"}function hU($){if(!AJ($))return!1;return $.version===ef&&gU($.thinkingType)&&xU($.effort)&&typeof $.timestamp==="number"&&Number.isFinite($.timestamp)}function jJ(){return bJ.join(X0(),"thinking-wire-cache.json")}function CJ(){let $=jJ();if(!uU($))return{};try{let f=JSON.parse(SU($,"utf-8"));if(!AJ(f))return{};let Z={};for(let[z,J]of Object.entries(f))if(hU(J))Z[z]=J;return Z}catch{return{}}}function cU($){let f=jJ();vU(bJ.dirname(f),{recursive:!0}),T0(f,JSON.stringify($))}function _J($,f){if($.version!==ef)return null;if(f-$.timestamp>EU)return null;return $}function OJ($,f){let Z=$.trim().toLowerCase(),z=f.trim().toLowerCase();if(!Z)return z;if(!z)return Z;return`${Z}::${z}`}function mU($,f,Z){if(Z==="ollama")return{thinkingType:"omit",effort:"reasoning_effort"};if(`${$} ${f}`.toLowerCase().includes("minimax"))return{thinkingType:"adaptive-disabled",effort:"reasoning_effort"};if(Z==="openai")return{thinkingType:"omit",effort:"reasoning_effort"};return{thinkingType:V9.thinkingType,effort:V9.effort}}function rU($,f){let Z=w8.get($);if(Z){let K=_J(Z,f);if(K)return K;w8.delete($)}let z=CJ()[$];if(!z)return null;let J=_J(z,f);if(!J)return null;return w8.set($,J),J}function oU($,f,Z,z=Date.now()){let J=rU(OJ($,f),z);if(J)return J;return{version:ef,...mU(f,$,Z),timestamp:z}}function pU($,f,Z,z=Date.now()){let J={version:ef,thinkingType:Z.thinkingType,effort:Z.effort,timestamp:Z.timestamp??z},K=OJ($,f);w8.set(K,J);let Q=CJ();return Q[K]=J,cU(Q),J}function y8($,f,Z=V9){let z={...$};if(Z.effort==="omit")delete z.reasoning_effort;else z.reasoning_effort=f.reasoningEffort;if(Z.thinkingType==="omit")delete z.thinking;else{let J=Z.thinkingType==="adaptive-disabled"?"adaptive":"enabled";z.thinking={type:f.thinkingEnabled?J:"disabled"}}return z}function dU($){return new Set($.split(",").map((f)=>f.trim().replace(/^['"]|['"]$/g,"").toLowerCase()).filter(Boolean))}function iU($){let f=$.match(/thinking\.type[\s\S]*?allowed:\s*([^)]+)/i);if(f?.[1]){let Z=dU(f[1]);if(Z.has("adaptive")&&Z.has("disabled"))return{thinkingType:"adaptive-disabled"};if(Z.has("enabled")&&Z.has("disabled"))return{thinkingType:"enabled-disabled"}}if(/unknown parameter[:\s]+['"`]?thinking['"`]?(?![\w.])/i.test($))return{thinkingType:"omit"};if(/unknown parameter[:\s]+['"`]?reasoning_effort['"`]?(?![\w.])/i.test($))return{effort:"omit"};return null}function lU($){try{let f=typeof $==="string"?$:$ instanceof URL?$.href:$.url;return new URL(f).hostname}catch{return""}}function DJ($,f){return new Response(f,{status:400,statusText:$.statusText,headers:$.headers})}function tU($,f){return $.thinkingType===f.thinkingType&&$.effort===f.effort}async function wJ($,f,Z,z){if(!Z?.body)return $(f,Z);let J=await FJ(Z.body);if(J==null)return $(f,Z);let K;try{K=JSON.parse(J)}catch{return $(f,Z)}if(!K||typeof K!=="object"||Array.isArray(K))return $(f,Z);let Q=e4.getStore(),G=z?.providerType??e(J0())?.type,Y=K;if(G==="ollama")return VJ($,f,Z,Y,Q);if(!Q)return $(f,Z);let P=lU(f),X=typeof Y.model==="string"?Y.model:"",W=oU(P,X,G),H=await $(f,{...Z,body:JSON.stringify(y8(Y,Q,W))});if(H.status!==400)return H;let M=await H.text(),F=iU(M);if(!F)return DJ(H,M);let q={version:ef,thinkingType:F.thinkingType??W.thinkingType,effort:F.effort??W.effort,timestamp:Date.now()};if(tU(W,q))return DJ(H,M);return pU(P,X,q),$(f,{...Z,body:JSON.stringify(y8(Y,Q,q))})}var e4,ef=1,EU=604800000,V9,w8;var L9=O(()=>{d();LJ();F$();e4=new RU,V9={version:ef,thinkingType:"enabled-disabled",effort:"reasoning_effort"},w8=new Map});var j9={};U0(j9,{toWireEffort:()=>nJ,thinkingSourceLabel:()=>b9,thinkingRequestStore:()=>e4,thinkingPayload:()=>Z4,thinkingEffortLabel:()=>B$,thinkingChoicesFromReasoning:()=>IJ,thinkingChoicesForModel:()=>c1,thinkingChoiceIndex:()=>T8,setThinkingOverride:()=>$4,setThinkingEffort:()=>m1,resolveThinkingRequest:()=>A9,resolveThinkingEffort:()=>e$,refreshThinkingChoices:()=>f4,parseThinkingEffort:()=>R0,getThinkingSnapshot:()=>kJ,getThinkingOverride:()=>TJ,clampThinkingEffort:()=>D9,applyThinkingToChatBody:()=>y8,THINKING_EFFORTS:()=>h$,DEFAULT_THINKING_EFFORT:()=>_9});function $4($){yJ=$}function TJ(){return yJ}function B$($){return $}function T8($,f=h$){let Z=f.length>0?f:h$,z=D9($,Z),J=Z.indexOf(z);return J>=0?J:0}function IJ($){let f=new Set;if($.toggle||$.efforts.includes("none"))f.add("off");for(let z of $.efforts){let J=R0(z);if(J)f.add(J)}if(h$.filter((z)=>z!=="off"&&f.has(z)).length===0)return[...h$];return h$.filter((z)=>f.has(z))}function c1($){let f=e(J0());if(f?.type==="ollama"){if(!$)return[...h$];let z=h1($,f.baseURL);if(!z)return[...h$];return PJ(z)}if(!$)return[...h$];let Z=tf($);if(!Z)return[...h$];return IJ(Z.reasoning)}async function f4($,f){let Z=e(J0()),z=f?.type??Z?.type,J=f?.baseURL??Z?.baseURL;if($)if(z==="ollama")await s4($,J);else await A8($,J);return c1($)}function D9($,f=h$){if(f.length===0||f.includes($))return $;if(f.includes("medium"))return"medium";if(f.includes("high"))return"high";let Z=f.filter((z)=>z!=="off");if(Z.length>0)return Z[Math.floor((Z.length-1)/2)];if(f.includes("off"))return"off";return _9}function b9($){if($==="cli")return"本次启动参数";if($==="project")return"项目";if($==="global")return"全局";return"默认"}function e$($,f){let Z,z;if($)Z=$,z="cli";else{let K=TJ();if(K)Z=K,z="cli";else{let Q=kJ();Z=Q.thinking??_9,z=Q.source}}let J=f??e(J0())?.defaultModel;return{thinking:D9(Z,c1(J)),source:z}}function kJ(){let $=R0(y0().thinking);if($!==void 0)return{thinking:$,source:"project"};let f=R0($0().thinking);if(f!==void 0)return{thinking:f,source:"global"};return{thinking:void 0,source:null}}function aU(){let $=y0();if($.thinking===void 0)return;let{thinking:f,...Z}=$;Q$(Z)}function m1($,f){if(f==="project"){Q$({...y0(),thinking:$});return}I0({...$0(),thinking:$}),aU()}function Z4(){let{thinking:$,source:f}=e$();return{thinking:$,source:f,label:B$($)}}function nJ($,f,Z){if($==="off")return"none";if($!=="max")return $;let J=(Z?tf(Z):void 0)?.reasoning.efforts??[];if(J.includes("max"))return"max";if(J.includes("xhigh")||f==="openai")return"xhigh";return"max"}function A9($){let{thinking:f}=e$($?.runOverride,$?.modelId),Z=$?.providerType??e(J0())?.type;return{reasoningEffort:nJ(f,Z,$?.modelId),thinkingEnabled:f!=="off"}}var h$,_9="medium",yJ;var $1=O(()=>{d();F9();O8();L9();h$=["off","low","medium","high","max"]});var z4={};U0(z4,{takeScopeFlags:()=>c$,scopeLabel:()=>P$,readScope:()=>V$});function V$($){if($===void 0||$===null||$==="")return{ok:!0,scope:void 0};if($==="global"||$==="project")return{ok:!0,scope:$};return{ok:!1}}function c$($){let f,Z=[];for(let z of $)if(z==="--project")f="project";else if(z==="--global")f="global";else Z.push(z);return{scope:f,rest:Z}}function P$($){return $==="project"?"project":"global"}var R9={};U0(R9,{takeScopeFlags:()=>c$,setMemoryOverride:()=>I8,setMemoryMode:()=>J4,searchMemories:()=>_f,resolveMemoryMode:()=>Lf,readMemoryScope:()=>V$,parseMemoryMode:()=>g0,memorySourceLabel:()=>$2,memoryPayload:()=>o1,memoryModeLabel:()=>r1,loadMemories:()=>L$,isMemoryEnabled:()=>f1,getMemoryTools:()=>n9,getMemorySystemPrompt:()=>k9,getMemorySnapshot:()=>hJ,getMemoryOverride:()=>xJ,formatMemoryLine:()=>I9,deleteMemory:()=>Q4,defaultMemoryScope:()=>f2,addMemory:()=>K4,DEFAULT_MEMORY_MODE:()=>EJ});import{readFileSync as sU,mkdirSync as eU,existsSync as T9,renameSync as $M,statSync as uJ}from"fs";import y9 from"path";import{tool as C9,jsonSchema as O9}from"ai";function I8($){gJ=$}function xJ(){return gJ}function r1($){return $}function $2($){if($==="cli")return"this run";if($==="project")return"project";if($==="global")return"global";return"default"}function hJ(){let $=g0(y0().memory);if($!==void 0)return{memory:$,source:"project"};let f=g0($0().memory);if(f!==void 0)return{memory:f,source:"global"};return{memory:void 0,source:null}}function Lf($){if($)return{memory:$,source:"cli"};let f=xJ();if(f)return{memory:f,source:"cli"};let Z=hJ();return{memory:Z.memory??EJ,source:Z.source}}function f1($){return Lf($).memory==="on"}function fM(){let $=y0();if($.memory===void 0)return;let{memory:f,...Z}=$;Q$(Z)}function J4($,f){if(f==="project"){Q$({...y0(),memory:$});return}I0({...$0(),memory:$}),fM()}function o1(){let{memory:$,source:f}=Lf();return{memory:$,source:f,label:r1($)}}function f2(){return T9(S1())?"project":"global"}function RJ($){return $==="global"||$==="project"?$:f2()}function cJ($){if($==="project")return y9.join(S1(),"memory.json");return y9.join(X0(),"memory.json")}function ZM($){if(typeof $!=="object"||$===null)return;let f=$;if(typeof f.content!=="string")return;let Z=Array.isArray(f.tags)?f.tags.filter((J)=>typeof J==="string"):[],z=typeof f.created==="string"?f.created:"";return{content:f.content,tags:Z,created:z}}function SJ($){try{$M($,`${$}.corrupt-${Date.now()}`)}catch{}}function zM($,f){try{let Z=uJ($);Vf.set($,{mtimeMs:Z.mtimeMs,size:Z.size,memories:f})}catch{Vf.delete($)}}function L$($="global"){let f=cJ($),Z;try{Z=uJ(f)}catch{return Vf.delete(f),[]}let z=Vf.get(f);if(z&&z.mtimeMs===Z.mtimeMs&&z.size===Z.size)return z.memories;let J;try{J=JSON.parse(sU(f,"utf-8"))}catch{return SJ(f),Vf.delete(f),[]}if(!Array.isArray(J))return SJ(f),Vf.delete(f),[];let K=J.flatMap((Q)=>{let G=ZM(Q);return G?[G]:[]});return Vf.set(f,{mtimeMs:Z.mtimeMs,size:Z.size,memories:K}),K}function mJ($,f){let Z=cJ(f);if(f==="project"&&!T9(S1())){console.warn(`\x1B[33m ⚠ Project memory write skipped: no .min-agent/ in ${process.cwd()}. Run "min-agent init" to create it first.\x1B[0m`);return}eU(y9.dirname(Z),{recursive:!0}),T0(Z,JSON.stringify($,null,2)),zM(Z,$)}function K4($,f=[],Z="global"){let z=L$(Z),J={content:$,tags:f,created:new Date().toISOString()};return z.push(J),mJ(z,Z),J}function Q4($,f="global"){let Z=L$(f);if($<0||$>=Z.length)return!1;return Z.splice($,1),mJ(Z,f),!0}function _f($,f="global"){let Z=L$(f),z=$.toLowerCase();return Z.map((J,K)=>({...J,index:K})).filter((J)=>J.content.toLowerCase().includes(z)||J.tags.some((K)=>K.toLowerCase().includes(z)))}function I9($,f,Z){let z=$.tags.length>0?` [${$.tags.join(", ")}]`:"",J=Z?.date?$.created.split("T")[0]:"",K=J?` (${J})`:"";return` #${f+1}: ${$.content}${z}${K}`}function vJ($,f){if($.length===0)return"";let Z=Math.max(0,$.length-w9),z=$.slice(Z).map((K,Q)=>({m:K,num:Z+Q+1})).reverse().map(({m:K,num:Q})=>{let G=K.tags.length>0?` [${K.tags.join(", ")}]`:"";return` ${Q}. ${K.content}${G}`}),J=$.length>w9?`
35
+ (${$.length-w9} older memories not shown — use memory_search to find them.)`:"";return[f,...z,J].filter(Boolean).join(`
36
+ `)}function k9($){if(!f1($))return"";let f=L$("project"),Z=L$("global");if(f.length===0&&Z.length===0)return"";let z=["## Memories","Background facts from previous conversations. Use them to personalize replies. They are not pending tasks and not a request to act.","Do not call APIs, run commands, or continue old work based on memories unless the current user message explicitly asks.","Do not use remembered credentials or API keys unless this message asks you to perform that action.","You can save new memories with the memory_save tool when the user tells you something worth remembering (preferences, project details, conventions, etc).",'Use scope "project" for repo-specific facts and "global" for preferences that apply everywhere.',""],J=[vJ(f,"### This project"),vJ(Z,f.length>0?"### Global":"")].filter((K)=>K.length>0);return[...z,...J].join(`
37
+ `)}function n9(){let $=C9({description:"Save a memory for future conversations. Use this when the user shares preferences, project conventions, important context, or asks you to remember something. Memories persist across sessions and are injected as background reference, not as work to resume. Do not store secrets, API keys, or passwords. Use scope project for this repository, global for all projects.",inputSchema:O9({type:"object",properties:{content:{type:"string",description:"The information to remember"},tags:{type:"array",items:{type:"string"},description:"Optional tags for categorization (e.g. 'preference', 'project', 'convention')"},scope:{type:"string",enum:["global","project"],description:"Where to store the memory. Defaults to project when .min-agent exists, otherwise global. Project requires .min-agent/ in cwd (created by min-agent init)."}},required:["content"]}),execute:async({content:z,tags:J,scope:K})=>{let Q=RJ(K);if(Q==="project"&&!T9(S1()))return`Cannot save project memory: no .min-agent/ in ${process.cwd()}. Run "min-agent init" first, or use scope global.`;let G=K4(z,J??[],Q);return`Saved ${Q} memory: "${z}" (tags: ${G.tags.length>0?G.tags.join(", "):"none"})`}}),f=C9({description:"Search through saved memories by keyword. Use this to recall previously saved information.",inputSchema:O9({type:"object",properties:{query:{type:"string",description:"Search keyword or phrase"},scope:{type:"string",enum:["global","project"],description:"Limit search to one store. Omit to search both."}},required:["query"]}),execute:async({query:z,scope:J})=>{let Q=(J==="global"||J==="project"?[J]:["project","global"]).flatMap((G)=>_f(z,G).map((Y)=>{let P=Y.tags.length>0?` [${Y.tags.join(", ")}]`:"";return`${G} #${Y.index+1}: ${Y.content}${P} (${Y.created.split("T")[0]})`}));if(Q.length===0)return`No memories found matching "${z}"`;return Q.join(`
38
+ `)}}),Z=C9({description:"Delete a memory by its number. Use memory_search first to find the index and scope.",inputSchema:O9({type:"object",properties:{index:{type:"number",description:"The memory number to delete (1-based)"},scope:{type:"string",enum:["global","project"],description:"Which store the number belongs to. Defaults to project when .min-agent exists, otherwise global. Project requires .min-agent/ in cwd (created by min-agent init)."}},required:["index"]}),execute:async({index:z,scope:J})=>{let K=RJ(J);if(Q4(z-1,K))return`${K} memory #${z} deleted.`;return`${K} memory #${z} not found.`}});return{memory_save:$,memory_search:f,memory_delete:Z}}var EJ="off",w9=30,gJ,Vf;var V1=O(()=>{d();F$();Vf=new Map});function JM($){return $==="cli"?"this run":$==="env"?"environment variable":$==="project"?"project":$==="global"?"global":"default"}function k8($){let{scope:f,rest:Z}=c$($.positionals),z=f??$.scope??"global";if(Z[0]==="--help"||Z[0]==="-h")return{ok:!0,lines:[Z2]};if(Z[0]==="network"){let G=g$(Z[1]);if(!G||Z.length>2)return{ok:!1,lines:[Z2]};return Uf({network:G},z),E4({network:G}),{ok:!0,lines:[`✓ Network set to ${G==="deny"?"denied":"allowed"} (${P$(z)})`]}}if(Z.length===1){let G=O$(Z[0]);if(!G)return{ok:!1,lines:[Z2]};Uf({mode:G},z),E4({mode:G});let Y=x4(G);return{ok:!0,lines:[`✓ Sandbox set to ${h4(G)} (${P$(z)})`,...Y?[Y]:[]]}}if(Z.length>1)return{ok:!1,lines:[Z2]};if($.flagMode||$.flagNetwork){Uf({...$.flagMode?{mode:$.flagMode}:{},...$.flagNetwork?{network:$.flagNetwork}:{}},z),E4({...$.flagMode?{mode:$.flagMode}:{},...$.flagNetwork?{network:$.flagNetwork}:{}});let G=[...$.flagMode?[`sandbox set to ${h4($.flagMode)}`]:[],...$.flagNetwork?[`network set to ${$.flagNetwork==="deny"?"denied":"allowed"}`]:[]],Y=$.flagMode?x4($.flagMode):null;return{ok:!0,lines:[`✓ ${G.join(", ")} (${P$(z)})`,...Y?[Y]:[]]}}let J=r4(),K=[...J.extraWriteRoots.length>0?[`Extra writable dirs: ${J.extraWriteRoots.join(", ")}`]:[],...J.extraReadRoots.length>0?[`Extra readable dirs: ${J.extraReadRoots.join(", ")}`]:[]],Q=x4(i0().mode);return{ok:!0,lines:[`Current sandbox: ${c4()} (${JM(J.source)})`,...K,...Q?[Q]:[],Z2]}}var Z2;var S9=O(()=>{d();E0();Z2=["Usage: min-agent sandbox [off|workspace|strict] [--project|--global]"," min-agent sandbox network allow|deny [--project|--global]"," min-agent --sandbox off|workspace|strict [--project|--global]"].join(`
39
+ `)});function KM($){return $==="cli"?"this run":$==="project"?"project":$==="global"?"global":"default"}function R8($){let{scope:f,rest:Z}=c$($.positionals),z=f??$.scope??"global";if(Z[0]==="--help"||Z[0]==="-h")return{ok:!0,lines:[n8]};if(Z.length===1){let Y=N$(Z[0]);if(!Y)return{ok:!1,lines:[n8]};return lf(Y,z),q8(Y),{ok:!0,lines:[`✓ Permission set to ${Hf(Y)} (${P$(z)})`]}}if(Z.length>1)return{ok:!1,lines:[n8]};if($.flagMode)return lf($.flagMode,z),q8($.flagMode),{ok:!0,lines:[`✓ Permission set to ${Hf($.flagMode)} (${P$(z)})`]};let J=m4(),K=i4(),Q=K??J.permission,G=K?"cli":J.source;return{ok:!0,lines:[`Current permission: ${Hf(Q)} (${KM(G)})`,n8]}}var n8;var v9=O(()=>{d();G$();n8=["Usage: min-agent permission [ask|accept-edits|allow-all] [--project|--global]"," min-agent --permission ask|accept-edits|allow-all [--project|--global]"].join(`
40
+ `)});function QM($){return $==="cli"?"this run":$==="project"?"project":$==="global"?"global":"default"}function v8($){let{scope:f,rest:Z}=c$($.positionals),z=f??$.scope??"global";if(Z[0]==="--help"||Z[0]==="-h")return{ok:!0,lines:[S8]};if(Z.length===1){let Q=R0(Z[0]);if(!Q)return{ok:!1,lines:[S8]};return m1(Q,z),$4(Q),{ok:!0,lines:[`✓ Thinking set to ${B$(Q)} (${P$(z)})`]}}if(Z.length>1)return{ok:!1,lines:[S8]};if($.flagEffort)return m1($.flagEffort,z),$4($.flagEffort),{ok:!0,lines:[`✓ Thinking set to ${B$($.flagEffort)} (${P$(z)})`]};let{thinking:J,source:K}=e$();return{ok:!0,lines:[`Current thinking: ${B$(J)} (${QM(K)})`,S8]}}var S8;var u9=O(()=>{$1();S8=["Usage: min-agent think [off|low|medium|high|max] [--project|--global]"," min-agent --think off|low|medium|high|max [--project|--global]"].join(`
41
+ `)});function E8($){let{scope:f,rest:Z}=c$($.positionals),z=f??$.scope??"global";if(Z[0]==="--help"||Z[0]==="-h")return{ok:!0,lines:[u8]};if(Z.length===1){let Q=g0(Z[0]);if(!Q)return{ok:!1,lines:[u8]};return J4(Q,z),I8(Q),{ok:!0,lines:[`✓ Memory set to ${r1(Q)} (${P$(z)})`]}}if(Z.length>1)return{ok:!1,lines:[u8]};if($.flagMode)return J4($.flagMode,z),I8($.flagMode),{ok:!0,lines:[`✓ Memory set to ${r1($.flagMode)} (${P$(z)})`]};let{memory:J,source:K}=Lf();return{ok:!0,lines:[`Current memory: ${r1(J)} (${$2(K)})`,u8]}}var u8;var E9=O(()=>{V1();u8=["Usage: min-agent memory [on|off] [--project|--global]"," min-agent --memory on|off [--project|--global]"].join(`
42
+ `)});var rJ={};U0(rJ,{runWriteConfig:()=>GM});async function GM($){let f=[],Z=!0;if($.sandbox!==void 0||$.network!==void 0){let z=k8({positionals:[],flagMode:$.sandbox,flagNetwork:$.network,scope:$.scope});if(f.push(...z.lines),!z.ok)Z=!1}if($.permission!==void 0){let z=R8({positionals:[],flagMode:$.permission,scope:$.scope});if(f.push(...z.lines),!z.ok)Z=!1}if($.think!==void 0){let z=v8({positionals:[],flagEffort:$.think,scope:$.scope});if(f.push(...z.lines),!z.ok)Z=!1}if($.memory!==void 0){let z=E8({positionals:[],flagMode:$.memory,scope:$.scope});if(f.push(...z.lines),!z.ok)Z=!1}if(console.log(f.join(`
43
+ `)),!Z)process.exitCode=1}var oJ=O(()=>{S9();v9();u9();E9()});function g8($,f,Z){let z=$==="openai"?"openai":$==="ollama"?"ollama":YM(f)??"provider";return PM(z,Z)}function x8($){let f=$.trim();if(!f||f.includes("/")||f.includes(":"))return"名称不能为空,且不能包含 / 或 :。";return null}function g9($){if($.length<4)return"****";return`…${$.slice(-4)}`}function pJ($,f){let Z=$.trim().toLowerCase();if(!Z)return[...f];return f.filter((z)=>z.toLowerCase().includes(Z))}function h8($,f,Z){let z=x8(f.name);if(z)return{error:z};let J=f.name.trim(),K=[...$.providers??[]],Q=K.findIndex((Y)=>Y.name===J);if(Q>=0&&!Z.overwrite)return{error:`已存在同名服务商 "${J}"。`};let G=iJ(f,J);if(Q>=0)K[Q]=G;else K.push(G);return{...$,providers:K,activeProvider:J}}function G4($,f){if(!($.providers??[]).find((z)=>z.name===f))return{error:`找不到服务商 "${f}"。`};return{...$,activeProvider:f}}function dJ($,f,Z){let z=x8(Z.name);if(z)return{error:z};let J=Z.name.trim(),K=[...$.providers??[]],Q=K.findIndex((Y)=>Y.name===f);if(Q<0)return{error:`找不到服务商 "${f}"。`};if(J!==f&&K.some((Y)=>Y.name===J))return{error:`已存在同名服务商 "${J}"。`};K[Q]=iJ(Z,J);let G=$.activeProvider===f?J:$.activeProvider;return{...$,providers:K,activeProvider:G}}function c8($,f){let Z=$.providers??[];if(!Z.some((K)=>K.name===f))return{error:`找不到服务商 "${f}"。`};let z=Z.filter((K)=>K.name!==f);if(z.length===0){let{activeProvider:K,...Q}=$;return{...Q,providers:[]}}let J=$.activeProvider===f?z[0]?.name:$.activeProvider;return{...$,providers:z,activeProvider:J}}function iJ($,f){return{name:f,type:$.type,baseURL:$.baseURL,apiKey:$.apiKey,defaultModel:$.defaultModel,...$.contextWindow!=null?{contextWindow:$.contextWindow}:{}}}function YM($){try{let f=new URL($).hostname.toLowerCase(),Z=f.startsWith("www.")?f.slice(4):f;if(!Z)return;return Z.replace(/\./g,"-")}catch{return}}function PM($,f){if(!f.includes($))return $;let Z=2;while(f.includes(`${$}-${Z}`))Z+=1;return`${$}-${Z}`}function lJ($){if($==="openai-compatible"||$==="openai"||$==="ollama")return $;throw s$(`Invalid --type value: "${$}"`,"use one of: openai-compatible, openai, ollama")}function tJ($){return[$.type,$.switch,$.remove].filter(Boolean).length}var m8=O(()=>{Y$()});function aJ($,f){return!$&&f}async function x9($,f,Z){if(tJ($)>1)throw new a("一次只能执行一种操作。");if($.remove){await MM($.remove,$.yes===!0,f);return}if($.switch){h9(G4(f.load(),$.switch),f);return}if($.type){await FM($,f);return}if(!f.isTty)throw new a("无法在非交互环境完成配置。",{hint:HM});let z=f.load(),J=Z??(UM(z)?"hub":"first-run");await f.runWizard(J)}function UM($){let f=e($);return Boolean(f?.baseURL&&f?.apiKey)}async function MM($,f,Z){if(!f)throw new a("删除需要确认。",{hint:"加上 --yes"});h9(c8(Z.load(),$),Z)}async function FM($,f){let Z=$.type,z=qM(Z,$.url),J=NM(Z,$.apiKey),K=await BM(Z,z,J,$.defaultModel,f.fetchLive),Q=f.load(),G=(Q.providers??[]).map((H)=>H.name).filter((H)=>Boolean(H)),P={name:($.name?.trim()||g8(Z,z,G)).trim(),type:Z,baseURL:z,apiKey:J,defaultModel:K,...$.contextWindow!=null?{contextWindow:$.contextWindow}:{}},X=$.yes===!0,W=h8(Q,P,{overwrite:X});if(sJ(W)&&W.error.startsWith("已存在同名服务商")&&!X)throw new a(W.error,{hint:"加上 --yes 以覆盖"});h9(W,f)}function qM($,f){if($==="openai")return XM;if($==="ollama")return N1(f?.trim()||WM);let Z=f?.trim()??"";if(!Z)throw new a("API 地址不能为空。");return Z.replace(/\/$/,"")}function NM($,f){if($==="ollama")return f?.trim()||"ollama";let Z=f?.trim()??"";if(!Z)throw new a("API 密钥不能为空。");return Z}async function BM($,f,Z,z,J){let K=z?.trim()??"";if(K)return K;let Q=await J(f,Z);if(Q.models[0])return Q.models[0];if($==="ollama")return"llama3";if(!Q.ok&&Q.status==null)throw G9("无法连接到该服务商。");throw new a("默认模型不能为空。")}function h9($,f){if(sJ($))throw new a($.error);f.save($),f.log(`已保存到 ${f.configPath()}`)}function sJ($){return Object.keys($).length===1&&"error"in $}var XM="https://api.openai.com/v1",WM="http://localhost:11434/v1",HM="使用 --type、--switch 或 --remove。例如: min-agent setup --type ollama";var c9=O(()=>{d();Y$();m8();m8()});var _;var Z1=O(()=>{_={inputBorder:"cyan",inputBorderDisabled:"gray",confirmBorder:"blue",pickerBorder:"blue",questionBorder:"blue",accent:"cyan",muted:"gray",tool:"yellow",error:"red",success:"green"}});async function eJ($){let f=$?.fetchImpl??fetch,Z=$?.timeoutMs??LM;try{if(!(await f(VM,{signal:AbortSignal.timeout(Z)})).ok)return{found:!1};return{found:!0,baseURL:N1(_M)}}catch{return{found:!1}}}var VM="http://localhost:11434/api/tags",LM=800,_M="http://localhost:11434/v1";var $K=O(()=>{d()});var ZK={};U0(ZK,{renderSetupWizard:()=>CM});import{useEffect as p9,useRef as r8,useState as L1}from"react";import{Box as p1,Text as _0,render as DM,useInput as fK}from"ink";import bM from"ink-spinner";import AM from"path";import{jsxDEV as s}from"react/jsx-dev-runtime";async function CM($){return new Promise((f)=>{let Z=DM(s(OM,{mode:$,onDone:(z)=>{Z.unmount(),f(z)}},void 0,!1,void 0,this),{exitOnCtrlC:!1})})}function OM({mode:$,onDone:f}){let[Z,z]=L1(()=>$==="session-gate"?{id:"gate"}:$==="hub"?{id:"hub"}:{id:"type"}),[J,K]=L1(null),[Q,G]=L1({found:!1}),[Y,P]=L1(""),[X,W]=L1(0),H=()=>W((U)=>U+1),M=v1(),F=()=>f("aborted"),q=()=>f("saved");return s(p1,{flexDirection:"column",paddingX:1,paddingY:1,children:[s(_0,{bold:!0,color:_.accent,children:"配置服务商"},void 0,!1,void 0,this),Z.id==="gate"&&s(Y4,{items:[{label:"开始配置",value:"start"},{label:"退出",value:"exit"}],onSelect:(U)=>{if(U==="exit")f("aborted");else z({id:"type"})},onCancel:()=>f("aborted")},void 0,!1,void 0,this),Z.id==="hub"&&s(wM,{config:M,onAdd:()=>{K({fromHub:!0,type:"openai-compatible",baseURL:o9,apiKey:"",defaultModel:"",name:""}),P(""),z({id:"type"})},onPick:(U)=>{let N=M.providers??[];if(U==="switch"&&N.length<=1){z({id:"message",text:"当前只有一个服务商,无需切换。",back:"hub"});return}z({id:"pick",action:U})},onDone:q},void 0,!1,void 0,this),Z.id==="pick"&&s(yM,{config:M,onCancel:()=>z({id:"hub"}),onSelect:(U)=>{let N=U.name??"";if(Z.action==="switch"){let B=G4(M,N);if(r9(B)){z({id:"message",text:B.error,back:"hub"});return}I0(B),m9(),H(),z({id:"hub"});return}if(Z.action==="delete"){z({id:"delete-confirm",name:N});return}if(Z.action==="test"){(async()=>{let B=await Mf(U.baseURL,U.apiKey);if(B.ok&&B.models.length>0){z({id:"message",text:`可访问,${B.models.length} 个模型`,back:"hub"});return}let D=B.status!=null?`HTTP ${B.status}。`:"",V=U.type==="ollama"?"请确认 Ollama 已启动。":"请检查 API 地址和密钥。";z({id:"message",text:gM(`无法连接到该服务商。${D}${V}`),back:"hub"})})();return}K(vM(U,!0)),P(""),z({id:"type"})}},void 0,!1,void 0,this),Z.id==="delete-confirm"&&s(Y4,{title:`确定删除服务商 "${Z.name}"?`,items:[{label:"删除",value:"yes"},{label:"取消",value:"no"}],onSelect:(U)=>{if(U!=="yes"){z({id:"hub"});return}let N=c8(v1(),Z.name);if(r9(N)){z({id:"message",text:N.error,back:"hub"});return}I0(N),m9(),H(),z({id:"hub"})},onCancel:()=>z({id:"hub"})},void 0,!1,void 0,this),Z.id==="message"&&s(RM,{text:Z.text,onClose:()=>{if(Z.back==="exit-saved")q();else z({id:"hub"})}},void 0,!1,void 0,this),Z.id==="type"&&s(TM,{detected:Q,onDetected:G,initial:J?.type,onCancel:()=>{if(J?.fromHub||$==="hub")z({id:"hub"});else F()},onSelect:(U)=>{let N=SM(U,J,Q);if(K(N),P(""),U==="openai")z({id:"key"});else z({id:"url"})}},void 0,!1,void 0,this),Z.id==="url"&&J&&s(z2,{label:J.type==="ollama"?"Ollama 地址":"API 地址",value:J.baseURL,error:Y,onChange:(U)=>K({...J,baseURL:U}),onCancel:()=>{P(""),z({id:"type"})},onSubmit:()=>{let U=J.baseURL.trim();if(!U){P("API 地址不能为空。");return}let N=J.type==="ollama"?N1(U):U.replace(/\/$/,"");if(K({...J,baseURL:N}),P(""),J.type==="ollama")z({id:"fetch"});else z({id:"key"})}},void 0,!1,void 0,this),Z.id==="key"&&J&&s(z2,{label:"API 密钥",value:J.apiKey,mask:!0,placeholder:J.existingKey?`已保存 (${g9(J.existingKey)}),回车保留`:void 0,error:Y,onChange:(U)=>K({...J,apiKey:U}),onCancel:()=>{if(P(""),J.type==="openai")z({id:"type"});else z({id:"url"})},onSubmit:()=>{if(!J.apiKey.trim()&&J.existingKey){K({...J,apiKey:J.existingKey}),P(""),z({id:"fetch"});return}if(!J.apiKey.trim()){P("API 密钥不能为空。");return}P(""),z({id:"fetch"})}},void 0,!1,void 0,this),Z.id==="fetch"&&J&&s(IM,{draft:J,onBack:()=>z(J.type==="ollama"?{id:"url"}:{id:"key"}),onList:(U)=>{K({...J,models:U}),P(""),z({id:"models",models:U})},onEmpty:()=>{P(""),z({id:"model-manual"})}},void 0,!1,void 0,this),Z.id==="models"&&J&&s(kM,{models:Z.models,current:J.defaultModel,onCancel:()=>z(J.type==="openai"?{id:"key"}:{id:"url"}),onSelect:(U)=>{K({...J,defaultModel:U}),P(""),z({id:"name"})}},void 0,!1,void 0,this),Z.id==="model-manual"&&J&&s(z2,{label:"无法获取模型列表,请手动输入默认模型",value:J.defaultModel,error:Y,onChange:(U)=>K({...J,defaultModel:U}),onCancel:()=>z(J.type==="openai"?{id:"key"}:{id:"url"}),onSubmit:()=>{if(!J.defaultModel.trim()){P("默认模型不能为空。");return}if(P(""),J.type==="openai-compatible")z({id:"context"});else z({id:"name"})}},void 0,!1,void 0,this),Z.id==="context"&&J&&s(z2,{label:"上下文窗口(token,回车跳过)",value:J.contextWindow!=null?String(J.contextWindow):"",error:Y,onChange:(U)=>{let N=U.trim();if(!N){K({...J,contextWindow:void 0});return}let B=Number.parseInt(N,10);K({...J,contextWindow:Number.isFinite(B)?B:void 0})},onCancel:()=>z({id:"model-manual"}),onSubmit:(U)=>{let N=U.trim();if(!N){K({...J,contextWindow:void 0}),P(""),z({id:"name"});return}let B=Number.parseInt(N,10);if(!Number.isFinite(B)||B<=0){P("上下文窗口必须是大于 0 的整数。");return}K({...J,contextWindow:B}),P(""),z({id:"name"})}},void 0,!1,void 0,this),Z.id==="name"&&J&&s(z2,{label:"名称",value:J.name,error:Y,onChange:(U)=>K({...J,name:U}),onCancel:()=>{if(J.models&&J.models.length>0)z({id:"models",models:J.models});else z({id:"model-manual"})},onSubmit:()=>{let U=x8(J.name);if(U){P(U);return}P(""),z({id:"summary"})}},void 0,!1,void 0,this),Z.id==="summary"&&J&&s(nM,{draft:J,error:Y,onCancel:()=>z({id:"name"}),onConfirm:()=>{let U=uM(J);if(r9(U)){P(U.error),z({id:"name"});return}if(I0(U),m9(),J.fromHub||$==="hub"){H(),K(null),z({id:"hub"});return}f("saved")}},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function wM({config:$,onAdd:f,onPick:Z,onDone:z}){let J=$.providers??[],K=[{label:"添加",value:"add"},{label:"设为当前",value:"switch"},{label:"修改",value:"edit"},{label:"删除",value:"delete"},{label:"测试连接",value:"test"},{label:"完成",value:"done"}];return s(p1,{flexDirection:"column",children:[J.map((Q)=>s(_0,{color:Q.name===$.activeProvider?_.accent:_.muted,children:[Q.name===$.activeProvider?"* ":" ",Q.name??"(未命名)"," ",Q.baseURL," ",Q.defaultModel??"未设置模型"]},Q.name??Q.baseURL,!0,void 0,this)),s(Y4,{items:K,onSelect:(Q)=>{if(Q==="add")f();else if(Q==="done")z();else Z(Q)},onCancel:z},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function yM({config:$,onSelect:f,onCancel:Z}){let z=$.providers??[],J=e($)?.name;return s(Y4,{items:z.map((K)=>({label:`${K.name??"(未命名)"}${K.name===J?" *":""} ${K.baseURL}`,value:K.name??""})),initial:Math.max(0,z.findIndex((K)=>K.name===J)),onSelect:(K)=>{let Q=z.find((G)=>G.name===K);if(Q)f(Q)},onCancel:Z},void 0,!1,void 0,this)}function TM({detected:$,onDetected:f,initial:Z,onSelect:z,onCancel:J}){p9(()=>{let G=!1;return eJ().then((Y)=>{if(!G)f(Y)}),()=>{G=!0}},[f]);let K=[{label:"OpenAI 兼容接口",hint:"OpenRouter、DeepSeek、Groq 等",value:"openai-compatible"},{label:"OpenAI",hint:"官方接口",value:"openai"},{label:"Ollama(本地)",hint:$.found?"已检测到":"本机模型",value:"ollama"}],Q=Z==="openai"?1:Z==="ollama"?2:$.found&&!Z?2:0;return s(Y4,{items:K,initial:Q,onSelect:(G)=>z(G),onCancel:J},`${Z??"auto"}-${$.found?"detected":"plain"}`,!1,void 0,this)}function IM({draft:$,onList:f,onEmpty:Z,onBack:z}){let J=r8(f),K=r8(Z);return J.current=f,K.current=Z,fK((Q,G)=>{if(G.escape)z()}),p9(()=>{let Q=!1;return Mf($.baseURL,$.apiKey||"ollama").then((G)=>{if(Q)return;if(G.ok&&G.models.length>0)J.current(G.models);else K.current()}),()=>{Q=!0}},[$.apiKey,$.baseURL]),s(p1,{children:[s(_0,{color:_.accent,children:s(bM,{type:"dots"},void 0,!1,void 0,this)},void 0,!1,void 0,this),s(_0,{color:_.muted,children:" 正在获取模型列表…"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function kM({models:$,current:f,onSelect:Z,onCancel:z}){let[J,K]=L1(""),[Q,G]=L1(0),Y=pJ(J,$),P=J.trim();o8((F,q,U)=>{if(q.escape){z();return}if(q.downArrow&&Y.length>0){G((B)=>(B+1)%Y.length);return}if(q.upArrow&&Y.length>0){G((B)=>(B-1+Y.length)%Y.length);return}if(U){if(Y.length>0)Z(Y[Math.min(Q,Y.length-1)]);else if(P)Z(P);return}if(q.backspace||q.delete){K((B)=>Array.from(B).slice(0,-1).join("")),G(0);return}if(q.ctrl||q.meta||q.tab)return;let N=F.replace(/[\r\n]+$/,"");if(N)K((B)=>B+N),G(0)});let X=Math.min(Q,Math.max(0,Y.length-1)),W=12,H=Math.min(X,Math.max(0,Y.length-W)),M=Y.slice(H,H+W);return s(p1,{flexDirection:"column",children:[s(_0,{color:_.muted,children:"输入可筛选"},void 0,!1,void 0,this),s(_0,{color:J?_.accent:_.muted,children:J||" "},void 0,!1,void 0,this),M.map((F,q)=>{let U=H+q===X;return s(_0,{color:U?_.accent:void 0,bold:U,children:[U?"▸ ":" ",F,F===f?" ← 当前":""]},F,!0,void 0,this)}),Y.length===0&&P!==""&&s(_0,{color:_.accent,children:["▸ 使用自定义模型: ",P]},void 0,!0,void 0,this),s(_0,{color:_.muted,children:"↑↓ 选择 · Enter 确认 · Esc 返回"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function z2({label:$,value:f,mask:Z,placeholder:z,error:J,onChange:K,onSubmit:Q,onCancel:G}){o8((P,X,W)=>{if(X.escape){G();return}if(W){Q(f);return}if(X.backspace||X.delete){K(Array.from(f).slice(0,-1).join(""));return}if(X.ctrl||X.meta||X.tab)return;let H=P.replace(/[\r\n]+$/,"");if(H)K(f+H)});let Y=Z?"*".repeat(Array.from(f).length):f;return s(p1,{flexDirection:"column",children:[s(_0,{children:$},void 0,!1,void 0,this),s(_0,{color:_.accent,children:Y||z||" "},void 0,!1,void 0,this),J?s(_0,{color:_.error,children:J},void 0,!1,void 0,this):null,s(_0,{color:_.muted,children:"Enter 确认 · Esc 返回"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function nM({draft:$,error:f,onConfirm:Z,onCancel:z}){return s(p1,{flexDirection:"column",children:[s(_0,{children:["类型 ",EM($.type)]},void 0,!0,void 0,this),s(_0,{children:["地址 ",$.baseURL]},void 0,!0,void 0,this),s(_0,{children:["密钥 ",g9($.apiKey)]},void 0,!0,void 0,this),s(_0,{children:["模型 ",$.defaultModel]},void 0,!0,void 0,this),s(_0,{children:["名称 ",$.name.trim()]},void 0,!0,void 0,this),f?s(_0,{color:_.error,children:f},void 0,!1,void 0,this):null,s(Y4,{items:[{label:"保存",value:"save"},{label:"返回",value:"back"}],onSelect:(J)=>{if(J==="save")Z();else z()},onCancel:z},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function RM({text:$,onClose:f}){return o8((Z,z,J)=>{if(z.escape||J)f()}),s(p1,{flexDirection:"column",children:[s(_0,{children:$},void 0,!1,void 0,this),s(_0,{color:_.muted,children:"Enter / Esc 继续"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Y4({title:$,items:f,initial:Z=0,onSelect:z,onCancel:J}){let[K,Q]=L1(Math.min(Math.max(0,Z),Math.max(0,f.length-1))),[G,Y]=L1("");return o8((P,X,W)=>{if(X.escape){J();return}if(f.length===0)return;if(X.downArrow){Y(""),Q((F)=>(F+1)%f.length);return}if(X.upArrow){Y(""),Q((F)=>(F-1+f.length)%f.length);return}if(X.backspace||X.delete){Y((F)=>F.slice(0,-1));return}let H=()=>{let F=G?Number.parseInt(G,10):NaN;if(Number.isFinite(F)&&F>=1&&F<=f.length)return z(f[F-1].value),!0;return!1};if(W){if(!H())z(f[K].value);return}if(P===" "){if(!H())z(f[K].value);return}if(X.ctrl||X.meta||X.tab)return;let M=P.replace(/[\r\n]+$/,"");if(M&&/^[0-9]$/.test(M)){let F=G+M,q=Number.parseInt(F,10);if(Number.isFinite(q)&&q>=1&&q<=f.length)Y(F),Q(q-1);else if(Number.isFinite(q)&&q>f.length){Y(M);let U=Number.parseInt(M,10);if(Number.isFinite(U)&&U>=1&&U<=f.length)Q(U-1)}}}),s(p1,{flexDirection:"column",children:[$?s(_0,{children:$},void 0,!1,void 0,this):null,f.map((P,X)=>s(_0,{color:X===K?_.accent:void 0,bold:X===K,children:[X===K?"▸ ":" ",X+1,". ",P.label,P.hint?s(_0,{color:_.muted,children:[" ",P.hint]},void 0,!0,void 0,this):null]},P.value,!0,void 0,this)),G?s(_0,{color:_.accent,children:["输入: ",G]},void 0,!0,void 0,this):null,s(_0,{color:_.muted,children:"↑↓ 选择 · 数字键跳转 · Enter/空格 确认 · Esc 返回"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function o8($){let f=r8(!1),Z=r8($);Z.current=$,p9(()=>{let z=setTimeout(()=>{f.current=!0},0);return()=>clearTimeout(z)},[]),fK((z,J)=>{let K=J.return||/[\r\n]+$/.test(z);if(K&&!f.current)return;Z.current(z,J,K)})}function SM($,f,Z){let z=f?.fromHub===!0||f?.editingName!=null,J=f?.editingName;if($==="openai")return{fromHub:z,editingName:J,type:$,baseURL:o9,apiKey:"",existingKey:f?.type==="openai"?f.existingKey??f.apiKey:f?.existingKey,defaultModel:f?.type==="openai"?f.defaultModel:"",name:f?.name??""};if($==="ollama")return{fromHub:z,editingName:J,type:$,baseURL:Z.baseURL||f?.baseURL||jM,apiKey:"ollama",defaultModel:f?.type==="ollama"?f.defaultModel:"llama3",name:f?.name??""};return{fromHub:z,editingName:J,type:$,baseURL:f?.type==="openai-compatible"?f.baseURL:o9,apiKey:"",existingKey:f?.existingKey,defaultModel:f?.defaultModel??"",name:f?.name??""}}function vM($,f){let Z=$.type??"openai-compatible";return{fromHub:f,editingName:$.name,type:Z,baseURL:$.baseURL,apiKey:"",existingKey:$.apiKey,defaultModel:$.defaultModel??"",contextWindow:$.contextWindow,name:$.name??""}}function uM($){let f=v1(),Z=(f.providers??[]).map((K)=>K.name).filter((K)=>Boolean(K)),J={name:$.name.trim()||g8($.type,$.baseURL,Z.filter((K)=>K!==$.editingName)),type:$.type,baseURL:$.baseURL,apiKey:$.apiKey||$.existingKey||($.type==="ollama"?"ollama":""),defaultModel:$.defaultModel.trim(),...$.contextWindow!=null?{contextWindow:$.contextWindow}:{}};if($.editingName)return dJ(f,$.editingName,J);return h8(f,J,{overwrite:!1})}function EM($){if($==="openai")return"OpenAI";if($==="ollama")return"Ollama";return"OpenAI 兼容接口"}function m9(){console.log(`已保存到 ${AM.join(X0(),"config.json")}`)}function gM($){return $.replace(/Bearer\s+\S+/gi,"Bearer ****").replace(/\bsk-[A-Za-z0-9_-]+/g,"sk-****")}function r9($){return Object.keys($).length===1&&"error"in $}var o9="https://api.openai.com/v1",jM="http://localhost:11434/v1";var zK=O(()=>{d();Z1();$K()});var GK={};U0(GK,{runSetupCommand:()=>QK,registerSetupCommand:()=>d9,offerInteractiveSetup:()=>hM});import xM from"path";import{Option as JK}from"commander";function d9($,f){$.command("setup").description("configure providers (interactively, or with flags)").addOption(new JK("--type <type>","openai-compatible, openai, or ollama").argParser(lJ)).option("--url <url>","api base URL").option("--api-key <key>","api key").option("--name <name>","provider name").option("--default-model <id>","default model to save").addOption(new JK("--context-window <n>","context window in tokens").argParser(l4("--context-window"))).option("--switch <name>","set the active provider").option("--remove <name>","remove a provider").option("-y, --yes","skip overwrite and delete confirmation").action(async(Z)=>{await QK(Z,{yes:Boolean(Z.yes||f().yes)})})}function KK(){return{isTty:Boolean(process.stdin.isTTY&&process.stdout.isTTY),load:v1,save:I0,fetchLive:Mf,log:($)=>{console.log($)},configPath:()=>xM.join(X0(),"config.json"),runWizard:async($)=>{let{renderSetupWizard:f}=await Promise.resolve().then(() => (zK(),ZK));return f($)}}}async function hM($){await x9({},{...KK(),isTty:!0},$)}async function QK($,f){let Z={type:$.type,url:$.url,apiKey:$.apiKey,name:$.name,defaultModel:$.defaultModel,contextWindow:$.contextWindow,switch:$.switch,remove:$.remove,yes:Boolean(f.yes||$.yes)};await x9(Z,KK())}var i9=O(()=>{d();_8();m8();c9()});import{Box as cM,Text as YK}from"ink";import mM from"ink-spinner";import{jsxDEV as p8}from"react/jsx-dev-runtime";function PK({label:$}){return p8(cM,{children:[p8(YK,{color:"cyan",children:p8(mM,{type:"dots"},void 0,!1,void 0,this)},void 0,!1,void 0,this),$&&p8(YK,{color:"gray",children:[" ",$]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var XK=()=>{};function Df($){WK=$}function HK($){let f=0,Z=(z,J,K)=>{let Q=Buffer?.isBuffer(z),G;if(typeof z==="string")G=z;else if(Q)G=z.toString(J||"utf-8");else if(z!=null)G=String(z);else return $.write(z,J,K);let Y="";if(f>0)Y+=`\x1B[${f}B\r`,f=0;Y+=G;let P=WK;if(P){let W=P.rowsAbove+(G.endsWith(`
44
+ `)?1:0);if(W>0)Y+=`\x1B[${W}A\x1B[${P.column}G`,f=W}let X=typeof z==="string"?Y:Buffer.from(Y,J||"utf-8");return $.write(X,J,K)};return new Proxy($,{get(z,J){if(J==="write")return Z;let K=Reflect.get(z,J,z);return typeof K==="function"?K.bind(z):K},set(z,J,K){return Reflect.set(z,J,K,z)}})}var WK=null;function oM($){return $>=768&&$<=879||$>=1155&&$<=1161||$>=1425&&$<=1469||$>=1552&&$<=1562||$>=1611&&$<=1631||$>=3633&&$<=3642||$>=3655&&$<=3662||$>=6832&&$<=6911||$>=7616&&$<=7679||$>=8203&&$<=8207||$>=8288&&$<=8292||$>=8400&&$<=8447||$>=65024&&$<=65039||$>=65056&&$<=65071||$===65279||$>=917760&&$<=917999}function pM($){return $>=4352&&$<=4447||$>=11904&&$<=12350||$>=12353&&$<=13311||$>=13312&&$<=19903||$>=19968&&$<=40959||$>=40960&&$<=42191||$>=43360&&$<=43391||$>=44032&&$<=55203||$>=63744&&$<=64255||$>=65040&&$<=65049||$>=65072&&$<=65135||$>=65280&&$<=65376||$>=65504&&$<=65510||$>=127744&&$<=128591||$>=128640&&$<=128767||$>=129280&&$<=129535||$>=131072&&$<=196605||$>=196608&&$<=262141}function dM($){let f=$.codePointAt(0);if(f===void 0)return 0;if(f<32||f>=127&&f<160)return 0;if(oM(f))return 0;if(pM(f)||UK.test($))return 2;return 1}function iM($){if($.length===0)return 0;if(UK.test($)||$.includes("‍"))return 2;let f=0;for(let Z of $)f+=dM(Z);return $.includes("️")?Math.max(f,2):f}function*_$($,f){for(let{segment:Z}of rM.segment($))yield{text:Z,width:f?.(Z)??iM(Z)}}function b0($,f){let Z=0;for(let{width:z}of _$($,f))Z+=z;return Z}function l0($,f,Z){let z=typeof $==="string"?$:$==null?"":String($);if(f<1)return[z];let J=[],K="",Q=0;for(let{text:G,width:Y}of _$(z,Z)){if(Q+Y>f&&K.length>0)J.push(K),K="",Q=0;K+=G,Q+=Y}return J.push(K),J}var rM,UK;var z1=O(()=>{rM=new Intl.Segmenter(void 0,{granularity:"grapheme"}),UK=/\p{Extended_Pictographic}/u});function l9($,f,Z){let z=[],J=0,K=$.split(`
45
+ `);for(let Q=0;Q<K.length;Q++){for(let G of l0(K[Q],f,Z))z.push({text:G,startIndex:J}),J+=Array.from(G).length;if(Q<K.length-1)J+=1}return z}function bf($,f,Z){let z=Array.from($).length;return Math.min(Math.max(f+Z,0),z)}function t9($,f,Z,z,J){let K=$[f];if(!K)return 0;let Q=Z-z;if(Q<=0)return K.startIndex;let G=0,Y=0;for(let{text:P,width:X}of _$(K.text,J)){if(G+X>Q){if(J?.(P)!==void 0)return K.startIndex+Y;return K.startIndex+Y+(Q-G<X/2?0:Array.from(P).length)}G+=X,Y+=Array.from(P).length}return K.startIndex+Y}function e0($,f,Z){let z=Array.from($);return z.splice(f,0,...Array.from(Z)),{value:z.join(""),caretIndex:f+Array.from(Z).length}}function P4($,f){if(f<=0)return{value:$,caretIndex:f};let Z=Array.from($);return Z.splice(f-1,1),{value:Z.join(""),caretIndex:f-1}}function FK($,f){let Z=Array.from($);if(f>=Z.length)return{value:$,caretIndex:f};return Z.splice(f,1),{value:Z.join(""),caretIndex:f}}function a9($,f,Z,z,J){let K=l9($,z,J),Q=0,G=0;for(let X=0;X<K.length;X++){let W=K[X],H=W.startIndex+Array.from(W.text).length;if(f>=W.startIndex&&f<=H){Q=X,G=f-W.startIndex;break}if(X===K.length-1)Q=X,G=Array.from(W.text).length}let Y=Q+Z;if(Y<0||Y>=K.length)return f;let P=b0(Array.from(K[Q].text).slice(0,G).join(""),J);return t9(K,Y,P,0,J)}function J2($,f){let Z=Array.from($),z=f-1;while(z>=0&&Z[z]!==`
46
+ `)z--;return z+1}function K2($,f){let Z=Array.from($),z=f;while(z<Z.length&&Z[z]!==`
47
+ `)z++;return z}function qK($,f){let Z=J2($,f);if(Z===f)return{value:$,caretIndex:f};let z=Array.from($);return z.splice(Z,f-Z),{value:z.join(""),caretIndex:Z}}function NK($,f){let Z=K2($,f);if(Z===f)return{value:$,caretIndex:f};let z=Array.from($);return z.splice(f,Z-f),{value:z.join(""),caretIndex:f}}function BK($,f){if(f<=0)return{value:$,caretIndex:f};let Z=Array.from($),z=f-1;while(z>=0&&/\s/.test(Z[z]))z--;while(z>=0&&!/\s/.test(Z[z]))z--;let J=z+1;return Z.splice(J,f-J),{value:Z.join(""),caretIndex:J}}function VK($,f){let Z=$+f,z=[],J=/\x1b\[3(?:;\d+)?[~$^]|\x7f/g,K=0,Q;while(Q=J.exec(Z))K=Q.index+Q[0].length,z.push(Q[0]===""?{kind:"backspace"}:{kind:"delete"});let G=Z.slice(K),Y=G.lastIndexOf("\x1B");if(Y===-1)return{buffer:"",actions:z};let P=G.slice(Y);return{buffer:P.length>lM?"\x1B":P,actions:z}}function LK($,f){let Z=$+f,z=[],J=0;MK.lastIndex=0;let K;while(K=MK.exec(Z)){J=K.index+K[0].length;let P=K[0];z.push(P.endsWith("H")||P.endsWith("1~")||P.endsWith("7~")?{kind:"home"}:{kind:"end"})}let Q=Z.slice(J),G=Q.lastIndexOf("\x1B");if(G===-1)return{buffer:"",actions:z};let Y=Q.slice(G);return{buffer:Y.length>tM?"\x1B":Y,actions:z}}var lM=32,MK,tM=8;var s9=O(()=>{z1();MK=/\x1b\[(?:[HF]|[1478]~)/g});import{existsSync as aM,mkdirSync as sM,readFileSync as eM,renameSync as $F}from"fs";import DK from"path";function bK(){return DK.join(X0(),"input-history.json")}function AK($=[]){return{entries:$,index:-1,draft:""}}function fF($){let f;try{f=JSON.parse($)}catch{return null}if(typeof f!=="object"||f===null||Array.isArray(f))return null;let Z=f.entries;if(!Array.isArray(Z)||Z.some((z)=>typeof z!=="string"))return null;return Z}function ZF($){return JSON.stringify({entries:$},null,2)}function zF($){if(!aM($))return[];let f;try{f=eM($,"utf-8")}catch{return[]}let Z=fF(f);if(Z)return Z;try{$F($,`${$}.corrupt-${Date.now()}`)}catch{}return[]}function JF($,f){try{sM(DK.dirname($),{recursive:!0}),T0($,ZF(f))}catch{}}function jK(){return zF(bK())}function e9($){JF(bK(),$)}function $5($,f){if(!f)return $;if($.entries.length>0&&$.entries[$.entries.length-1]===f)return $;let Z=[...$.entries,f];if(Z.length>_K)Z.splice(0,Z.length-_K);return{entries:Z,index:-1,draft:""}}function CK($,f){let Z=f.toLowerCase();if(!Z)return null;for(let z=$.entries.length-1;z>=0;z--)if($.entries[z].toLowerCase().includes(Z))return $.entries[z];return null}function OK($,f,Z){let z=$.entries.length;if(z===0)return{text:$.draft,state:$};let J=z-1,K=(G)=>G>=0&&G<=J&&!Z?.($.entries[G]),Q=$.index===-1?-1:Math.max(0,Math.min(J,$.index));if(f===1){let G=Q===-1?J:Q-1;for(let Y=G;Y>=0;Y--)if(K(Y))return{text:$.entries[Y],state:{...$,index:Y}};if(Q!==-1)return{text:$.entries[Q],state:$};return{text:$.draft,state:$}}if(Q===-1)return{text:$.draft,state:$};for(let G=Q+1;G<=J;G++)if(K(G))return{text:$.entries[G],state:{...$,index:G}};return{text:$.draft,state:{...$,index:-1}}}function f5($,f){if($.index===-1&&$.draft===f)return $;return{entries:$.entries,index:-1,draft:f}}function d8($,f){return f.ctrl===!0&&$==="c"||$==="\x03"}function wK($,f,Z=null,z=0){if(f===""){if(Z!==null&&z-Z<=Z5)return{state:$,value:"",exit:!0,armedAt:null};return{state:$,value:"",exit:!1,armedAt:z}}return{state:f.trim()?$5($,f):{entries:$.entries,index:-1,draft:""},value:"",exit:!1,armedAt:null}}var _K=1000,Z5=2000;var z5=O(()=>{d();F$()});var TK={};U0(TK,{slashMenuWindow:()=>l8,setSlashArgProvider:()=>w$,sessionSlashCommands:()=>K5,parseSlashArgs:()=>yK,isKnownSlashCommandInput:()=>Q5,getSlashArgOptions:()=>Y5,filterSlashCommands:()=>J5,clearSlashArgProviders:()=>KF,applySlashArgCompletion:()=>P5,SLASH_COMMANDS:()=>i8});function J5($,f=i8){let Z=$.slice(1).trim().toLowerCase();if(Z==="")return f;return f.filter((z)=>z.name.startsWith(Z)||(z.aliases??[]).some((J)=>J.startsWith(Z)))}function K5($,f=i8){if($==="ollama")return f;return f.filter((Z)=>Z.name!=="ctx")}function l8($,f,Z){let z=Number.isFinite(Z)?Math.max(1,Math.floor(Z)):Math.max(1,$.length),J=$.length===0?0:Math.min(Math.max(0,f),$.length-1);if($.length<=z)return{start:0,shown:[...$],extraAbove:0,extraBelow:0};let K=Math.max(0,Math.min(J-z+1,$.length-z)),Q=$.slice(K,K+z);return{start:K,shown:Q,extraAbove:K,extraBelow:$.length-(K+Q.length)}}function Q5($,f=i8){if(!$.startsWith("/"))return!1;let Z=$.slice(1).trim().split(/\s/,1)[0]?.toLowerCase()??"";if(!Z)return!0;return f.some((z)=>z.name===Z||(z.aliases??[]).some((J)=>J===Z))}function w$($,f){G5.set($,f)}function KF(){G5.clear()}function QF($){let f=[],Z="",z=null;for(let J of $)if(z)if(J===z)z=null;else Z+=J;else if(J==='"'||J==="'")z=J;else if(/\s/.test(J)){if(Z)f.push(Z),Z=""}else Z+=J;if(Z)f.push(Z);return f}function yK($){if(!$.startsWith("/"))return null;let f=$.slice(1);if(!/\s/.test(f))return null;let Z=QF(f.trim()),z=Z[0]??"",J=Z.slice(1),K=/\s$/.test(f)?"":J.pop()??"";return{command:z,tokens:J,partial:K}}function Y5($){let f=yK($);if(!f)return[];let Z=G5.get(f.command);if(!Z)return[];let z=f.partial.toLowerCase();return Z(f.tokens,f.partial).filter((J)=>J.value.toLowerCase().startsWith(z))}function P5($,f){return/\s$/.test($)?`${$}${f} `:`${$.replace(/\S+$/,f)} `}var i8,G5;var t8=O(()=>{i8=[{name:"new",description:"新建会话(保留当前)"},{name:"compact",description:"压缩上下文"},{name:"model",description:"选择/切换模型"},{name:"models",description:"列出可用模型"},{name:"provider",description:"选择/切换服务商"},{name:"memory",description:"查看/开关记忆,或保存一条",argHint:"[on|off|t] [--project]"},{name:"tokens",description:"显示上下文占用、累计用量与成本"},{name:"ctx",description:"选择本地模型上下文窗口"},{name:"budget",description:"查看/设置预算上限",argHint:"[n] [--project]"},{name:"permission",description:"查看/设置确认模式",argHint:"[ask|accept-edits|allow-all] [--project]"},{name:"think",description:"选择思考强度",aliases:["thinking"]},{name:"sandbox",description:"查看/设置隔离",argHint:"[off|workspace|strict] [--project]"},{name:"undo",description:"撤销上一轮"},{name:"redo",description:"重发最后一条消息"},{name:"diff",description:"显示工作区未提交变更"},{name:"plan",description:"切换只读计划模式"},{name:"sessions",description:"列出/切换已保存会话",argHint:"[id]",aliases:["resume"]},{name:"reload",description:"重新加载规则"},{name:"rename",description:"重命名当前会话",argHint:"<title>"},{name:"attach",description:"附加本地图片",argHint:"<path>",aliases:["image"]},{name:"mcp",description:"显示 MCP 状态"},{name:"skills",description:"显示/启用/禁用 skills",argHint:"[list|info <name>|enable|disable <name> [--project]]"},{name:"path",description:"显示工作目录",aliases:["pwd"]},{name:"paste",description:"粘贴剪贴板图片",argHint:"[t]"},{name:"help",description:"显示帮助"},{name:"exit",description:"退出",aliases:["quit","q"]}];G5=new Map});function a8($){let f=$.match(GF);if(!f)return null;return{event:{button:parseInt(f[1],10),col:parseInt(f[2],10),row:parseInt(f[3],10),press:f[4]==="M"},rest:$.slice((f.index??0)+f[0].length)}}var IK="\x1B[?1000h\x1B[?1002h\x1B[?1006h",kK="\x1B[?1000l\x1B[?1002l\x1B[?1006l",GF,Q2=64,X5=65,X4=32,nK=31;var G2=O(()=>{GF=/\x1b\[<(\d+);(\d+);(\d+)([Mm])/});function e8($){return $?5:5}function RK($){if($<=0)return 0;return Math.max(1,$-YF)}function $6($){return Math.max(1,$-5)}function SK($){return Math.max(1,$-1-2)}function f6($){return Math.max(8,$-4-2)}function vK($,f,Z){if($<=0)return;return Math.max(2,$-f-2-Z)}function P2($,f){if($<=0)return Number.POSITIVE_INFINITY;return Math.max(f,$-2-2)}function uK($,f){return Math.max(1,$)+Math.max(0,f)+2}function EK($,f,Z,z){let J=Z>0?Z+5:z>0?z+4:0;return uK($,f)+J}function M5($,f,Z,z){let J=P2($,3);if(!Number.isFinite(J))return Number.POSITIVE_INFINITY;return Math.max(4,J-uK(f,Z)-z)}function t0($,f,Z){if(f<=0)return{start:0,lines:[],above:0,below:$.length};if($.length<=f)return{start:0,lines:$,above:0,below:0};let z=0,J=0,K=0,Q=f;for(let G=0;G<3;G++){let Y=(z>0?1:0)+(J>0?1:0);Q=Math.max(1,f-Y);let P=Math.max(0,$.length-Q);K=Math.max(0,Math.min(Z,P)),z=K,J=Math.max(0,$.length-(K+Q))}return{start:K,lines:$.slice(K,K+Q),above:z,below:J}}var W5=5,Y2=3,H5=5,U5=4,s8=6,YF=1;var xK={};U0(xK,{writeClipboard:()=>N5,getClipboardImage:()=>q5});import{execSync as _1}from"child_process";import{readFileSync as PF,unlinkSync as XF}from"fs";import WF from"path";import HF from"os";function F5($){let f=PF($);try{XF($)}catch{}return f.length>0?f:null}function gK(){return WF.join(HF.tmpdir(),`min-agent-paste-${Date.now()}.png`)}function q5(){switch(process.platform){case"darwin":return UF();case"linux":return MF();case"win32":return FF();default:return null}}function N5($){switch(process.platform){case"darwin":try{return _1("pbcopy",{input:$,stdio:"pipe"}),!0}catch{return!1}case"linux":{try{return _1("xclip -selection clipboard",{input:$,stdio:"pipe"}),!0}catch{}try{return _1("xsel --clipboard --input",{input:$,stdio:"pipe"}),!0}catch{}return!1}case"win32":try{return _1('powershell -NoProfile -Command "Set-Clipboard -Value ([Console]::In.ReadToEnd())"',{input:$,stdio:"pipe"}),!0}catch{return!1}default:return!1}}function UF(){let $=gK();try{_1(`pngpaste "${$}" 2>/dev/null`,{stdio:"pipe"});let f=F5($);if(f)return{data:f,mimeType:"image/png"}}catch{}try{let f=`
48
+ set tmpFile to POSIX file "${$}"
49
+ try
50
+ set imgData to the clipboard as «class PNGf»
51
+ set fp to open for access tmpFile with write permission
52
+ write imgData to fp
53
+ close access fp
54
+ return "ok"
55
+ on error
56
+ return "no_image"
57
+ end try
58
+ `;if(_1(`osascript -e '${f.replace(/'/g,"'\\''")}'`,{encoding:"utf-8"}).trim()==="ok"){let z=F5($);if(z)return{data:z,mimeType:"image/png"}}}catch{}return null}function MF(){try{let $=_1("xclip -selection clipboard -t image/png -o 2>/dev/null",{maxBuffer:10485760});if($.length>0)return{data:$,mimeType:"image/png"}}catch{}try{let $=_1("xsel --clipboard --output 2>/dev/null",{maxBuffer:10485760});if($.length>8&&$[0]===137&&$[1]===80)return{data:$,mimeType:"image/png"}}catch{}return null}function FF(){let $=gK();try{let f=`
59
+ Add-Type -AssemblyName System.Windows.Forms
60
+ $img = [System.Windows.Forms.Clipboard]::GetImage()
61
+ if ($img) { $img.Save('${$.replace(/\\/g,"\\\\")}', [System.Drawing.Imaging.ImageFormat]::Png); Write-Output 'ok' }
62
+ else { Write-Output 'no_image' }
63
+ `;if(_1(`powershell -NoProfile -Command "${f}"`,{encoding:"utf-8"}).trim()==="ok"){let z=F5($);if(z)return{data:z,mimeType:"image/png"}}}catch{}return null}var Z6=()=>{};function mK($,f){let Z=[],z=$+f;while(!0){let J=z.indexOf("\x1B[200~");if(J===-1)return{buffer:Z.length>0?z:qF(z),pastes:Z,active:!1};let K=z.slice(J+6),Q=K.indexOf("\x1B[201~");if(Q===-1)return{buffer:"\x1B[200~"+K,pastes:Z,active:!0};Z.push(K.slice(0,Q)),z=K.slice(Q+6)}}function rK($,f){if(f)return!0;return $.includes("\x1B[200~")||$.includes("\x1B[201~")||$.includes("[200~")||$.includes("[201~")}function qF($){let f=$.lastIndexOf("\x1B");if(f===-1)return"";let Z=$.slice(f);return"\x1B[200~".startsWith(Z)?Z:""}var hK="\x1B[?2004h",cK="\x1B[?2004l";function V5(){return{nextCodePoint:NF,nextImageId:1,nextSnippetId:1,attachments:new Map}}function z6(){return V5()}function AF($){return`[图片 #${$}]`}function jF($,f){return`[粘贴 #${$} · ${f} 行]`}function CF($){let f=$.replace(/\r\n/g,`
64
+ `).replace(/\r/g,`
65
+ `);return f.endsWith(`
66
+ `)?f.slice(0,-1):f}function oK($,f){let Z=CF(f);if(Z.length>BF)return{kind:"reject",notice:_F,draft:$};if(!Z.includes(`
67
+ `))return{kind:"text",text:Z,draft:$};let{char:z,draft:J}=lK($,{kind:"snippet",id:$.nextSnippetId,text:Z,lineCount:Z.split(`
68
+ `).length});return{kind:"snippet",char:z,draft:J}}function pK($,f){if(f==null)return{kind:"none",draft:$};if(f.data.length>VF)return{kind:"reject",notice:LF,draft:$};let{char:Z,draft:z}=lK($,{kind:"image",id:$.nextImageId,data:f.data,mimeType:f.mimeType});return{kind:"image",char:Z,draft:z}}function dK($,f){let Z=new Set(Array.from(f)),z=new Map([...$.attachments].filter(([J])=>Z.has(J)));if(z.size===$.attachments.size)return $;return{...$,attachments:z}}function OF($,f){return Array.from($).map((Z)=>{let z=f.attachments.get(Z);if(z)return _5(z);return D5(Z)?B5:Z}).join("")}function wF($,f){let Z=[],z="",J=()=>{if(!z)return;Z.push({type:"text",text:z}),z=""};for(let K of Array.from($)){let Q=f.attachments.get(K);if(Q?.kind==="image"){J(),Z.push({type:"image",image:Q.data,mimeType:Q.mimeType});continue}if(Q?.kind==="snippet"){J(),Z.push({type:"text",text:TF(Q.id,Q.text,Z)});continue}z+=D5(K)?B5:K}if(J(),!Z.some((K)=>K.type==="image"))return Z.map((K)=>K.type==="text"?K.text:"").join("");return Z}function iK($,f){return{display:OF($,f),content:wF($,f)}}function J6($,f,Z){let z=f.attachments.get($);if(!z)return;return Math.min(b0(_5(z)),Z)}function yF($,f,Z){let z=f.attachments.get($);if(!z)return;return IF(_5(z),Z)}function L5($,f,Z){return yF($,f,Z)??(D5($)?B5:$)}function _5($){return $.kind==="image"?AF($.id):jF($.id,$.lineCount)}function TF($,f,Z){let z=`--- 粘贴 #${$} ---
69
+ ${f}
70
+ --- 粘贴 #${$} ---`;if(Z.length===0)return z;let J=Z[Z.length-1];if(J?.type==="text"&&J.text.endsWith(`
71
+ `))return z;return`
72
+ ${z}`}function lK($,f){let Z=String.fromCodePoint($.nextCodePoint),z=new Map($.attachments);return z.set(Z,f),{char:Z,draft:{nextCodePoint:$.nextCodePoint+1,nextImageId:f.kind==="image"?$.nextImageId+1:$.nextImageId,nextSnippetId:f.kind==="snippet"?$.nextSnippetId+1:$.nextSnippetId,attachments:z}}}function D5($){let f=$.codePointAt(0);return f!==void 0&&f>=DF&&f<=bF}function IF($,f){if(f<1)return"";if(b0($)<=f)return $;let Z="…",z=b0(Z),J="",K=0;for(let{text:Q,width:G}of _$($)){if(K+G+z>f)break;J+=Q,K+=G}return J+=Z,K+=z,K<f?`${J}${" ".repeat(f-K)}`:J}var NF=57344,BF=1e6,VF=5242880,LF="图片超过 5MB,未附加",_F="粘贴内容过大,未附加",DF=57344,bF=63743,B5="�";var tK=O(()=>{z1()});import{useState as X2,useEffect as Af,useMemo as aK,useRef as j0,useCallback as K6}from"react";import{Box as y$,Text as a0,useInput as kF,useStdin as nF,useStdout as RF}from"ink";import{jsxDEV as N0}from"react/jsx-dev-runtime";function SF($){return/^\[\d{1,2}(;\d{0,2})?u?$/.test($)||/^\d{1,2};\d{1,2}u$/.test($)}function vF($,f){let Z=$+f,z=!1,J;while((J=Z.indexOf(eK))!==-1)Z=Z.slice(J+eK.length),z=!0;let K=Z.lastIndexOf("\x1B");return{buffer:K===-1?"":Z.slice(K),shiftEnter:z}}function $Q({onSubmit:$,disabled:f,placeholder:Z,columns:z,terminalRows:J,onSelectionMode:K,onExit:Q,onRowsChange:G,onNotice:Y}){let[P,X]=X2({value:"",caretIndex:0}),{value:W,caretIndex:H}=P,[M,F]=X2(0),[q,U]=X2(!1),{stdin:N}=nF(),{stdout:B}=RF(),D=j0(""),V=j0(""),b=j0(""),C=j0(""),S=j0(""),I=j0(!1),j=j0(V5()),w=j0(Y);w.current=Y;let E=z||80,[l,h]=X2(()=>AK(jK())),t=j0(l),[v,T]=X2(!1),r=j0(null),R=j0(null),m=K6(()=>{if(r.current===null&&R.current===null)return;if(R.current!==null)clearTimeout(R.current),R.current=null;r.current=null,T(!1)},[]),K0=K6((c)=>{if(r.current=c,T(!0),R.current!==null)clearTimeout(R.current);R.current=setTimeout(()=>{R.current=null,r.current=null,T(!1)},Z5)},[]);Af(()=>()=>m(),[m]);let x=j0(P),y=K6((c)=>{m();let g=c(x.current.value,x.current.caretIndex);x.current=g,X(g),j.current=dK(j.current,g.value);let W0=f5(t.current,g.value);if(W0!==t.current)t.current=W0,h(W0)},[m]),n0=(c)=>{t.current=$5(t.current,c.display),h(t.current),e9(t.current.entries),$(c)},P0=K6((c)=>{let g=oK(j.current,c);if(g.kind==="text"){if(g.text)y((W0,p0)=>e0(W0,p0,g.text));return}if(g.kind==="snippet"){j.current=g.draft,y((W0,p0)=>e0(W0,p0,g.char));return}w.current?.(g.notice)},[y]),F0=(c)=>{let{text:g,state:W0}=OK(t.current,c,Q5);if(t.current=W0,h(W0),g!==x.current.value){let p0={value:g,caretIndex:Array.from(g).length};x.current=p0,X(p0)}};Af(()=>()=>{Df(null)},[]);let f0=e(J0())?.type,Q0=aK(()=>J5(W,K5(f0)),[W,f0]),Y0=W.startsWith("/")&&!/\s/.test(W.slice(1))&&!q&&Q0.length>0,A=Y0?Math.min(M,Q0.length-1):0,o=Y0?Q0[A]:void 0,i=aK(()=>Y0?[]:Y5(W),[W,Y0]),u=!Y0&&!q&&i.length>0,G0=u?Math.min(M,i.length-1):0,O0=u?i[G0]:void 0;Af(()=>{if(Y0||u)F(0)},[Y0,u]);let z0=(c)=>{if(c.argHint)y(()=>({value:`/${c.name} `,caretIndex:c.name.length+2}));else n0({display:`/${c.name}`,content:`/${c.name}`}),j.current=z6(),y(()=>({value:"",caretIndex:0}))},w0=(c)=>{y((g)=>{let W0=P5(g,c.value);return{value:W0,caretIndex:Array.from(W0).length}})},rf=j0(z0);rf.current=z0;let xZ=j0(w0);xZ.current=w0;let I3=j0(Y0);I3.current=Y0;let hZ=j0(u);hZ.current=u;let cZ=j0(P0);cZ.current=P0,kF((c,g)=>{if(f)return;if(d8(c,g)){let k=x.current.value,p=wK(t.current,k,r.current,Date.now());if(p.exit){m(),Q();return}if(p.state.entries!==t.current.entries)e9(p.state.entries);if(t.current=p.state,h(p.state),p.armedAt!==null){K0(p.armedAt);return}m(),j.current=z6(),y(()=>({value:"",caretIndex:0}));return}if(m(),g.ctrl&&c==="b"){K?.();return}if(g.ctrl&&c==="v"){let k=pK(j.current,q5());if(k.kind==="image")j.current=k.draft,y((p,d0)=>e0(p,d0,k.char));else if(k.kind==="reject")w.current?.(k.notice);return}if(rK(c,I.current))return;let W0=c.replace(/[\r\n]+$/,""),p0=g.return||/[\r\n]+$/.test(c);if(g.escape){if(Y0||u)U(!0);else if(t.current.index!==-1){let k=f5(t.current,t.current.draft);if(t.current=k,h(k),k.draft!==x.current.value){let p={value:k.draft,caretIndex:Array.from(k.draft).length};x.current=p,X(p)}}return}if(U(!1),Y0){if(g.upArrow){F((k)=>(k-1+Q0.length)%Q0.length);return}if(g.downArrow){F((k)=>(k+1)%Q0.length);return}if(g.tab){if(Q0.length===1&&o){z0(o);return}F((k)=>g.shift?(k-1+Q0.length)%Q0.length:(k+1)%Q0.length);return}if(p0){if(o)z0(o);return}}if(u){if(g.upArrow){F((k)=>(k-1+i.length)%i.length);return}if(g.downArrow){F((k)=>(k+1)%i.length);return}if(g.tab){if(O0)w0(O0);return}}let Pf=g;if(Pf.home){y((k,p)=>({value:k,caretIndex:J2(k,p)}));return}if(Pf.end){y((k,p)=>({value:k,caretIndex:K2(k,p)}));return}if(g.upArrow){let{value:k,caretIndex:p}=x.current,d0=f6(z),k1=a9(k,p,-1,d0,(u$)=>J6(u$,j.current,d0));if(k1!==p){y(()=>({value:k,caretIndex:k1}));return}F0(1);return}if(g.downArrow){let{value:k,caretIndex:p}=x.current,d0=f6(z),k1=a9(k,p,1,d0,(u$)=>J6(u$,j.current,d0));if(k1!==p){y(()=>({value:k,caretIndex:k1}));return}F0(-1);return}if(c===`
73
+ `&&!g.return){y((k,p)=>e0(k,p,`
74
+ `));return}if(p0){let k=x.current.value;if(k.endsWith("\\")){y((d0,v4)=>e0(d0.slice(0,-1),v4,`
75
+ `));return}let p=iK(k,j.current);if(p.display.trim()||j.current.attachments.size>0)n0(p);j.current=z6(),y(()=>({value:"",caretIndex:0}));return}if(g.leftArrow){y((k,p)=>({value:k,caretIndex:bf(k,p,-1)}));return}if(g.rightArrow){y((k,p)=>({value:k,caretIndex:bf(k,p,1)}));return}if(g.backspace){y((k,p)=>P4(k,p));return}if(g.escape||g.pageUp||g.pageDown)return;if(g.ctrl&&c==="r"){let k=CK(t.current,x.current.value);if(k){let p={value:k,caretIndex:Array.from(k).length};x.current=p,X(p)}return}if(g.ctrl&&c==="a"){y((k,p)=>({value:k,caretIndex:J2(k,p)}));return}if(g.ctrl&&c==="e"){y((k,p)=>({value:k,caretIndex:K2(k,p)}));return}if(g.ctrl&&c==="k"){y((k,p)=>NK(k,p));return}if(g.ctrl&&c==="u"){y((k,p)=>qK(k,p));return}if(g.ctrl&&c==="w"){y((k,p)=>BK(k,p));return}if(g.meta&&c==="b"){y((k,p)=>({value:k,caretIndex:Math.max(0,p-1)}));return}if(g.meta&&c==="f"){y((k,p)=>({value:k,caretIndex:Math.min(Array.from(k).length,p+1)}));return}if(g.ctrl||g.meta)return;if(SF(c))return;if(/^\[<.*[Mm]$/.test(c)||c.startsWith("[<")||/^[\d;,]+[Mm]$/.test(c))return;if(g.tab){y((k,p)=>e0(k,p," "));return}if(c)y((k,p)=>e0(k,p,W0))},{isActive:!f});let cW=W==="",mZ=v?"再按一次 Ctrl+C 退出":Z,rZ=W.split(`
76
+ `),oZ=rZ.length>1,mW=f?_.inputBorderDisabled:_.inputBorder,S4=f6(E),Q8=(c)=>J6(c,j.current,S4),c0=l9(W,S4,Q8),k3=Math.min(H,Array.from(W).length),U1=c0.length-1,G8=Array.from(c0[U1].text).length;for(let c=0;c<c0.length;c++){let g=c0[c],W0=g.startIndex+Array.from(g.text).length;if(k3>=g.startIndex&&k3<=W0){U1=c,G8=k3-g.startIndex;break}}let n3=b0(Array.from(c0[U1].text).slice(0,G8).join(""),Q8);if(n3>=S4){if(U1===c0.length-1)c0.push({text:"",startIndex:c0[U1].startIndex+Array.from(c0[U1].text).length});U1++,G8=0,n3=0}let Yf=oZ?1:0,rW=M5(J,c0.length,Yf,H5),oW=M5(J,c0.length,Yf,U5),j$=Y0?l8(Q0,A,rW):null,C$=u?l8(i,G0,oW):null,pZ=j$?j$.shown.length+H5:C$?C$.shown.length+U5:0,dZ=EK(c0.length,Yf,j$?.shown.length??0,C$?.shown.length??0),iZ=J-c0.length-Yf-pZ,Y8=j0(c0);Y8.current=c0;let R3=j0(iZ);R3.current=iZ;let lZ=j0(Yf);lZ.current=Yf;let tZ=j0(j$);tZ.current=j$;let aZ=j0(C$);aZ.current=C$;let sZ=j0(Q8);sZ.current=Q8,Af(()=>{G?.(dZ)},[dZ,G]),Af(()=>()=>G?.(Y2),[G]),Af(()=>{if(!N||f)return;let c=(g)=>{let W0=g.toString("utf-8"),p0=mK(S.current,W0);S.current=p0.buffer,I.current=p0.active;for(let K$ of p0.pastes)cZ.current(K$);let{buffer:Pf,shiftEnter:k}=vF(D.current,W0);if(D.current=Pf,k)y((K$,E$)=>e0(K$,E$,`
77
+ `));let{buffer:p,actions:d0}=VK(b.current,W0);if(b.current=p,d0.length>0)for(let K$ of d0)y((E$,M1)=>K$.kind==="backspace"?P4(E$,M1):FK(E$,M1));let{buffer:v4,actions:k1}=LK(C.current,W0);if(C.current=v4,k1.length>0)for(let K$ of k1)y((E$,M1)=>({value:E$,caretIndex:K$.kind==="home"?J2(E$,M1):K2(E$,M1)}));V.current+=W0;let u$;while(u$=a8(V.current))if(V.current=u$.rest,u$.event.button===0&&u$.event.press){let K$=u$.event.row-R3.current;if(K$>=0&&K$<Y8.current.length){let E$=u$.event.col;y((M1)=>({value:M1,caretIndex:t9(Y8.current,K$,E$,W5,sZ.current)}))}else{let M1=I3.current?1:0,eZ=u$.event.row-(R3.current+Y8.current.length+lZ.current+3+M1);if(I3.current){let u4=tZ.current?.shown[eZ];if(u4)rf.current(u4)}else if(hZ.current){let u4=aZ.current?.shown[eZ];if(u4)xZ.current(u4)}}}if(V.current.length>64){let K$=V.current.lastIndexOf("\x1B");V.current=K$===-1?"":V.current.slice(K$)}};return N.on("data",c),()=>{N.off("data",c)}},[N,f,y]),Af(()=>{return B.write(`${hK}${IK}`),()=>{B.write(`${kK}${cK}`)}},[B]);{let c=c0.length-1-U1;Df({rowsAbove:c+1+Yf+pZ,column:W5+n3})}return N0(y$,{flexDirection:"column",flexShrink:0,width:"100%",children:[N0(y$,{flexDirection:"column",borderStyle:"round",borderColor:mW,paddingX:1,width:"100%",children:[cW&&mZ?N0(y$,{children:[N0(a0,{color:f?_.inputBorderDisabled:_.inputBorder,children:sK},void 0,!1,void 0,this),N0(a0,{inverse:!0,children:" "},void 0,!1,void 0,this),N0(a0,{color:_.muted,dimColor:!0,wrap:"truncate-end",children:mZ},void 0,!1,void 0,this)]},void 0,!0,void 0,this):c0.map((c,g)=>{let W0=Array.from(c.text),p0=g===U1,Pf=p0?G8:W0.length,k=W0.slice(0,Pf).map((d0)=>L5(d0,j.current,S4)).join(""),p=W0.slice(Pf).map((d0)=>L5(d0,j.current,S4)).join("");return N0(y$,{children:[N0(a0,{color:f?_.inputBorderDisabled:_.inputBorder,children:g===0?sK:" "},void 0,!1,void 0,this),N0(a0,{wrap:"truncate-end",children:[k,p0&&N0(a0,{inverse:!0,children:" "},void 0,!1,void 0,this),p]},void 0,!0,void 0,this)]},g,!0,void 0,this)}),oZ&&N0(y$,{justifyContent:"flex-end",children:N0(a0,{color:_.muted,dimColor:!0,wrap:"truncate-end",children:[rZ.length," 行 | Shift+Enter/Ctrl+J 换行 | Enter 发送"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Y0&&o&&N0(y$,{flexDirection:"column",borderStyle:"round",borderColor:_.inputBorder,paddingX:1,marginTop:1,width:"100%",children:[N0(y$,{children:N0(a0,{color:_.muted,children:W.trim()==="/"?"命令":`/${W.slice(1)} 命令`},void 0,!1,void 0,this)},void 0,!1,void 0,this),j$?.shown.map((c,g)=>{let W0=j$.start+g===A;return N0(y$,{children:[N0(a0,{color:W0?_.accent:_.muted,children:W0?"❯ ":" "},void 0,!1,void 0,this),N0(a0,{bold:W0,color:W0?_.accent:void 0,children:["/",c.name,c.argHint?` ${c.argHint}`:""]},void 0,!0,void 0,this),N0(a0,{color:_.muted,dimColor:!0,wrap:"truncate-end",children:[" ",c.description]},void 0,!0,void 0,this)]},c.name,!0,void 0,this)}),N0(y$,{children:N0(a0,{color:_.muted,dimColor:!0,wrap:"truncate-end",children:[j$&&j$.extraAbove+j$.extraBelow>0?`还有 ${j$.extraAbove+j$.extraBelow} 项 · `:"","↑↓ 选择 · Tab/Enter 执行 · Esc 关闭"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),u&&N0(y$,{flexDirection:"column",borderStyle:"round",borderColor:_.inputBorder,paddingX:1,marginTop:1,width:"100%",children:[C$?.shown.map((c,g)=>{let W0=C$.start+g===G0;return N0(y$,{children:[N0(a0,{color:W0?_.accent:_.muted,children:W0?"❯ ":" "},void 0,!1,void 0,this),N0(a0,{bold:W0,color:W0?_.accent:void 0,children:c.value},void 0,!1,void 0,this),c.description&&N0(a0,{color:_.muted,dimColor:!0,wrap:"truncate-end",children:[" ",c.description]},void 0,!0,void 0,this)]},c.value,!0,void 0,this)}),N0(y$,{children:N0(a0,{color:_.muted,dimColor:!0,wrap:"truncate-end",children:[C$&&C$.extraAbove+C$.extraBelow>0?`还有 ${C$.extraAbove+C$.extraBelow} 项 · `:"","↑↓ 选择 · Tab 补全 · Enter 执行 · Esc 关闭"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var sK="❯ ",eK="\x1B[13;2u";var fQ=O(()=>{z1();s9();z5();t8();d();G2();G2();Z1();Z6();tK()});function ZQ(){if("NO_COLOR"in process.env)return!1;if(process.env.FORCE_COLOR==="0")return!1;return!0}class W2{buffer="";inCodeBlock=!1;codeLang="";tableRows=[];inTable=!1;write($){this.buffer+=$;let f="",Z=ZQ()?zQ:JQ;while(!0){let z=this.buffer.indexOf(`
78
+ `);if(z===-1)break;let J=this.buffer.slice(0,z);if(this.buffer=this.buffer.slice(z+1),this.inCodeBlock||J.startsWith("```")){if(this.inTable)f+=this.renderTable(Z),this.tableRows=[],this.inTable=!1;f+=this.formatLine(J,Z)+`
79
+ `;continue}if(this.isTableRow(J)){if(this.isTableSeparator(J)){this.inTable=!0;continue}this.inTable=!0,this.tableRows.push(this.parseTableRow(J));continue}if(this.inTable)f+=this.renderTable(Z),this.tableRows=[],this.inTable=!1;f+=this.formatLine(J,Z)+`
80
+ `}if(!this.inTable&&!this.inCodeBlock&&this.buffer.length>0){if(!this.buffer.startsWith("|")&&!this.buffer.startsWith("`")){let z=this.buffer;this.buffer="",f+=this.formatInline(z,Z)}}if(this.inTable&&this.buffer.length>0&&!this.buffer.startsWith("|")){if(f+=this.renderTable(Z),this.tableRows=[],this.inTable=!1,this.buffer.length>0&&!this.buffer.startsWith("`")){let z=this.buffer;this.buffer="",f+=this.formatInline(z,Z)}}return f}flush(){let $=ZQ()?zQ:JQ,f="";if(this.inTable&&this.buffer.length>0){if(this.isTableRow(this.buffer)){if(!this.isTableSeparator(this.buffer))this.tableRows.push(this.parseTableRow(this.buffer));this.buffer=""}}if(this.inTable&&this.tableRows.length>0)f+=this.renderTable($),this.tableRows=[],this.inTable=!1;if(!this.buffer)return f;return f+=this.formatLine(this.buffer,$),this.buffer="",f}isTableRow($){let f=$.trim();return f.startsWith("|")&&f.endsWith("|")&&f.includes("|",1)}isTableSeparator($){return/^\s*\|[\s:]*-+[\s:|-]*\|\s*$/.test($)}parseTableRow($){return $.trim().slice(1,-1).split("|").map((f)=>f.trim())}clipToWidth($,f){let Z=0,z="";for(let J of $){let K=b0(J);if(Z+K>f)break;z+=J,Z+=K}return z}padToWidth($,f){let Z=this.clipToWidth($,f),z=f-b0(Z);return z>0?Z+" ".repeat(z):Z}renderTable($){if(this.tableRows.length===0)return"";let f=Math.max(0,...this.tableRows.map((Y)=>Y.length));if(f===0)return"";let Z=Array(f).fill(0),z=64;for(let Y of this.tableRows)for(let P=0;P<Y.length;P++)Z[P]=Math.min(z,Math.max(Z[P],b0(Y[P]??"")));let J=[],K=`${$.dim}┌${Z.map((Y)=>"─".repeat(Math.max(0,Y+2))).join("┬")}┐${$.reset}`,Q=`${$.dim}├${Z.map((Y)=>"─".repeat(Math.max(0,Y+2))).join("┼")}┤${$.reset}`,G=`${$.dim}└${Z.map((Y)=>"─".repeat(Math.max(0,Y+2))).join("┴")}┘${$.reset}`;J.push(K);for(let Y=0;Y<this.tableRows.length;Y++){let P=this.tableRows[Y],X=Z.map((W,H)=>{let M=P[H]??"",F=this.padToWidth(M,W);return Y===0?`${$.bold}${F}${$.reset}`:F});if(J.push(`${$.dim}│${$.reset} ${X.join(` ${$.dim}│${$.reset} `)} ${$.dim}│${$.reset}`),Y===0)J.push(Q)}return J.push(G),J.join(`
81
+ `)+`
82
+ `}formatInline($,f){return $.split(/(`[^`]*`)/g).map((z)=>{if(z.startsWith("`")&&z.endsWith("`")&&z.length>=2){let K=z.slice(1,-1);return`${f.cyan}${K}${f.reset}`}let J=z;return J=J.replace(/\*\*([^*]+)\*\*/g,`${f.bold}$1${f.reset}`),J=J.replace(/\*([^*]+)\*/g,`${f.italic}$1${f.reset}`),J=J.replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${f.cyan}$1${f.reset} ${f.dim}($2)${f.reset}`),J}).join("")}formatLine($,f){if($.startsWith("```")){if(!this.inCodeBlock)return this.inCodeBlock=!0,this.codeLang=$.slice(3).trim(),`${f.dim}┌─ ${this.codeLang||"code"} ${"─".repeat(Math.max(0,40-(this.codeLang?.length??0)))}${f.reset}`;return this.inCodeBlock=!1,this.codeLang="",`${f.dim}└${"─".repeat(44)}${f.reset}`}if(this.inCodeBlock)return`${f.dim}│${f.reset} ${$}`;if($.startsWith("### "))return`${f.bold}${this.formatInline($.slice(4),f)}${f.reset}`;if($.startsWith("## "))return`${f.bold}${this.formatInline($.slice(3),f)}${f.reset}`;if($.startsWith("# "))return`${f.bold}${f.cyan}${this.formatInline($.slice(2),f)}${f.reset}`;if(/^---+$/.test($))return`${f.dim}${"─".repeat(44)}${f.reset}`;let Z=$.match(/^(\s*)>\s?(.*)$/);if(Z){let z=Z[1],J=Z[2];return`${z}${f.dim}▎${f.reset} ${this.formatInline(J,f)}`}if(/^\s*\d+\.\s/.test($)){let z=$.match(/^(\s*)(\d+\.)(\s)(.*)$/);if(z)return`${z[1]}${f.yellow}${z[2]}${f.reset}${z[3]}${this.formatInline(z[4],f)}`}if($.match(/^\s*[-*]\s/))return $.replace(/^(\s*)([-*])(\s)(.*)$/,(z,J,K,Q,G)=>{return`${J}${f.cyan}•${f.reset}${Q}${this.formatInline(G,f)}`});return this.formatInline($,f)}}var zQ,JQ;var b5=O(()=>{z1();zQ={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",cyan:"\x1B[36m",green:"\x1B[32m",yellow:"\x1B[33m",magenta:"\x1B[35m",gray:"\x1B[90m",underline:"\x1B[4m"},JQ={reset:"",bold:"",dim:"",italic:"",cyan:"",green:"",yellow:"",magenta:"",gray:"",underline:""}});function W4($){return $.replace(/\x1b\[[0-9;]*m/g,"")}function G6($,f,Z){if(Z<=f)return $;let z="",J=0,K=!1;for(let Q of $.split(/(\x1b\[[0-9;]*m)/g)){if(Q.startsWith("\x1B[")){if(K&&Q===uF){if(J<Z)z+=Q+KQ;else z+=A5+Q,K=!1;continue}z+=Q;continue}for(let{text:G,width:Y}of _$(Q)){let P=J,X=J+Y,W=X>f&&P<Z;if(W&&!K)z+=KQ,K=!0;else if(!W&&K)z+=A5,K=!1;z+=G,J=X}}if(K)z+=A5;return z}function EF($,f,Z){if(Z<=f)return"";let z="",J=0;for(let{text:K,width:Q}of _$(QQ($))){let G=J+Q;if(G>f&&J<Z)z+=K;if(J=G,J>=Z)break}return z}function QQ($){let f=Q6.get($);if(f!==void 0)return f;let Z=W4($);if(Q6.size>512)Q6.clear();return Q6.set($,Z),Z}function GQ($,f,Z){let z=[];for(let J=0;J<Z.length;J++){let K=Z[J],Q=$[J];if(!K||!Q)continue;z.push(gF(EF(Q,K.start,K.end),f[J]??"plain"))}while(z.length>0&&z[z.length-1]==="")z.pop();return z.join(`
83
+ `)}function gF($,f){if(f==="user-head"&&$.startsWith("> "))return $.slice(2);if(f==="tool-head")return $.replace(/^⚡ .*?[▸▾] /,"");if(f==="thinking-head")return $.replace(/^💭 .*?[▸▾] /,"");if((f==="tool-body"||f==="thinking-body")&&$.startsWith(" "))return $.slice(2);return $}function j5($,f){if(f==="user"&&$.startsWith("> "))return"> ";if(f==="tool"){let Z=$.match(/^⚡ .*?[▸▾] /);return Z?Z[0]:""}if(f==="thinking"){let Z=$.match(/^💭 .*?[▸▾] /);return Z?Z[0]:""}return""}function YQ($,f){let Z=$.start<f&&$.end>0?{start:$.start,end:Math.min(f,$.end)}:null,z=$.end>f?{start:Math.max(0,$.start-f),end:$.end-f}:null;return{head:Z&&Z.end>Z.start?Z:null,tail:z&&z.end>z.start?z:null}}function PQ($,f){let Z=[],z=0;for(let{text:G,width:Y}of _$($))Z.push({ch:G,start:z,end:z+Y}),z+=Y;let J=Z.find((G)=>f>=G.start&&f<G.end);if(!J||/\s/.test(J.ch))return{start:f,end:f};let K=Z.indexOf(J),Q=K;while(K>0&&!/\s/.test(Z[K-1].ch))K--;while(Q<Z.length-1&&!/\s/.test(Z[Q+1].ch))Q++;return{start:Z[K].start,end:Z[Q].end}}function H2($,f,Z,z=1){let J=Math.max(0,$.length-1);return{row:Math.min(J,Math.max(0,f-1)),col:Math.max(0,Z-1-z)}}function XQ($,f){let Z=new Map;for(let z=0;z<$.length;z++){let J=f[z],K=$[z];if(!J||!K||K.end<=K.start)continue;let Q=Z.get(J.part);if(!Q)Q=[],Z.set(J.part,Q);Q[J.shown]=K}return Z}function C5($,f,Z){let z=$.map(()=>null),J=Math.min(f.row,Z.row),K=Math.max(f.row,Z.row);for(let Q=J;Q<=K;Q++){let G=$[Q];if(Q<0||Q>=$.length||G===null)continue;let Y=b0(QQ(G)),P,X;if(f.row===Z.row)P=Math.min(f.col,Z.col),X=Math.max(f.col,Z.col)+1;else if(Q===f.row)if(f.row<Z.row)P=f.col,X=Y;else P=0,X=f.col+1;else if(Q===Z.row)if(f.row<Z.row)P=0,X=Z.col+1;else P=Z.col,X=Y;else P=0,X=Y;if(P=Math.max(0,P),X>P)z[Q]={start:P,end:X}}return z}var uF="\x1B[0m",KQ="\x1B[7m",A5="\x1B[27m",Q6;var WQ=O(()=>{z1();Q6=new Map});function HQ(){return{pending:null,selection:null}}function O5($){$.pending=null,$.selection=null}function UQ($,f,Z){let{button:z,row:J,col:K,press:Q}=f,G=(z&nK)===0,Y=$.pending!=null;if(G&&Y&&((z&X4)!==0||z===0&&Q)){let P=$.pending;if(J===P.row&&K===P.col&&$.selection==null)return null;return $.selection={anchor:P,cur:{row:J,col:K}},{type:"selection",selection:$.selection}}if(z===0&&Q)return $.selection=null,$.pending=J>=1&&J<=Z?{row:J,col:K}:null,{type:"selection",selection:null};if(z===0&&!Q){let{selection:P,pending:X}=$;if($.pending=null,$.selection=null,P&&(P.anchor.row!==P.cur.row||P.anchor.col!==P.cur.col))return{type:"copy",selection:P};if(X)return{type:"click",row:X.row,col:X.col}}return null}var MQ=O(()=>{G2()});function FQ(){return{row:-1,col:-1,at:Number.NEGATIVE_INFINITY,count:0}}function qQ($,f){let Z=f.row===$.row&&Math.abs(f.col-$.col)<=2&&f.at-$.at<=400;return $.count=Z?$.count+1:1,$.row=f.row,$.col=f.col,$.at=f.at,$.count}import xF,{useMemo as w5,useEffect as y5,useRef as $$,useState as T5,useCallback as hF}from"react";import{Box as f$,Text as T$,useInput as cF,useStdin as mF}from"ink";import{jsxDEV as q0}from"react/jsx-dev-runtime";function rF($,f){let Z=[],z="",J=0,K="";for(let Q of $.split(/(\x1b\[[0-9;]*m)/g)){if(Q.startsWith("\x1B[")){if(Q===I5)K="";else K+=Q;z+=Q;continue}for(let{text:G,width:Y}of _$(Q))if(J>0&&J+Y>f)Z.push(z+I5),z=K+G,J=Y;else z+=G,J+=Y}return Z.push(z+I5),Z}function NQ($,f){let Z="",z=0;for(let{text:J,width:K}of _$($)){if(z+K>f)break;Z+=J,z+=K}return Z}function oF($){let f=$.replace(/\s+$/,"").split(`
84
+ `);if(f.length<=k5)return f;let Z=f.length-k5;return[...f.slice(0,k5),`… 结果还有 ${Z} 行未显示`]}function BQ($){return $.role==="tool"||$.role==="thinking"}function Y6($,f){return $.role==="thinking"?!f.has($.id):f.has($.id)}function VQ($,f,Z,z){let J=Math.max(1,z-b0($)),K=b0(f+Z)<=J?`${$}${f}${Z}`:`${$}${NQ(f,Math.max(1,J-b0(Z)-1))}…${Z}`;return[NQ(K,z)]}function pF($,f,Z){let z=SK(f);switch($.role){case"user":return l0(`> ${$.content}`,z);case"assistant":try{let J=new W2,Q=(J.write(typeof $.content==="string"?$.content:String($.content??""))+J.flush()).replace(/\n$/,"");if(Q==="")return[];let G=Q.split(`
85
+ `),Y=0,P=G.length;while(Y<P&&G[Y].trim()==="")Y++;while(P>Y&&G[P-1].trim()==="")P--;if(Y===P)return[];let X=[];for(let W=Y;W<P;W++)X.push(...rF(G[W],z));return X}catch{return l0(typeof $.content==="string"?$.content:String($.content??""),z)}case"thinking":{let J=$.content.trim();if(!J)return[];let K=J.replace(/\s+/g," "),Q=`\uD83D\uDCAD 思考 ${Z?"▾":"▸"} `;if(!Z){let Y=J.split(`
86
+ `).length,P=Y>1?` → ${Y} 行`:"";return VQ(Q,K,P,z)}let G=l0(Q,z);for(let Y of J.replace(/\s+$/,"").split(`
87
+ `))G.push(...l0(` ${Y}`,z));return G}case"tool":{let J=$.toolName??"",K=$.content.replace(/\s+/g," ").trim(),Q=`⚡ ${J} ${Z?"▾":"▸"} `;if(!Z){let P=$.toolResultSummary?` → ${$.toolResultSummary}`:"";return VQ(Q,K,P,z)}let G=l0(`${Q}${K}`,z);if($.toolChildren&&$.toolChildren.length>0)for(let P of $.toolChildren){let X=P.summary?` ${P.summary}`:"";G.push(...l0(` ↳ ${P.name}${X}`,z))}let Y=$.toolResult;if(Y&&Y.trim()!=="")for(let P of oF(Y))G.push(...l0(` ${P}`,z));return G}default:{if(!$.content)return[];let J=[];for(let K of $.content.split(`
88
+ `))J.push(...l0(K,z));return J}}}function LQ($){let f=0;for(let Z=0;Z<$.length;Z++)f=f*31+$.charCodeAt(Z)|0;return String(f)}function iF($,f,Z){return[$.id,String($.content.length),LQ($.content.slice(0,64)+$.content.slice(-32)),String($.toolResult?.length??0),$.toolResult?LQ($.toolResult.slice(0,64)):"",String(f),Z?"1":"0",$.toolName??"",$.toolResultSummary??"",($.toolChildren??[]).map((z)=>`${z.name}:${z.summary}`).join("|")].join("\x00")}function P6($,f,Z){let z=iF($,f,Z),J=U2.get(z);if(J!==void 0)return J;let K=pF($,f,Z);if(U2.size>=dF){let Q=U2.keys().next().value;if(Q!==void 0)U2.delete(Q)}return U2.set(z,K),K}function lF($,f,Z){return P6($,f,Z).length+($.role==="user"?DQ:0)}function tF($,f,Z,z){let J=f.reduce((H,M)=>H+M,0);if(Z<=0)return{winTop:0,winBottom:J,above:0,below:0,parts:$.map((H,M)=>({msg:H,start:0,count:f[M]??0}))};let K=0,Q=0,G=0,Y=Z;for(let H=0;H<3;H++){let M=(K>0?1:0)+(Q>0?1:0);Y=Math.max(1,Z-M);let F=Math.max(0,J-Y);G=z===null?F:Math.min(z,F),K=G,Q=Math.max(0,J-(G+Y))}let P=Math.min(J,G+Y),X=[],W=0;for(let H=0;H<$.length;H++){let M=f[H]??0;if(W<P&&W+M>G){let F=Math.max(0,G-W),q=Math.min(M-F,P-W-F);X.push({msg:$[H],start:F,count:q})}W+=M}return{winTop:G,winBottom:P,above:K,below:Q,parts:X}}function bQ({messages:$,maxHeight:f,columns:Z=80,onCopyNotice:z,selectionMode:J,onExitSelectionMode:K,interactive:Q=!0}){let[G,Y]=T5(null),[P,X]=T5(new Set),[W,H]=T5(null),M=w5(()=>$.map((A)=>lF(A,Z,Y6(A,P))),[$,Z,P]),F=w5(()=>tF($,M,f??0,G),[$,M,f,G]),q=$$(F);q.current=F;let U=w5(()=>sF(F,Z,P),[F,Z,P]),N=$$(U.rows);N.current=U.rows;let B=$$(U.kinds);B.current=U.kinds;let D=$$(U.partMeta);D.current=U.partMeta;let V=$$(z);V.current=z;let b=$$(Boolean(J));b.current=Boolean(J);let C=$$(null),S=$$(FQ()),I=(A)=>H2(U.rows,A.row,A.col),j=W?C5(U.rows,I(W.anchor),I(W.cur)):null,w=j?XQ(j,U.partMeta):null,E=hF((A)=>{let o=N.current,i=GQ(o,B.current,C5(o,H2(o,A.anchor.row,A.anchor.col),H2(o,A.cur.row,A.cur.col)));if(i==="")V.current?.("未选中文本");else if(N5(i))V.current?.(`已复制 ${Array.from(i).length} 字`);else V.current?.("复制失败")},[]),l=$$(E);l.current=E;let h=$$(W);h.current=W;let t=$$(K);t.current=K;let v=()=>{let A=h.current;if(A)return A;if(C.current)return{anchor:C.current,cur:C.current};let i=N.current.findIndex((G0)=>G0!=null),u=i>=0?{row:i+1,col:2}:{row:1,col:2};return{anchor:u,cur:u}},T=(A)=>{let o=Math.max(1,N.current.length);return{anchor:A.anchor,cur:{row:Math.max(1,Math.min(o,A.cur.row)),col:Math.max(1,A.cur.col)}}},r=(A,o)=>{let i=v(),u=Math.max(1,N.current.length),G0=Math.max(1,Math.min(u,i.cur.row+A));if(A!==0)while(G0>=1&&G0<=u&&N.current[G0-1]==null){let rf=G0+Math.sign(A);if(rf<1||rf>u)break;G0=rf}let O0=N.current[G0-1],z0=O0?b0(W4(O0)):0,w0=Math.max(1,Math.min(2+z0,i.cur.col+o));H({anchor:i.anchor,cur:{row:G0,col:w0}})};y5(()=>{if(!J)return;H((A)=>A??v())},[J,v]);let R=(A)=>{X((o)=>{let i=new Set(o);if(i.has(A))i.delete(A);else i.add(A);return i})},m=$$(R);m.current=R;let K0=(A)=>{Y((o)=>{let i=o??q.current.winTop;return Math.max(0,i-A)})},x=(A)=>{Y((o)=>{if(o===null)return o;let i=q.current.winTop+q.current.below;return o+A>=i?null:o+A})},y=$$(HQ());cF((A,o)=>{if(b.current){let i=o;if(o.escape){H(null),t.current?.();return}if(o.return){let u=h.current??v();l.current(u),t.current?.();return}if(o.leftArrow){r(0,-1);return}if(o.rightArrow){r(0,1);return}if(o.upArrow){r(-1,0);return}if(o.downArrow){r(1,0);return}if(i.home){let u=v();H({anchor:u.anchor,cur:{row:u.cur.row,col:1}});return}if(i.end){let u=v(),G0=N.current[u.cur.row-1],O0=G0?b0(W4(G0)):0;H({anchor:u.anchor,cur:{row:u.cur.row,col:2+O0}});return}if(o.pageUp)K0(F.winBottom-F.winTop),H((u)=>u?T(u):u);else if(o.pageDown)x(F.winBottom-F.winTop),H((u)=>u?T(u):u);return}if(!A.startsWith("[<")&&!/^[\d;,]+[Mm]$/.test(A))O5(y.current),H(null);if(o.pageUp){let i=F.winBottom-F.winTop;K0(i)}else if(o.pageDown){let i=F.winBottom-F.winTop;x(i)}if((A===" "||A==="o")&&!o.ctrl&&!o.meta){let i=Math.floor((F.winTop+F.winBottom)/2),u=0;for(let G0=0;G0<$.length;G0++){let O0=M[G0]??0;if(i>=u&&i<u+O0&&BQ($[G0])){m.current($[G0].id);break}u+=O0}}},{isActive:Boolean(Q&&f&&f>0)});let n0=$$($.length);y5(()=>{if($.length<n0.current)Y(null);n0.current=$.length},[$]);let P0=(A)=>{let{above:o,parts:i}=q.current,u=A-1;if(u<0)return;if(o>0){if(u-=1,u<0)return}for(let G0 of i){if(u<G0.count){if(BQ(G0.msg))m.current(G0.msg.id);return}u-=G0.count}},F0=(A,o)=>{let i=N.current,u=H2(i,A,o),G0=i[u.row];if(!G0)return;let O0=PQ(W4(G0),u.col);if(O0.end<=O0.start)return;let z0={anchor:{row:u.row+1,col:O0.start+2},cur:{row:u.row+1,col:O0.end+1}};H(z0),l.current(z0)},f0=(A)=>{let o=A-1,i=D.current[o];if(!i)return;let u=o,G0=o;while(u>0&&D.current[u-1]?.part===i.part)u--;while(G0<D.current.length-1&&D.current[G0+1]?.part===i.part)G0++;let O0=N.current[G0],z0=O0?b0(W4(O0)):0,w0={anchor:{row:u+1,col:2},cur:{row:G0+1,col:Math.max(2,1+z0)}};H(w0),l.current(w0)},{stdin:Q0}=mF(),Y0=$$("");if(y5(()=>{if(!Q0||!f||f<=0)return;let A=(o)=>{Y0.current+=o.toString("utf-8");let i;while(i=a8(Y0.current)){Y0.current=i.rest;let{button:u,row:G0}=i.event,O0=N.current.length;if(u===Q2||u===X5||u===Q2+X4||u===X5+X4){if(G0>=1&&G0<=O0+2){if(O5(y.current),!b.current)H(null);if(u===Q2||u===Q2+X4)K0(3);else x(3);if(b.current)H((w0)=>w0?T(w0):w0)}continue}let z0=UQ(y.current,i.event,f);if(z0?.type==="selection")H(z0.selection);else if(z0?.type==="copy")l.current(z0.selection);else if(z0?.type==="click"){C.current={row:z0.row,col:z0.col};let w0=qQ(S.current,{row:z0.row,col:z0.col,at:Date.now()});if(w0>=3)f0(z0.row);else if(w0===2)F0(z0.row,z0.col);else P0(z0.row)}}if(Y0.current.length>64){let u=Y0.current.lastIndexOf("\x1B");Y0.current=u===-1?"":Y0.current.slice(u)}};return Q0.on("data",A),()=>{Q0.off("data",A)}},[Q0,f,T,P0,x,K0,f0,F0]),!f||f<=0)return q0(f$,{flexDirection:"column",children:[$.length===0&&q0(f$,{paddingLeft:1,paddingTop:1,children:q0(T$,{color:"gray",children:"输入消息开始对话,输入 /help 查看命令,Esc 取消运行"},void 0,!1,void 0,this)},void 0,!1,void 0,this),$.map((A)=>q0(_Q,{message:A,lines:P6(A,Z,Y6(A,P))},A.id,!1,void 0,this))]},void 0,!0,void 0,this);return q0(f$,{flexDirection:"column",height:f,overflow:"hidden",width:"100%",children:[$.length===0&&q0(f$,{paddingLeft:1,paddingTop:1,children:q0(T$,{color:"gray",children:"输入消息开始对话,输入 /help 查看命令,Esc 取消运行"},void 0,!1,void 0,this)},void 0,!1,void 0,this),F.above>0&&q0(f$,{paddingLeft:1,flexShrink:0,children:q0(T$,{color:"gray",dimColor:!0,children:["… 以上 ",F.above," 行"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),F.parts.map(({msg:A,start:o,count:i},u)=>q0(_Q,{message:A,lines:P6(A,Z,Y6(A,P)),start:o,count:i,selection:w?.get(u)},A.id,!1,void 0,this)),F.below>0&&q0(f$,{paddingLeft:1,flexShrink:0,children:q0(T$,{color:"gray",dimColor:!0,children:"↓ 按 PageDown 回到底部"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function AQ($,f,Z,z=f.length){if($.role!=="user")return{lines:f.slice(Z,Z+z),marginTop:!1,lineOffset:Z};let J=DQ;if(Z===0)return{lines:f.slice(0,Math.max(0,z-J)),marginTop:!0,lineOffset:0};let K=Z-J;return{lines:f.slice(K,K+z),marginTop:!1,lineOffset:K}}function aF($,f){if($.role==="user")return f===0?"user-head":"plain";if($.role==="tool")return f===0?"tool-head":"tool-body";if($.role==="thinking")return f===0?"thinking-head":"thinking-body";return"plain"}function sF($,f,Z){let z=[],J=[],K=[];if($.above>0)z.push(null),J.push("plain"),K.push(null);for(let Q=0;Q<$.parts.length;Q++){let G=$.parts[Q],Y=P6(G.msg,f,Y6(G.msg,Z)),{lines:P,marginTop:X,lineOffset:W}=AQ(G.msg,Y,G.start,G.count);if(X)z.push(null),J.push("plain"),K.push(null);for(let H=0;H<P.length;H++)z.push(P[H]),J.push(aF(G.msg,W+H)),K.push({part:Q,shown:H})}if($.below>0)z.push(null),J.push("plain"),K.push(null);return{rows:z,kinds:J,partMeta:K}}var I5="\x1B[0m",k5=120,dF=256,U2,DQ=1,_Q;var jQ=O(()=>{b5();z1();G2();WQ();MQ();Z6();U2=new Map;_Q=xF.memo(function({message:f,lines:Z,start:z=0,count:J,selection:K}){let{lines:Q,marginTop:G}=AQ(f,Z,z,J);if(Q.length===0){if(!G)return null;return q0(f$,{height:1,flexShrink:0},void 0,!1,void 0,this)}let Y=K,P=(M,F)=>{let q=Y?.[M];return q&&q.end>q.start?G6(F,q.start,q.end):F},X=(M)=>{let F=Y?.[0];if(!F)return{head:null,tail:null};return YQ(F,b0(M))},W=(M,F)=>F?G6(M,F.start,F.end):M,H=(M,F)=>F?G6(M,F.start,F.end):M;switch(f.role){case"user":{let M=Q[0]??"",F=Q.slice(1),q=j5(M,"user"),U=q?X(q):null,N=q?H(M.slice(q.length),U.tail):P(0,M);return q0(f$,{flexDirection:"column",paddingLeft:1,marginTop:G?1:0,flexShrink:0,children:[q0(f$,{flexWrap:"nowrap",children:[q!==""&&q0(f$,{flexShrink:0,children:q0(T$,{color:"cyan",bold:!0,children:W(q,U.head)},void 0,!1,void 0,this)},void 0,!1,void 0,this),q0(T$,{wrap:"truncate-end",children:N},void 0,!1,void 0,this)]},void 0,!0,void 0,this),F.map((B,D)=>q0(T$,{wrap:"truncate-end",children:P(D+1,B)},D,!1,void 0,this))]},void 0,!0,void 0,this)}case"assistant":return q0(f$,{flexDirection:"column",paddingLeft:1,flexShrink:0,children:Q.map((M,F)=>q0(T$,{wrap:"truncate-end",children:P(F,M)},F,!1,void 0,this))},void 0,!1,void 0,this);case"thinking":case"tool":{let M=Q[0]??"",F=Q.slice(1),q=f.role==="thinking",U=j5(M,q?"thinking":"tool"),N=U?X(U):null,B=U?H(M.slice(U.length),N.tail):P(0,M),D=q?void 0:f.toolIsError?"red":U?"gray":void 0;return q0(f$,{flexDirection:"column",paddingLeft:1,flexShrink:0,children:[q0(f$,{flexWrap:"nowrap",children:[U!==""&&q0(f$,{flexShrink:0,children:q0(T$,{color:q?"gray":"yellow",dimColor:q,children:W(U,N.head)},void 0,!1,void 0,this)},void 0,!1,void 0,this),q0(T$,{color:D,dimColor:q,wrap:"truncate-end",children:B},void 0,!1,void 0,this)]},void 0,!0,void 0,this),F.map((V,b)=>q0(T$,{color:D,dimColor:q,wrap:"truncate-end",children:P(b+1,V)},b,!1,void 0,this))]},void 0,!0,void 0,this)}case"system":return q0(f$,{flexDirection:"column",paddingLeft:1,flexShrink:0,children:Q.map((M,F)=>q0(T$,{wrap:"truncate-end",children:P(F,M)},F,!1,void 0,this))},void 0,!1,void 0,this);default:return null}},($,f)=>$.message.id===f.message.id&&$.start===f.start&&$.count===f.count&&$.lines===f.lines&&$.selection===f.selection)});function m$($,f,Z){if(!$)return!1;if(Z===`
89
+ `&&!f.return)return!1;return Boolean(f.return)}import{useEffect as eF,useMemo as CQ,useRef as $q,useState as OQ}from"react";import{Box as d1,Text as J1,useInput as fq}from"ink";import{jsxDEV as x0}from"react/jsx-dev-runtime";function wQ($,f){let Z=$6(f);return String($??"").split(`
90
+ `).flatMap((z)=>l0(z,Z))}function yQ($,f,Z=0){let z=wQ($,f).length+s8;return Math.min(z,P2(Z,s8))}function TQ({message:$,onConfirm:f,columns:Z,maxRows:z}){let J=CQ(()=>wQ($,Z),[$,Z]),K=Math.max(0,z-s8),[Q,G]=OQ(0),[Y,P]=OQ(1),X=CQ(()=>t0(J,K,Q),[J,K,Q]),W=X.above>0||X.below>0,H=$q(!1);eF(()=>{let q=setTimeout(()=>{H.current=!0},0);return()=>clearTimeout(q)},[]),fq((q,U)=>{if(U.escape){f(!1);return}let N=q.replace(/[\r\n]+/g,"").trim().toLowerCase();if(N==="y"){f(!0);return}if(N==="n"){f(!1);return}if(m$(H.current,U,q)){f(Y===0);return}if(U.leftArrow){P((B)=>B===0?B:B-1);return}if(U.rightArrow){P((B)=>B===1?B:B+1);return}if(U.upArrow){if(W)G((B)=>t0(J,K,B-1).start);else P((B)=>B===0?B:B-1);return}if(U.downArrow){if(W)G((B)=>t0(J,K,B+1).start);else P((B)=>B===1?B:B+1);return}if(U.pageUp){if(!W)return;let B=Math.max(1,X.lines.length);G((D)=>t0(J,K,D-B).start);return}if(U.pageDown){if(!W)return;let B=Math.max(1,X.lines.length);G((D)=>t0(J,K,D+B).start);return}});let M=Y===0,F=Y===1;return x0(d1,{flexDirection:"column",flexShrink:0,width:"100%",borderStyle:"round",borderColor:_.confirmBorder,paddingX:1,children:[x0(d1,{flexShrink:0,children:x0(J1,{bold:!0,color:_.confirmBorder,wrap:"truncate-end",children:"⚠ 请求执行权限"},void 0,!1,void 0,this)},void 0,!1,void 0,this),K>0&&x0(d1,{flexDirection:"column",height:K,overflow:"hidden",flexShrink:0,width:"100%",children:[X.above>0&&x0(d1,{paddingLeft:1,flexShrink:0,children:x0(J1,{color:_.muted,dimColor:!0,children:["… 以上 ",X.above," 行"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),X.lines.map((q,U)=>x0(d1,{paddingLeft:1,flexShrink:0,children:x0(J1,{wrap:"truncate-end",children:q},void 0,!1,void 0,this)},U,!1,void 0,this)),X.below>0&&x0(d1,{paddingLeft:1,flexShrink:0,children:x0(J1,{color:_.muted,dimColor:!0,children:["↓ 还有 ",X.below," 行"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),x0(d1,{marginTop:1,flexShrink:0,height:1,overflow:"hidden",width:"100%",children:[x0(J1,{bold:!0,color:M?_.success:_.muted,children:M?"▸ ":" "},void 0,!1,void 0,this),x0(J1,{bold:!0,color:M?_.success:void 0,children:"[y] 允许"},void 0,!1,void 0,this),x0(J1,{color:_.muted,children:"  "},void 0,!1,void 0,this),x0(J1,{bold:!0,color:F?_.error:_.muted,children:F?"▸ ":" "},void 0,!1,void 0,this),x0(J1,{bold:!0,color:F?_.error:void 0,children:"[N] 拒绝"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),x0(d1,{flexShrink:0,height:1,overflow:"hidden",width:"100%",children:x0(J1,{color:_.muted,wrap:"truncate-end",children:W?"←→ 选择 · ↑↓ 滚动 · Enter 确认 · y/n 快捷 · Esc 拒绝":"←→/↑↓ 选择 · Enter 确认 · y/n 快捷 · Esc 拒绝"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var IQ=O(()=>{z1();Z1()});import{useEffect as n5,useMemo as R5,useRef as D1,useState as b1}from"react";import{Box as X$,Text as h0,useInput as kQ}from"ink";import{jsxDEV as M0,Fragment as Gq}from"react/jsx-dev-runtime";function nQ($){return $?6:2}function RQ($,f,Z,z=!1){let J=$6(Z),K=`❓ ${u1($)}`.split(`
91
+ `).flatMap((X)=>l0(X,J)),Q=g1(E1(f)),G=Math.max(1,J-nQ(z)),Y=Q.map((X,W)=>({label:X,lines:`${W+1}. ${X}`.split(`
92
+ `).flatMap((H)=>l0(H,G))})),P=[...K.map((X)=>({text:X,kind:"prompt"})),...Y.flatMap((X,W)=>X.lines.map((H,M)=>({text:H,kind:"option",optionIndex:W,optionLead:M===0})))];return{promptLines:K,optionBlocks:Y,body:P,lines:P.map((X)=>X.text),hasOptions:Q.length>0}}function SQ($,f,Z,z=0,J=!1){let K=RQ($,f,Z,J),Q=e8(K.hasOptions),G=K.lines.length+Q;return Math.min(G,P2(z,Q))}function Zq($,f,Z){if(Z<=0||!/^[0-9]$/.test(f))return null;let z=$+f,J=Number.parseInt(z,10);if(Number.isFinite(J)&&J>=1&&J<=Z)return{buf:z,index:J-1};let K=Number.parseInt(f,10);if(Number.isFinite(K)&&K>=1&&K<=Z)return{buf:f,index:K-1};return null}function zq($,f,Z,z,J){if(f<=0||$<=0)return 0;let K=Array.from({length:$},()=>"x"),Q=t0(K,f,Z),G=Q.start,Y=Q.start+Q.lines.length;if(z>=G&&J<=Y)return Q.start;if(z<G)return t0(K,f,z).start;let P=Math.max(0,J-Math.max(1,Q.lines.length));return t0(K,f,P).start}function Jq($,f){let Z=$.findIndex((K)=>K.kind==="option"&&K.optionIndex===f);if(Z<0)return{start:0,end:0};let J=$.slice(Z).findIndex((K)=>K.kind!=="option"||K.optionIndex!==f);return{start:Z,end:J<0?$.length:Z+J}}function vQ($){return Array.from($.replace(/[\r\n]+$/,"")).filter((f)=>{let Z=f.codePointAt(0)??0;return Z>=32&&Z!==127}).join("")}function uQ({prompt:$,options:f,multiple:Z=!1,onAnswer:z,columns:J,maxRows:K}){let Q=R5(()=>RQ($,f,J,Z),[$,f,J,Z]);if(Q.hasOptions)return M0(Kq,{layout:Q,multiple:Z,onAnswer:z,maxRows:K},void 0,!1,void 0,this);return M0(Qq,{layout:Q,onAnswer:z,maxRows:K},void 0,!1,void 0,this)}function Kq({layout:$,multiple:f,onAnswer:Z,maxRows:z}){let J=e8(!0),K=Math.max(0,z-J),[Q,G]=b1(0),[Y,P]=b1(0),[X,W]=b1(""),[H,M]=b1(()=>new Set),[F,q]=b1(""),[U,N]=b1(0),B=D1(0),D=D1(""),V=D1(H),b=D1(""),C=D1(0),S=D1(!1);B.current=Q,D.current=X,V.current=H,b.current=F,C.current=U;let I=$.optionBlocks.length,j=$.optionBlocks.findIndex((x)=>o4(x.label)),w=Q===j,E=Jq($.body,Math.min(Q,Math.max(0,I-1)));n5(()=>{let x=setTimeout(()=>{S.current=!0},0);return()=>clearTimeout(x)},[]),n5(()=>{P((x)=>zq($.body.length,K,x,E.start,E.end))},[$.body.length,K,E.start,E.end]);let l=R5(()=>t0($.lines,K,Y),[$.lines,K,Y]),h=l.above>0||l.below>0,t=()=>{D.current="",W("")},v=(x)=>{let y=x(b.current,C.current);b.current=y.value,C.current=y.caretIndex,q(y.value),N(y.caretIndex)},T=(x)=>{let y=new Set(V.current);if(y.has(x))y.delete(x);else y.add(x);V.current=y,M(y)},r=()=>{let x=yz({multiple:f,choices:$.optionBlocks.map((y)=>y.label),index:B.current,checked:V.current,otherText:b.current});if(!x)return;Z(JSON.stringify(x))};kQ((x,y)=>{if(y.escape){Z(null);return}if(I===0)return;if(y.downArrow){t(),G((f0)=>(f0+1)%I);return}if(y.upArrow){t(),G((f0)=>(f0-1+I)%I);return}let n0=new Set(l.lines.map((f0,Q0)=>$.body[l.start+Q0]?.optionIndex).filter((f0)=>f0!=null)).size,P0=Math.max(1,n0);if(y.pageDown){t(),G((f0)=>Math.min(I-1,f0+P0));return}if(y.pageUp){t(),G((f0)=>Math.max(0,f0-P0));return}if(m$(S.current,y,x)){r();return}if(f&&x===" "){if(w&&V.current.has(j)&&b.current.length>0){v((f0,Q0)=>e0(f0,Q0," "));return}T(B.current);return}if(!f&&x===" "){if(w)v((f0,Q0)=>e0(f0,Q0," "));return}if(w&&(y.leftArrow||y.rightArrow)){v((f0,Q0)=>({value:f0,caretIndex:bf(f0,Q0,y.leftArrow?-1:1)}));return}if(w&&(y.backspace||y.delete)){if(v((f0,Q0)=>P4(f0,Q0)),f&&b.current.length===0&&V.current.has(j))T(j);return}if(w&&y.ctrl&&x==="a"){v((f0)=>({value:f0,caretIndex:0}));return}if(w&&y.ctrl&&x==="e"){v((f0)=>({value:f0,caretIndex:Array.from(f0).length}));return}if(w&&y.ctrl&&x==="u"){v(()=>({value:"",caretIndex:0}));return}if(y.backspace||y.delete){W((f0)=>{let Q0=Array.from(f0).slice(0,-1).join("");return D.current=Q0,Q0});return}if(y.ctrl||y.meta||y.tab)return;let F0=vQ(x);if(!F0)return;if(w){if(v((f0,Q0)=>e0(f0,Q0,F0)),f&&!V.current.has(j))T(j);return}if(F0.length===1&&/^[0-9]$/.test(F0)){let f0=Zq(D.current,F0,I);if(f0)D.current=f0.buf,W(f0.buf),G(f0.index);return}if(j>=0){if(t(),G(j),v((f0,Q0)=>e0(f0,Q0,F0)),f&&!V.current.has(j))T(j)}});let R=[h?"↑↓/PgUpDn 移动":"↑↓ 移动",f?"空格 勾选":"","数字键跳转","Enter 确认","Esc 取消",X?`数字 ${X}`:""].filter(Boolean).join(" · "),m=w||f&&H.has(j)&&F.length>0,K0=w;return M0(X$,{flexDirection:"column",flexShrink:0,width:"100%",borderStyle:"round",borderColor:_.questionBorder,paddingX:1,children:[K>0&&M0(X$,{flexDirection:"column",height:K,overflow:"hidden",flexShrink:0,width:"100%",children:[l.above>0&&M0(X$,{flexShrink:0,children:M0(h0,{color:_.muted,dimColor:!0,children:["… 以上 ",l.above," 行"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),l.lines.map((x,y)=>{let n0=l.start+y,P0=$.body[n0];if(!P0)return null;let F0=P0.kind==="prompt",f0=P0.optionIndex??-1,Q0=P0.kind==="option"&&f0===Q,Y0=f&&H.has(f0),A=F0?"":P0.optionLead?`${Q0?"❯ ":" "}${f?Y0?"[x] ":"[ ] ":""}`:" ".repeat(nQ(f));return M0(X$,{flexShrink:0,children:[!F0&&M0(h0,{color:Q0?_.accent:_.muted,children:A},void 0,!1,void 0,this),M0(h0,{bold:F0||Q0,color:F0?_.questionBorder:Q0?_.accent:_.muted,wrap:"truncate-end",children:x},void 0,!1,void 0,this)]},`${P0.kind}-${f0}-${n0}`,!0,void 0,this)}),l.below>0&&M0(X$,{flexShrink:0,children:M0(h0,{color:_.muted,dimColor:!0,children:["↓ 还有 ",l.below," 行"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),M0(X$,{marginTop:1,flexShrink:0,height:1,overflow:"hidden",width:"100%",children:m||K0?M0(Gq,{children:[M0(h0,{bold:!0,color:_.questionBorder,children:["→"," "]},void 0,!0,void 0,this),M0(h0,{children:Array.from(F).slice(0,K0?U:F.length).join("")},void 0,!1,void 0,this),K0&&M0(h0,{color:_.muted,inverse:!0,children:" "},void 0,!1,void 0,this),K0&&M0(h0,{children:Array.from(F).slice(U).join("")},void 0,!1,void 0,this)]},void 0,!0,void 0,this):M0(h0,{color:_.muted,dimColor:!0,children:"→ 选「其他」后可输入"},void 0,!1,void 0,this)},void 0,!1,void 0,this),M0(X$,{flexShrink:0,children:M0(h0,{color:_.muted,dimColor:!0,wrap:"truncate-end",children:R},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Qq({layout:$,onAnswer:f,maxRows:Z}){let z=e8(!1),J=Math.max(0,Z-z),[K,Q]=b1(""),[G,Y]=b1(0),[P,X]=b1(0),W=D1(""),H=D1(0),M=D1(!1);W.current=K,H.current=G,n5(()=>{let B=setTimeout(()=>{M.current=!0},0);return()=>clearTimeout(B)},[]);let F=R5(()=>t0($.lines,J,P),[$.lines,J,P]),q=F.above>0||F.below>0,U=(B)=>{let D=B(W.current,H.current);W.current=D.value,H.current=D.caretIndex,Q(D.value),Y(D.caretIndex)};kQ((B,D)=>{if(D.escape){f(null);return}if(D.return){if(!m$(M.current,D,B))return;f(W.current.trim());return}if(q){let b=Math.max(1,F.lines.length);if(D.upArrow){X((C)=>t0($.lines,J,C-1).start);return}if(D.downArrow){X((C)=>t0($.lines,J,C+1).start);return}if(D.pageUp){X((C)=>t0($.lines,J,C-b).start);return}if(D.pageDown){X((C)=>t0($.lines,J,C+b).start);return}}if(D.leftArrow){U((b,C)=>({value:b,caretIndex:bf(b,C,-1)}));return}if(D.rightArrow){U((b,C)=>({value:b,caretIndex:bf(b,C,1)}));return}if(D.backspace||D.delete){U((b,C)=>P4(b,C));return}if(D.ctrl&&B==="a"){U((b)=>({value:b,caretIndex:0}));return}if(D.ctrl&&B==="e"){U((b)=>({value:b,caretIndex:Array.from(b).length}));return}if(D.ctrl&&B==="u"){U(()=>({value:"",caretIndex:0}));return}if(D.ctrl&&B==="k"){U((b,C)=>{let S=Array.from(b);return S.splice(C),{value:S.join(""),caretIndex:C}});return}if(D.ctrl||D.meta)return;if(D.upArrow||D.downArrow||D.tab)return;let V=vQ(B);if(!V)return;U((b,C)=>e0(b,C,V))});let N=q?"Enter 提交 · Esc 取消 · ↑↓ 滚动 · ←→ 光标":"Enter 提交 · Esc 取消 · ←→ 光标";return M0(X$,{flexDirection:"column",flexShrink:0,width:"100%",borderStyle:"round",borderColor:_.questionBorder,paddingX:1,children:[J>0&&M0(X$,{flexDirection:"column",height:J,overflow:"hidden",flexShrink:0,width:"100%",children:[F.above>0&&M0(X$,{flexShrink:0,children:M0(h0,{color:_.muted,dimColor:!0,children:["… 以上 ",F.above," 行"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),F.lines.map((B,D)=>M0(X$,{flexShrink:0,children:M0(h0,{bold:!0,color:_.questionBorder,wrap:"truncate-end",children:B},void 0,!1,void 0,this)},`${F.start+D}:${B}`,!1,void 0,this)),F.below>0&&M0(X$,{flexShrink:0,children:M0(h0,{color:_.muted,dimColor:!0,children:["↓ 还有 ",F.below," 行"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),M0(X$,{marginTop:1,flexShrink:0,height:1,overflow:"hidden",width:"100%",children:[M0(h0,{bold:!0,color:_.questionBorder,children:["→"," "]},void 0,!0,void 0,this),M0(h0,{children:Array.from(K).slice(0,G).join("")},void 0,!1,void 0,this),M0(h0,{color:_.muted,inverse:!0,children:" "},void 0,!1,void 0,this),M0(h0,{children:Array.from(K).slice(G).join("")},void 0,!1,void 0,this)]},void 0,!0,void 0,this),M0(X$,{flexShrink:0,children:M0(h0,{color:_.muted,dimColor:!0,wrap:"truncate-end",children:N},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var EQ=O(()=>{z1();Z1();s9();p4()});function i1($){let f=Math.max(0,Math.round($));if(f<1000)return String(f);if(f<1e5)return`${(f/1000).toFixed(1).replace(/\.0$/,"")}k`;if(f<1e6)return`${Math.round(f/1000)}k`;if(f<1e7)return`${(f/1e6).toFixed(1).replace(/\.0$/,"")}M`;return`${Math.round(f/1e6)}M`}function Yq($,f){if($<=0||f<=0)return null;return Math.round($/f*100)}function gQ($,f,Z=0){return{context:$.lastInputTokens>0?$.lastInputTokens:Z,input:$.totalInputTokens,output:$.totalOutputTokens,contextWindow:f}}function xQ($){let f=Yq($.context,$.contextWindow);if(f==null)return"";return`${i1($.context)}/${i1($.contextWindow)} ${f}%`}function hQ($,f,Z=!1){let z=[`思考 ${$}`];if(Z)z.push("记忆 开");if(f&&f>0)z.push(`窗口 ${i1(f)}`);return z.join(" · ")}import{Box as cQ,Text as S5}from"ink";import{jsxDEV as M2}from"react/jsx-dev-runtime";function mQ({state:$,columns:f=80}){let Z=$.model||"unknown",z=B$(e$(void 0,$.model).thinking),J=hQ(z,$.tokenInfo?.contextWindow,f1()),K=$.tokenInfo?xQ($.tokenInfo):"",Q=Math.max(8,f-2),G=$.copyNotice?`✓ ${$.copyNotice}`:$.selectionMode?"选择模式 ↑↓←→扩选 Enter复制 Esc退出":null,Y=G?b0(G):0;return M2(cQ,{flexDirection:"column",flexShrink:0,width:"100%",children:[M2(S5,{dimColor:!0,wrap:"truncate-end",children:G?`${"─".repeat(Math.max(0,Q-Y-2))} ${G}`:"─".repeat(Q)},void 0,!1,void 0,this),M2(cQ,{children:[M2(S5,{children:" \uD83E\uDD16 min-agent"},void 0,!1,void 0,this),M2(S5,{color:"gray",wrap:"truncate-end",children:[" ","(",Z," · ",J,")",K?` ${K}`:""]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var rQ=O(()=>{$1();V1();z1()});import{useEffect as oQ,useState as v5}from"react";import{Box as K1,Text as W$,useInput as Pq,useStdout as Xq}from"ink";import{jsxDEV as A0}from"react/jsx-dev-runtime";function pQ($){let f=Math.max(4,$-11);return Math.min(6+f+3,Math.max(6,$-2))}function dQ({currentModel:$,onSelect:f,onCancel:Z}){let[z,J]=v5(null),[K,Q]=v5(""),[G,Y]=v5(0),{stdout:P}=Xq();oQ(()=>{let C=!1,S=$0(),I=e(S);if(I?.baseURL&&I?.apiKey)Ff(I.baseURL,I.apiKey).then((j)=>{if(!C)J(j)}).catch(()=>{if(!C)J([])});else J([]);return()=>{C=!0}},[]);let X=P.rows||24,W=Math.max(4,X-11),H=K.trim().toLowerCase(),M=(z??[]).filter((C)=>C.toLowerCase().includes(H)),F=Math.min(G,Math.max(0,M.length-1)),q=Math.min(F,Math.max(0,M.length-W)),U=M.slice(q,q+W),N=q,B=M.length-(q+U.length);oQ(()=>{Y(0)},[]),Pq((C,S)=>{let I=C.replace(/[\r\n]+$/,""),j=S.return||/[\r\n]+$/.test(C);if(S.escape){Z();return}if(S.pageDown){if(M.length>0)Y((w)=>Math.min(M.length-1,w+W));return}if(S.pageUp){if(M.length>0)Y((w)=>Math.max(0,w-W));return}if(M.length>0){if(S.downArrow){Y((w)=>(w+1)%M.length);return}if(S.upArrow){Y((w)=>(w-1+M.length)%M.length);return}}if(j){if(M.length>0)f(M[F]);else if(H!=="")f(H);return}if(S.backspace||S.delete){Q((w)=>Array.from(w).slice(0,-1).join(""));return}if(S.ctrl&&C==="u"){Q("");return}if(S.ctrl||S.meta||S.tab)return;if(I)Q((w)=>w+I)});let D=z===null,V=z!==null&&M.length===0&&H==="",b=H;return A0(K1,{flexDirection:"column",flexShrink:0,width:"100%",borderStyle:"round",borderColor:_.pickerBorder,paddingX:1,children:[A0(K1,{children:[A0(W$,{bold:!0,color:_.pickerBorder,children:"选择模型"},void 0,!1,void 0,this),A0(W$,{color:_.muted,children:$?` (当前: ${$})`:""},void 0,!1,void 0,this)]},void 0,!0,void 0,this),A0(K1,{children:[A0(W$,{color:_.muted,children:"筛选: "},void 0,!1,void 0,this),A0(W$,{color:K?_.accent:_.muted,children:K||"输入字符过滤,↑↓/PgUpDn 导航"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),D&&A0(K1,{children:A0(W$,{color:_.muted,dimColor:!0,children:"正在获取模型列表..."},void 0,!1,void 0,this)},void 0,!1,void 0,this),V&&A0(K1,{children:A0(W$,{color:_.muted,dimColor:!0,children:"无法获取模型列表(可输入模型名后按 Enter)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),z!==null&&N>0&&A0(K1,{children:A0(W$,{color:_.muted,dimColor:!0,children:["… 上方还有 ",N," 个模型"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),z!==null&&U.map((C,S)=>A0(K1,{children:[A0(W$,{color:S===F-q?_.accent:_.muted,children:S===F-q?"❯ ":" "},void 0,!1,void 0,this),A0(W$,{bold:S===F-q,color:S===F-q?_.accent:void 0,children:C},void 0,!1,void 0,this),C===$&&A0(W$,{color:_.success,children:" ← 当前"},void 0,!1,void 0,this)]},C,!0,void 0,this)),B>0&&A0(K1,{children:A0(W$,{color:_.muted,dimColor:!0,children:["… 下方还有 ",B," 个模型(输入字符过滤)"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),z!==null&&M.length===0&&b!==""&&A0(K1,{children:[A0(W$,{color:_.accent,bold:!0,children:["❯"," "]},void 0,!0,void 0,this),A0(W$,{color:_.accent,bold:!0,children:["使用自定义模型: ",b]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),A0(K1,{children:A0(W$,{color:_.muted,dimColor:!0,wrap:"truncate-end",children:"↑↓/PgUpDn 选择 · Enter 确认 · Esc 取消"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var iQ=O(()=>{d();Z1()});import{useEffect as lQ,useRef as X6,useState as tQ}from"react";import{Box as F2,Text as jf,useInput as Wq}from"ink";import{jsxDEV as I$}from"react/jsx-dev-runtime";function aQ(){return 11}function sQ({scope:$,modelId:f,onSelect:Z,onCancel:z}){let J=e(J0()),K=f??J?.defaultModel,Q=e$(void 0,K),[G,Y]=tQ(()=>c1(K)),[P,X]=tQ(()=>T8(Q.thinking,c1(K))),W=X6(!1),H=X6(!1),M=X6(P),F=X6(G);return M.current=P,F.current=G,lQ(()=>{let q=setTimeout(()=>{W.current=!0},0);return()=>clearTimeout(q)},[]),lQ(()=>{if(!K)return;let q=!1;return f4(K,{type:J?.type,baseURL:J?.baseURL}).then((U)=>{if(q||U.length===0)return;if(Y(U),H.current){X((N)=>Math.min(N,Math.max(0,U.length-1)));return}X(T8(e$(void 0,K).thinking,U))}),()=>{q=!0}},[K,J?.baseURL,J?.type]),Wq((q,U)=>{if(U.escape){z();return}let N=F.current;if(N.length===0)return;if(U.downArrow){H.current=!0,X((B)=>(B+1)%N.length);return}if(U.upArrow){H.current=!0,X((B)=>(B-1+N.length)%N.length);return}if(m$(W.current,U,q)){let B=N[M.current];if(B)Z(B)}}),I$(F2,{flexDirection:"column",flexShrink:0,width:"100%",borderStyle:"round",borderColor:_.pickerBorder,paddingX:1,children:[I$(F2,{children:[I$(jf,{bold:!0,color:_.pickerBorder,children:"选择思考强度"},void 0,!1,void 0,this),$==="project"&&I$(jf,{color:_.muted,children:"(写入当前项目)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),I$(F2,{children:I$(jf,{color:_.muted,children:["当前: ",B$(Q.thinking),"(",b9(Q.source),")"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),G.map((q,U)=>{let N=U===P;return I$(F2,{children:[I$(jf,{color:N?_.accent:_.muted,children:N?"❯ ":" "},void 0,!1,void 0,this),I$(jf,{bold:N,color:N?_.accent:void 0,children:B$(q)},void 0,!1,void 0,this),q===Q.thinking&&I$(jf,{color:_.success,children:" ← 当前"},void 0,!1,void 0,this)]},q,!0,void 0,this)}),I$(F2,{children:I$(jf,{color:_.muted,dimColor:!0,wrap:"truncate-end",children:"↑↓ 选择 · Enter 确认 · Esc 取消"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var eQ=O(()=>{d();$1();Z1()});var fG={};U0(fG,{tokensForCtxLevel:()=>W6,setOllamaContextChoice:()=>Of,parseCtxChoice:()=>q2,matchCtxLevel:()=>Cf,isCtxLevel:()=>u5,isCtxChoice:()=>Uq,ctxPayload:()=>U6,ctxChoiceLabel:()=>l1,configuredCtxChoice:()=>g5,activeProviderIsOllama:()=>E5,CTX_LEVELS:()=>H6,CTX_CHOICES:()=>H$,CTX_AUTO:()=>Q1});function u5($){return H6.includes($)}function Uq($){return $===Q1||u5($)}function W6($){return $G[$]}function Cf($){return Hq.get(Math.floor($))??null}function q2($){if($==null)return null;let f=$.trim().toLowerCase();if(!f)return null;if(f==="auto"||f==="default")return Q1;if(u5(f))return f;if(!/^\d+$/.test(f))return null;return Cf(Number(f))}function l1($){return $===Q1?"自动":$}function E5(){return e($0())?.type==="ollama"}function g5(){let $=e($0())?.contextWindow;if(typeof $!=="number"||!Number.isFinite($)||$<=0)return{choice:Q1};let f=Cf($);if(f)return{choice:f,tokens:W6(f)};return{choice:Q1,tokens:Math.floor($)}}function Of($){let f=$0(),Z=e(f);if(!Z)return{ok:!1,reason:"no-provider"};if(Z.type!=="ollama")return{ok:!1,reason:"not-ollama"};if($===Q1)delete Z.contextWindow;else Z.contextWindow=W6($);return I0(f),$===Q1?{ok:!0,choice:$}:{ok:!0,choice:$,tokens:W6($)}}function U6(){let $=e($0());if($?.type!=="ollama")return{configurable:!1,level:null};let f=$.contextWindow;if(typeof f!=="number"||!Number.isFinite(f)||f<=0)return{configurable:!0,level:Q1};return{configurable:!0,level:Cf(f)}}var H6,Q1="auto",H$,$G,Hq;var H4=O(()=>{d();H6=["2k","4k","8k","12k","16k","32k","64k","128k","256k"],H$=[...H6,Q1],$G={"2k":2048,"4k":4096,"8k":8192,"12k":12288,"16k":16384,"32k":32768,"64k":65536,"128k":131072,"256k":262144},Hq=new Map(H6.map(($)=>[$G[$],$]))});import{useEffect as Mq,useRef as ZG,useState as Fq}from"react";import{Box as N2,Text as U4,useInput as qq}from"ink";import{jsxDEV as r$}from"react/jsx-dev-runtime";function zG(){return 4+H$.length+1}function JG(){let $=e($0())?.contextWindow;if(typeof $==="number"&&Number.isFinite($)&&$>0)return Math.floor($);return}function Nq(){let $=JG();if($==null)return l1("auto");return Cf($)??i1($)}function Bq(){let $=JG();if($==null)return"auto";return Cf($)}function KG({onSelect:$,onCancel:f}){let Z=Bq(),[z,J]=Fq(()=>{let G=Z?H$.indexOf(Z):-1;return G>=0?G:H$.length-1}),K=ZG(!1),Q=ZG(z);return Q.current=z,Mq(()=>{let G=setTimeout(()=>{K.current=!0},0);return()=>clearTimeout(G)},[]),qq((G,Y)=>{if(Y.escape){f();return}if(Y.downArrow){J((P)=>(P+1)%H$.length);return}if(Y.upArrow){J((P)=>(P-1+H$.length)%H$.length);return}if(m$(K.current,Y,G)){let P=H$[Q.current];if(P)$(P)}}),r$(N2,{flexDirection:"column",flexShrink:0,width:"100%",borderStyle:"round",borderColor:_.pickerBorder,paddingX:1,children:[r$(N2,{children:r$(U4,{bold:!0,color:_.pickerBorder,children:"选择上下文窗口"},void 0,!1,void 0,this)},void 0,!1,void 0,this),r$(N2,{children:r$(U4,{color:_.muted,children:["当前: ",Nq()]},void 0,!0,void 0,this)},void 0,!1,void 0,this),H$.map((G,Y)=>{let P=Y===z;return r$(N2,{children:[r$(U4,{color:P?_.accent:_.muted,children:P?"❯ ":" "},void 0,!1,void 0,this),r$(U4,{bold:P,color:P?_.accent:void 0,children:l1(G)},void 0,!1,void 0,this),G===Z&&r$(U4,{color:_.success,children:" ← 当前"},void 0,!1,void 0,this)]},G,!0,void 0,this)}),r$(N2,{children:r$(U4,{color:_.muted,dimColor:!0,wrap:"truncate-end",children:"↑↓ 选择 · Enter 确认 · Esc 取消"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var QG=O(()=>{d();H4();Z1()});var GG={};U0(GG,{listProviderChoices:()=>M4,applyProviderSwitch:()=>x5});function Vq($){return Boolean($.name?.trim())}function M4(){let $=J0(),f=e($)?.name;return($.providers??[]).filter(Vq).map((Z)=>({name:Z.name,baseURL:Z.baseURL,defaultModel:Z.defaultModel,current:Z.name===f}))}function Lq(){let $=y0();if($.activeProvider===void 0)return;let{activeProvider:f,...Z}=$;Q$(Z)}function x5($){let f=G4($0(),$);if("error"in f)return{ok:!1,message:f.error};I0(f),Lq();let Z=e(f);return{ok:!0,name:$,defaultModel:Z?.defaultModel??""}}var M6=O(()=>{d()});import{useEffect as _q,useRef as h5,useState as Dq}from"react";import{Box as t1,Text as A1,useInput as bq,useStdout as Aq}from"ink";import{jsxDEV as m0}from"react/jsx-dev-runtime";function YG($){let f=Math.max(1,M4().length),Z=Math.max(4,$-11),z=Math.min(f,Z),J=f>Z?2:0;return 4+z+J+1}function PG({onSelect:$,onCancel:f}){let Z=M4(),z=Z.find((N)=>N.current)?.name,[J,K]=Dq(()=>{let N=Z.findIndex((B)=>B.current);return N>=0?N:0}),Q=h5(!1),G=h5(J),Y=h5(Z);G.current=J,Y.current=Z;let{stdout:P}=Aq(),X=P.rows||24,W=Math.max(4,X-11),H=Z.length===0?0:Math.min(J,Z.length-1),M=Math.min(H,Math.max(0,Z.length-W)),F=Z.slice(M,M+W),q=M,U=Z.length-(M+F.length);return _q(()=>{let N=setTimeout(()=>{Q.current=!0},0);return()=>clearTimeout(N)},[]),bq((N,B)=>{if(B.escape){f();return}let D=Y.current;if(D.length===0)return;if(B.pageDown){K((V)=>Math.min(D.length-1,V+W));return}if(B.pageUp){K((V)=>Math.max(0,V-W));return}if(B.downArrow){K((V)=>(V+1)%D.length);return}if(B.upArrow){K((V)=>(V-1+D.length)%D.length);return}if(m$(Q.current,B,N)){let V=D[G.current];if(V)$(V.name)}}),m0(t1,{flexDirection:"column",flexShrink:0,width:"100%",borderStyle:"round",borderColor:_.pickerBorder,paddingX:1,children:[m0(t1,{children:m0(A1,{bold:!0,color:_.pickerBorder,children:"选择服务商"},void 0,!1,void 0,this)},void 0,!1,void 0,this),m0(t1,{children:m0(A1,{color:_.muted,children:["当前: ",z??"无"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Z.length===0&&m0(t1,{children:m0(A1,{color:_.muted,dimColor:!0,children:"无已配置服务商"},void 0,!1,void 0,this)},void 0,!1,void 0,this),q>0&&m0(t1,{children:m0(A1,{color:_.muted,dimColor:!0,children:["… 上方还有 ",q," 个服务商"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),F.map((N,B)=>{let D=B===H-M;return m0(t1,{children:[m0(A1,{color:D?_.accent:_.muted,children:D?"❯ ":" "},void 0,!1,void 0,this),m0(A1,{bold:D,color:D?_.accent:void 0,wrap:"truncate-end",children:jq(N)},void 0,!1,void 0,this),N.current&&m0(A1,{color:_.success,children:" ← 当前"},void 0,!1,void 0,this)]},N.name,!0,void 0,this)}),U>0&&m0(t1,{children:m0(A1,{color:_.muted,dimColor:!0,children:["… 下方还有 ",U," 个服务商"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),m0(t1,{children:m0(A1,{color:_.muted,dimColor:!0,wrap:"truncate-end",children:"↑↓/PgUpDn 选择 · Enter 确认 · Esc 取消"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function jq($){return`${$.name} ${$.baseURL}`}var XG=O(()=>{M6();Z1()});import{generateText as Cq}from"ai";async function WG($,f){let Z=f.find((G)=>G.role==="user");if(!Z)return null;let z=typeof Z.content==="string"?Z.content:Array.isArray(Z.content)?Z.content.filter((G)=>("text"in G)).map((G)=>G.text??"").join(" "):"";if(!z.trim())return null;let J=f.find((G)=>G.role==="assistant"),K=J?typeof J.content==="string"?J.content.slice(0,200):"":"",Q=K?`User: ${z.slice(0,300)}
93
+ Assistant: ${K}`:`User: ${z.slice(0,300)}`;try{return(await Cq({model:$,messages:[{role:"system",content:Oq},{role:"user",content:Q}],temperature:0.5,maxOutputTokens:30})).text.trim().replace(/^["']|["']$/g,"").slice(0,60)||null}catch{return null}}var Oq=`Generate a very short title (max 50 chars) for this conversation.
94
+ Output ONLY the title text, nothing else. No quotes, no prefix.
95
+ The title should capture the main topic or intent.`;var HG=()=>{};function MG($){UG.add($)}function F4($){return UG.has($)}var UG;var F6=O(()=>{UG=new WeakSet});import{tool as wq,jsonSchema as yq}from"ai";function k$(){return{goal:"",todos:[],nextId:1}}function m5($){$.goal="",$.todos.length=0,$.nextId=1}function B2($,f){if(!$){m5(f);return}f.goal=$.goal,f.todos=$.todos.map((Z)=>({...Z})),f.nextId=$.nextId}function Iq($){return typeof $==="string"&&c5.includes($)}function FG($){if(!$||typeof $!=="object")return;let f=$,Z=[];if(Array.isArray(f.todos))for(let K of f.todos){if(!K||typeof K!=="object")continue;let Q=K;if(typeof Q.id!=="number"||typeof Q.text!=="string")continue;Z.push({id:Q.id,text:Q.text,status:Iq(Q.status)?Q.status:"pending"})}let z=Z.reduce((K,Q)=>Math.max(K,Q.id),0),J=typeof f.nextId==="number"&&Number.isFinite(f.nextId)&&f.nextId>z?Math.floor(f.nextId):z+1;return{goal:typeof f.goal==="string"?f.goal:"",todos:Z,nextId:J}}function kq($){if(typeof $.content==="string")return $.content;if(!Array.isArray($.content))return"";return $.content.filter((f)=>f.type==="text"&&typeof f.text==="string").map((f)=>f.text).join(`
96
+ `)}function r5($){let f=$.trim().replace(/[\s\p{P}\p{S}\p{Emoji_Presentation}\p{Extended_Pictographic}]/gu,"");return f.length===0||nq.test(f)}function Rq($){let f=$.trim();if(!f||r5(f))return;return f.slice(0,Tq)}function qG($,f){if($.goal.trim()&&!r5($.goal))return;for(let Z of f){if(Z.role!=="user")continue;if(F4(Z))continue;let z=Rq(kq(Z));if(!z)continue;$.goal=z;return}}function NG($){let f=$.goal.trim()&&!r5($.goal)?$.goal:"";if(!f&&$.todos.length===0)return"";let Z={pending:"pending",in_progress:"in_progress",done:"done",cancelled:"cancelled"},z=["## Current Task","This block tracks progress for the current user request. It is not a reason to start extra work.","If the task list is missing or empty, there is no pending work to resume. Follow the current user message only. Keep the list accurate with the todo tool."];if(f)z.push("","### Original goal",f);if($.todos.length>0){z.push("","### Task list");for(let J of $.todos)z.push(`- [${Z[J.status]}] #${J.id} ${J.text}`)}return z.join(`
97
+ `)}function q6($){let f=$?.silent??!1,Z=$?.store??k$(),z=()=>{if(Z.todos.length===0)return"No tasks.";let K={pending:"○",in_progress:"◐",done:"●",cancelled:"✕"};return Z.todos.map((Q)=>` ${K[Q.status]} #${Q.id} ${Q.text}`).join(`
98
+ `)},J=()=>{if(f||Z.todos.length===0)return;console.log(`\x1B[90m ┌─ Tasks${"─".repeat(36)}\x1B[0m`);for(let K of Z.todos){let Q=K.status==="done"?"\x1B[32m●\x1B[0m":K.status==="in_progress"?"\x1B[33m◐\x1B[0m":K.status==="cancelled"?"\x1B[90m✕\x1B[0m":"\x1B[90m○\x1B[0m",G=K.status==="done"||K.status==="cancelled"?"\x1B[90m":"",Y=G?"\x1B[0m":"";console.log(`\x1B[90m │\x1B[0m ${Q} ${G}#${K.id} ${K.text}${Y}`)}console.log(`\x1B[90m └${"─".repeat(44)}\x1B[0m`)};return wq({description:`Create or update tasks to track progress. The list persists across context compaction and auto-continue. Use this FREQUENTLY to:
99
+ - Plan multi-step work by creating tasks upfront (research, then the deliverable)
100
+ - Mark research tasks done before more searching — then write the output
101
+ - Mark tasks as in_progress when starting them
102
+ - Mark tasks as done when completed
103
+ - Give the user visibility into your progress
104
+
105
+ To create new tasks: provide items with "text" and optionally "status" (defaults to "pending").
106
+ To update existing tasks: provide items with "id" and "status".
107
+ You can mix creates and updates in one call.`,inputSchema:yq({type:"object",properties:{todos:{type:"array",description:"List of tasks to create or update",items:{type:"object",properties:{text:{type:"string",description:"Task description (for new tasks)"},status:{type:"string",description:"Status: pending, in_progress, done, cancelled"},id:{type:"number",description:"Task ID (for updating existing tasks)"}}}}},required:["todos"]}),execute:async({todos:K})=>{let Q=[];for(let G of K)if(G.id!=null){let Y=Z.todos.find((P)=>P.id===G.id);if(!Y){Q.push(`task #${G.id} not found`);continue}if(G.status){if(!c5.includes(G.status)){Q.push(`invalid status "${G.status}" for task #${G.id}`);continue}Y.status=G.status}if(G.text)Y.text=G.text}else if(G.text)Z.todos.push({id:Z.nextId++,text:G.text,status:c5.includes(G.status)?G.status:"pending"});else Q.push("item needs either an id (update) or text (create)");return J(),Q.length>0?`${z()}
108
+
109
+ Warnings: ${Q.join("; ")}`:z()}})}var c5,Tq=4000,nq;var wf=O(()=>{F6();c5=["pending","in_progress","done","cancelled"];nq=/^(你好|您好|嗨|哈喽|哈罗|哈囉|在吗|在嗎|早上好|晚上好|早安|午安|hello|hi|hey|yo|sup|thanks|thankyou|thx|ty|谢谢|谢谢你|多谢|感谢|ok|okay|好的|收到)$/i});var yf={};U0(yf,{withSessionLock:()=>L2,saveSessionWithTitle:()=>iq,saveSession:()=>D$,sanitizeForStorage:()=>b2,renameSession:()=>i5,loadSession:()=>Z$,loadExecHistory:()=>lq,listSessions:()=>a1,deleteSession:()=>d5});import{readFileSync as BG,mkdirSync as Sq,existsSync as V2,readdirSync as vq,unlinkSync as uq,openSync as Eq,readSync as gq,closeSync as xq,statSync as hq}from"fs";import o5 from"path";import{randomUUID as cq}from"crypto";function p5(){return o5.join(X0(),"sessions")}async function L2($,f){if(!$)return f();let Z=N6.get($)??Promise.resolve(),z,J=new Promise((Q)=>{z=Q}),K=Z.then(()=>J);N6.set($,K),await Z;try{return await f()}finally{if(z(),N6.get($)===K)N6.delete($)}}function D2($){if(!_2.test($))throw Error(`invalid session id: ${$}`);return o5.join(p5(),`${$}.json`)}function LG($,f){let Z=Eq($,"r");try{let z=Buffer.alloc(Math.min(hq($).size,f));if(z.length===0)return"";return gq(Z,z,0,z.length,0),z.toString("utf-8")}finally{xq(Z)}}function mq($,f){let Z=0,z=!1,J=!1;for(let K=f;K<$.length;K++){let Q=$[K];if(z){if(J)J=!1;else if(Q==="\\")J=!0;else if(Q==='"')z=!1;continue}if(Q==='"')z=!0;else if(Q==="{")Z++;else if(Q==="}"){if(Z--,Z===0)return K}}return-1}function _G($){let f=$.indexOf('"meta"');if(f<0)return null;let Z=$.indexOf("{",f);if(Z<0)return null;let z=mq($,Z);if(z<0)return null;try{return JSON.parse($.slice(Z,z+1))}catch{return null}}function rq(){return cq()}function oq($){if(typeof $==="string")return $;return $.map((f)=>f.type==="text"?f.text:"").join(" ").trim()}function pq($){let f=$.find((z)=>z.role==="user");if(!f)return"Untitled";return oq(f.content).slice(0,60)||"Untitled"}function b2($){return $.filter((f)=>!F4(f)).map((f)=>{if(!Array.isArray(f.content))return f;let Z=f.content.map((z)=>{if(z.type!=="image"||z.image==null||typeof z.image==="string")return z;let J=null;if(Buffer.isBuffer(z.image)||z.image instanceof Uint8Array)J=Buffer.isBuffer(z.image)?z.image:Buffer.from(z.image);else if(typeof z.image==="object"&&!(z.image instanceof URL)){let Q=z.image.data;if(Buffer.isBuffer(Q)||Q instanceof Uint8Array)J=Buffer.isBuffer(Q)?Q:Buffer.from(Q)}if(!J)return z;let K=z.mimeType??"image/png";return{...z,image:`data:${K};base64,${J.toString("base64")}`}});return{...f,content:Z}})}function D$($,f,Z,z,J){let K=p5();Sq(K,{recursive:!0});let Q=f&&_2.test(f)?f:rq(),G=new Date().toISOString(),Y=f?dq(Q):null,P=J===void 0&&f?Z$(Q)?.taskState:void 0,X=J??P,W={meta:{id:Q,title:Z??Y?.title??pq($),created:z??Y?.created??G,updated:G,messageCount:$.length},...X?{taskState:X}:{},messages:b2($)};return T0(D2(Q),JSON.stringify(W,null,2)),Q}function dq($){let f=D2($);if(!V2(f))return null;try{return _G(LG(f,VG))}catch{return null}}async function iq($,f,Z){let z=null;try{z=await WG(f,$)}catch{}return D$($,Z,z??void 0)}function Z$($){if(!_2.test($))return null;let f=D2($);if(!V2(f))return null;try{let Z=JSON.parse(BG(f,"utf-8")),z=FG(Z.taskState);return z?{...Z,taskState:z}:Z}catch{return null}}function lq($){if(!$)return{ok:!0,messages:[],sessionId:void 0};let f=Z$($);if(!f)return{ok:!1,error:`会话不存在: ${$}`};return{ok:!0,messages:[...f.messages],sessionId:$,taskState:f.taskState}}function a1(){let $=p5();if(!V2($))return[];return vq($).filter((f)=>f.endsWith(".json")).map((f)=>{try{return _G(LG(o5.join($,f),VG))}catch{return null}}).filter((f)=>f!==null).sort((f,Z)=>Z.updated.localeCompare(f.updated))}function d5($){if(!_2.test($))return!1;let f=D2($);if(!V2(f))return!1;try{return uq(f),!0}catch{return!1}}function i5($,f){if(!_2.test($))return!1;let Z=D2($);if(!V2(Z))return!1;try{let z=JSON.parse(BG(Z,"utf-8"));return z.meta.title=f,z.meta.updated=new Date().toISOString(),T0(Z,JSON.stringify(z,null,2)),!0}catch{return!1}}var N6,_2,VG=65536;var n$=O(()=>{F$();d();HG();F6();wf();N6=new Map;_2=/^[a-zA-Z0-9_-]+$/});import{useEffect as tq,useState as DG}from"react";import{Box as j1,Text as R$,useInput as aq,useStdout as sq}from"ink";import{jsxDEV as k0}from"react/jsx-dev-runtime";function bG($){let f=Math.max(4,$-11);return Math.min(6+f+3,Math.max(6,$-2))}function eq($){let f=$.updated.split("T")[0]??"";return`${$.id} ${f} ${$.title} (${$.messageCount})`}function AG({currentId:$,onSelect:f,onCancel:Z}){let z=a1(),[J,K]=DG(""),[Q,G]=DG(0),{stdout:Y}=sq(),P=Y.rows||24,X=Math.max(4,P-11),W=J.trim().toLowerCase(),H=z.filter((V)=>V.id.toLowerCase().includes(W)||V.title.toLowerCase().includes(W)),M=Math.min(Q,Math.max(0,H.length-1)),F=Math.min(M,Math.max(0,H.length-X)),q=H.slice(F,F+X),U=F,N=H.length-(F+q.length);tq(()=>{G(0)},[]),aq((V,b)=>{let C=V.replace(/[\r\n]+$/,""),S=b.return||/[\r\n]+$/.test(V);if(b.escape){Z();return}if(b.pageDown){if(H.length>0)G((I)=>Math.min(H.length-1,I+X));return}if(b.pageUp){if(H.length>0)G((I)=>Math.max(0,I-X));return}if(H.length>0){if(b.downArrow){G((I)=>(I+1)%H.length);return}if(b.upArrow){G((I)=>(I-1+H.length)%H.length);return}}if(S){if(H.length>0)f(H[M].id);return}if(b.backspace||b.delete){K((I)=>Array.from(I).slice(0,-1).join(""));return}if(b.ctrl&&V==="u"){K("");return}if(b.ctrl||b.meta||b.tab)return;if(C)K((I)=>I+C)});let B=H.length===0&&W==="",D=H.length===0&&W!=="";return k0(j1,{flexDirection:"column",flexShrink:0,width:"100%",borderStyle:"round",borderColor:_.pickerBorder,paddingX:1,children:[k0(j1,{children:[k0(R$,{bold:!0,color:_.pickerBorder,children:"选择会话"},void 0,!1,void 0,this),k0(R$,{color:_.muted,children:$?` (当前: ${$})`:""},void 0,!1,void 0,this)]},void 0,!0,void 0,this),k0(j1,{children:[k0(R$,{color:_.muted,children:"筛选: "},void 0,!1,void 0,this),k0(R$,{color:J?_.accent:_.muted,children:J||"输入字符过滤标题或 id"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),B&&k0(j1,{children:k0(R$,{color:_.muted,dimColor:!0,children:"无已保存的会话"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D&&k0(j1,{children:k0(R$,{color:_.muted,dimColor:!0,children:"没有匹配的会话"},void 0,!1,void 0,this)},void 0,!1,void 0,this),U>0&&k0(j1,{children:k0(R$,{color:_.muted,dimColor:!0,children:["… 上方还有 ",U," 个会话"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),q.map((V,b)=>k0(j1,{children:[k0(R$,{color:b===M-F?_.accent:_.muted,children:b===M-F?"❯ ":" "},void 0,!1,void 0,this),k0(R$,{bold:b===M-F,color:b===M-F?_.accent:void 0,wrap:"truncate-end",children:eq(V)},void 0,!1,void 0,this),V.id===$&&k0(R$,{color:_.success,children:" ←"},void 0,!1,void 0,this)]},V.id,!0,void 0,this)),N>0&&k0(j1,{children:k0(R$,{color:_.muted,dimColor:!0,children:["… 下方还有 ",N," 个会话"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),k0(j1,{children:k0(R$,{color:_.muted,dimColor:!0,wrap:"truncate-end",children:"↑↓/PgUpDn 选择 · Enter 确认 · Esc 取消"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var jG=O(()=>{n$();Z1()});import{useCallback as $N,useEffect as CG,useState as OG}from"react";import{Box as l5,useInput as fN,useStdout as ZN}from"ink";import{jsxDEV as U$}from"react/jsx-dev-runtime";function wG({initialState:$,onSubmit:f,onConfirm:Z,onQuestionAnswer:z,onModelPick:J,onModelCancel:K,onThinkPick:Q,onThinkCancel:G,onCtxPick:Y,onCtxCancel:P,onProviderPick:X,onProviderCancel:W,onSessionPick:H,onSessionCancel:M,onToggleSelectionMode:F,onExitSelectionMode:q,onExit:U,onCopyNotice:N,onNotice:B}){let{stdout:D}=ZN(),[V,b]=OG({columns:D.columns||80,rows:D.rows||0});if(CG(()=>{let P0=()=>b({columns:D.columns||80,rows:D.rows||0});return D.on("resize",P0),()=>{D.off("resize",P0)}},[D]),fN((P0,F0)=>{if(d8(P0,F0)){if($.confirmMessage){Z(!1);return}if($.question){z(null);return}if($.modelPicker){K();return}if($.thinkPicker){G();return}if($.ctxPicker){P();return}if($.providerPicker){W();return}if($.sessionPicker){M();return}if($.selectionMode){q();return}if($.isRunning)U();return}if(F0.ctrl&&P0==="b"){if($.confirmMessage||$.question||$.modelPicker||$.thinkPicker||$.ctxPicker||$.providerPicker||$.sessionPicker)return;if($.isRunning)return;if(!$.selectionMode)return;F();return}if(F0.escape&&$.isRunning&&!$.confirmMessage&&!$.question&&!$.modelPicker&&!$.thinkPicker&&!$.ctxPicker&&!$.providerPicker&&!$.sessionPicker)U()}),$.confirmMessage||$.question||$.modelPicker||$.thinkPicker||$.ctxPicker||$.providerPicker||$.sessionPicker)Df(null);let{columns:C,rows:S}=V,I=RK(S),[j,w]=OG(Y2),E=$N((P0)=>{w((F0)=>F0===P0?F0:P0)},[]),l=Boolean($.confirmMessage),h=Boolean($.question),t=Boolean($.modelPicker),v=Boolean($.thinkPicker),T=Boolean($.ctxPicker),r=Boolean($.providerPicker),R=Boolean($.sessionPicker),m=l||h||t||v||T||r||R;CG(()=>{if(m)w(Y2)},[m]);let K0=l?yQ($.confirmMessage??"",C,I):h?SQ($.question.prompt,$.question.options,C,I,Boolean($.question.multiple)):t?pQ(I):v?aQ():T?zG():r?YG(I):R?bG(I):j,x=$.isRunning&&!l&&!h&&!t&&!v&&!T&&!r&&!R,n0=vK(I,K0,x?1:0);return U$(l5,{flexDirection:"column",width:"100%",height:I||void 0,overflow:"hidden",children:[!t&&U$(l5,{flexDirection:"column",flexGrow:1,flexShrink:1,minHeight:0,overflow:"hidden",width:"100%",children:U$(bQ,{messages:$.messages,maxHeight:n0,columns:C,onCopyNotice:N,selectionMode:Boolean($.selectionMode),onExitSelectionMode:q,interactive:!m},void 0,!1,void 0,this)},void 0,!1,void 0,this),x&&U$(l5,{paddingLeft:1,flexShrink:0,width:"100%",children:U$(PK,{label:$.spinnerText||"思考中..."},void 0,!1,void 0,this)},void 0,!1,void 0,this),U$(mQ,{state:$,columns:C},void 0,!1,void 0,this),$.confirmMessage?U$(TQ,{message:$.confirmMessage,onConfirm:Z,columns:C,maxRows:K0},void 0,!1,void 0,this):$.question?U$(uQ,{prompt:$.question.prompt,options:$.question.options,multiple:Boolean($.question.multiple),onAnswer:z,columns:C,maxRows:K0},void 0,!1,void 0,this):$.modelPicker?U$(dQ,{currentModel:$.model,onSelect:J,onCancel:K},void 0,!1,void 0,this):$.thinkPicker?U$(sQ,{scope:$.thinkPicker.scope,modelId:$.model,onSelect:(P0)=>Q(P0,$.thinkPicker.scope),onCancel:G},void 0,!1,void 0,this):$.ctxPicker?U$(KG,{onSelect:Y,onCancel:P},void 0,!1,void 0,this):$.providerPicker?U$(PG,{onSelect:X,onCancel:W},void 0,!1,void 0,this):$.sessionPicker?U$(AG,{currentId:$.sessionId,onSelect:H,onCancel:M},void 0,!1,void 0,this):U$($Q,{onSubmit:f,disabled:$.isRunning||Boolean($.selectionMode),placeholder:$.isRunning?"按 Esc 取消运行...":"输入消息... (Ctrl+J 换行)",columns:C,terminalRows:I,onSelectionMode:F,onExit:U,onRowsChange:E,onNotice:B},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var yG=O(()=>{XK();fQ();jQ();IQ();EQ();rQ();iQ();eQ();QG();XG();jG();z5()});function TG($,f,Z){let z=-1;if(f)z=$.findIndex((Q)=>Q.role==="tool"&&Q.toolCallId===f);if(z===-1){for(let Q=$.length-1;Q>=0;Q--)if($[Q].role==="tool"&&$[Q].toolName==="task"){z=Q;break}}if(z===-1)return $;let J=$[z],K=$.slice();return K[z]={...J,toolChildren:[...J.toolChildren??[],Z]},K}import{render as zN}from"ink";import{jsxDEV as JN}from"react/jsx-dev-runtime";class t5{state;rerender=null;inkInstance=null;callbacks;pendingDelta="";deltaTimer=null;pendingThinking="";thinkingTimer=null;copyNoticeTimer=null;constructor($,f,Z){this.state={messages:[],isRunning:!1,model:f,sessionId:Z},this.callbacks=$}appElement(){return JN(wG,{initialState:this.state,onSubmit:this.callbacks.onSubmit,onConfirm:this.callbacks.onConfirm,onQuestionAnswer:this.callbacks.onQuestionAnswer,onModelPick:this.callbacks.onModelPick,onModelCancel:this.callbacks.onModelCancel,onThinkPick:this.callbacks.onThinkPick,onThinkCancel:this.callbacks.onThinkCancel,onCtxPick:this.callbacks.onCtxPick,onCtxCancel:this.callbacks.onCtxCancel,onProviderPick:this.callbacks.onProviderPick,onProviderCancel:this.callbacks.onProviderCancel,onSessionPick:this.callbacks.onSessionPick,onSessionCancel:this.callbacks.onSessionCancel,onToggleSelectionMode:this.callbacks.onToggleSelectionMode,onExitSelectionMode:this.callbacks.onExitSelectionMode,onExit:this.callbacks.onExit,onCopyNotice:($)=>this.showCopyNotice($),onNotice:this.callbacks.onNotice},void 0,!1,void 0,this)}start(){this.inkInstance=zN(this.appElement(),{exitOnCtrlC:!1,stdout:HK(process.stdout)})}update($){if(this.state={...this.state,...$},this.inkInstance)this.inkInstance.rerender(this.appElement())}addMessage($){this.flushPendingDeltas(),this.flushPendingThinking(),this.state.messages=[...this.state.messages,$],this.update({})}messageCount(){return this.state.messages.length}setToolResult($,f,Z,z,J){let K=[...this.state.messages],Q=K.findIndex((G)=>G.role==="tool"&&G.toolCallId===$);if(Q===-1)for(let G=K.length-1;G>=0;G--){let Y=K[G];if(Y.role==="tool"&&Y.toolName===f&&Y.toolResult===void 0){Q=G;break}}if(Q===-1)return;K[Q]={...K[Q],toolResultSummary:Z,toolResult:z,toolIsError:J},this.state.messages=K,this.update({})}truncateMessages($){this.state.messages=this.state.messages.slice(0,$),this.update({})}appendToLast($){if(this.pendingDelta+=$,this.deltaTimer!==null)return;this.deltaTimer=setTimeout(()=>{this.deltaTimer=null,this.applyPendingDelta()},16)}appendToThinking($){if(this.pendingThinking+=$,this.thinkingTimer!==null)return;this.thinkingTimer=setTimeout(()=>{this.thinkingTimer=null,this.applyPendingThinking()},16)}applyPendingThinking(){let $=this.pendingThinking;if(this.pendingThinking="",!$)return;let f=[...this.state.messages],Z=f[f.length-1];if(Z&&Z.role==="thinking")f[f.length-1]={...Z,content:Z.content+$},this.state.messages=f,this.update({});else this.addMessage({id:`thinking-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,role:"thinking",content:$,timestamp:Date.now()})}flushPendingThinking(){if(this.thinkingTimer!==null)clearTimeout(this.thinkingTimer),this.thinkingTimer=null;this.applyPendingThinking()}applyPendingDelta(){let $=this.pendingDelta;if(this.pendingDelta="",!$)return;let f=[...this.state.messages],Z=f[f.length-1];if(Z&&Z.role==="assistant")f[f.length-1]={...Z,content:Z.content+$},this.state.messages=f,this.update({});else if($.trim()!=="")this.addMessage({id:`msg-${Date.now()}`,role:"assistant",content:$,timestamp:Date.now()})}flushPendingDeltas(){if(this.deltaTimer!==null)clearTimeout(this.deltaTimer),this.deltaTimer=null;this.applyPendingDelta()}setRunning($,f){if(!$)this.flushPendingDeltas(),this.flushPendingThinking();if(this.state.isRunning===$&&this.state.spinnerText===f)return;this.update({isRunning:$,spinnerText:f})}showConfirm($){this.update({confirmMessage:$,selectionMode:!1})}hideConfirm(){this.update({confirmMessage:void 0})}showQuestion($,f,Z=!1){let z=g1(E1(f));this.update({question:{prompt:u1($),...z.length>0?{options:z}:{},...Z?{multiple:!0}:{}},selectionMode:!1})}hideQuestion(){this.update({question:void 0})}showModelPicker(){this.update({modelPicker:!0,selectionMode:!1})}hideModelPicker(){this.update({modelPicker:!1})}showThinkPicker($="global"){this.update({thinkPicker:{scope:$},selectionMode:!1})}hideThinkPicker(){this.update({thinkPicker:void 0})}showCtxPicker(){this.update({ctxPicker:!0,selectionMode:!1})}hideCtxPicker(){this.update({ctxPicker:void 0})}showProviderPicker(){this.update({providerPicker:!0,selectionMode:!1})}hideProviderPicker(){this.update({providerPicker:!1})}showSessionPicker(){this.update({sessionPicker:!0,selectionMode:!1})}hideSessionPicker(){this.update({sessionPicker:!1})}setSessionId($){this.update({sessionId:$})}setSelectionMode($){this.update({selectionMode:$})}toggleSelectionMode(){this.update({selectionMode:!this.state.selectionMode})}appendToolChild($,f){this.state.messages=TG(this.state.messages,$,f),this.update({})}setModel($){this.update({model:$})}setTokenInfo($){this.update({tokenInfo:$})}showCopyNotice($){if(this.update({copyNotice:$}),this.copyNoticeTimer!==null)clearTimeout(this.copyNoticeTimer);this.copyNoticeTimer=setTimeout(()=>{this.copyNoticeTimer=null,this.update({copyNotice:void 0})},2500)}destroy(){if(this.flushPendingDeltas(),this.flushPendingThinking(),this.copyNoticeTimer!==null)clearTimeout(this.copyNoticeTimer),this.copyNoticeTimer=null;if(this.deltaTimer!==null)clearTimeout(this.deltaTimer),this.deltaTimer=null;if(this.thinkingTimer!==null)clearTimeout(this.thinkingTimer),this.thinkingTimer=null;Df(null);try{process.stdout.write("\x1B[?1000l\x1B[?1002l\x1B[?1006l")}catch{}this.inkInstance?.unmount(),this.inkInstance=null}}var IG=O(()=>{yG();p4()});import{existsSync as KN,mkdirSync as QN,readdirSync as GN,statSync as YN,unlinkSync as PN,writeFileSync as XN}from"fs";import a5 from"path";import{randomBytes as WN}from"crypto";function FN(){return a5.join(X0(),"tool-output")}function qN($){let f=Date.now();if(f-kG<MN)return;if(kG=f,!KN($))return;try{for(let Z of GN($)){if(!Z.startsWith("tool-")||!Z.endsWith(".txt"))continue;let z=a5.join($,Z);try{if(f-YN(z).mtimeMs>UN)PN(z)}catch{}}}catch{}}function e5($){let f=FN();QN(f,{recursive:!0}),qN(f);let Z=`tool-${Date.now()}-${WN(4).toString("hex")}.txt`,z=a5.join(f,Z);return XN(z,$,"utf-8"),z}function NN($,f,Z,z,J,K){if(J.length<=f&&K<=Z)return{text:$,cut:!1};let Q=[],G=0,Y=(P,X)=>{let W=Buffer.byteLength(J[P],"utf-8")+(X?0:1);if(G+W>Z)return!1;if(z==="head")Q.push(J[P]);else Q.unshift(J[P]);return G+=W,!0};if(z==="head"){for(let P=0;P<J.length&&Q.length<f;P++)if(!Y(P,Q.length===0)){if(Q.length===0){let X=Buffer.from(J[P],"utf-8"),W=Math.min(Z,X.length);while(W>0&&(X[W]&192)===128)W--;Q.push(X.subarray(0,W).toString("utf-8"))}break}}else for(let P=J.length-1;P>=0&&Q.length<f;P--)if(!Y(P,Q.length===0)){if(Q.length===0){let X=Buffer.from(J[P],"utf-8"),W=X.length-Z;if(W<0)W=0;while(W<X.length&&(X[W]&192)===128)W++;Q.unshift(X.subarray(W).toString("utf-8"))}break}return{text:Q.join(`
110
+ `),cut:!0}}function B0($,f={}){let Z=f.maxLines??HN,z=f.maxBytes??s5,J=f.direction??"head",K=$.split(`
111
+ `),Q=Buffer.byteLength($,"utf-8");if(K.length<=Z&&Q<=z)return{content:$,truncated:!1};let G=e5($),Y=NN($,Z,z,J,K,Q),P=`...output truncated...
112
+
113
+ `;return{content:J==="tail"?`${P}${nG(G)}
114
+
115
+ ${Y.text}`:`${Y.text}
116
+
117
+ ${P}${nG(G)}`,truncated:!0,outputPath:G}}var HN=2000,s5=51200,UN=604800000,MN=600000,kG=0,nG=($)=>`The tool output was truncated. Full output saved to: ${$}
118
+ Use the read tool with startLine/endLine, or grep, to inspect further.`;var b$=O(()=>{d()});import{mkdirSync as BN,readdirSync as VN,unlinkSync as LN,writeFileSync as _N}from"fs";import $7 from"path";function B6(){return $7.join(X0(),"logs")}function bN($){let f=$.getFullYear(),Z=String($.getMonth()+1).padStart(2,"0"),z=String($.getDate()).padStart(2,"0");return $7.join(B6(),`min-agent.${f}-${Z}-${z}.log`)}function RG(){try{BN(B6(),{recursive:!0});let $=Date.now()-DN*24*60*60*1000;for(let f of VN(B6())){let Z=f.match(/^min-agent\.(\d{4})-(\d{2})-(\d{2})\.log$/);if(!Z)continue;if(new Date(`${Z[1]}-${Z[2]}-${Z[3]}T00:00:00`).getTime()<$)try{LN($7.join(B6(),f))}catch{}}}catch{}}function f7($,f){try{let Z=new Date,z=`${String(Z.getHours()).padStart(2,"0")}:${String(Z.getMinutes()).padStart(2,"0")}:${String(Z.getSeconds()).padStart(2,"0")}`;_N(bN(Z),`[${z}] [${$}]${AN()} ${CN(f)}
119
+ `,{flag:"a"})}catch{}}function AN(){if(!s1)return"";return` [run=${s1.runId} pass=${s1.pass}]`}function Z7(){let $=Math.random().toString(36).slice(2,8);return s1={runId:$,pass:0},$}function SG(){if(!s1)Z7();return s1.pass++,s1.pass}function vG(){s1=null}function CN($){let f=$;for(let Z of jN)f=f.replace(Z,"$1***");return f}function Z0($,f){f7($,f)}function uG($,f=200){let Z=typeof $==="string"?$:JSON.stringify($)??String($);return Z.length>f?Z.slice(0,f)+"…":Z}function z7($,f){f7("info",`tool_call ${$} ${uG(f)}`)}function A2($,f){f7("info",`tool_result ${$} ${uG(f)}`)}var DN=7,s1=null,jN;var Tf=O(()=>{d();jN=[/\b(Bearer\s+)[A-Za-z0-9._~+/-]{8,}/g,/\b(api[_-]?key|apikey|token|secret|password|passwd)\s*[:=]\s*["']?[A-Za-z0-9._~+/-]{6,}["']?/gi,/\b(sk-[A-Za-z0-9_-]{6,})/g,/\b(gh[pousr]_[A-Za-z0-9]{20,})/g]});var L4={};U0(L4,{syncMcpConnections:()=>B4,shutdownMcp:()=>ff,saveMcpConfig:()=>C2,resolveMcpTimeouts:()=>M7,readMcpResource:()=>_6,mcpConfigPathFor:()=>H7,loadMcpConfigFile:()=>C1,loadMcpConfigEntries:()=>G1,loadMcpConfig:()=>pN,listMcpCatalog:()=>$f,isRemoteMcpConfig:()=>U7,initMcp:()=>nf,getMcpTools:()=>V4,getMcpStatus:()=>o$,getMcpReadOnlyToolIds:()=>N7,getMcpPrompt:()=>D6,getMcpCatalogTools:()=>O2,formatResourceContents:()=>$Y,formatPromptResult:()=>fY,formatMcpServerBinding:()=>V6,discoverMcpExtras:()=>dG,connectMcpServer:()=>lG,checkMcpServer:()=>L6,checkAllMcpServers:()=>q7,buildMcpToolsMap:()=>sG});import{Client as Q7}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as ON}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as wN}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as yN}from"@modelcontextprotocol/sdk/client/sse.js";import{UnauthorizedError as TN,auth as EG}from"@modelcontextprotocol/sdk/client/auth.js";import{tool as j2,jsonSchema as q4}from"ai";import{readFileSync as rG,writeFileSync as oG,mkdirSync as pG,statSync as IN,existsSync as kN}from"fs";import kf from"path";import{createServer as nN}from"http";import{spawn as J7}from"child_process";import{Writable as RN}from"stream";import{randomUUID as SN}from"crypto";function G7($){if(typeof $==="string")return $.length>gG?$.slice(0,gG)+"… [truncated]":$;if(Array.isArray($))return $.slice(0,vN).map(G7);if($!==null&&typeof $==="object"){let f={};for(let[Z,z]of Object.entries($))f[Z]=G7(z);return f}return $}function mN(){return kf.join(X0(),"mcp.json")}function rN(){return kf.join(process.cwd(),".min-agent","mcp.json")}function H7($){return $==="project"?rN():mN()}function oN($){let f=P7.get($);try{let Z=IN($);if(f&&f.mtimeMs===Z.mtimeMs&&f.size===Z.size)return f;let z=JSON.parse(rG($,"utf-8")),J={mtimeMs:Z.mtimeMs,size:Z.size,config:z};return P7.set($,J),J}catch{return null}}function C1($){return oN(H7($))?.config??{mcpServers:{}}}function pN(){return{mcpServers:{...C1("global").mcpServers,...C1("project").mcpServers}}}function G1(){let $=C1("global"),f=C1("project");return Object.entries({...$.mcpServers,...f.mcpServers}).map(([Z,z])=>({name:Z,config:z,scope:f.mcpServers[Z]!==void 0?"project":"global"}))}function C2($,f="global"){let Z=H7(f);if(f==="project"&&!kN(kf.join(process.cwd(),".min-agent"))){console.warn(`\x1B[33m ⚠ Project MCP write skipped: no .min-agent/ in ${process.cwd()}. Run "min-agent init" to create it first.\x1B[0m`);return}let z=kf.dirname(Z);pG(z,{recursive:!0}),oG(Z,JSON.stringify($,null,2),"utf-8"),P7.delete(Z)}function U7($){return typeof $.url==="string"&&$.url.trim().length>0}function M7($){return{connectTimeout:$.connectTimeout??$.timeout??xG,callTimeout:$.callTimeout??$.timeout??xG}}function X7($){return JSON.stringify($)}function dN($){let f=new Headers($.headers??{}),Z=$.token?.trim();if(Z&&!f.has("Authorization"))f.set("Authorization",`Bearer ${Z}`);if([...f.keys()].length===0)return;return{headers:f}}function iN($){let f=[],Z="";return{stream:new RN({write(J,K,Q){Z+=String(J);let G=-1;while((G=Z.indexOf(`
120
+ `))!==-1){let Y=Z.slice(0,G).trim();if(Z=Z.slice(G+1),!Y)continue;if(f.push(Y),f.length>hN)f.shift();Z0("warn",`mcp "${$}" stderr: ${Y}`)}Q()}}),lines:f}}async function lN($){let f=[],Z;do{let z=await $.listTools(Z?{cursor:Z}:void 0);f.push(...z.tools),Z=z.nextCursor}while(Z);return f}async function K7($,f){let Z=[],z;do{let J=await $(z);if(Z.push(...J.items),z=J.nextCursor,Z.length>=f)return Z.slice(0,f)}while(z);return Z}async function dG($){let f=$.getServerCapabilities(),Z=[],z=[],J=[];if(f?.resources){try{Z=await K7(async(K)=>{let Q=await $.listResources(K?{cursor:K}:void 0);return{items:Q.resources.map((G)=>({uri:G.uri,name:G.name,...G.description?{description:G.description}:{},...G.mimeType?{mimeType:G.mimeType}:{}})),nextCursor:Q.nextCursor}},uN)}catch{Z=[]}try{z=await K7(async(K)=>{let Q=await $.listResourceTemplates(K?{cursor:K}:void 0);return{items:Q.resourceTemplates.map((G)=>({uriTemplate:G.uriTemplate,name:G.name,...G.description?{description:G.description}:{},...G.mimeType?{mimeType:G.mimeType}:{}})),nextCursor:Q.nextCursor}},EN)}catch{z=[]}}if(f?.prompts)try{J=await K7(async(K)=>{let Q=await $.listPrompts(K?{cursor:K}:void 0);return{items:Q.prompts.map((G)=>({name:G.name,...G.description?{description:G.description}:{},...G.arguments&&G.arguments.length>0?{arguments:G.arguments}:{}})),nextCursor:Q.nextCursor}},gN)}catch{J=[]}return{resources:Z,resourceTemplates:z,prompts:J}}async function W7($,f,Z,z={}){let J=await lN($),K=await dG($);return{client:$,transport:f,tools:J,...K,callTimeout:M7(Z).callTimeout,signature:X7(Z),...z}}async function tN($,f,Z){let z,J;if(Array.isArray(f.command))[z,...J]=f.command;else if(typeof f.command==="string")z=f.command,J=f.args??[];else throw Error(`MCP "${$}" has empty command`);if(!z)throw Error(`MCP "${$}" has empty command`);let K=iN($),Q=new ON({command:z,args:J,env:{...process.env,...f.environment??{}},stderr:"pipe"});Q.stderr?.pipe(K.stream),Z?.onTransport?.(Q);let G=new Q7({name:"min-agent",version:"0.1.0"});try{return await G.connect(Q),await W7(G,Q,f,{stderrSink:K})}catch(Y){await Q.close().catch(()=>{});let P=K.lines.length?`
121
+ Server stderr (last ${K.lines.length} lines):
122
+ ${K.lines.map((X)=>` ${X}`).join(`
123
+ `)}`:"";throw Error(`${Y?.message??String(Y)}${P}`)}}class F7{name;serverConfig;tokensStore;clientInfo;discoveryStore;verifier;pendingState;pendingCode;pendingError;resolveCode;rejectCode;callbackServer;callbackBase="http://127.0.0.1";redirectUrl="";constructor($,f,Z){this.name=$;this.serverConfig=f;this.loadStore(Z)}static async create($,f){let Z=kf.join(X0(),"mcp-oauth",`${N4($)}-${mG($).toString(16)}.json`),z=new F7($,f,Z);return await z.bindCallbackServer(),z}storeFile(){return kf.join(X0(),"mcp-oauth",`${N4(this.name)}-${mG(this.name).toString(16)}.json`)}loadStore($){try{let f=JSON.parse(rG($,"utf-8"));this.clientInfo=f.clientInfo,this.tokensStore=f.tokens,this.discoveryStore=f.discovery}catch{}}saveStore(){let $=this.storeFile();pG(kf.dirname($),{recursive:!0}),oG($,JSON.stringify({...this.clientInfo?{clientInfo:this.clientInfo}:{},...this.tokensStore?{tokens:this.tokensStore}:{},...this.discoveryStore?{discovery:this.discoveryStore}:{}},null,2),"utf-8")}settleCode($){this.pendingCode=$,this.resolveCode?.($)}failCode($){this.pendingError=$,this.rejectCode?.($)}bindCallbackServer(){return new Promise(($,f)=>{let Z=nN((z,J)=>{let K=new URL(z.url??"/",this.callbackBase),Q=K.searchParams.get("code"),G=K.searchParams.get("state"),Y=K.searchParams.get("error"),P=Q?"<html><body><h3>min-agent: authorization complete</h3><p>You can close this tab and return to the terminal.</p></body></html>":"<html><body><h3>min-agent: authorization failed</h3><p>Check the terminal for details.</p></body></html>";if(J.writeHead(Q?200:400,{"Content-Type":"text/html; charset=utf-8"}),J.end(P),this.pendingState&&G&&G!==this.pendingState){this.failCode(Error("OAuth state mismatch — authorization attempt rejected"));return}if(Q)this.settleCode(Q);else this.failCode(Error(Y?`OAuth authorization failed: ${Y}`:"OAuth authorization failed: no code returned"))});Z.on("error",(z)=>{this.failCode(Error(`OAuth callback server failed: ${z.message}`))}),Z.listen(0,"127.0.0.1",()=>{let z=Z.address();if(!z||typeof z==="string"){f(Error("OAuth callback server could not bind a port"));return}this.callbackServer=Z,this.callbackBase=`http://127.0.0.1:${z.port}`,this.redirectUrl=`${this.callbackBase}/callback`,$()})})}close(){this.callbackServer?.close(),this.callbackServer=void 0}waitForCode(){if(this.pendingCode)return Promise.resolve(this.pendingCode);if(this.pendingError)return Promise.reject(this.pendingError);return new Promise(($,f)=>{this.resolveCode=$,this.rejectCode=f})}get clientMetadata(){let $=this.serverConfig.oauth,f={redirect_uris:[this.redirectUrl],client_name:"min-agent"};if(typeof $==="object"&&$){if($.clientId)f.client_id=$.clientId;if($.clientSecret)f.client_secret=$.clientSecret;if($.scope)f.scope=$.scope}return f}clientInformation(){if(!this.clientInfo)return;return("redirect_uris"in this.clientInfo?this.clientInfo.redirect_uris:[]).includes(this.redirectUrl)?this.clientInfo:void 0}saveClientInformation($){this.clientInfo=$,this.saveStore()}tokens(){return this.tokensStore}saveTokens($){this.tokensStore=$,this.saveStore()}saveDiscoveryState($){this.discoveryStore=$,this.saveStore()}discoveryState(){return this.discoveryStore}saveCodeVerifier($){this.verifier=$}codeVerifier(){if(!this.verifier)throw Error("No PKCE code verifier for this session");return this.verifier}state(){return this.pendingState=SN(),this.pendingState}redirectToAuthorization($){aN($.href)}}function aN($){let f=process.platform;try{if(f==="darwin")J7("open",[$],{detached:!0,stdio:"ignore"}).unref();else if(f==="win32")J7("cmd",["/c","start","",$],{detached:!0,stdio:"ignore"}).unref();else J7("xdg-open",[$],{detached:!0,stdio:"ignore"}).unref()}catch(Z){Z0("warn",`mcp oauth: failed to open browser: ${Z.message}`)}}async function sN($,f,Z){if(!f.oauth||f.token?.trim())return;let z=await F7.create($,f);try{if(await EG(z,{serverUrl:Z.href})==="REDIRECT"){console.log(`\x1B[90m MCP "${$}" needs authorization — a browser tab was opened. Waiting for login…\x1B[0m`);let K=await Promise.race([z.waitForCode(),new Promise((Q,G)=>{setTimeout(()=>G(Error("OAuth authorization timed out after 5 minutes")),cN)})]);await EG(z,{serverUrl:Z.href,authorizationCode:K})}return z}catch(J){throw z.close(),Error(`MCP "${$}" OAuth failed: ${J?.message??String(J)}`)}}async function eN($,f,Z){let z=f.url?.trim();if(!z)throw Error(`MCP "${$}" has empty url`);let J;try{J=new URL(z)}catch{throw Error(`MCP "${$}" has invalid url: ${z}`)}if(J.protocol!=="http:"&&J.protocol!=="https:")throw Error(`MCP "${$}" url must be http or https`);let K=dN(f),Q=f.remoteTransport??"auto",G=await sN($,f,J);if(G)Z?.onOAuthProvider?.(G);let Y=async()=>{let X=new Q7({name:"min-agent",version:"0.1.0"}),W=new wN(J,K||G?{requestInit:K,authProvider:G}:void 0);Z?.onTransport?.(W);try{return await X.connect(W),await W7(X,W,f,{oauthProvider:G})}catch(H){throw await W.close().catch(()=>{}),H}},P=async()=>{let X=new Q7({name:"min-agent",version:"0.1.0"}),W=new yN(J,K||G?{requestInit:K,authProvider:G}:void 0);Z?.onTransport?.(W);try{return await X.connect(W),await W7(X,W,f,{oauthProvider:G})}catch(H){throw await W.close().catch(()=>{}),H}};try{if(Q==="streamable-http")return await Y();if(Q==="sse")return await P();try{return await Y()}catch(X){try{return await P()}catch{throw X}}}catch(X){G?.close();let W=X instanceof Error?X.message:String(X);if(X instanceof TN||W.includes("Unauthorized")||W.includes("401")){if(f.oauth===!1)throw Error(`MCP "${$}" requires authentication but OAuth is disabled in config`);throw Error(`MCP "${$}" requires authentication. Add a "token" field to the server config, or configure OAuth:
124
+ min-agent mcp add ${$} --url ${z} --token YOUR_TOKEN`)}throw Error(`MCP "${$}" remote connection failed: ${W}`)}}async function $B($,f,Z){if(U7(f))return await eN($,f,Z);return await tN($,f,Z)}function V6($){if(U7($)){let Z=$.remoteTransport??"auto";return`${$.url} [remote:${Z}]`}return(Array.isArray($.command)?$.command.join(" "):`${$.command??""} ${($.args??[]).join(" ")}`.trim())||"(no command)"}async function iG($,f){let Z=M7(f).connectTimeout,z,J={transport:null},K={provider:null},Q=new Promise((Y,P)=>{z=setTimeout(()=>P(Error(`connection timed out after ${Z}ms`)),Z)}),G=$B($,f,{onTransport:(Y)=>{J.transport=Y},onOAuthProvider:(Y)=>{K.provider=Y}});G.catch(()=>{});try{return{server:await Promise.race([G,Q])}}catch(Y){return await J.transport?.close().catch(()=>{}),K.provider?.close(),G.then((P)=>tG(P)).catch(()=>{}),{error:Y}}finally{if(z)clearTimeout(z)}}async function lG($,f){if(f.enabled===!1)return null;let{server:Z,error:z}=await iG($,f);if(Z)return delete e1[$],console.log(`\x1B[90m MCP "${$}" connected (${Z.tools.length} tools, ${Z.resources.length} resources, ${Z.prompts.length} prompts)\x1B[0m`),Z0("info",`mcp "${$}" connected (${Z.tools.length} tools, ${Z.resources.length} resources, ${Z.prompts.length} prompts)`),Z;let J=z?.message??String(z);return e1[$]=J,console.error(`\x1B[31m MCP "${$}" failed: ${J}\x1B[0m`),Z0("error",`mcp "${$}" failed: ${J}`),null}async function L6($,f){if(f.enabled===!1)return{name:$,enabled:!1,ok:!0,toolCount:0};let{server:Z,error:z}=await iG($,f);if(!Z)return{name:$,enabled:!0,ok:!1,toolCount:0,error:z instanceof Error?z.message:String(z)};let J=Z.tools.length;try{await Z.client.close()}catch{}return Z.oauthProvider?.close(),{name:$,enabled:!0,ok:!0,toolCount:J}}async function q7(){let $=G1();return(await Promise.allSettled($.map(({name:Z,config:z})=>L6(Z,z)))).map((Z,z)=>Z.status==="fulfilled"?Z.value:{name:$[z]?.name??"unknown",enabled:!0,ok:!1,toolCount:0,error:String(Z.reason)})}async function tG($){try{await $.client.close()}catch{}$.oauthProvider?.close()}async function aG($,f){await tG(f),delete z$[$],delete e1[$]}async function ff(){If=null,await Promise.all(Object.entries(z$).map(([$,f])=>aG($,f))),z$={}}function B4(){let $=hG.then(()=>fB());return hG=$.catch(()=>{}),$}async function fB(){If=null;let $=G1();for(let[J,K]of Object.entries(z$)){let Q=$.find((G)=>G.name===J);if(!Q||Q.config.enabled===!1||X7(Q.config)!==K.signature)await aG(J,K)}let f=$.filter(({name:J,config:K})=>{if(K.enabled===!1)return!1;let Q=z$[J];if(!Q)return!0;return X7(K)!==Q.signature}),Z=await Promise.allSettled(f.map(async({name:J,config:K})=>{let Q=await lG(J,K);if(Q)z$[J]=Q})),z=new Set;return Z.forEach((J,K)=>{if(J.status==="rejected"){let Q=f[K].name;z.add(Q),e1[Q]=String(J.reason),console.error(`\x1B[31m MCP "${Q}" failed: ${String(J.reason)}\x1B[0m`),Z0("error",`mcp "${Q}" failed: ${String(J.reason)}`)}}),$.map(({name:J,config:K})=>{let Q=z$[J];if(K.enabled===!1)return{name:J,state:"disabled"};if(Q){let G=f.some((Y)=>Y.name===J);return{name:J,state:G?"connected":"unchanged",tools:Q.tools.length}}return{name:J,state:"failed",...e1[J]?{error:e1[J]}:{}}})}async function nf(){If=null,await ff(),await B4()}function V4(){if(If)return If;return Y7=new Set,If=sG(z$,Y7),If}function N7(){return V4(),Y7}function sG($,f){let Z={},z=new Set;for(let[J,K]of Object.entries($))for(let Q of K.tools){let G=`${N4(J)}_${N4(Q.name)}`,Y=2;while(z.has(G))G=`${N4(J)}_${N4(Q.name)}_${Y++}`;z.add(G);let P=Q.inputSchema??{},X={...P,...P.type?{}:{type:"object"},...P.properties?{}:{properties:{}}},W=Q.annotations?.readOnlyHint===!0;if(W)f?.add(G);let H=`[${J}] ${Q.description??`MCP tool: ${Q.name}`}`+(W?" (read-only)":""),M=Q.outputSchema;Z[G]=j2({description:H,inputSchema:q4(X),...M&&M.type==="object"?{outputSchema:q4(M)}:{},execute:async(F,q)=>{try{let U=[AbortSignal.timeout(K.callTimeout)];if(q?.abortSignal)U.push(q.abortSignal);let N=U.length===1?U[0]:AbortSignal.any(U),B=await K.client.callTool({name:Q.name,arguments:F??{}},void 0,{signal:N});if(B.isError)return B0(`Error: ${JSON.stringify(B.content)}`,{direction:"head"}).content;if(B.structuredContent!==void 0)return G7(B.structuredContent);let V=B.content.filter((b)=>b.type==="text").map((b)=>b.text??"").join(`
125
+ `)||JSON.stringify(B.content);return B0(V,{direction:"head"}).content}catch(U){return B0(`MCP tool error: ${U.message}`,{direction:"head"}).content}}})}return Z}function o$(){let $={};for(let{name:f,config:Z}of G1()){let z=z$[f];$[f]={connected:!!z,enabled:Z.enabled!==!1,tools:z?.tools.map((J)=>J.name)??[],resource_count:z?.resources.length??0,prompt_count:z?.prompts.length??0,...e1[f]?{error:e1[f]}:{}}}return $}function $f($){return{servers:($?[$]:Object.keys(z$)).flatMap((Z)=>{let z=z$[Z];if(!z)return[];return[{name:Z,resources:z.resources,templates:z.resourceTemplates,prompts:z.prompts}]})}}function cG(){return Object.keys(z$)}function eG($,f){if($){let z=z$[$];if(!z)return`MCP server "${$}" is not connected. Connected: ${cG().join(", ")||"none"}`;return z}let Z=cG();if(Z.length===0)return"No MCP servers connected.";if(Z.length===1)return z$[Z[0]];return`Multiple MCP servers are connected (${Z.join(", ")}). Pass server to choose which ${f} to use.`}async function _6($,f){let Z=eG(f,"resource");if(typeof Z==="string")return Z;try{let z=await Z.client.readResource({uri:$},{timeout:Z.callTimeout});return $Y(z.contents)}catch(z){return`Failed to read resource: ${z instanceof Error?z.message:String(z)}`}}async function D6($,f,Z){let z=eG(Z,"prompt");if(typeof z==="string")return z;try{let J=await z.client.getPrompt({name:$,...f&&Object.keys(f).length>0?{arguments:f}:{}},{timeout:z.callTimeout});return fY(J)}catch(J){return`Failed to get prompt: ${J instanceof Error?J.message:String(J)}`}}function $Y($){if($.length===0)return"(empty resource)";return $.map((f)=>{if(typeof f.text==="string")return f.text;if(typeof f.blob==="string"){if(f.blob.length<=xN)return f.blob;return`[binary ${f.mimeType??"application/octet-stream"} ${f.blob.length} chars, omitted]`}return JSON.stringify(f)}).join(`
126
+
127
+ `)}function fY($){let f=$.description?`${$.description}
128
+
129
+ `:"",Z=$.messages.map((z)=>{let J=z.content;if(J&&typeof J==="object"&&"type"in J&&J.type==="text"&&"text"in J)return`${z.role}: ${String(J.text)}`;return`${z.role}: ${JSON.stringify(J)}`}).join(`
130
+ `);return f+Z}function O2(){if(Object.keys(z$).length===0)return{};let $=j2({description:"List MCP resources and resource URI templates from connected servers. Use this before mcp_read_resource. Optional server name limits the listing to one server.",inputSchema:q4({type:"object",properties:{server:{type:"string",description:"MCP server name. Omit to list every connected server."}}}),execute:async({server:J})=>{let K=$f(J);if(K.servers.length===0)return J?`MCP server "${J}" is not connected.`:"No MCP servers connected.";let Q=K.servers.flatMap((G)=>{let Y=G.resources.map((X)=>` resource ${X.uri} ${X.name}${X.description?` — ${X.description}`:""}`),P=G.templates.map((X)=>` template ${X.uriTemplate} ${X.name}${X.description?` — ${X.description}`:""}`);if(Y.length===0&&P.length===0)return[`[${G.name}] (no resources)`];return[`[${G.name}]`,...Y,...P]});return B0(Q.join(`
131
+ `),{direction:"head"}).content}}),f=j2({description:"Read an MCP resource by URI. Use mcp_list_resources first. Pass server when more than one MCP server is connected.",inputSchema:q4({type:"object",properties:{uri:{type:"string",description:"Resource URI from mcp_list_resources"},server:{type:"string",description:"MCP server name when multiple servers are connected"}},required:["uri"]}),execute:async({uri:J,server:K})=>B0(await _6(J,K),{direction:"head"}).content}),Z=j2({description:"List MCP prompt templates from connected servers. Use this before mcp_get_prompt. Optional server name limits the listing to one server.",inputSchema:q4({type:"object",properties:{server:{type:"string",description:"MCP server name. Omit to list every connected server."}}}),execute:async({server:J})=>{let K=$f(J);if(K.servers.length===0)return J?`MCP server "${J}" is not connected.`:"No MCP servers connected.";let Q=K.servers.flatMap((G)=>{if(G.prompts.length===0)return[`[${G.name}] (no prompts)`];return[`[${G.name}]`,...G.prompts.map((Y)=>{let P=Y.arguments?.map((X)=>`${X.name}${X.required?"*":""}`).join(", ");return` ${Y.name}${P?`(${P})`:""}${Y.description?` — ${Y.description}`:""}`})]});return B0(Q.join(`
132
+ `),{direction:"head"}).content}}),z=j2({description:"Fill an MCP prompt template. Use mcp_list_prompts first. Pass server when more than one MCP server is connected.",inputSchema:q4({type:"object",properties:{name:{type:"string",description:"Prompt name from mcp_list_prompts"},server:{type:"string",description:"MCP server name when multiple servers are connected"},arguments:{type:"object",additionalProperties:{type:"string"},description:"Prompt arguments as string values"}},required:["name"]}),execute:async({name:J,server:K,arguments:Q})=>B0(await D6(J,Q,K),{direction:"head"}).content});return{mcp_list_resources:$,mcp_read_resource:f,mcp_list_prompts:Z,mcp_get_prompt:z}}function N4($){return $.replace(/[^a-zA-Z0-9_-]/g,"_")}function mG($){let f=5381;for(let Z=0;Z<$.length;Z++)f=(f<<5)+f+$.charCodeAt(Z)>>>0;return f}var gG=8000,vN=500,uN=200,EN=100,gN=100,xN=2048,xG=30000,hN=20,cN=300000,z$,e1,If=null,Y7,P7,hG;var S$=O(()=>{b$();d();Tf();z$={},e1={},Y7=new Set,P7=new Map;hG=Promise.resolve()});var I2={};U0(I2,{setSkillEnabled:()=>L7,scanSkillDir:()=>B7,readFrontmatterValue:()=>w2,getStaleDisabledSkills:()=>D4,getSkillsTool:()=>PY,getSkills:()=>YY,getSkill:()=>A6,getBuiltinSkillsDir:()=>KY,getAllSkills:()=>P1,discoverSkills:()=>A$,collectLoadedSkillNames:()=>b4,buildSkillsPrompt:()=>XY,buildSkillReloadNote:()=>D7,buildSkillContent:()=>_7,attachSkills:()=>T2,SELF_CONFIG_SKILL:()=>YB});import{tool as ZB,jsonSchema as zB}from"ai";import{readFileSync as JB,existsSync as JY,readdirSync as KB,realpathSync as ZY}from"fs";import QB from"os";import S0 from"path";import{globSync as GB}from"glob";function KY(){return S0.join(b8(),"skills")}function PB(){let $=process.env.MIN_AGENT_NO_BUILTIN_SKILLS?.trim().toLowerCase();return $!=="1"&&$!=="true"}function XB($,f){let Z=S0.relative($,f);return Z===""||!Z.startsWith("..")&&!S0.isAbsolute(Z)}function Y1($){return Array.isArray($)?$.filter((f)=>typeof f==="string"):[]}function y2(){let $=y0(),f=new Set(Y1($.enabledSkills)),Z=new Set,z=new Map;for(let J of Y1($0().disabledSkills)){if(f.has(J))continue;Z.add(J),z.set(J,"global")}for(let J of Y1($.disabledSkills))Z.add(J),z.set(J,"project");return{disabled:Z,scopeOf:z}}function V7($,f){let Z=f.disabled.has($.name);return{...$,enabled:!Z,...Z?{disabledScope:f.scopeOf.get($.name)}:{}}}function MB(){let $=process.env.MIN_AGENT_SKILLS_DIRS?.trim();if($)return $.split(S0.delimiter).map((f)=>f.trim()).filter(Boolean).map((f)=>S0.resolve(f));return[S0.join(QB.homedir(),".agents","skills"),S0.join(process.cwd(),".min-agent","skills"),S0.join(process.cwd(),".agents","skills"),S0.join(process.cwd(),".opencode","skills"),S0.join(process.cwd(),".claude","skills")]}function FB($,f){if($===f)return!0;try{return ZY($)===ZY(f)}catch{return!1}}function B7($,f=QY){if(!JY($))return[];let Z=GB("**/SKILL.md",{cwd:$,absolute:!0,follow:!0,maxDepth:WB,ignore:["**/node_modules/**","**/.git/**","**/dist/**"]}).sort((J,K)=>J.split(S0.sep).length-K.split(S0.sep).length||J.localeCompare(K)),z=new Map;for(let J of Z){let K=NB(J,f);if(!K||z.has(K.name))continue;z.set(K.name,K)}return[...z.values()]}function zY($,f,Z){let z=$[f.name];if(z&&FB(z.location,f.location)){if(f.builtin&&!z.builtin)$[f.name]={...z,builtin:!0};return}if(z){let J=z.version&&f.version&&z.version!==f.version?` (version ${z.version} → ${f.version})`:"";Z?.(`\x1B[33m ⚠ Duplicate skill "${f.name}": ${f.location} overrides ${z.location}${J}\x1B[0m`)}$[f.name]=f}function A$($){let f=$?.silent?null:QY,Z={};for(let K of MB())for(let Q of B7(K,f))zY(Z,Q,f);if(PB()){let K=KY();for(let Q of B7(K,f))zY(Z,{...Q,builtin:XB(K,Q.location)},f)}let z=y2();O1=Object.fromEntries(Object.entries(Z).map(([K,Q])=>[K,V7(Q,z)]));let J=Object.keys(O1).length;if(J>0&&!$?.silent){let K=Object.values(O1).filter((Q)=>Q.enabled).length;f?.(`\x1B[90m Skills: ${K} enabled${J>K?`, ${J-K} disabled`:""}\x1B[0m`)}}function b6($){let f=$.trim(),Z=f.match(/^"([\s\S]*)"$/)??f.match(/^'([\s\S]*)'$/);return Z?Z[1]:f}function w2($,f){let Z=$.split(`
133
+ `),z=Z.findIndex((P)=>new RegExp(`^${f}:(\\s|$)`).test(P));if(z===-1)return null;let J=Z[z].slice(f.length+1).trim(),K=/^[|>][+-]?\d*$/.test(J),Q=[];for(let P of Z.slice(z+1)){if(P.trim()!==""&&!/^\s/.test(P))break;Q.push(P.replace(/^\s+/,""))}if(J&&!K){let P=Q.filter((X)=>X!=="").join(" ");return b6(P?`${J} ${P}`:J)}let Y=(K&&J.startsWith(">")?Q.join(" "):Q.join(`
134
+ `)).trim();return Y===""?null:Y}function GY($,f){let Z=$.split(`
135
+ `),z=Z.findIndex((P)=>new RegExp(`^\\s*${f}:(\\s|$)`).test(P));if(z===-1)return[];let J=Z[z],K=J.match(/^\s*/)[0].length,Q=J.slice(J.indexOf(":")+1).trim(),G=Q.match(/^\[([\s\S]*)\]$/);if(G)return G[1].split(",").map((P)=>b6(P)).filter(Boolean);if(Q)return[b6(Q)].filter(Boolean);let Y=[];for(let P of Z.slice(z+1)){if(P.trim()==="")continue;if(P.match(/^\s*/)[0].length<=K)break;let W=P.trim();if(!W.startsWith("- "))break;Y.push(b6(W.slice(2)))}return Y}function qB($){let f=$.split(`
136
+ `),Z=f.findIndex((P)=>/^metadata:(\s|$)/.test(P));if(Z===-1)return[];let z=f[Z].match(/^\s*/)[0].length,J=f.slice(Z+1).findIndex((P)=>{if(P.trim()===""||/^\s*$/.test(P))return!1;return P.match(/^\s*/)[0].length>z&&/^requires:(\s|$)/.test(P.trim())});if(J===-1)return[];let Q=f[Z+1+J].match(/^\s*/)[0].length,G=f.slice(Z+1+J+1).findIndex((P)=>{if(P.trim()===""||/^\s*$/.test(P))return!1;return P.match(/^\s*/)[0].length>Q&&/^bins:(\s|$)/.test(P.trim())});if(G===-1)return[];let Y=f.slice(Z+1+J+1+G).join(`
137
+ `);return GY(Y,"bins")}function NB($,f){let Z;try{Z=JB($,"utf-8").replace(/^\uFEFF/,"").replace(/\r\n/g,`
138
+ `)}catch(Y){return f?.(`\x1B[33m ⚠ Skill skipped (unreadable): ${$} — ${Y.message}\x1B[0m`),null}let z=Z.match(/^---[ \t]*\n([\s\S]*?)\n---[ \t]*(?:\n([\s\S]*))?$/);if(!z)return f?.(`\x1B[33m ⚠ Skill skipped (missing --- frontmatter block): ${$}\x1B[0m`),null;let J=z[1],K=w2(J,"name"),Q=w2(J,"description"),G=[!K&&"name",!Q&&"description"].filter(Boolean);if(!K||!Q)return f?.(`\x1B[33m ⚠ Skill skipped (frontmatter missing ${G.join(", ")}): ${$}\x1B[0m`),null;return{name:K,description:Q,location:$,content:(z[2]??"").trim(),enabled:!0,allowedTools:GY(J,"allowed-tools"),requiredBins:qB(J),version:w2(J,"version")??void 0,builtin:!1,alwaysLoad:BB(J,"always-load")}}function BB($,f){let Z=w2($,f);if(Z==null)return!1;let z=Z.trim().toLowerCase();return z==="true"||z==="yes"||z==="1"}function P1(){let $=y2();return Object.values(O1).map((f)=>V7(f,$))}function YY(){return P1().filter(($)=>$.enabled)}function A6($){let f=O1[$];return f?V7(f,y2()):void 0}function D4(){let $=y0();return[...new Set([...Y1($0().disabledSkills),...Y1($.disabledSkills),...Y1($.enabledSkills)])].filter((Z)=>!O1[Z])}function L7($,f,Z){if(Z==="global"){let J=$0(),K=new Set(Y1(J.disabledSkills));for(let Q of $)if(f)K.delete(Q);else K.add(Q);J.disabledSkills=[...K],I0(J)}else{let J=y0(),K=new Set(Y1(J.disabledSkills)),Q=new Set(Y1(J.enabledSkills)),G=new Set(Y1($0().disabledSkills));for(let Y of $)if(f)if(K.delete(Y),G.has(Y))Q.add(Y);else Q.delete(Y);else K.add(Y),Q.delete(Y);Q$({...J,disabledSkills:[...K],enabledSkills:[...Q]})}let z=y2();return $.map((J)=>{let K=!z.disabled.has(J);return{name:J,enabled:K,...K===f?{}:{blockedBy:z.scopeOf.get(J)}}})}function VB($){let f=[],Z=0,z=(J,K)=>{let Q;try{Q=KB(J,{withFileTypes:!0})}catch{return}for(let G of Q){if(G.name==="SKILL.md"||G.name.startsWith("."))continue;if(Z++,f.length<HB)f.push(G.isDirectory()?`${S0.join(J,G.name)}/`:S0.join(J,G.name));if(G.isDirectory()&&K>0)z(S0.join(J,G.name),K-1)}};return z($,2),{entries:f.sort(),total:Z}}function LB($){if($.length===0)return[];let f=(process.env.PATH??"").split(S0.delimiter).filter(Boolean),Z=process.platform==="win32"?["",".exe",".cmd",".bat",".ps1"]:[""],z=(J)=>f.some((K)=>Z.some((Q)=>JY(S0.join(K,`${J}${Q}`))));return $.filter((J)=>!z(J))}function _7($){let f=S0.dirname($.location),{entries:Z,total:z}=VB(f),J=LB($.requiredBins),K=[`<skill_content name="${_B($.name)}">`,`# Skill: ${$.name}`,"",`Base directory for this skill: ${f}`,"Relative paths in this skill (e.g., scripts/, reference/) are relative to this base directory.","",$.allowedTools.length?`This skill declares allowed-tools: ${_4($.allowedTools.join(", "))}. Prefer these tools while the skill is active.`:"",J.length?`⚠ Required binaries not found on PATH: ${J.join(", ")}. Tell the user to install them before running this skill's commands.`:"",Z.length?["<skill_files>",...Z.map((Q)=>` <file>${_4(Q)}</file>`),z>Z.length?` <note>${z-Z.length} more entries not listed; use glob on the base directory</note>`:"","</skill_files>"].filter(Boolean).join(`
139
+ `):"","",$.content,"</skill_content>"].filter(Boolean).join(`
140
+ `);return B0(K,{direction:"head",maxBytes:UB}).content}function PY($=new Set){return ZB({description:"Load a specialized skill when the task at hand matches one of the skills listed in the system prompt. Use this tool to inject the skill's instructions and resources into the current conversation. The skill name must match one of the skills listed in your system prompt under available_skills.",inputSchema:zB({type:"object",properties:{name:{type:"string",description:"The name of the skill from available_skills"}},required:["name"]}),execute:async({name:f})=>{let Z=y2(),z=Object.keys(O1).filter((K)=>!Z.disabled.has(K)).sort();if(Z.disabled.has(f))return`Skill "${f}" is disabled (${Z.scopeOf.get(f)} scope). Available skills: ${z.join(", ")||"none"}`;let J=O1[f];if(!J)return`Skill "${f}" not found. Available skills: ${z.length?z.join(", "):"none"}`;if($.has(f))return`Skill "${f}" is already loaded in this conversation — its instructions are still in effect above. Base directory: ${S0.dirname(J.location)}`;return $.add(f),_7(J)}})}function _4($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function _B($){return _4($).replace(/"/g,"&quot;")}function DB($){return $.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function XY($){if($.length===0)return"";return["Skills provide specialized instructions and workflows for specific tasks.","Use the skill tool to load a skill when a task matches its description.",$.some((Z)=>Z.alwaysLoad)?"Skills with always_load already have their full instructions in this prompt. Do not call the skill tool for those unless compaction dropped them.":"","","<available_skills>",...$.flatMap((Z)=>[" <skill>",` <name>${_4(Z.name)}</name>`,` <description>${_4(Z.description)}</description>`,` <location>${_4(Z.location)}</location>`,Z.alwaysLoad?" <always_load>true</always_load>":"",Z.builtin?" <builtin>true</builtin>":""," </skill>"]),"</available_skills>"].filter((Z)=>Z!=="").join(`
141
+ `)}function AB($){if(typeof $==="string")return $;if(!$||typeof $!=="object")return"";let f=$;if(typeof f.text==="string")return f.text;let Z=f.output;if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&typeof Z.value==="string")return Z.value;return""}function b4($){let f=new Set,Z=(z)=>{for(let J of z.matchAll(bB))f.add(DB(J[1]))};for(let z of $)if(typeof z.content==="string")Z(z.content);else if(Array.isArray(z.content))for(let J of z.content)Z(AB(J));return f}function D7($){if($.length===0)return"";return["## Skills Previously Loaded",...$.map((Z)=>{let z=O1[Z];return z?`${Z} (base dir: ${S0.dirname(z.location)})`:Z}).map((Z)=>`- ${Z}`),"Their full instructions were dropped during compaction. Re-call the skill tool if you still need them."].join(`
142
+ `)}function T2($,f){let Z=YY();if(Z.length===0)return"";let z=f??new Set,J=Z.filter((Q)=>Q.alwaysLoad);for(let Q of J)z.add(Q.name);$.skill=PY(z);let K=XY(Z);if(J.length===0)return K;return[K,"","The following skills are already loaded for this conversation. Follow them without calling the skill tool again.",...J.map(_7)].join(`
143
+ `)}var YB="self-config",WB=3,HB=20,UB=32768,O1,QY=($)=>process.stderr.write(`${$}
144
+ `),bB;var v$=O(()=>{d();X9();b$();O1={};bB=/<skill_content name="([^"]*)"/g});var NY={};U0(NY,{runWithInstructionTracker:()=>A7,resetActiveInstructionTracker:()=>C7,loadInstructions:()=>X1,getActiveInstructionTracker:()=>j7,findProjectInstructions:()=>FY,fetchRemoteInstructions:()=>qY,InstructionTracker:()=>C6});import{AsyncLocalStorage as jB}from"async_hooks";import{readFileSync as j6,existsSync as k2}from"fs";import r0 from"path";import CB from"os";function OB($,f){let Z=r0.relative($,f);return Z===""||!Z.startsWith("..")&&!r0.isAbsolute(Z)}function UY($,f){let Z=[],z=r0.resolve($);while(z!==r0.dirname(f)&&OB(f,z)){if(Z.push(z),z===f)break;z=r0.dirname(z)}return Z}class C6{loaded=new Set;isLoaded($){return this.loaded.has(r0.resolve($))}markLoaded($){this.loaded.add(r0.resolve($))}reset(){this.loaded.clear()}resolveForFile($){let f=[],Z=process.cwd();for(let z of UY(r0.dirname(r0.resolve($)),Z)){for(let J of HY){let K=r0.join(z,J);if(k2(K)&&!this.isLoaded(K))try{let Q=j6(K,"utf-8").trim();if(Q)this.markLoaded(K),f.push(`Instructions from: ${K}
145
+ ${Q}`)}catch{}}if(f.length>0)break}return f}}async function A7($){return b7.run(new C6,$)}function j7(){return b7.getStore()??MY}function C7(){let $=b7.getStore();if($)$.reset();else MY.reset()}function FY(){let $=[],f=r0.parse(process.cwd()).root;for(let Z of UY(process.cwd(),f)){let z=r0.join(Z,".min-agent","AGENTS.md");if(k2(z)){$.push(z);break}let J=HY.find((K)=>k2(r0.join(Z,K)));if(J){$.push(r0.join(Z,J));break}}return $}function wB(){let $=[],f=df();if(k2(f))$.push(f);return $}function yB(){let f=$0().instructions??[],Z=[];for(let z of f){if(z.startsWith("http://")||z.startsWith("https://"))continue;let J=z.startsWith("~/")?r0.join(CB.homedir(),z.slice(2)):r0.isAbsolute(z)?z:r0.resolve(process.cwd(),z);if(k2(J))Z.push(J)}return Z}async function IB($){let f=WY.get($);if(f&&Date.now()-f.fetchedAt<TB)return f.text;try{let Z=await fetch($,{signal:AbortSignal.timeout(5000)});if(Z.ok){let z=await Z.text();if(z.trim())return WY.set($,{fetchedAt:Date.now(),text:z}),z}}catch{}return null}async function qY($){let f=$0(),Z=$??f.instructions??[];return(await Promise.all(Z.filter((J)=>J.startsWith("http://")||J.startsWith("https://")).map(async(J)=>{let K=await IB(J);return K?`Instructions from: ${J}
146
+ ${K}`:""}))).filter(Boolean)}async function X1(){let $=[];for(let Z of wB())try{let z=j6(Z,"utf-8").trim();if(z)$.push(`Instructions from: ${Z}
147
+ ${z}`)}catch{}for(let Z of FY())try{let z=j6(Z,"utf-8").trim();if(z)$.push(`Instructions from: ${Z}
148
+ ${z}`)}catch{}for(let Z of yB())try{let z=j6(Z,"utf-8").trim();if(z)$.push(`Instructions from: ${Z}
149
+ ${z}`)}catch{}let f=await qY();return $.push(...f),$}var HY,b7,MY,TB=60000,WY;var Zf=O(()=>{d();HY=["AGENTS.md","RULES.md","CLAUDE.md"];b7=new jB,MY=new C6;WY=new Map});function VY($,f){let Z=Error(`${BY}: no ${$} for ${f}ms`);return Z.name="ProviderStallError",Z}function O6($,f=4){let Z=[],z=$;for(let J=0;J<f&&z!=null;J++){if(z instanceof Error){Z.push(z.message),z=z.cause;continue}Z.push(String(z));break}return Z.join(" | ")}function y7($){return O6($).includes(BY)}function kB($,f){let Z=typeof f?.body==="string"?f.body:"",z=`bytes=${Z.length}`;try{let J=JSON.parse(Z||"{}"),K=J.tools?.map((Q)=>Q.function?.name??"?")??[];z+=` model=${J.model??"?"} messages=${J.messages?.length??0} tools=${K.length} stream=${J.stream??!1}`}catch{}return`trace request ${$} ${z}`}function nB($,f,Z){if(!$.body||f<=0)return $;let J=$.body.getReader(),K,Q=()=>{if(K)clearTimeout(K);K=void 0},G=new ReadableStream({async pull(Y){(()=>{Q(),K=setTimeout(()=>Z(VY("stream",f)),f)})();try{let{done:X,value:W}=await J.read();if(Q(),X){Y.close();return}Y.enqueue(W)}catch(X){Q(),Y.error(X)}},cancel(Y){return Q(),J.cancel(Y)}});return new Response(G,{status:$.status,statusText:$.statusText,headers:$.headers})}function LY($={}){let f=$.firstByteTimeoutMs??O7,Z=$.idleTimeoutMs??w7,z=$.fetchImpl??fetch,J=$.now??Date.now,K=$.trace??!1;return async(Q,G)=>{let Y=typeof Q==="string"?Q:Q instanceof URL?Q.toString():Q.url,P=new AbortController,X,W=(U)=>{X=U,Z0("warn",`${U.message} (${Y})`),P.abort(U)},H=G?.signal,M=()=>P.abort(H?.reason);if(H)if(H.aborted)M();else H.addEventListener("abort",M,{once:!0});let F;if(f>0)F=setTimeout(()=>W(VY("first byte",f)),f);if(K)Z0("info",kB(Y,G));let q=J();try{let U=await z(Q,{...G,signal:P.signal});if(F)clearTimeout(F);if(K)Z0("info",`trace response ${Y} status=${U.status} ttfb=${J()-q}ms`);return nB(U,Z,W)}catch(U){if(F)clearTimeout(F);if(X)throw X;throw U}finally{H?.removeEventListener("abort",M)}}}var BY="min-agent: provider stalled",O7=180000,w7=90000;var T7=O(()=>{Tf()});function A4($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function RB($){return $.replace(/<\/?(?:think|thinking)>/gi,"")}function w6($,f){if(!A4($))return"";return typeof $[f]==="string"?$[f]:""}function SB($){if(!Array.isArray($))return"";return $.map((f)=>{let Z=w6(f,"text");if(Z)return Z;return w6(f,"content")}).join("")}function I7($){if(typeof $==="string")return $;if(!A4($))return"";return w6($,"content")||w6($,"text")}function vB($){let f=SB($.reasoning_details),Z=I7($.reasoning_content)||I7($.reasoning)||I7($.thinking);return RB(`${f}${Z}`)}function uB(){let $="";return(f)=>{if(!f)return"";if($&&f.startsWith($)){let Z=f.slice($.length);return $=f,Z}return $+=f,f}}function _Y($,f){let Z=f(vB($));if(!Z)return!1;let z=typeof $.content==="string"?$.content:"";return $.content=`<think>${Z}</think>${z}`,!0}function EB($,f=(Z)=>Z){if(!A4($)||!Array.isArray($.choices))return!1;let Z=!1;for(let z of $.choices){if(!A4(z))continue;if(A4(z.delta)&&_Y(z.delta,f))Z=!0;if(A4(z.message)&&_Y(z.message,f))Z=!0}return Z}function gB($,f){let Z=$.replace(/\r$/,"");if(!Z.startsWith("data:"))return $;let z=Z.slice(5).trim();if(!z||z==="[DONE]")return $;try{let J=JSON.parse(z);if(!EB(J,f))return $;let K=$.startsWith("data: ")?"data: ":"data:",Q=$.endsWith("\r")?"\r":"";return`${K}${JSON.stringify(J)}${Q}`}catch{return $}}function DY($,f){let Z=$.endsWith(`
150
+ `);return(Z?$.slice(0,-1):$).split(`
151
+ `).map((J)=>gB(J,f)).join(`
152
+ `)+(Z?`
153
+ `:"")}function xB($){let f=new TextDecoder,Z=new TextEncoder,z=$.getReader(),J=uB(),K="";return new ReadableStream({async pull(Q){for(;;){let{done:G,value:Y}=await z.read();if(G){if(K+=f.decode(),K)Q.enqueue(Z.encode(DY(K,J)));Q.close();return}K+=f.decode(Y,{stream:!0});let P=K.lastIndexOf(`
154
+ `);if(P<0)continue;let X=K.slice(0,P+1);K=K.slice(P+1),Q.enqueue(Z.encode(DY(X,J)));return}},cancel(Q){return z.cancel(Q)}})}function hB($){let f=($.headers.get("content-type")??"").toLowerCase();if(f.includes("event-stream"))return!0;if(!f||f.startsWith("text/plain"))return!0;return!1}function bY($){if(!$.body||$.status>=400)return $;if(!hB($))return $;return new Response(xB($.body),{status:$.status,statusText:$.statusText,headers:$.headers})}var OY={};U0(OY,{resolveModelForProvider:()=>CY,resolveModel:()=>p$,modelFetch:()=>jY});import{createOpenAI as k7}from"@ai-sdk/openai";function AY($,f){let Z=typeof $==="string"?Number($):$;if(typeof Z!=="number"||!Number.isFinite(Z)||Z<0)return f;return Z}function jY(){let $=J0(),f=LY({firstByteTimeoutMs:AY(process.env.MIN_AGENT_REQUEST_TIMEOUT_MS??$.agent?.requestTimeoutMs,O7),idleTimeoutMs:AY(process.env.MIN_AGENT_STREAM_IDLE_TIMEOUT_MS??$.agent?.streamIdleTimeoutMs,w7),trace:process.env.MIN_AGENT_TRACE==="1"||process.env.MIN_AGENT_TRACE==="true"});return(Z,z)=>wJ(f,Z,z).then(bY)}function CY($,f){if(!$.baseURL||!$.apiKey)throw Error("Not configured. Run: min-agent setup");let Z=f??$.defaultModel;if(!Z)throw Error("No model specified. Run: min-agent setup");let z=jY();switch($.type??"openai-compatible"){case"openai":return k7({apiKey:$.apiKey,fetch:z}).chat(Z);case"ollama":return k7({baseURL:N1($.baseURL),apiKey:$.apiKey||"ollama",fetch:z}).chat(Z);case"openai-compatible":return k7({baseURL:$.baseURL,apiKey:$.apiKey,fetch:z}).chat(Z);default:throw Error(`Unknown provider type: ${$.type}`)}}function p$($,f){let Z=J0(),z=f?Z.providers?.find((J)=>J.name===f):e(Z);if(!z)throw Error(f?`Provider "${f}" not found`:"Not configured. Run: min-agent setup");return CY(z,$)}var Rf=O(()=>{d();T7();L9()});var v7={};U0(v7,{getContextWindowInfo:()=>d$,getContextWindow:()=>$V,extractModelContextLength:()=>y6,DEFAULT_CONTEXT_WINDOW:()=>j4});import{readFileSync as cB,mkdirSync as mB,existsSync as rB}from"fs";import wY from"path";function TY(){return wY.join(X0(),"context-window-cache.json")}function IY(){let $=TY();if(!rB($))return{};try{return JSON.parse(cB($,"utf-8"))}catch{return{}}}function pB($){let f=TY();mB(wY.dirname(f),{recursive:!0}),T0(f,JSON.stringify($))}function dB($){return $==="fallback"?oB:yY}function iB($){let f=tf($);if(f?.contextWindow)return{tokens:f.contextWindow,source:"detected"};let Z=R7.get($);if(Z&&Date.now()-Z.timestamp<=dB(Z.source))return{tokens:Z.contextWindow,source:Z.source};let z=IY()[$];if(!z||z.source!=="detected")return null;if(Date.now()-z.timestamp>yY)return null;return R7.set($,{...z,source:"detected"}),{tokens:z.contextWindow,source:"detected"}}function n2($,f,Z){let z={contextWindow:f,timestamp:Date.now(),source:Z};if(R7.set($,z),Z!=="detected")return;let J=IY();J[$]=z,pB(J)}function y6($){if(!$||typeof $!=="object")return null;let f=$,Z=[f,f.meta,f.limits,f.limit,f.model_info],z=["context_length","max_model_len","max_model_length","max_context_length","context_window","max_input_tokens","max_total_tokens","context","general.context_length"];for(let J of Z){if(!J||typeof J!=="object")continue;let K=J;for(let Q of z){let G=K[Q];if(typeof G==="number"&&Number.isFinite(G)&&G>=4096)return Math.floor(G)}}return null}function S7($,f){let Z=$.find((z)=>z&&typeof z==="object"&&z.id===f);if(Z)return Z;return $.find((z)=>{if(!z||typeof z!=="object")return!1;let J=z.id;return typeof J==="string"&&(J.endsWith(`/${f}`)||f.endsWith(`/${J}`))})}async function lB($,f,Z){if(!$.includes("openrouter"))return null;try{let z=await fetch("https://openrouter.ai/api/v1/models",{headers:{Authorization:`Bearer ${f}`},signal:AbortSignal.timeout(8000)});if(!z.ok)return null;let J=await z.json();return y6(S7(J.data??[],Z))}catch{return null}}async function tB($,f,Z){if(!$.includes("vllm"))return null;try{let z=`${$.replace(/\/$/,"")}/models`,J=await fetch(z,{headers:{Authorization:`Bearer ${f}`},signal:AbortSignal.timeout(5000)});if(!J.ok)return null;let K=await J.json();return y6(S7(K.data??[],Z))}catch{return null}}async function kY($,f,Z){if(!$)return null;try{let z=`${$.replace(/\/$/,"")}/models`,J=await fetch(z,{headers:{Authorization:`Bearer ${f}`},signal:AbortSignal.timeout(8000)});if(!J.ok)return null;let K=await J.json(),Q=Array.isArray(K)?K:K.data??[];return y6(S7(Q,Z))}catch{return null}}async function aB($,f){if(!$.includes("localhost")&&!$.includes("127.0.0.1")&&!$.includes("ollama"))return null;return(await s4(f,$))?.contextWindow??null}async function sB($,f){let Z=await s4(f,$);if(Z?.contextWindow)return n2(f,Z.contextWindow,"detected"),{tokens:Z.contextWindow,source:"detected"};let z=await kY($,"ollama",f);if(z){let J=Math.min(z,B9);return n2(f,J,"detected"),{tokens:J,source:"detected"}}return n2(f,j8,"fallback"),{tokens:j8,source:"fallback"}}async function eB($,f){let Z=e($),z=Z?.baseURL??"",J=Z?.apiKey??"";if(Z?.type==="ollama")return sB(z,f);let K=await A8(f,z);if(K?.contextWindow)return{tokens:K.contextWindow,source:"detected"};let G=(await Promise.all([lB(z,J,f),aB(z,f),tB(z,J,f),kY(z,J,f)])).find((Y)=>Y!==null);if(G)return n2(f,G,"detected"),{tokens:G,source:"detected"};return n2(f,j4,"fallback"),{tokens:j4,source:"fallback"}}async function d$($){let f=J0(),Z=e(f);if(Z?.contextWindow)return{tokens:Z.contextWindow,source:"config"};let z=$??Z?.defaultModel;if(!z)return{tokens:j4,source:"fallback"};if(Z?.type==="ollama"){let Q=h1(z,Z.baseURL);if(Q?.contextWindow)return{tokens:Q.contextWindow,source:"detected"}}else{let Q=iB(z);if(Q)return Q}let J=n7.get(z);if(J)return J;let K=eB(f,z);n7.set(z,K);try{return await K}finally{n7.delete(z)}}async function $V($){return(await d$($)).tokens}var j4=512000,yY=604800000,oB=600000,R7,n7;var Sf=O(()=>{F$();d();F9();O8();R7=new Map,n7=new Map});var n6={};U0(n6,{pruneToolOutputs:()=>R2,needsCompaction:()=>m7,estimateTokens:()=>y1,estimateStringTokens:()=>I6,estimateOverheadTokens:()=>k6,compactMessages:()=>v2,applyToolPrune:()=>S2,TokenTracker:()=>zf,PRUNE_TARGET_RATIO:()=>c7,PRUNE_PRESSURE_RATIO:()=>h7,COMPACTION_RATIO:()=>T6});import{generateText as fV}from"ai";class zf{_lastInputTokens=0;_totalOutputTokens=0;_totalInputTokens=0;listeners=new Set;subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}emit(){for(let $ of this.listeners)$()}update($){this._totalInputTokens+=$.inputTokens??0,this._totalOutputTokens+=$.outputTokens??0,this._lastInputTokens=$.inputTokens??0,this.emit()}add($){this._totalInputTokens+=$.inputTokens??0,this._totalOutputTokens+=$.outputTokens??0,this.emit()}get lastInputTokens(){return this._lastInputTokens}get totalInputTokens(){return this._totalInputTokens}get totalOutputTokens(){return this._totalOutputTokens}summary(){return`context: ${this._lastInputTokens} | total in: ${this._totalInputTokens} out: ${this._totalOutputTokens}`}reset(){this._lastInputTokens=0,this._totalInputTokens=0,this._totalOutputTokens=0,this.emit()}resetContext(){this._lastInputTokens=0,this.emit()}}function HV($){return $>=11904&&$<=40959||$>=63744&&$<=64255||$>=65280&&$<=65519||$>=131072&&$<=262141||$>=12352&&$<=12543||$>=44032&&$<=55215}function w1($){let f=0,Z=0;for(let z of $)if(HV(z.codePointAt(0)??0))Z++;else f++;return f/4+Z*0.7}function MV($){if(typeof $.text==="string")return w1($.text);if($.type==="image"||$.type==="file")return UV;if($.type==="tool-call"&&$.input!==void 0)try{return w1(JSON.stringify($.input))}catch{return 0}return 0}function uY($){let f=$.content;if(typeof f==="string")return w1(f);if(Array.isArray(f)){let Z=0;for(let z of f){if(cY(z)){let J=gY(z);Z+=J?w1(J):0;continue}Z+=MV(z)}return Z}return 0}function y1($){return Math.ceil($.reduce((f,Z)=>f+uY(Z),0))}function I6($){return Math.ceil(w1($))}function E7($){return Math.ceil(uY($))}function k6($,f){let Z=w1($);for(let[z,J]of Object.entries(f??{})){Z+=w1(z);let K=J;if(typeof K?.description==="string")Z+=w1(K.description);let Q=K?.inputSchema??K?.parameters;if(Q!=null)try{Z+=w1(JSON.stringify(Q))}catch{}}return Math.ceil(Z)}async function EY($){if($?.maxTokens)return{tokens:$.maxTokens,source:"config"};try{return await d$($?.modelId)}catch{return{tokens:j4,source:"fallback"}}}async function m7($,f,Z){if(Z?.force)return!0;let J=(await EY(Z)).tokens*T6,K=Z?.overheadTokens??0;if(f&&f.lastInputTokens>0)return f.lastInputTokens>J;return y1($)+K>J}function gY($){let f=$.output;if(typeof f==="string")return f;if(f&&typeof f==="object"&&"value"in f){let Z=f.value;if(typeof Z==="string")return Z}return null}function FV($){return $.includes(vY)}function qV($){let f=/Full output saved to:\s*(\S+)/.exec($);return f?`, full output: ${f[1]}`:""}function NV($,f){return`[${vY}: ${$}, ${f.length} chars${qV(f)}]`}function g7($){if(typeof $==="string"){if($.length<=u7)return $;return`${$.slice(0,u7)}
155
+
156
+ [... ${$.length-u7} chars omitted from old tool call ...]`}if(Array.isArray($))return $.map(g7);if($&&typeof $==="object")return Object.fromEntries(Object.entries($).map(([f,Z])=>[f,g7(Z)]));return $}function xY($){if(typeof $.content==="string")return $.content.includes("<skill_content");if(Array.isArray($.content))return $.content.some((f)=>(f.type==="tool-result"||f.type==="tool-call")&&("toolName"in f)&&WV.has(f.toolName));return!1}function BV($){let f=[];for(let Z=0;Z<$.length;Z++){let z=$[Z].role;if(z==="user"||z==="assistant")f.push(Z)}return f}function VV($){let f=[];for(let Z=0;Z<$.length;Z++)if($[Z].role==="assistant")f.push(Z);return f}function LV($){let f=VV($);if(f.length<=nY)return 0;return f[f.length-nY]}function _V($){if($.role!=="tool"||!Array.isArray($.content)||xY($))return null;let f=[...$.content],Z=!1;for(let z=0;z<f.length;z++){let J=f[z];if(J.type!=="tool-result")continue;let K=gY(J);if(!K||FV(K)||K.length<=GV)continue;f[z]={...J,output:{type:"text",value:NV(J.toolName,K)}},Z=!0}return Z?{...$,content:f}:null}function DV($){if($.role!=="assistant"||!Array.isArray($.content)||xY($))return null;let f=[...$.content],Z=!1;for(let z=0;z<f.length;z++){let J=f[z];if(J.type!=="tool-call"||J.input===void 0)continue;let K=g7(J.input),Q=K===J.input;if(!Q)try{Q=JSON.stringify(K)===JSON.stringify(J.input)}catch{Q=!1}if(Q)continue;f[z]={...J,input:K},Z=!0}return Z?{...$,content:f}:null}function R2($,f={}){let Z=LV($),z=[];for(let Q=0;Q<Z;Q++){let G=$[Q],Y=G.role==="tool"?_V(G):G.role==="assistant"?DV(G):null;if(!Y)continue;z.push({index:Q,pruned:Y,tokensSaved:Math.max(0,E7(G)-E7(Y))})}if(z.length===0)return $;let J=f.pressureTokens??f.targetTokens,K=new Map;if(f.force||J==null)for(let Q of z)K.set(Q.index,Q.pruned);else{let Q=y1($)+(f.overheadTokens??0);if(Q<=J)return $;let G=f.targetTokens??J;for(let Y of[...z].sort((P,X)=>X.tokensSaved-P.tokensSaved)){if(Q<=G)break;if(Y.tokensSaved<=0)continue;K.set(Y.index,Y.pruned),Q-=Y.tokensSaved}}if(K.size===0)return $;return $.map((Q,G)=>K.get(G)??Q)}function S2($,f={}){let Z=R2($,f);if(Z===$)return!1;return $.length=0,$.push(...Z),!0}async function bV($,f){let Z=await EY(f),z=Math.min(QV,Math.max(KV,Math.floor(Z.tokens*JV))),J=BV($);if(J.length===0)return{headEnd:0,tailStart:0};let K=0,Q=$.length;for(let P=J.length-1;P>=0;P--){let X=J[P],W=P<J.length-1?J[P+1]:$.length,H=0;for(let M=X;M<W;M++)H+=E7($[M]);if(K+H>z&&K>0)break;K+=H,Q=X}if(Q>=$.length)Q=J[J.length-1];let G=f?.keepRecentTurns??zV,Y=[];for(let P=0;P<$.length;P++)if($[P].role==="user")Y.push(P);if(Q===0&&Y.length>G)Q=Y[Y.length-G];return{headEnd:Q,tailStart:Q}}function jV($){let Z=J0().compaction?.model;if(Z)return p$(Z);return $}function CV($){let f=$[0];if(f?.role==="system"&&typeof f.content==="string"&&f.content.includes("[Context Summary"))return f.content.match(/\[Context Summary[^\]]*\]\n\n([\s\S]*)/)?.[1]?.split(hY)[0]?.trimEnd();return}function OV($){let f=$[0];if(f?.role!=="system"||typeof f.content!=="string")return[];let Z=f.content.split(hY)[1];if(!Z)return[];return Z.split(`
157
+ `).filter((z)=>z.startsWith("- ")).map((z)=>z.slice(2).replace(/\s*\(base dir:.*$/,"").trim()).filter(Boolean)}function wV($,f){let Z=f?.trim()?["The original user goal that must be preserved in ## Goal:",f.trim(),""].join(`
158
+ `):"",z=$?["Update the anchored summary below using the conversation history above.","Preserve still-true details, remove stale details, and merge in the new facts.","","<previous-summary>",$,"</previous-summary>"].join(`
159
+ `):"Create a new anchored summary from the conversation history above.";return[Z,z,"",ZV].filter(Boolean).join(`
160
+ `)}function cY($){return typeof $==="object"&&$!==null&&"type"in $&&$.type==="tool-result"}function x7($,f){if($.length<=f)return $;return`${$.slice(0,f)}
161
+ [... ${$.length-f} chars omitted ...]`}function SY($){return XV.has($)?PV:YV}function yV($){if(typeof $.content==="string")return $.content;if(Array.isArray($.content)){let f=[];for(let Z of $.content)if("text"in Z&&typeof Z.text==="string")f.push(Z.text);else if(Z.type==="tool-call"){let z="toolName"in Z?String(Z.toolName):"tool",J="";try{J=JSON.stringify("input"in Z?Z.input:void 0)}catch{J=""}f.push(`[tool-call ${z}] ${x7(J,SY(z))}`)}else if(cY(Z)){let z=Z.toolName||"tool",J=Z.output,K=typeof J==="string"?J:J&&typeof J==="object"&&("value"in J)&&J.value!=null?String(J.value):JSON.stringify(J);f.push(`[tool-result ${z}] ${x7(K,SY(z))}`)}return f.join(`
162
+ `)}return""}function TV($){let f=$.map((z)=>`[${z.role}]: ${x7(yV(z),1500)}`).join(`
163
+
164
+ `);if(f.length<=RY)return f;let Z=Math.floor((RY-40)/2);return`${f.slice(0,Z)}
165
+
166
+ [... middle omitted ...]
167
+
168
+ ${f.slice(-Z)}`}async function IV($,f,Z){let z=()=>fV({model:$,system:AV,messages:[{role:"user",content:f}],abortSignal:Z?.abortSignal});try{let J=await z();if(J.text.trim())return J;console.error("[compaction] empty summary, retrying once")}catch(J){if(Z?.abortSignal?.aborted)throw J;console.error("[compaction] summary attempt failed, retrying once:",J)}return z()}async function v2($,f,Z){let z=R2($,{force:!0}),J=()=>z===$?{messages:$,compacted:!1}:{messages:z,compacted:!0},{headEnd:K,tailStart:Q}=await bV(z,Z);if(K<=0)return J();let G=z.slice(0,K),Y=z.slice(Q),P=CV(G),X=TV(G),W=jV(f);try{let H=wV(P,Z?.taskGoal),M=await IV(W,X+`
169
+
170
+ `+H,Z),F=M.text,q=b4(Y),U=[...new Set([...b4(G),...OV(G)])].filter((D)=>!q.has(D)),N=D7(U);return{messages:[{role:"system",content:`[Context Summary - Previous conversation was compacted]
171
+
172
+ ${F}${N?`
173
+
174
+ ${N}`:""}`},...Y],compacted:!0,usage:M.usage}}catch(H){return console.error("[compaction] summary generation failed, keeping pruned messages:",H),J()}}var ZV=`Output exactly the Markdown structure shown below. Keep the section order unchanged.
175
+
176
+ ## Goal
177
+ - [single-sentence task summary]
178
+
179
+ ## Constraints & Preferences
180
+ - [user constraints, preferences, specs, or "(none)"]
181
+
182
+ ## Progress
183
+ ### Done
184
+ - [completed work or "(none)"]
185
+
186
+ ### In Progress
187
+ - [current work or "(none)"]
188
+
189
+ ### Blocked
190
+ - [blockers or "(none)"]
191
+
192
+ ## Key Decisions
193
+ - [decision and why, or "(none)"]
194
+
195
+ ## Next Steps
196
+ - [ordered next actions or "(none)"]
197
+
198
+ ## Critical Context
199
+ - [important technical facts, numbers, dates, scores, URLs, errors, open questions, or "(none)"]
200
+
201
+ ## Relevant Files
202
+ - [file or directory path: why it matters, or "(none)"]
203
+
204
+ Rules:
205
+ - Keep every section, even when empty.
206
+ - Use terse bullets, not prose paragraphs.
207
+ - Preserve exact file paths, commands, error strings, and identifiers when known.
208
+ - Do not mention the summary process or that context was compacted.`,T6=0.75,h7=0.6,c7=0.45,zV=2,JV=0.04,KV=2000,QV=48000,nY=4,GV=400,u7=500,YV=400,PV=2500,RY=1e5,vY="old tool output omitted",XV,WV,UV=800,AV=`You are an anchored context summarization assistant for coding sessions.
209
+
210
+ Summarize only the conversation history you are given. The newest turns may be kept verbatim outside your summary, so focus on the older context that still matters for continuing the work.
211
+
212
+ If the prompt includes a <previous-summary> block, treat it as the current anchored summary. Update it with the new history by preserving still-true details, removing stale details, and merging in new facts.
213
+
214
+ Always follow the exact output structure requested by the user prompt. Keep every section, preserve exact file paths, identifiers, numeric scores, dates, and URLs when known, and prefer terse bullets over paragraphs.
215
+
216
+ When the history includes web search or fetched pages, copy concrete facts (names, scores, dates, URLs) into Critical Context. Do not drop numbers.
217
+
218
+ Do not answer the conversation itself. Do not mention that you are summarizing, compacting, or merging context. Respond in the same language as the conversation.`,hY="## Skills Previously Loaded";var T1=O(()=>{d();Rf();Sf();v$();XV=new Set(["search_web","web_fetch"]),WV=new Set(["skill"])});var R6={};U0(R6,{getModelPrice:()=>u2,formatCost:()=>hV,estimateCost:()=>E2});import{readFileSync as kV,mkdirSync as nV,existsSync as RV}from"fs";import oY from"path";function pY(){return oY.join(X0(),"pricing-cache.json")}function dY(){let $=pY();if(!RV($))return{};try{return JSON.parse(kV($,"utf-8"))}catch{return{}}}function vV($){let f=pY();nV(oY.dirname(f),{recursive:!0}),T0(f,JSON.stringify($))}function uV($){let f=o7.get($);if(f&&Date.now()-f.timestamp<=mY)return f;let Z=dY()[$];if(Z&&Date.now()-Z.timestamp<=mY)return o7.set($,Z),Z;return null}function EV($,f){let Z={price:f,timestamp:Date.now()};o7.set($,Z);let z=dY();z[$]=Z,vV(z)}function gV($){let f=$0().pricing?.[$];if(!f)return null;if(typeof f.inputPerMillion!=="number"||typeof f.outputPerMillion!=="number")return null;return{inputPerMillion:f.inputPerMillion,outputPerMillion:f.outputPerMillion}}async function xV($){try{let f=await fetch("https://models.dev/api.json",{signal:AbortSignal.timeout(1e4)});if(!f.ok)return null;let Z=await f.json();for(let z of Object.values(Z)){if(!z.models)continue;for(let[J,K]of Object.entries(z.models))if(J===$||J.endsWith(`/${$}`)||$.endsWith(`/${J}`)){let Q=K?.pricing;if(Q&&typeof Q.input==="number"&&typeof Q.output==="number")return{inputPerMillion:Q.input,outputPerMillion:Q.output}}}return null}catch{return null}}async function u2($){let f=gV($);if(f)return f;let Z=uV($);if(Z)return Z.price;let z=rY.get($);if(z!==void 0&&Date.now()-z<=SV)return null;let J=r7.get($);if(J)return J;let K=xV($).then((Q)=>{if(Q)EV($,Q);else rY.set($,Date.now());return Q});r7.set($,K);try{return await K}finally{r7.delete($)}}function E2($,f){if(!f)return null;let Z=$.inputTokens/1e6*f.inputPerMillion+$.outputTokens/1e6*f.outputPerMillion;return Z>0?Z:null}function hV($){if($===null)return"--";return $>=0.1?`$${$.toFixed(3)}`:`$${$.toFixed(4)}`}var mY=604800000,o7,r7,SV=3600000,rY;var C4=O(()=>{F$();d();o7=new Map,r7=new Map,rY=new Map});var sY={};U0(sY,{resolveBashTimeout:()=>aY,resetSandboxWarningShown:()=>pV,killActiveProcesses:()=>i7,executeBash:()=>v6,bashTool:()=>l7,DEFAULT_BASH_TIMEOUT_MS:()=>tY});import{tool as cV,jsonSchema as mV}from"ai";import{spawn as rV}from"child_process";import oV from"path";function aY($){if(typeof $==="number"&&Number.isFinite($)&&$>=0)return Math.floor($);let f=J0().tools?.bashTimeoutMs;if(typeof f==="number"&&Number.isFinite(f)&&f>=0)return Math.floor(f);return tY}function pV(){d7=!1}function dV(){if(p7)return;p7=!0;let $=()=>{if(vf.size===0){process.removeListener("SIGINT",$),p7=!1,process.kill(process.pid,"SIGINT");return}for(let f of[...vf])iV(f)};process.on("SIGINT",$)}function iV($){if($.killed=!0,$.settled=!0,$.timer)clearTimeout($.timer);t7($.proc.pid),$.resolve(S6($)+`
219
+
220
+ [Command interrupted by user.]`)}function i7(){for(let $ of vf){if($.killed=!0,$.settled=!0,$.timer)clearTimeout($.timer);t7($.proc.pid),$.resolve(S6($)+`
221
+
222
+ [Command interrupted by user.]`)}vf.clear()}async function v6($,f,Z){return dV(),new Promise((z)=>{let J=process.platform==="win32",K=Z?oV.resolve(process.cwd(),Z):process.cwd(),Q=o3($,K,{...process.env,...J?{PYTHONIOENCODING:"utf-8"}:{}});if("error"in Q){z(Q.error);return}let G="";if(Q.warning&&!d7)d7=!0,G=`${Q.warning}
223
+
224
+ `;let Y={proc:void 0,resolve:(H)=>z(G+H),stdoutChunks:[],stderrChunks:[],killed:!1,settled:!1,stdoutTruncated:!1,stderrTruncated:!1};vf.add(Y);let P=rV(Q.file,Q.args,{shell:Q.shell,cwd:Q.cwd,stdio:["ignore","pipe","pipe"],detached:process.platform!=="win32",env:Q.env});Y.proc=P;let X=(H,M)=>(F)=>{if(H.reduce((U,N)=>U+N.byteLength,0)>=lY){Y[M]=!0;return}H.push(F)};P.stdout?.on("data",X(Y.stdoutChunks,"stdoutTruncated")),P.stderr?.on("data",X(Y.stderrChunks,"stderrTruncated"));let W=aY(f);if(W>0)Y.timer=setTimeout(()=>{Y.killed=!0,Y.settled=!0,t7(P.pid),Y.resolve(S6(Y)+`
225
+
226
+ [Command timed out after ${W}ms and was killed. Retry with a larger timeout if needed.]`)},W);P.on("close",(H)=>{if(vf.delete(Y),Y.timer)clearTimeout(Y.timer);if(Y.killed||Y.settled)return;Y.settled=!0;let M=S6(Y);if(H===0)Y.resolve(M||"(no output)");else Y.resolve(`Exit code ${H}
227
+ ${M||"(no output)"}`)}),P.on("error",(H)=>{if(vf.delete(Y),Y.timer)clearTimeout(Y.timer);if(Y.killed||Y.settled)return;Y.settled=!0,Y.resolve(`Error: ${H.message}`)})})}function S6($){let f=Buffer.concat($.stdoutChunks).toString("utf-8").trim(),Z=Buffer.concat($.stderrChunks).toString("utf-8").trim(),z=f;if(Z)z=z?`${z}
228
+
229
+ --- stderr ---
230
+ ${Z}`:Z;if($.stdoutTruncated||$.stderrTruncated)z+=`
231
+
232
+ [Output capped at ${lY} bytes; the remainder was discarded.]`;if(Buffer.byteLength(z,"utf-8")<=iY)return z;let K=e5(z);return`${lV(z,iY)}
233
+
234
+ Full output saved to: ${K}`}function lV($,f){let Z=Buffer.from($,"utf-8"),z=Math.floor(f*0.5),J=Math.floor(f*0.1),K=z;while(K>0&&(Z[K]&192)===128)K--;let Q=Z.length-J;while(Q<Z.length&&(Z[Q]&192)===128)Q++;return Z.subarray(0,K).toString("utf-8")+`
235
+
236
+ ...(truncated, ${Z.length} bytes total)...
237
+
238
+ `+Z.subarray(Math.max(Q,K)).toString("utf-8")}function t7($){if(!$)return;try{if(process.platform!=="win32")process.kill(-$,"SIGTERM"),setTimeout(()=>{try{process.kill(-$,"SIGKILL")}catch{}},3000);else process.kill($,"SIGTERM")}catch{}}var lY=204800,iY=1e5,tY=600000,vf,p7=!1,d7=!1,l7;var g2=O(()=>{G$();b$();E0();d();vf=new Set;l7=cV({description:"Run a shell command. Use this for system operations, running builds, tests, git commands, etc. The command runs in the current working directory (or `cwd` if specified). Commands are killed after 10 minutes by default; set `timeout` for anything expected to run longer (or shorter).",inputSchema:mV({type:"object",properties:{command:{type:"string",description:"The shell command to execute"},timeout:{type:"number",description:"Timeout in milliseconds. Defaults to 600000 (10 minutes). Set a smaller value for quick commands or a larger one for long builds."},cwd:{type:"string",description:"Working directory for the command (relative to the current directory or absolute)"}},required:["command"]}),execute:async({command:$,timeout:f,cwd:Z})=>{if(!qf()&&K9($)){if(!await x$(`Execute dangerous command: ${$}`))return"Command rejected by user."}return v6($,f,Z)}})});import{tool as tV,jsonSchema as aV}from"ai";import{createReadStream as eY}from"fs";import{stat as sV,readFile as eV}from"fs/promises";import{createInterface as $L}from"readline";import fL from"path";function zL($,f,Z){return new Promise((z,J)=>{let K=[],Q=$L({input:eY($),crlfDelay:1/0}),G=0;Q.on("line",(Y)=>{if(G++,G>=f&&G<=Z)K.push(Y);if(G>Z)Q.close()}),Q.on("close",()=>z(K.join(`
239
+ `))),Q.on("error",J)})}function JL($,f){return new Promise((Z,z)=>{let J=[],K=0,Q=!1,G=0,Y=eY($);Y.on("data",(P)=>{let X=typeof P==="string"?Buffer.from(P):P;if(K+=X.byteLength,K>f){let W=X.byteLength-(K-f);J.push(X.subarray(0,W)),Q=!0,Y.destroy();return}J.push(X)}),Y.on("close",()=>{G=Buffer.concat(J).toString("utf-8").split(`
240
+ `).length,Z({text:Buffer.concat(J).toString("utf-8"),truncated:Q,totalLines:G})}),Y.on("error",z)})}var ZL=20971520,u6;var a7=O(()=>{b$();Zf();E0();u6=tV({description:"Read the contents of a file. Returns the file content as text. Use this to understand code, check configurations, etc.",inputSchema:aV({type:"object",properties:{filePath:{type:"string",description:"Path to the file to read (relative to cwd or absolute)"},startLine:{type:"number",description:"Start line number (1-indexed)"},endLine:{type:"number",description:"End line number (1-indexed, inclusive)"}},required:["filePath"]}),execute:async({filePath:$,startLine:f,endLine:Z})=>{let z=q$($,"read");if(z)return`Error: ${z}`;let J=fL.resolve(process.cwd(),$);try{let K=await sV(J);if(K.isDirectory())return`Error: ${$} is a directory, not a file`;if(K.size>ZL&&!f&&!Z){let{text:Y,truncated:P,totalLines:X}=await JL(J,s5),W=Y;if(P)W+=`
241
+
242
+ ...(file too large: ${K.size} bytes, ${X}+ lines — use startLine/endLine to read specific ranges)...`;return W}let Q;if(f!=null||Z!=null){let Y=f??1,P=Z??Number.MAX_SAFE_INTEGER;if(Y<1)return"Error: startLine must be >= 1";if(Z!=null&&P<Y)return`Error: endLine (${P}) must be >= startLine (${Y})`;if(Q=await zL(J,Y,P),!Q)return`Error: no lines found in range ${Y}-${P}`}else Q=await eV(J,"utf-8");let G=j7().resolveForFile(J);if(G.length>0)Q+=`
243
+
244
+ <system-reminder>
245
+ `+G.join(`
246
+
247
+ `)+`
248
+ </system-reminder>`;return B0(Q,{direction:"head"}).content}catch(K){return`Error reading file: ${K.message}`}}})});import{tool as KL,jsonSchema as QL}from"ai";import{mkdir as GL,writeFile as YL}from"fs/promises";import{existsSync as PL}from"fs";import $P from"path";var fP=10485760,ZP;var zP=O(()=>{G$();E0();F$();ZP=KL({description:"Write content to a file. Creates the file if it doesn't exist, overwrites if it does (unless `append` is true). Creates parent directories as needed.",inputSchema:QL({type:"object",properties:{filePath:{type:"string",description:"Path to the file to write (relative to cwd or absolute)"},content:{type:"string",description:"The content to write to the file"},append:{type:"boolean",description:"If true, append to the file instead of overwriting"}},required:["filePath","content"]}),execute:async({filePath:$,content:f,append:Z})=>{if(Buffer.byteLength(f,"utf-8")>fP)return`Error: content exceeds ${fP} bytes. Write in smaller chunks or check the content size.`;let z=q$($,"write");if(z)return`Error: ${z}`;let J=$P.resolve(process.cwd(),$);if(!Nf()){let K=PL(J),Q=Z?`Append to file: ${$}`:K?`Overwrite existing file: ${$}`:`Create new file: ${$}`;if(!await x$(Q))return"Write rejected by user."}try{if(await GL($P.dirname(J),{recursive:!0}),Z)await YL(J,f,{flag:"a",encoding:"utf-8"});else await of(J,f);return`Written ${Buffer.byteLength(f,"utf-8")} bytes to ${$}${Z?" (appended)":""}`}catch(K){return`Error writing file: ${K instanceof Error?K.message:String(K)}`}}})});import{tool as XL,jsonSchema as WL}from"ai";import{readFile as HL}from"fs/promises";import UL from"path";var JP;var KP=O(()=>{G$();E0();F$();JP=XL({description:"Edit a file by replacing a specific text block with new content. The oldText must match exactly (including whitespace and indentation). Use this for precise edits instead of rewriting entire files.",inputSchema:WL({type:"object",properties:{filePath:{type:"string",description:"Path to the file to edit (relative to cwd or absolute)"},oldText:{type:"string",description:"The exact text to find and replace (must match exactly)"},newText:{type:"string",description:"The new text to replace it with"}},required:["filePath","oldText","newText"]}),execute:async({filePath:$,oldText:f,newText:Z})=>{if(!f)return"Error: oldText must not be empty";if(f===Z)return"No change: oldText equals newText";let z=q$($,"write");if(z)return`Error: ${z}`;let J=UL.resolve(process.cwd(),$),K;try{K=await HL(J,"utf-8")}catch(X){return`Error: cannot read ${$}: ${X instanceof Error?X.message:String(X)}`}let Q=K.split(f).length-1;if(Q===0){let X=K.split(`
249
+ `),H=f.split(`
250
+ `)[0].trim(),M=X.findIndex((F)=>F.includes(H));if(M>=0){let F=X.slice(Math.max(0,M-1),M+3).join(`
251
+ `);return`Error: oldText not found exactly. Found similar content near line ${M+1}:
252
+ ${F}
253
+
254
+ Make sure whitespace and indentation match exactly.`}return`Error: oldText not found in ${$}. Make sure the text matches exactly including whitespace.`}if(Q>1)return`Error: oldText found ${Q} times in ${$}. Please provide more context to make the match unique.`;if(!Nf()){let X=(H)=>H.length>80?H.slice(0,80)+"...":H;if(!await x$(`Edit ${$}:
255
+ replace "${X(f)}"
256
+ with "${X(Z)}"`))return"Edit rejected by user."}let G=K.replace(f,Z);try{await of(J,G)}catch(X){return`Error: cannot write ${$}: ${X instanceof Error?X.message:String(X)}`}let Y=f.split(`
257
+ `).length,P=Z.split(`
258
+ `).length;return`Edited ${$}: replaced ${Y} line(s) with ${P} line(s)`}})});import{tool as ML,jsonSchema as FL}from"ai";import{readFileSync as qL,existsSync as YP}from"fs";import{mkdir as NL,readFile as BL,rename as VL,unlink as E6,writeFile as LL}from"fs/promises";import g6 from"path";function _L($){let f=[],Z=null,z=null,J=null,K=0,Q=0,G=$.replace(/\r\n/g,`
259
+ `).split(`
260
+ `);for(let Y of G){if(z===null&&Y.startsWith("--- ")){J=Y.slice(4);continue}if(z===null&&J!==null&&Y.startsWith("+++ ")){let P=Y.slice(4);if(Z)f.push(Z);Z={path:DL(P),isNew:J==="/dev/null",hunks:[]},z=null,J=null;continue}if(z===null&&Y.startsWith("@@ ")){let P=Y.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(P&&Z)z={oldStart:parseInt(P[1],10),oldCount:P[2]?parseInt(P[2],10):1,newStart:parseInt(P[3],10),newCount:P[4]?parseInt(P[4],10):1,lines:[]},Z.hunks.push(z),K=z.oldCount,Q=z.newCount;continue}if(z&&Z){if(Y.startsWith("+"))z.lines.push({type:"add",text:Y.slice(1)}),Q--;else if(Y.startsWith("-"))z.lines.push({type:"delete",text:Y.slice(1)}),K--;else if(Y.startsWith(" "))z.lines.push({type:"context",text:Y.slice(1)}),K--,Q--;if(K<=0&&Q<=0)z=null}}if(Z)f.push(Z);return f}function DL($){let f=$.trim();if(f==="/dev/null")return f;if(f.startsWith("a/"))return f.slice(2);if(f.startsWith("b/"))return f.slice(2);return f}function bL($,f,Z){if(Z.length===0)return Math.max(0,Math.min(f,$.length));for(let z=Math.max(0,f-QP);z<=Math.min($.length-Z.length,f+QP);z++){let J=!0;for(let K=0;K<Z.length;K++)if($[z+K]!==Z[K]){J=!1;break}if(J)return z}return-1}function GP($,f){let Z=f.lines.filter((Q)=>Q.type!=="add").map((Q)=>Q.text),z=bL($,f.oldStart-1,Z);if(z===-1)return{error:`第 ${f.oldStart} 行附近的 hunk 未找到匹配(需要匹配 ${Z.length} 行)`};let J=[...$.slice(0,z)],K=z;for(let Q of f.lines)if(Q.type==="context")J.push($[K]),K++;else if(Q.type==="delete")K++;else J.push(Q.text);return J.push(...$.slice(K)),{lines:J}}function AL($,f=process.cwd()){let Z=[];for(let z of $){let J=g6.resolve(f,z.path),K=YP(J);if(z.isNew&&!K){let Y=[];for(let P of z.hunks){let X=GP(Y,P);if("error"in X)return{ok:!1,error:`${z.path}: ${X.error}`};Y.length=0,Y.push(...X.lines)}Z.push({file:z,content:Y.join(`
261
+ `)+(Y.length>0?`
262
+ `:""),original:null});continue}if(!K)return{ok:!1,error:`${z.path}: 文件不存在`};let Q;try{Q=qL(J,"utf-8")}catch(Y){return{ok:!1,error:`${z.path}: 读取失败 ${Y instanceof Error?Y.message:String(Y)}`}}let G=Q.split(`
263
+ `);for(let Y of z.hunks){let P=GP(G,Y);if("error"in P)return{ok:!1,error:`${z.path}: ${P.error}`};G.length=0,G.push(...P.lines)}Z.push({file:z,content:G.join(`
264
+ `),original:Q})}return{ok:!0,contents:Z}}function s7($){return $ instanceof Error?$.message:String($)}async function jL($){let f=process.cwd(),Z=[];for(let J of $){let K=g6.resolve(f,J.file.path);if(J.original===null){if(YP(K))return{ok:!1,error:`${J.file.path}: 文件已存在,未应用任何更改`};continue}let Q;try{Q=await BL(K,"utf-8")}catch(G){return{ok:!1,error:`${J.file.path}: 读取失败 ${s7(G)}`}}if(Q!==J.original)return{ok:!1,error:`${J.file.path}: 文件在确认期间已被修改,未应用任何更改`}}for(let J of $){let K=g6.resolve(f,J.file.path),Q=P8(K);try{await NL(g6.dirname(K),{recursive:!0}),await LL(Q,J.content,"utf-8")}catch(G){for(let Y of Z)await E6(Y.tmp).catch(()=>{});return await E6(Q).catch(()=>{}),{ok:!1,error:`${J.file.path}: 写入失败 ${s7(G)}`}}Z.push({rel:J.file.path,target:K,tmp:Q,original:J.original})}let z=[];for(let J of Z)try{await VL(J.tmp,J.target),z.push(J)}catch(K){for(let Q of[...z].reverse())try{if(Q.original!==null)await of(Q.target,Q.original);else await E6(Q.target).catch(()=>{})}catch{}for(let Q of Z.slice(z.length))await E6(Q.tmp).catch(()=>{});return{ok:!1,error:`${J.rel}: 写入失败 ${s7(K)},已回滚其他文件`}}return{ok:!0}}var QP=3,PP;var XP=O(()=>{G$();E0();F$();PP=ML({description:"Apply a unified diff to the working tree. Use this for precise multi-file edits or when you have a generated diff. Supports standard unified diff format (---/+++ headers, @@ hunks, context/delete/add lines). New files are created when the diff targets /dev/null. Conflicts are reported without partial writes.",inputSchema:FL({type:"object",properties:{diff:{type:"string",description:"The unified diff text to apply"}},required:["diff"]}),execute:async({diff:$})=>{let f=_L($);if(f.length===0)return"Error: 无法解析 diff(缺少 ---/+++ 文件头)";for(let K of f){let Q=q$(K.path,"write");if(Q)return`Error: ${Q}`}let Z=AL(f);if(!Z.ok)return`Error: ${Z.error}`;let z=Z.contents.map((K)=>{let Q=K.file.hunks.reduce((Y,P)=>Y+P.lines.filter((X)=>X.type==="delete").length,0),G=K.file.hunks.reduce((Y,P)=>Y+P.lines.filter((X)=>X.type==="add").length,0);return` ${K.file.path} ${K.file.isNew?"(new)":""} -${Q}/+${G}`}).join(`
265
+ `);if(!Nf()){if(!await x$(`Apply patch to ${Z.contents.length} file(s)?
266
+ ${z}`))return"Patch rejected by user."}let J=await jL(Z.contents);if(!J.ok)return`Error: ${J.error}`;return`Applied patch:
267
+ ${z}`}})});import{tool as CL,jsonSchema as OL}from"ai";import{glob as wL}from"glob";var x6;var e7=O(()=>{b$();E0();x6=CL({description:"Find files matching a glob pattern. Returns a list of file paths. Use this to discover project structure and find files.",inputSchema:OL({type:"object",properties:{pattern:{type:"string",description:"Glob pattern to match (e.g. 'src/**/*.ts', '*.json')"},cwd:{type:"string",description:"Directory to search in (defaults to working directory)"}},required:["pattern"]}),execute:async({pattern:$,cwd:f})=>{let Z=q$(f??".","read");if(Z)return`Error: ${Z}`;try{let z=await wL($,{cwd:f??process.cwd(),ignore:["**/node_modules/**","**/.git/**","**/dist/**","**/build/**"],nodir:!0});if(z.length===0)return"No files found matching pattern";let J;if(z.length>100)J=z.slice(0,100).join(`
268
+ `)+`
269
+
270
+ ... (${z.length-100} more files)`;else J=z.join(`
271
+ `);return B0(J,{direction:"head"}).content}catch(z){return`Error: ${z.message}`}}})});import{tool as yL,jsonSchema as TL}from"ai";import{readdir as IL,readFile as WP,stat as HP}from"fs/promises";import{spawn as kL}from"child_process";import $Z from"path";function SL($){let f=$.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${f}$`)}function vL($,f,Z,z){let J=["--no-heading","--line-number","-i","-e",$,"--max-count","1","-g","!*.lock","--max-filesize",String(MP)];for(let K of z)J.push("-g",`!${K}/**`);if(Z){let K=Z.source.replace(/^\^/,"").replace(/\$$/,"").replace(/\\\./g,".").replace(/\.\*/g,"*");J.push("-g",K)}return J.push(f),new Promise((K)=>{let Q=kL("rg",J,{stdio:["ignore","pipe","pipe"]}),G=[],Y=0,P=!1,X=(H)=>{if(P)return;P=!0,clearTimeout(W),K(H)},W=setTimeout(()=>{Q.kill("SIGKILL"),X(null)},15000);Q.stdout.on("data",(H)=>{if(Y+=H.byteLength,Y>nL){Q.kill("SIGKILL"),X(null);return}G.push(H)}),Q.on("error",()=>X(null)),Q.on("close",(H)=>{if(H===1)X([]);else if(H===0)X(Buffer.concat(G).toString("utf-8").split(`
272
+ `).filter(Boolean).slice(0,h6));else X(null)})})}async function uL($,f,Z,z){let J=[$];await Promise.all(Array.from({length:RL},async()=>{while(J.length>0&&z.length<h6){let Q=J.pop(),G;try{G=await IL(Q,{withFileTypes:!0})}catch{continue}await Promise.all(G.map(async(Y)=>{let P=$Z.join(Q,Y.name);if(Y.isDirectory()){if(!UP.has(Y.name)&&z.length<h6)J.push(P);return}if(!Y.isFile())return;if(Z&&!Z.test(Y.name))return;try{if((await HP(P)).size>MP)return;let W=await WP(P,"utf-8");if(W.includes("\x00"))return;let H=W.split(`
273
+ `);for(let M=0;M<H.length&&z.length<h6;M++)if(f.test(H[M]))z.push(`${$Z.relative(process.cwd(),P)}:${M+1}:${H[M]}`)}catch{}}))}}))}var UP,h6=500,MP=5242880,nL=8388608,RL=8,c6;var fZ=O(()=>{b$();E0();UP=new Set(["node_modules",".git","dist","build",".next",".out","coverage",".min-agent"]);c6=yL({description:"Search for a pattern in files using regex. Returns matching lines with file paths and line numbers. Use this to find code references, usages, and definitions.",inputSchema:TL({type:"object",properties:{pattern:{type:"string",description:"The regex pattern to search for"},path:{type:"string",description:"File or directory path to search in (defaults to current directory)"},include:{type:"string",description:"File pattern to include (e.g. '*.ts')"}},required:["pattern"]}),execute:async({pattern:$,path:f,include:Z})=>{try{let z=new RegExp($),J=Z?SL(Z):null,K=$Z.resolve(process.cwd(),f??"."),Q=q$(K,"read");if(Q)return`Error: ${Q}`;let G=[],Y=await HP(K).catch(()=>null);if(!Y)return`Error: path not found: ${f??"."}`;if(Y.isFile())try{let X=await WP(K,"utf-8");if(!X.includes("\x00"))X.split(`
274
+ `).forEach((W,H)=>{if(z.test(W))G.push(`${K}:${H+1}:${W}`)})}catch{}else{let X=await vL($,K,J,[...UP]);if(X!==null)G.push(...X);else await uL(K,z,J,G)}let P=G.length>0?G.join(`
275
+ `):"No matches found";return B0(P,{direction:"head"}).content}catch(z){return`Error: ${z.message}`}}})});import{lookup as EL}from"dns/promises";import{isIP as NP}from"net";function FP($){if($.length!==4||$.some((z)=>Number.isNaN(z)))return!0;let[f,Z]=$;if(f===0||f===10||f===127)return!0;if(f===169&&Z===254)return!0;if(f===172&&Z>=16&&Z<=31)return!0;if(f===192&&Z===168)return!0;if(f===100&&Z>=64&&Z<=127)return!0;if(f===198&&(Z===18||Z===19))return!0;return!1}function gL($){let f=$.slice(7);if(f.includes("."))return f.split(".").map(Number);let Z=f.split(":");if(Z.length!==2)return null;let z=parseInt(Z[0],16),J=parseInt(Z[1],16);if(Number.isNaN(z)||Number.isNaN(J))return null;return[z>>8,z&255,J>>8,J&255]}function qP($){if($.startsWith("::ffff:")){let f=gL($);if(f)return FP(f);return!0}if(NP($)===6){let f=$.toLowerCase();if(f==="::1"||f.startsWith("::"))return!0;if(f.startsWith("fc")||f.startsWith("fd"))return!0;if(f.startsWith("fe8")||f.startsWith("fe9")||f.startsWith("fea")||f.startsWith("feb"))return!0;if(f.startsWith("2001:db8"))return!0;return!1}return FP($.split(".").map(Number))}async function BP($){let f;try{f=new URL($)}catch{return"Invalid URL"}if(f.protocol!=="http:"&&f.protocol!=="https:")return"Only http/https URLs are allowed";let Z=f.hostname;if(Z==="localhost"||Z.endsWith(".localhost")||Z.endsWith(".local")||Z.endsWith(".internal"))return`Blocked: local hostname "${Z}"`;if(NP(Z))return qP(Z)?`Blocked: private/internal IP "${Z}"`:null;try{let z=await EL(Z,{all:!0});for(let J of z)if(qP(J.address))return`Blocked: "${Z}" resolves to private address "${J.address}"`}catch{}return null}async function x2($,f){if(!$.body)return{text:"",truncated:!1};let Z=$.body.getReader(),z=[],J=0,K=!1;for(;;){let{done:Q,value:G}=await Z.read();if(Q)break;if(J+=G.byteLength,J>f){z.push(Buffer.from(G.subarray(0,G.byteLength-(J-f)))),K=!0,await Z.cancel();break}z.push(Buffer.from(G))}return{text:Buffer.concat(z).toString("utf-8"),truncated:K}}var ZZ=()=>{};function h2($){return`Configure a working instance via "${$.configKey}" in ~/.min-agent/config.json or the ${$.envName} env var.`}function zZ($,f){let Z=$.trim();if(Z==="")return{ok:!1,error:`${f} is empty`};let z;try{z=new URL(Z)}catch{return{ok:!1,error:`${f} is not a valid absolute URL: ${Z}`}}if(z.protocol!=="http:"&&z.protocol!=="https:")return{ok:!1,error:`${f} must use http or https, got "${z.protocol}"`};return z.search="",z.hash="",{ok:!0,base:z.toString().replace(/\/+$/,"")}}function m6($,f){let Z=process.env[$.envName];if(Z?.trim())return zZ(Z,$.envName);if(f?.trim())return zZ(f,`"${$.configKey}" in config.json`);return zZ($.fallback,"the built-in default backend URL")}function Jf($){if($ instanceof Error){if($.name==="TimeoutError"||$.name==="AbortError")return"the request timed out";let f=$.cause,Z=typeof f==="object"&&f!==null?f.code:void 0;if(typeof Z==="string")return`${$.message} (${Z})`;return $.message}return String($)}function rL(){let $=process.env[LP];if($?.trim())return $.trim();let f=$0().serperApiKey;if(f?.trim())return f.trim();return cL.trim()}function _P(){return`Set your Serper API key via "serperApiKey" in ~/.min-agent/config.json or the ${LP} env var, or configure a SearXNG instance via "webSearchURL" / MIN_AGENT_SEARXNG_URL.`}function oL($){if(typeof $!=="object"||$===null)return null;let f=$;if(!V0(f.link)||f.link.trim()==="")return null;return{title:V0(f.title)?f.title:"",url:f.link,content:V0(f.snippet)?f.snippet:"",engine:JZ(f.link),score:0,publishedDate:V0(f.date)?f.date:"",imgSrc:""}}function pL(){return{...l6(),questions:[]}}function VP($,f){return(Array.isArray($)?$:[]).map((Z)=>{if(typeof Z==="object"&&Z!==null){let z=Z;if(V0(z[f]))return z[f]}return""}).filter((Z)=>Z.trim()!=="")}function dL($){if(typeof $!=="object"||$===null)return pL();let f=$,Z=(Array.isArray(f.organic)?f.organic:[]).map(oL).filter((P)=>P!==null),z=[],J=f.answerBox;if(typeof J==="object"&&J!==null){let P=J;for(let X of["answer","snippet","title"])if(V0(P[X])&&P[X].trim()){z.push(J$(P[X]));break}}let K=VP(f.relatedSearches,"query"),Q=VP(f.peopleAlsoAsk,"question"),G=[],Y=f.knowledgeGraph;if(typeof Y==="object"&&Y!==null){let P=Y,X=V0(P.title)?P.title:"",W=V0(P.description)?P.description:"";if(X||W)G.push({infobox:X,content:W})}return{results:Z,answers:z,suggestions:K,corrections:[],infoboxes:G,unresponsive_engines:[],questions:Q}}async function iL($,f){return t6(xL,{method:"POST",headers:{"X-API-KEY":f,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify($),signal:AbortSignal.timeout(hL)},dL)}function lL($){let f=_P();switch($.kind){case"network":return`Search error: could not reach the Serper search API (${$.message}). This is not a problem with the query.`;case"invalid-json":if($.bodyTooLarge)return`Search error: the search API response exceeded ${c2/1024/1024} MB and could not be parsed. Narrow the query or request fewer results.`;return`Search error: the search API returned a non-JSON response${$.sample?` (starts with: ${$.sample})`:""}.`;case"http":{let Z=$.backendMessage?` Backend message: ${$.backendMessage}.`:"";if($.status===429)return`Search error: the search API is rate-limiting (HTTP 429).${Z} Wait a few seconds before retrying.`;if($.status===401||$.status===403)return`Search error: the search API rejected the API key (HTTP ${$.status}).${Z} ${f}`;if($.status===400||$.status===422)return`Search error: the search API rejected these parameters (HTTP ${$.status}).${Z} Fix the arguments and retry; retrying with the same values will fail again.`;if($.status>=500)return`Search error: the search API failed with HTTP ${$.status}.${Z} It may be temporarily overloaded — retry once.`;return`Search error: HTTP ${$.status} from the search API.${Z}`}}}function tL($,f,Z){let z={q:$.query,num:Z},J=($.language??"").trim().toLowerCase();if(J)if(o6.test(J)&&J!=="all")z.hl=J.replace("_","-");else f.push(`ignored invalid language "${$.language}"; use a code like "zh", "en" or "zh-CN"`);let K=($.time_range??"").trim().toLowerCase();if(K)if(r6.has(K))z.tbs=mL[K];else f.push(`ignored invalid time_range "${K}"; valid values: day, week, month, year`);return z}async function DP($,f,Z){let z=rL();if(!z)return`Search error: no Serper API key configured. ${_P()}`;let J=i6($.max_results,Z),K=tL($,Z,J),Q=await iL(K,z);if(Q.kind!=="ok")return lL(Q);let G=Q.data,Y=p6(G.results).slice(0,J),P=Z.map((W)=>`Note: ${W}`).join(`
276
+ `);if(Y.length===0){let W=[`No search results found for "${f}".`];if(P)W.push(P);if(G.questions.length>0)W.push(`Related questions: ${G.questions.slice(0,5).join(" · ")}`);if(G.suggestions.length>0)W.push(`Related searches: ${G.suggestions.slice(0,8).join(" · ")}`);if(G.questions.length===0&&G.suggestions.length===0)W.push("Try a different query or a broader wording.");return W.join(`
277
+
278
+ `)}let X=[];if(P)X.push(P);for(let W of G.answers)X.push(`Answer: ${J$(W)}`);for(let W of G.infoboxes)X.push(`Infobox${W.infobox?` (${J$(W.infobox)})`:""}: ${O4(J$(W.content),600)}`);if(X.push(`Found ${Y.length} result${Y.length===1?"":"s"} for "${f}":`),X.push(d6(Y)),G.questions.length>0)X.push(`Related questions: ${G.questions.slice(0,5).join(" · ")}`);if(G.suggestions.length>0)X.push(`Related searches: ${G.suggestions.slice(0,8).join(" · ")}`);return B0(X.join(`
279
+
280
+ `),{direction:"head"}).content}var LP="MIN_AGENT_SERPER_API_KEY",xL="https://google.serper.dev/search",hL=35000,cL="7913c19ae7a80320771b843ddffa152c9162c9f2",mL;var bP=O(()=>{d();b$();a6();mL={day:"qdr:d",week:"qdr:w",month:"qdr:m",year:"qdr:y"}});function CP(){if(process.env[m2.envName]?.trim())return!0;return!!$0().webSearchURL?.trim()}function eL($){if(typeof $!=="object"||$===null)return null;let f=$;if(!V0(f.url))return null;return{title:V0(f.title)?f.title:"",url:f.url,content:V0(f.content)?f.content:"",engine:V0(f.engine)?f.engine:"",score:typeof f.score==="number"?f.score:0,publishedDate:V0(f.publishedDate)?f.publishedDate:"",imgSrc:V0(f.img_src)?f.img_src:V0(f.thumbnail)?f.thumbnail:""}}function $_($){if(typeof $!=="object"||$===null)return l6();let f=$,Z=(Array.isArray(f.results)?f.results:[]).map(eL).filter((Y)=>Y!==null),z=(Array.isArray(f.answers)?f.answers:[]).map((Y)=>{if(V0(Y))return Y;if(typeof Y==="object"&&Y!==null){let P=Y;if(V0(P.answer))return P.answer;if(V0(P.content))return P.content}return""}).filter((Y)=>Y!==""),J=Array.isArray(f.suggestions)?f.suggestions.filter(V0):[],K=Array.isArray(f.corrections)?f.corrections.filter(V0):[],Q=(Array.isArray(f.infoboxes)?f.infoboxes:[]).map((Y)=>{if(typeof Y!=="object"||Y===null)return null;let P=Y;return{infobox:V0(P.infobox)?P.infobox:"",content:V0(P.content)?P.content:""}}).filter((Y)=>Y!==null&&(Y.infobox!==""||Y.content!=="")),G=(Array.isArray(f.unresponsive_engines)?f.unresponsive_engines:[]).map((Y)=>{if(!Array.isArray(Y)||!V0(Y[0]))return null;return[Y[0],V0(Y[1])?Y[1]:""]}).filter((Y)=>Y!==null);return{results:Z,answers:z,suggestions:J,corrections:K,infoboxes:Q,unresponsive_engines:G}}async function AP($,f){return t6(`${$}/search?${f}`,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(aL)},$_)}function jP($){let f=h2(m2);switch($.kind){case"network":return`Search error: could not reach the search backend (${$.message}). The instance may be down or the network may be unavailable — this is not a problem with the query. ${f}`;case"invalid-json":if($.bodyTooLarge)return`Search error: the search backend response exceeded ${c2/1024/1024} MB and could not be parsed. Narrow the query or request fewer engines.`;return`Search error: the search backend returned a non-JSON response${$.sample?` (starts with: ${$.sample})`:""}. The instance most likely has the JSON output format disabled. ${f}`;case"http":{let Z=$.backendMessage?` Backend message: ${$.backendMessage}.`:"";if($.status===429)return`Search error: the search backend is rate-limiting (HTTP 429).${Z} Wait a few seconds before retrying, or use a different instance. ${f}`;if($.status===401||$.status===403)return`Search error: the search backend rejected the request (HTTP ${$.status}).${Z} The instance likely requires authentication or has the JSON output format disabled. ${f}`;if($.status===400||$.status===422)return`Search error: the search backend rejected these parameters (HTTP ${$.status}).${Z} Fix the arguments and retry; retrying with the same values will fail again.`;if($.status>=500)return`Search error: the search backend failed with HTTP ${$.status}.${Z} It may be temporarily overloaded — retry once, then try a different instance. ${f}`;return`Search error: HTTP ${$.status} from the search backend.${Z} ${f}`}}}function f_(){let $=process.env.MIN_AGENT_SEARXNG_FALLBACK_ENGINES;if($!==void 0)return $.trim();let f=$0().webSearchFallbackEngines;if(f!==void 0)return f.trim();return sL}function Z_($,f){let Z=new URLSearchParams({q:$.query,format:"json",categories:"general"}),z=($.language??"").trim();if(z)if(o6.test(z))Z.set("language",z.replace("_","-"));else f.push(`ignored invalid language "${z}"; use a code like "zh", "en" or "zh-CN"`);let J=($.time_range??"").trim().toLowerCase();if(J)if(r6.has(J))Z.set("time_range",J);else f.push(`ignored invalid time_range "${J}"; valid values: day, week, month, year`);return Z}function z_($,f){let Z=$;if(f&&f.length>0){let K=new Set(f.map((Q)=>Q.toLowerCase()));Z=$.filter(([Q])=>K.has(Q.toLowerCase()))}if(Z.length===0)return"";let z=Z.map(([K,Q])=>Q?`${K} (${Q})`:K).join(", ");return`${f?"The requested engines are unavailable":"The backend reports these engines as unavailable (instance-wide list, may include engines this query did not use)"}: ${z}. Try a different query, or pass "engines" explicitly (e.g. "google,bing").`}async function OP($,f,Z){let z=m6(m2,$0().webSearchURL);if(!z.ok)return`Search error: ${z.error}. ${h2(m2)}`;let J=i6($.max_results,Z),K=Z_({...$,query:f},Z),Q=await AP(z.base,K),G=null;if(Q.kind==="ok"&&Q.data.results.length===0){let H=f_();if(H){let M=new URLSearchParams(K);M.set("engines",H);let F=await AP(z.base,M);if(F.kind==="ok"&&F.data.results.length>0)Q=F,G=H;else if(F.kind!=="ok")Z.push(`the fallback engines (${H}) also failed: ${jP(F).replace(/^Search error: /,"")}`)}}if(Q.kind!=="ok")return jP(Q);let Y=Q.data,P=p6(Y.results).slice(0,J),X=Z.map((H)=>`Note: ${H}`).join(`
281
+ `);if(P.length===0){let H=[`No search results found for "${f}".`];if(X)H.push(X);let M=z_(Y.unresponsive_engines,G?G.split(","):null);if(M)H.push(M);if(Y.corrections.length>0)H.push(`Did you mean: ${Y.corrections.join(", ")}`);if(Y.suggestions.length>0)H.push(`Related queries: ${Y.suggestions.slice(0,8).join(", ")}`);if(!M&&Y.corrections.length===0&&Y.suggestions.length===0)H.push("Try a different query or a broader wording.");return H.join(`
282
+
283
+ `)}let W=[];if(X)W.push(X);for(let H of Y.answers)W.push(`Answer: ${J$(H)}`);for(let H of Y.infoboxes)W.push(`Infobox${H.infobox?` (${J$(H.infobox)})`:""}: ${O4(J$(H.content),600)}`);if(W.push(`Found ${P.length} result${P.length===1?"":"s"} for "${f}"${G?` via fallback engines ${G}`:""}:`),W.push(d6(P)),Y.corrections.length>0)W.push(`Did you mean: ${Y.corrections.join(", ")}`);if(Y.suggestions.length>0)W.push(`Related queries: ${Y.suggestions.slice(0,8).join(", ")}`);return B0(W.join(`
284
+
285
+ `),{direction:"head"}).content}var m2,aL=20000,sL="google,bing";var KZ=O(()=>{d();b$();a6();m2={envName:"MIN_AGENT_SEARXNG_URL",configKey:"webSearchURL",fallback:"https://searxng.xc.lonae.com"}});import{tool as J_,jsonSchema as K_}from"ai";function V0($){return typeof $==="string"}function J$($){return $.replace(/\s+/g," ").trim()}function O4($,f){let Z=Array.from($);if(Z.length<=f)return $;return Z.slice(0,f-1).join("")+"…"}function JZ($){try{return new URL($).hostname.replace(/^www\./,"")}catch{return $}}function Y_($){if(!$)return"";let f=Date.parse($);if(Number.isNaN(f))return J$($);return new Date(f).toISOString().slice(0,10)}function P_($){try{let f=new URL($),Z=f.hostname.toLowerCase().replace(/^www\./,""),z=f.pathname.replace(/\/+$/,""),J=[...f.searchParams].filter(([Q])=>!Q.toLowerCase().startsWith("utm_")&&!G_.has(Q.toLowerCase()));J.sort((Q,G)=>Q[0]<G[0]?-1:Q[0]>G[0]?1:0);let K=J.map(([Q,G])=>`${Q}=${G}`).join("&");return`${Z}${z}${K?`?${K}`:""}`}catch{return $.trim().toLowerCase()}}function p6($){let f=new Set;return $.filter((Z)=>{let z=P_(Z.url);if(f.has(z))return!1;return f.add(z),!0})}function d6($){return $.map((f,Z)=>{let z=[`${Z+1}. ${J$(f.title)||JZ(f.url)}`,` ${f.url}`],J=[],K=Y_(f.publishedDate);if(K)J.push(K);if(f.engine)J.push(f.engine);if(J.length>0)z.push(` [${J.join(" · ")}]`);let Q=O4(J$(f.content),Q_);if(Q)z.push(` ${Q}`);return z.join(`
286
+ `)}).join(`
287
+
288
+ `)}function i6($,f){if($===void 0)return s6;let Z=Math.floor(Number($));if(!Number.isFinite(Z)||Z<1)return f.push(`ignored invalid max_results "${$}"; using ${s6}`),s6;if(Z>e6)return f.push(`max_results capped at ${e6}`),e6;return Z}function l6(){return{results:[],answers:[],suggestions:[],corrections:[],infoboxes:[],unresponsive_engines:[]}}function X_($){if(typeof $!=="object"||$===null)return"";let f=$;for(let Z of["error","detail","message"]){let z=f[Z];if(V0(z)&&z.trim())return J$(z);if(typeof z==="object"&&z!==null){let J=z.message;if(V0(J)&&J.trim())return J$(J)}}return""}async function t6($,f,Z){let z;try{z=await fetch($,f)}catch(P){return{kind:"network",message:Jf(P)}}let J,K;try{let P=await x2(z,c2);J=P.text,K=P.truncated}catch(P){return{kind:"network",message:Jf(P)}}let Q,G=!1;try{Q=JSON.parse(J)}catch{G=!0}let Y=G?"":X_(Q);if(!z.ok)return{kind:"http",status:z.status,backendMessage:Y};if(G)return{kind:"invalid-json",bodyTooLarge:K,sample:O4(J$(J),100)};if(K)return{kind:"invalid-json",bodyTooLarge:!0,sample:""};if(Y)return{kind:"http",status:z.status,backendMessage:Y};return{kind:"ok",data:Z(Q)}}var c2=2097152,s6=10,e6=30,Q_=300,r6,o6,G_,wP;var a6=O(()=>{ZZ();E0();bP();KZ();KZ();r6=new Set(["day","week","month","year"]),o6=/^(all|[a-z]{2,3}([-_][a-zA-Z]{2,4})?)$/,G_=new Set(["ref","ref_src","referrer","fbclid","gclid","msclkid","igshid","mc_cid","mc_eid","spm","source"]);wP=J_({description:`Search the web via Google. Returns ranked results with title, URL, source and a snippet. Use this for current information, news, documentation, or anything needing up-to-date knowledge. Today's date: ${new Date().toISOString().slice(0,10)}. When the user asks about the latest or newest state of something, use the current year in the query or set time_range (day, week, month, year) — do not append an older year from your training knowledge. A few targeted queries plus fetching the best sources is enough; then produce the user's deliverable instead of searching exhaustively.`,inputSchema:K_({type:"object",properties:{query:{type:"string",description:"The search query"},language:{type:"string",description:"Search language code, e.g. zh, en, zh-CN (default: en)"},time_range:{type:"string",description:"Time range filter: day, week, month, year"},max_results:{type:"number",description:`Maximum number of results to return (default ${s6}, max ${e6})`}},required:["query"]}),execute:async($)=>{if(i0().network==="deny")return`Search error: ${n1()}`;let f=($.query??"").trim();if(!f)return'Search error: "query" must be a non-empty string.';let Z=[];if(CP())return OP($,f,Z);return DP($,f,Z)}})});import{tool as W_,jsonSchema as H_}from"ai";function $3($,f){let{content:Z}=B0($,{direction:"head"});if(!f)return Z;return`${Z}
289
+
290
+ ...(response body was cut off at ${QZ/1024/1024} MB)`}function yP($,f){switch($.kind){case"ok":return`HTTP 200 but the body had almost no readable content (${f} may require JavaScript)`;case"binary":return`non-text response (${$.contentType})`;case"http":return`HTTP ${$.status}${$.statusText?` ${$.statusText}`:""}`;case"network":return $.message}}function q_($){return/html|xhtml/i.test($)}function N_($){if(!$)return!0;let f=$.toLowerCase();if(f.startsWith("text/"))return!0;return/(json|xml|javascript|ecmascript|yaml|csv|graphql|x-www-form-urlencoded|\+json)/.test(f)}async function B_($,f){let Z;try{Z=await fetch($,{method:f,headers:{"User-Agent":F_,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,application/json;q=0.9,*/*;q=0.8"},signal:AbortSignal.timeout(U_)})}catch(J){return{kind:"network",message:Jf(J)}}let z=Z.headers.get("content-type")??"";if(!Z.ok)return{kind:"http",status:Z.status,statusText:Z.statusText};if(!N_(z))return{kind:"binary",contentType:z};try{let{text:J,truncated:K}=await x2(Z,QZ);if(J.includes("\x00"))return{kind:"binary",contentType:z||"unknown (binary)"};return{kind:"ok",text:J,bodyTruncated:K,html:q_(z)||L_(J)}}catch(J){return{kind:"network",message:Jf(J)}}}async function V_($){let f=m6(IP,$0().webFetchURL);if(!f.ok)return{kind:"unavailable",reason:f.error};let Z;try{Z=await fetch(`${f.base}/v1/scrape`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:$,formats:["markdown"],onlyMainContent:!0,waitFor:3000,timeout:30000}),signal:AbortSignal.timeout(M_)})}catch(P){return{kind:"unavailable",reason:`could not reach the scrape backend (${Jf(P)})`}}let z,J;try{let P=await x2(Z,QZ);z=P.text,J=P.truncated}catch(P){return{kind:"unavailable",reason:`could not read the scrape response (${Jf(P)})`}}let K;try{K=JSON.parse(z)}catch{return{kind:"unavailable",reason:Z.ok?"the scrape backend returned a non-JSON response":`HTTP ${Z.status} from the scrape backend`}}let Q=typeof K==="object"&&K!==null?K:{};if(!Z.ok){let P=typeof Q.error==="string"?Q.error:Z.statusText;return{kind:"unavailable",reason:`HTTP ${Z.status} from the scrape backend${P?` (${P})`:""}`}}let G=typeof Q.data==="object"&&Q.data!==null?Q.data:{},Y=typeof G.markdown==="string"?G.markdown:typeof G.content==="string"?G.content:"";if(!Y.trim())return{kind:"unavailable",reason:"the scrape backend returned no content for this URL"};return{kind:"ok",markdown:Y,bodyTruncated:J}}function L_($){return/^\s*(<!doctype html|<html\b|<head\b)/i.test($)}function TP($){if($.trim().length<200)return!1;return $.replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]*>/g,"").trim().length>100}var IP,QZ=2097152,U_=8000,M_=35000,F_="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",kP;var nP=O(()=>{b$();ZZ();d();E0();IP={envName:"MIN_AGENT_FIRECRAWL_URL",configKey:"webFetchURL",fallback:"https://fireclawl.xc.lonae.com"},kP=W_({description:"Fetch content from a URL. Use this to access web pages, APIs, or any HTTP resource. Returns the response body as text, or markdown for HTML pages (JavaScript-rendered pages go through a scrape backend). Do not re-fetch URLs you already have; extract what you need and produce the user's deliverable.",inputSchema:H_({type:"object",properties:{url:{type:"string",description:"The URL to fetch"},method:{type:"string",description:"HTTP method (default: GET)"}},required:["url"]}),execute:async({url:$,method:f})=>{if(i0().network==="deny")return`Error: ${n1()}`;let Z=($??"").trim();if(!Z)return'Error: "url" must be a non-empty string.';let z=await BP(Z);if(z)return`Error: ${z}`;let J=(f??"GET").trim().toUpperCase()||"GET",K=await B_(Z,J);if(K.kind==="ok"&&!K.html&&TP(K.text))return $3(K.text,K.bodyTruncated);if(K.kind==="binary")return`Error: the response is not text (Content-Type: ${K.contentType}). Use a different tool to download binary content.`;if(J!=="GET"){if(K.kind==="ok")return $3(K.text,K.bodyTruncated);return`Error: ${yP(K,Z)}`}let Q=await V_(Z);if(Q.kind==="ok")return $3(Q.markdown,Q.bodyTruncated);if(K.kind==="ok"&&TP(K.text))return[`Note: returning raw HTML — the scrape backend could not convert this page (${Q.reason}).`,$3(K.text,K.bodyTruncated)].join(`
291
+
292
+ `);return[`Failed to fetch content from ${Z}.`,`Direct request: ${yP(K,Z)}`,`Scrape backend: ${Q.reason}`,h2(IP)].join(`
293
+ `)}})});import{tool as __,jsonSchema as D_}from"ai";var RP;var SP=O(()=>{G$();p4();RP=__({description:`Ask the user a question and wait for the answer. Use this instead of listing choices in your message when you need a decision or missing information.
294
+
295
+ Use this when:
296
+ - The task is ambiguous and you need more information
297
+ - There are multiple valid approaches and you want the user to choose
298
+ - You need confirmation before a potentially destructive action
299
+ - You're unsure about a requirement or preference
300
+
301
+ Provide a clear, specific question. When the user should pick from known choices, pass them in options — they appear as a selectable list. The list always ends with「其他」so the user can type a custom answer. Set multiple to true when several choices can apply at once (checkboxes). Prefer plain strings; {label, description} objects are also accepted.`,inputSchema:D_({type:"object",properties:{question:{type:"string",description:"The question to ask the user"},options:{type:"array",items:{anyOf:[{type:"string"},{type:"object",properties:{label:{type:"string"},description:{type:"string"},key:{type:"string"}}}]},description:"Optional list of choices. Prefer plain strings; {label, description} objects are also accepted."},multiple:{type:"boolean",description:"If true, the user can check several options before submitting. Defaults to false (single choice)."}},required:["question"]}),execute:async({question:$,options:f,multiple:Z})=>{let z=u1($);if(!z.trim())return"Error: question is required.";let J=g1(E1(f)),K=await J9(z,J.length>0?J:void 0,Boolean(Z));if(K===null)return"User cancelled the question";let Q=Tz(K);if(Q.length===0)return"User cancelled the question";if(J.length>0)return Iz(Q);return`User answered: ${Q.join(`
302
+ `)}`}})});import{tool as b_,jsonSchema as A_}from"ai";async function C_($,f){let Z=JSON.stringify({jsonrpc:"2.0",id:1,method:"tools/call",params:{name:"get_code_context_exa",arguments:{query:$,tokensNum:f}}}),z=await fetch(j_,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream",...process.env.EXA_API_KEY?{Authorization:`Bearer ${process.env.EXA_API_KEY}`}:{}},body:Z,signal:AbortSignal.timeout(30000)});if(!z.ok)throw Error(`Exa API returned ${z.status}`);return await O_(await z.text())}async function O_($){for(let f of $.split(`
303
+ `)){if(!f.startsWith("data: "))continue;try{let z=JSON.parse(f.slice(6))?.result?.content?.[0]?.text;if(z)return z}catch{}}try{let Z=JSON.parse($)?.result?.content?.[0]?.text;if(Z)return Z}catch{}return null}var j_="https://mcp.exa.ai/mcp",vP;var uP=O(()=>{b$();E0();vP=b_({description:`Search and get relevant context for any programming task using Exa Code API.
304
+ Provides high-quality, fresh context for libraries, SDKs, and APIs.
305
+ Use this for ANY question or task related to programming — finding code examples, documentation, API references, and patterns.
306
+
307
+ Usage:
308
+ - Adjustable token count (1000-50000) for focused or comprehensive results
309
+ - Default 5000 tokens for balanced context
310
+ - Examples: 'React useState hook examples', 'Python pandas dataframe filtering', 'Express.js middleware', 'Rust async trait implementation'`,inputSchema:A_({type:"object",properties:{query:{type:"string",description:"Search query for APIs, libraries, SDKs. E.g. 'React useState hook examples', 'Express.js middleware'"},tokensNum:{type:"number",description:"Number of tokens to return (1000-50000). Default 5000. Use lower for focused queries, higher for comprehensive docs."}},required:["query"]}),execute:async({query:$,tokensNum:f})=>{if(i0().network==="deny")return`Code search error: ${n1()}`;if(!process.env.EXA_API_KEY?.trim())return"Code search error: EXA_API_KEY is not set. Configure it in your environment to enable code search.";let Z=Math.max(1000,Math.min(50000,f??5000));try{let z=await C_($,Z);if(!z)return"No code snippets or documentation found. Try a different query, be more specific about the library or concept, or check spelling.";return B0(z,{direction:"head"}).content}catch(z){return`Code search error: ${z instanceof Error?z.message:String(z)}`}}})});function f3(){let $={bash:l7,read:u6,write:ZP,edit:JP,apply_patch:PP,glob:x6,grep:c6,search_web:wP,web_fetch:kP,question:RP};if(process.env.EXA_API_KEY)$.codesearch=vP;return $}var GZ=O(()=>{g2();a7();zP();KP();XP();e7();fZ();a6();nP();SP();uP()});import{execSync as w_}from"child_process";import{existsSync as Z3,readFileSync as y_,readdirSync as T_,statSync as I_}from"fs";import uf from"path";function I1(){let $=process.cwd(),f=Z3(uf.join($,".git")),Z;if(f)try{Z=w_("git branch --show-current",{encoding:"utf-8",cwd:$,timeout:5000}).trim()}catch{}let z=[],J=[],K=[],Q=[{file:"bun.lock",lang:"TypeScript/JavaScript",pm:"bun"},{file:"yarn.lock",lang:"TypeScript/JavaScript",pm:"yarn"},{file:"pnpm-lock.yaml",lang:"TypeScript/JavaScript",pm:"pnpm"},{file:"package.json",lang:"TypeScript/JavaScript",pm:"npm"},{file:"tsconfig.json",lang:"TypeScript"},{file:"Cargo.toml",lang:"Rust",pm:"cargo"},{file:"go.mod",lang:"Go"},{file:"pyproject.toml",lang:"Python",pm:"pip/uv"},{file:"requirements.txt",lang:"Python",pm:"pip"},{file:"Gemfile",lang:"Ruby",pm:"bundler"},{file:"pom.xml",lang:"Java",pm:"maven"},{file:"build.gradle",lang:"Java/Kotlin",pm:"gradle"},{file:"composer.json",lang:"PHP",pm:"composer"},{file:"Makefile",lang:""},{file:"Dockerfile",lang:""}],G,Y;for(let W of Q)if(Z3(uf.join($,W.file))){if(J.push(W.file),W.lang&&!z.includes(W.lang))z.push(W.lang);if(W.pm&&!G)G=W.pm}if(Z3(uf.join($,"package.json")))try{let W=JSON.parse(y_(uf.join($,"package.json"),"utf-8")),H={...W.dependencies,...W.devDependencies};if(H.next)Y="Next.js";else if(H.nuxt)Y="Nuxt";else if(H["@angular/core"])Y="Angular";else if(H.vue)Y="Vue";else if(H.react)Y="React";else if(H.svelte)Y="Svelte";else if(H.express)Y="Express";else if(H.fastify)Y="Fastify";else if(H.hono)Y="Hono";else if(H.effect)Y="Effect"}catch{}let P=["src/index.ts","src/index.js","src/main.ts","src/main.js","src/app.ts","src/app.js","index.ts","index.js","main.ts","main.js","app.ts","app.js","src/lib.rs","main.go","main.py","app.py"];for(let W of P)if(Z3(uf.join($,W)))K.push(W);let X=[];if(X.push(`Directory: ${$}`),f)X.push(`Git: yes (branch: ${Z??"unknown"})`);if(z.length)X.push(`Languages: ${z.join(", ")}`);if(Y)X.push(`Framework: ${Y}`);if(G)X.push(`Package manager: ${G}`);if(J.length)X.push(`Config files: ${J.join(", ")}`);if(K.length)X.push(`Entry points: ${K.join(", ")}`);try{let W=T_($).filter((H)=>!H.startsWith(".")||H===".env.example").filter((H)=>H!=="node_modules"&&H!==".git").slice(0,30).map((H)=>{return I_(uf.join($,H)).isDirectory()?`${H}/`:H});X.push(`Structure: ${W.join(", ")}`)}catch{}return{directory:$,isGitRepo:f,branch:Z,languages:z,framework:Y,packageManager:G,entryFiles:K,configFiles:J,summary:X.join(`
311
+ `)}}function Ef($,f){let Z=["You are an expert AI coding assistant. You help users with software engineering tasks including writing code, debugging, refactoring, and architecture decisions.","","# Principles","- Be concise and direct. Minimize output tokens while maintaining quality.","- NEVER add comments to code unless asked. Write self-documenting code.","- Follow existing code conventions in the project. Mimic style, libraries, and patterns.","- NEVER assume a library is available — check package.json/Cargo.toml/etc first.","- Prefer editing existing files over creating new ones.","- After making changes, run lint/typecheck/build if available.","- NEVER commit unless explicitly asked.","- When the user asks to configure, install, or manage MCP servers, skills, rules, memory, permission, sandbox, providers, plugins, or other min-agent settings, follow the built-in `self-config` skill (already loaded). If its instructions are missing, load it with the skill tool before making changes.","","# Workflow","- For greetings, thanks, or general chat with no concrete task, reply directly — do not call any tools. Memories and session state are not a reason to start work; only the current user message is. The Project Structure below already covers the basics; do not re-explore the codebase just to answer a greeting.","- When you need a choice or a missing preference before you can proceed, call the question tool with concrete options. Do not list those choices in your message. Set multiple to true when several answers can apply together.","- Use search tools (grep, glob) to understand the codebase before making changes, only once the user gives a concrete task.","- Use the search_web tool for live web search. Never emit XML tags such as <web_search>.","- After a few targeted web searches and fetching the best sources, stop researching and produce the requested output.","- Do not keep searching for completeness, extra models, or slightly better numbers. Mark uncertain dates or scores as estimates and move on.","- If the user asked for a file or other artifact, write it as soon as the required fields can be filled. Then stop.","- Use the edit tool for precise changes instead of rewriting entire files.","- When fixing bugs: read the relevant code, understand the issue, fix it, verify.","- When adding features: explore existing patterns first, then implement consistently.","- Run tests after changes when a test command is available.","","# Environment","<env>",` Working directory: ${$.directory}`,` Git repo: ${$.isGitRepo?`yes (branch: ${$.branch??"unknown"})`:"no"}`,` Platform: ${process.platform}`,` Date: ${new Date().toDateString()}`,$.languages.length?` Languages: ${$.languages.join(", ")}`:"",$.framework?` Framework: ${$.framework}`:"",$.packageManager?` Package manager: ${$.packageManager}`:"","</env>","","# Project Structure","```",$.summary,"```"].filter(Boolean);if(f.length>0)Z.push("","# User Instructions",""),Z.push(...f);return Z.join(`
312
+ `)}var r2=()=>{};import{tool as k_,jsonSchema as n_}from"ai";import{existsSync as EP,readdirSync as gP,statSync as R_}from"fs";import{pathToFileURL as S_}from"url";import w4 from"path";function u_($){if($.readOnly===!0)return!1;if($.dangerous===!1)return!1;return!0}function xP(){return z3}function E_($){return $.map((f)=>{if(!EP(f))return`${f}:missing`;let Z=gP(f).filter((J)=>J.endsWith(".ts")||J.endsWith(".js")||J.endsWith(".mjs")).sort(),z=Z.map((J)=>R_(w4.join(f,J)).mtimeMs).join(",");return`${f}:${Z.join(",")}:${z}`}).join("|")}async function J3($){let f=$??v_,Z=E_(f);if(o2&&o2.signature===Z)return z3=o2.readOnlyIds,o2.tools;let z=await g_(f);return o2={signature:Z,tools:z,readOnlyIds:z3},z}async function g_($){let f={},Z=new Set;for(let J of $){if(!EP(J))continue;let K=gP(J).filter((Q)=>Q.endsWith(".ts")||Q.endsWith(".js")||Q.endsWith(".mjs"));for(let Q of K){let G=w4.join(J,Q),Y=w4.basename(Q,w4.extname(Q));try{let P=await import(S_(G).href);for(let[X,W]of Object.entries(P)){if(!c_(W))continue;let H=X==="default"?Y:`${Y}_${X}`;if(f[H]){console.warn(`\x1B[33m ⚠ Plugin tool "${H}" from ${G} conflicts with an existing tool; skipping\x1B[0m`);continue}let M={},F=[];for(let[q,U]of Object.entries(W.parameters)){let N=h_(U.type);M[q]={type:N,...U.description?{description:U.description}:{}},F.push(q)}if(W.readOnly===!0)Z.add(H);f[H]=k_({description:W.description,inputSchema:n_({type:"object",properties:M,required:F}),execute:async(q)=>{if(u_(W)&&!qf()){let U=x_(q);if(!await x$(`运行自定义工具 ${H}${U?`
313
+ ${U}`:""}`))return"自定义工具已被拒绝。"}try{let U=await W.execute(q);return typeof U==="string"?U:JSON.stringify(U)??"undefined"}catch(U){return`Plugin error: ${String(U instanceof Error?U.message:U)}`}}})}}catch(P){console.error(`\x1B[90m Plugin "${Q}" failed to load: ${String(P instanceof Error?P.message:P)}\x1B[0m`)}}}z3=Z;let z=Object.keys(f).length;if(z>0)console.log(`\x1B[90m Plugins loaded: ${z} tool(s)\x1B[0m`);return f}function x_($){try{let f=JSON.stringify($);if(!f||f==="{}")return"";return f.length>400?`${f.slice(0,400)}…`:f}catch{return""}}function h_($){if($==="number"||$==="boolean"||$==="object"||$==="array")return $;return"string"}function c_($){if(!$||typeof $!=="object")return!1;let f=$;return typeof f.description==="string"&&typeof f.parameters==="object"&&typeof f.execute==="function"}var v_,o2=null,z3;var YZ=O(()=>{d();G$();v_=[w4.join(process.cwd(),".min-agent","tools"),w4.join(X0(),"tools")],z3=new Set});var rP={};U0(rP,{identityPayload:()=>cP,extractSources:()=>mP,WEB_RESEARCH_TOOLS:()=>y4,STEER_PROMPT:()=>XZ,RESEARCH_TOTAL_CAP:()=>d_,RESEARCH_STUB_RESULT:()=>Q3,RESEARCH_STOP_AFTER:()=>p_,RESEARCH_STEER_AFTER:()=>o_,REPEAT_TOTAL_THRESHOLD:()=>r_,LOOP_HALT_MESSAGE:()=>G3,EXACT_LOOP_THRESHOLD:()=>m_,DoomLoopDetector:()=>T4,DELIVER_PROMPT:()=>K3});function PZ($,f){if(typeof $!=="number"||!Number.isFinite($)||$<1)return f;return Math.floor($)}function p2($){try{if($===null||typeof $!=="object")return JSON.stringify($);if(Array.isArray($))return JSON.stringify($.map(p2));let f={};for(let Z of Object.keys($).sort())f[Z]=p2($[Z]);return JSON.stringify(f)}catch{return String($)}}function l_($){if($&&typeof $==="object"&&!Array.isArray($))return $;return null}function t_($){if(typeof $!=="string")return"";return $.toLowerCase().replace(/\s+/g," ").trim()}function a_($){try{return new URL($.trim()).hostname.toLowerCase().replace(/^www\./,"")}catch{return""}}function hP($){if(typeof $!=="string")return"";try{let f=new URL($.trim()),Z=f.hostname.toLowerCase().replace(/^www\./,""),z=f.pathname.replace(/\/+$/,"");return`${f.protocol}//${Z}${z}${f.search}`}catch{return $.trim().toLowerCase()}}function cP($,f){let Z=l_(f);if($==="search_web"&&Z)return p2({query:t_(Z.query)});if($==="web_fetch"&&Z)return p2({url:hP(Z.url)});return p2(f)}function mP($){let f=new Set,Z=new Set;for(let z of $.match(s_)??[]){let J=hP(z);if(J)f.add(J);let K=a_(z);if(K)Z.add(K)}return{urls:[...f],hosts:[...Z]}}class T4{lastCall={key:"",count:0};callCounts=new Map;webTotal=0;inFlight=0;batchProductive=!1;unproductiveRounds=0;steered=!1;capped=!1;delivered=!1;seenUrls=new Set;seenHosts=new Set;steerAfter;stopAfter;totalCap;constructor($){this.steerAfter=PZ($?.steerAfter,3),this.stopAfter=Math.max(PZ($?.stopAfter,5),this.steerAfter+1),this.totalCap=PZ($?.totalCap,24)}get webResearchCount(){return this.webTotal}get researchCapped(){return this.capped}get producedArtifact(){return this.delivered}get unproductiveStreak(){return this.unproductiveRounds}record($,f){return this.observe($,f)==="halt"}observe($,f){let Z=`${$}\x00${cP($,f)}`;if(this.lastCall.key===Z)this.lastCall.count++;else this.lastCall={key:Z,count:1};let z=(this.callCounts.get(Z)??0)+1;if(this.callCounts.set(Z,z),this.lastCall.count>=3||z>=5)return this.lastCall={key:"",count:0},this.callCounts.delete(Z),"halt";if(y4.has($)){if(this.webTotal++,this.inFlight===0)this.batchProductive=!1;if(this.inFlight++,!this.capped&&this.webTotal>=this.totalCap)return this.markCapped(),"cap";return"ok"}if(i_.has($))this.delivered=!0,this.unproductiveRounds=0;return"ok"}observeResult($,f){if(!y4.has($))return"ok";let Z=typeof f==="string"?f:$D(f);if(!e_.test(Z.trim())){let{urls:z,hosts:J}=mP(Z),K=0;for(let Q of z)if(!this.seenUrls.has(Q))this.seenUrls.add(Q),K++;for(let Q of J)if(!this.seenHosts.has(Q))this.seenHosts.add(Q),K++;if(K>0)this.batchProductive=!0}if(this.inFlight>0)this.inFlight--;if(this.inFlight>0)return"ok";if(this.batchProductive)return this.unproductiveRounds=0,"ok";if(this.unproductiveRounds++,this.capped)return"ok";if(this.unproductiveRounds>=this.stopAfter)return this.markCapped(),"cap";if(!this.steered&&this.unproductiveRounds>=this.steerAfter)return this.steered=!0,"steer";return"ok"}markCapped(){this.capped=!0,this.steered=!0}promptHint(){if(this.capped)return["## Research budget","search_web and web_fetch have been removed for the rest of this turn.","Produce the requested deliverable from information already in the conversation."].join(`
314
+ `);if(this.webTotal<4)return"";let $=["## Research budget",`Research calls this turn: ${this.webTotal}/${this.totalCap}; rounds without new sources: ${this.unproductiveRounds}/${this.stopAfter}.`];if(this.steered||this.unproductiveRounds>=this.steerAfter)$.push("Recent searches added nothing new. Stop searching and produce the requested deliverable; mark uncertain fields instead of looking for more.");else $.push("Keep queries targeted: fetch the best sources, then write the output.");return $.join(`
315
+ `)}reset(){this.lastCall={key:"",count:0},this.callCounts.clear(),this.webTotal=0,this.inFlight=0,this.batchProductive=!1,this.unproductiveRounds=0,this.steered=!1,this.capped=!1,this.delivered=!1,this.seenUrls.clear(),this.seenHosts.clear()}}function $D($){try{return JSON.stringify($)??String($)}catch{return String($)}}var m_=3,r_=5,o_=3,p_=5,d_=24,y4,i_,XZ="Your last few searches and page fetches returned nothing new. Stop calling search_web and web_fetch. Using only what you already have, produce the user's requested deliverable now (files, code, or a complete answer). If some fields are uncertain, mark them and proceed — do not search again.",K3="The research tools have been removed for the rest of this turn. Do not try to search again. Using the information already in this conversation, produce the user's requested deliverable now (write files with the write/edit tools). If a fact is missing, note the gap and still write the output.",Q3="Web search and page fetch are disabled for the rest of this turn. Produce the user's requested deliverable from information already in this conversation. If a fact is missing, note the gap and still write the output.",G3="同一操作连续重复了多次,已停止以免空转。发送消息可继续。",s_,e_;var Y3=O(()=>{y4=new Set(["search_web","web_fetch"]),i_=new Set(["write","edit","apply_patch"]);s_=/https?:\/\/[^\s"'<>)\]}]+/g,e_=/^(error|search error|fetch error)\b/i});function oP($){return $.toLowerCase()}function fD($){let f=oP($),Z=null;for(let z of WZ){let J=f.indexOf(z.open);if(J>=0&&(!Z||J<Z.index))Z={index:J,tag:z}}return Z}class HZ{buf="";feed($){return this.buf+=$,this.drain(!1)}flush(){return this.drain(!0)}drain($){let f="",Z="",z=!1;while(this.buf.length>0){let J=fD(this.buf);if(!J){if($)f+=this.buf,this.buf="";else{let P=ZD(this.buf);if(P>=0)f+=this.buf.slice(0,P),this.buf=this.buf.slice(P);else f+=this.buf,this.buf=""}break}if(J.index>0){let P=this.buf.slice(0,J.index);if(P=P.replace(/\n+$/,""),P)f+=P;this.buf=this.buf.slice(J.index)}let K=oP(this.buf),Q=J.tag.open.length,G=K.indexOf(J.tag.close,Q);if(G<0){if($)Z+=this.buf.slice(Q),this.buf="";else if(this.buf.length-Q>16384)Z+=this.buf.slice(Q),this.buf="",z=!0;break}let Y=this.buf.slice(Q,G);Z+=Y,z=!0,this.buf=this.buf.slice(G+J.tag.close.length)}if(z)f=f.replace(/^\n+/,"");return{display:f,thinking:Z}}}function ZD($){let f=Math.max(0,$.length-72),z=$.slice(f).lastIndexOf("<");if(z<0)return-1;let J=f+z,K=$.slice(J).toLowerCase();if(K.length>64)return-1;for(let Q of WZ)if(Q.open.startsWith(K))return J;return-1}function Qf($){let f=$;for(let{open:Z,close:z}of WZ){let J=new RegExp(Z.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"[\\s\\S]*?"+z.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi");f=f.replace(J,"")}return f}var Kf,WZ;var P3=O(()=>{Kf=String.fromCharCode(96),WZ=[{open:"<think>",close:"</think>"},{open:"<thinking>",close:"</thinking>"},{open:`<${Kf}think${Kf}>`,close:`<${Kf}/think${Kf}>`},{open:`<${Kf}redacted_thinking${Kf}>`,close:`<${Kf}/redacted_thinking${Kf}>`}]});function zD($){return $.replace(/\s+/g," ").trim()}function iP($){return $===void 0||$===">"||$==="/"||$===" "||$==="\t"||$===`
316
+ `||$==="\r"}function JD($){let f=$.toLowerCase(),Z=0;while(Z<f.length){let z=f.indexOf("<web_search",Z);if(z<0)return null;if(!iP(f[z+11])){Z=z+1;continue}let J=$.indexOf(">",z);if(J<0)return null;return{index:z,openLen:J-z+1,raw:$.slice(z,J+1)}}return null}function KD($,f){let Z=$.toLowerCase(),z=f;while(z<Z.length){let J=Z.indexOf("</web_search",z);if(J<0)return null;if(!iP(Z[J+12])){z=J+1;continue}let K=$.indexOf(">",J);if(K<0)return null;return{innerEnd:J,tagEnd:K+1}}return null}function pP($){return(/\bquery\s*=\s*"([^"]*)"/i.exec($)??/\bquery\s*=\s*'([^']*)'/i.exec($))?.[1]?.trim()??""}function dP($,f=""){let Z=$.trim();if(!Z){let K=f.trim();return K?{kind:"invoke",query:K}:{kind:"results",query:"",body:""}}let z=QD.exec(Z);if(z)return{kind:"results",query:z[1].trim()||f,body:Z};if(/^\d+\.\s+Title\s*:/m.test(Z)&&/\bURL\s*:/m.test(Z))return{kind:"results",query:f,body:Z};let J=zD(Z)||f;if(J&&J.length<=500&&!/\bURL\s*:\s*https?:\/\//i.test(Z))return{kind:"invoke",query:J};return{kind:"results",query:f||J,body:Z}}function GD($){let f=Math.max(0,$.length-80),z=$.slice(f).lastIndexOf("<");if(z<0)return-1;let J=f+z,K=$.slice(J).toLowerCase();if(K.length>72)return-1;if("<web_search".startsWith(K)||"</web_search".startsWith(K))return J;if(K.startsWith("<web_search")&&!K.includes(">"))return J;if(K.startsWith("</web_search")&&!K.includes(">"))return J;return-1}class X3{buf="";feed($){return this.buf+=$,this.drain(!1)}flush(){return this.drain(!0)}drain($){let f=[],Z=!1,z=(J)=>{if(!J)return;let K=f[f.length-1];if(K?.type==="display")K.text+=J;else f.push({type:"display",text:J})};while(this.buf.length>0){let J=JD(this.buf);if(!J){if($)z(this.buf),this.buf="";else{let G=GD(this.buf);if(G>=0)z(this.buf.slice(0,G)),this.buf=this.buf.slice(G);else z(this.buf),this.buf=""}break}if(J.index>0){let G=this.buf.slice(0,J.index);if(G=G.replace(/\n+$/,""),G)z(G);this.buf=this.buf.slice(J.index)}let K=KD(this.buf,J.openLen);if(!K){let G=this.buf.length-J.openLen;if($||G>65536){let Y=this.buf.slice(J.openLen);f.push({type:"search",block:dP(Y,pP(J.raw))}),Z=!0,this.buf=""}break}let Q=this.buf.slice(J.openLen,K.innerEnd);f.push({type:"search",block:dP(Q,pP(J.raw))}),Z=!0,this.buf=this.buf.slice(K.tagEnd).replace(/^\n+/,"")}if(Z){let J=f[0];if(J?.type==="display")J.text=J.text.replace(/^\n+/,"")}return f.filter((J)=>J.type==="search"||J.text.length>0)}}function UZ($){let f=new X3,Z=[...f.feed($),...f.flush()],z="",J=[];for(let K of Z)if(K.type==="display")z+=K.text;else J.push(K.block);return{display:z,blocks:J,slices:Z}}function W1($){let{slices:f}=UZ($);if(f.every((Z)=>Z.type==="display"))return $;return f.map((Z)=>{if(Z.type==="display")return Z.text;return Z.block.kind==="results"?Z.block.body:Z.block.query}).join("").replace(/^\n+/,"").replace(/\n+$/,"")}var QD;var d2=O(()=>{QD=/^Search results for\s+"([^"]*)"\s*:/im});var FZ={};U0(FZ,{truncateDisplay:()=>H1,toolResultText:()=>I4,summarizeToolResult:()=>W3,summarizeToolCall:()=>i2,formatToolArgs:()=>aP});function H1($,f){let Z=Array.from($);if(Z.length<=f)return $;return Z.slice(0,Math.max(1,f-1)).join("")+"…"}function MZ($){return $.replace(/\s+/g," ").trim()}function tP($){return typeof $==="object"&&$!==null&&!Array.isArray($)?$:null}function v0($,f){let Z=$[f];return typeof Z==="string"?MZ(Z):""}function lP($){let f=$.split("/").filter(Boolean);return f.length<=2?$:`…/${f.slice(-2).join("/")}`}function aP($,f=60){let Z=tP($);if(!Z)return"";let z=[];for(let[J,K]of Object.entries(Z)){if(K===void 0||K===null)continue;let Q=typeof K==="string"?MZ(K):JSON.stringify(K);if(Q===void 0)continue;z.push(`${J}=${H1(Q,f)}`)}return z.join(" ")}function i2($,f,Z=120){let z=tP(f);if(!z)return"";let J=YD($,z);return H1(J||aP(z,60),Z)}function YD($,f){switch($){case"search_web":{let Z=v0(f,"query");if(!Z)return"";let z=[],J=v0(f,"categories");if(J&&J!=="general")z.push(J);let K=v0(f,"language");if(K)z.push(K);let Q=v0(f,"time_range");if(Q)z.push(`past ${Q}`);let G=v0(f,"engines");if(G)z.push(`via ${G}`);return`"${Z}"${z.length>0?` (${z.join(", ")})`:""}`}case"web_fetch":{let Z=v0(f,"url"),z=v0(f,"method");return Z?`${z&&z.toUpperCase()!=="GET"?`${z.toUpperCase()} `:""}${Z}`:""}case"read":{let Z=v0(f,"filePath");if(!Z)return"";let{startLine:z,endLine:J}=f,K=typeof z==="number"||typeof J==="number"?`:${z??1}-${J??""}`:"";return`${lP(Z)}${K}`}case"write":case"edit":case"apply_patch":{let Z=v0(f,"filePath")||v0(f,"path");return Z?lP(Z):""}case"bash":return v0(f,"command");case"grep":{let Z=v0(f,"pattern");if(!Z)return"";let z=v0(f,"path"),J=v0(f,"include"),K=[z,J].filter(Boolean).join(" ");return`${Z}${K?` in ${K}`:""}`}case"glob":return v0(f,"pattern");case"todo":{let Z=f.todos;return Array.isArray(Z)?`${Z.length} item${Z.length===1?"":"s"}`:""}case"skill":return v0(f,"name");case"question":return v0(f,"question");case"task":return v0(f,"description");case"explore":case"codesearch":return v0(f,"query");default:return""}}function I4($){if(typeof $==="string")return $;if($===void 0||$===null)return"";try{return JSON.stringify($,null,2)}catch{return String($)}}function W3($,f,Z=!1,z=100){let J=I4(f).trim();if(J==="")return Z?"error":"(empty)";let K=MZ(J.split(`
317
+ `,1)[0]??"");if(Z||/^(error|search error)\b/i.test(K))return H1(K.replace(/^Error:\s*/i,""),z);if($==="search_web"){let G=/^Found (\d+) results? for /m.exec(J);if(G)return`${G[1]} results`;if(/^No search results found/m.test(J))return"no results";let Y=J.match(/^\d+\.\s+Title\s*:/gm);if(Y&&Y.length>0)return`${Y.length} results`;if(/^Search results for /m.test(J))return"results"}if($==="skill"){let G=/^<skill_content name="([^"]*)"/m.exec(J);if(G)return H1(`loaded ${G[1]} (${J.split(`
318
+ `).length} lines)`,z);return H1(K,z)}let Q=J.split(`
319
+ `).length;if(Q===1)return H1(K,z);return H1(`${K} (${Q} lines)`,z)}function eP($){let f=$??e($0())?.defaultModel??"unknown";console.log(`${u0.bold}\uD83E\uDD16 min-agent${u0.reset} ${u0.dim}(${f})${u0.reset}`)}function H3(){console.log(`${u0.dim}${"─".repeat(60)}${u0.reset}`)}function qZ($,f){let Z=i2($,f,160);console.log(`
320
+ ${u0.yellow}⚡ ${$}${u0.reset} ${u0.dim}${Z}${u0.reset}`)}function l2($,f,Z=!1){let z=I4(f).replace(/\s+$/,""),J=z===""?[]:z.split(`
321
+ `),K=[],Q=0;for(let W of J){if(K.length>=PD)break;if(Q+W.length>sP)break;K.push(W),Q+=W.length+1}if(K.length===0&&J.length>0)K.push(H1(J[0],sP));let G=J.length-K.length,Y=G>0?` (${G} more line${G===1?"":"s"})`:"",P=Z?`${u0.red} ✗${u0.reset}`:`${u0.green} ✓${u0.reset}`,X=K.join(`
322
+ ${u0.dim} `);console.log(`${P} ${u0.dim}${X}${Y}${u0.reset}
323
+ `)}function $X($,f,Z,z){let J=f?.inputTokens??0,K=f?.outputTokens??0,Q=J+K,G=z!==void 0?z:J,Y="";if(G>0&&Z&&Z>0){let P=Math.round(G/Z*100);Y=` | Context: ${XD(P)} ${P}%`}console.log(`${u0.dim}Done in ${$} step(s) | Tokens: ${J} in / ${K} out / ${Q} total${Y}${u0.reset}`)}function XD($){let Z=Math.max(0,Math.min(100,$)),z=Math.round(Z/100*10),J=10-z;return`${$>=80?"\x1B[31m":$>=50?"\x1B[33m":"\x1B[32m"}${"█".repeat(z)}${"░".repeat(J)}\x1B[0m\x1B[90m`}var u0,PD=20,sP=1200;var fX=O(()=>{d();u0={reset:"\x1B[0m",dim:"\x1B[2m",bold:"\x1B[1m",cyan:"\x1B[36m",green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m",magenta:"\x1B[35m",gray:"\x1B[90m"}});var BZ={};U0(BZ,{createSaveThrottle:()=>NZ});function NZ($,f=2000,Z=Date.now){let z=0,J,K=!1,Q=()=>{J=void 0,K=!1,z=Z();try{$()}catch{}};return{request(){if(J){K=!0;return}let G=Z()-z;if(G>=f){Q();return}K=!0,J=setTimeout(Q,f-G)},flush(){if(J)clearTimeout(J),J=void 0;if(K)Q()},cancel(){if(J)clearTimeout(J);J=void 0,K=!1}}}var YX={};U0(YX,{readOnlyBashTool:()=>GX,isReadOnlyCommand:()=>QX,createExploreTool:()=>FD});import{tool as zX,jsonSchema as JX,streamText as WD,stepCountIs as HD}from"ai";function UD(){return`You are a file search specialist. You excel at thoroughly navigating and exploring codebases.
324
+
325
+ Your strengths:
326
+ - Rapidly finding files using glob patterns
327
+ - Searching code and text with powerful regex patterns
328
+ - Reading and analyzing file contents
329
+
330
+ Guidelines:
331
+ - Use glob for broad file pattern matching
332
+ - Use grep for searching file contents with regex
333
+ - Use read when you know the specific file path
334
+ - Use bash ONLY for read-only inspection (ls, find, cat, wc, head, tail, grep, git status/log/diff)
335
+ - Adapt your search approach based on the thoroughness level specified
336
+ - Return file paths as absolute paths in your final response
337
+ - Do NOT create, modify, or delete any files
338
+ - Do NOT run commands that change system state
339
+
340
+ Complete the search request efficiently and report findings clearly.
341
+
342
+ Working directory: ${process.cwd()}
343
+ Platform: ${process.platform}`}function MD($){let f=J0().agent?.exploreMaxSteps,Z=$??f??ZX;return Number.isFinite(Z)&&Z>=1?Math.floor(Z):ZX}function FD($,f,Z,z={}){return zX({description:`Deep codebase exploration agent. Use this to understand project structure, find files by patterns, search code for keywords, trace module relationships, or answer questions about the codebase.
344
+
345
+ Specify thoroughness:
346
+ - "quick": basic search, 1-3 tool calls
347
+ - "medium": moderate exploration, follow references
348
+ - "thorough": comprehensive analysis across multiple locations and naming conventions
349
+
350
+ Examples:
351
+ - "Find all API route handlers" (medium)
352
+ - "How does the auth system work?" (thorough)
353
+ - "Where is the database config?" (quick)`,inputSchema:JX({type:"object",properties:{query:{type:"string",description:"What to explore or find in the codebase"},thoroughness:{type:"string",description:"Search depth: quick, medium, or thorough (default: medium)"}},required:["query"]}),execute:async({query:J,thoroughness:K})=>{let Q=K??"medium";console.error(`\x1B[90m ┌─ Explore (${Q}): ${J.slice(0,60)}\x1B[0m`);try{let G=await qD(J,Q,$,f,z);if(G.usage)Z?.(G.usage);return console.error("\x1B[90m └─ ✓ Done\x1B[0m"),B0(G.text,{direction:"tail"}).content}catch(G){if(f?.aborted)return"Explore cancelled by user.";return Z0("error",`explore agent failed: ${G?.message??String(G)}`),console.error(`\x1B[90m └─ ✗ Failed: ${G.message}\x1B[0m`),`Explore error: ${G.message}`}}})}async function qD($,f,Z,z,J={}){let K=p$(Z),Q={glob:x6,grep:c6,read:u6,bash:GX},Y=[{role:"user",content:`Thoroughness level: ${f}
354
+ ${f==="quick"?"Do a quick search (1-3 tool calls max).":""}
355
+ ${f==="medium"?"Do a moderate exploration, follow references if needed.":""}
356
+ ${f==="thorough"?"Do a comprehensive analysis. Check multiple locations, naming conventions, and cross-references.":""}
357
+
358
+ Task: ${$}`}],P=new AbortController,X=z?AbortSignal.any([z,P.signal]):P.signal,W=WD({model:K,system:UD(),messages:Y,tools:Q,stopWhen:HD(MD(J.maxSteps)),maxRetries:2,abortSignal:X,onError({error:F}){Z0("warn",`explore step failed (will retry): ${String(F)}`)}}),H="";for await(let F of W.fullStream)switch(F.type){case"text-delta":H+=F.text;break;case"tool-call":if(console.error(`\x1B[90m │ ⚡ ${F.toolName}\x1B[0m`),J.shouldStop?.())return Z0("warn","explore agent stopped: parent budget reached"),P.abort(),{text:W1(Qf(H))+`
359
+
360
+ [Explore stopped: run budget reached]`};break;case"error":return Z0("error",`explore stream error: ${String(F.error)}`),P.abort(),{text:W1(Qf(H))||`[Explore error: ${F.error}]`}}let M;try{M=await W.usage}catch{}return{text:W1(Qf(H))||"(explore agent produced no output)",usage:M}}function QX($){let f=$.trim();if(!f)return!1;if(/[<>|]|&&|;|`|\$\(/.test(f))return!1;let Z=f.split(/\s+/),z=Z[0].toLowerCase();if(!KX.has(z))return!1;if(z==="git"){let J=Z[1]?.toLowerCase();if(!J||!ND.has(J))return!1}if(z==="find"&&/\s-(delete|exec|ok|execdir)\b/.test(f))return!1;if((z==="sed"||z==="awk"||z==="perl")&&/\s-i(\.[a-zA-Z0-9_-]+)?\b/.test(f))return!1;return!0}var ZX=20,KX,ND,GX;var PX=O(()=>{Rf();g2();a7();e7();fZ();P3();d2();b$();Tf();d();KX=new Set(["ls","find","cat","wc","head","tail","grep","rg","tree","pwd","stat","du","file","which","echo","printf","sort","uniq","cut","tr","awk","sed","basename","dirname","realpath","env","printenv","git"]),ND=new Set(["status","log","diff","show","rev-parse","branch","remote","tag","ls-files","help","--version","version"]);GX=zX({description:"Run a READ-ONLY shell command (ls, find, cat, wc, head, tail, grep, git status/log/diff, etc.). File modification, redirection, and command chaining are blocked.",inputSchema:JX({type:"object",properties:{command:{type:"string",description:"The read-only shell command to execute"},timeout:{type:"number",description:"Timeout in milliseconds"},cwd:{type:"string",description:"Working directory (relative or absolute)"}},required:["command"]}),execute:async({command:$,timeout:f,cwd:Z})=>{if(!QX($))return`Error: "${$.slice(0,80)}" is not a read-only command. Allowed: ${[...KX].join(", ")} (read-only git subcommands only).`;return v6($,f,Z)}})});var VZ={};U0(VZ,{setSubAgentListener:()=>bD,createTaskTool:()=>AD});import{tool as BD,jsonSchema as VD,streamText as LD,stepCountIs as _D}from"ai";function DD($){let f=J0().agent?.subAgentMaxSteps,Z=$??f??XX;return Number.isFinite(Z)&&Z>=1?Math.floor(Z):XX}function WX(){return`You are a focused sub-agent executing a specific task. Complete the task thoroughly and return a clear result.
361
+
362
+ Rules:
363
+ - Focus only on the assigned task
364
+ - Be thorough but concise
365
+ - Use tools as needed to complete the task
366
+ - Return a clear summary of what you did and the result
367
+
368
+ Working directory: ${process.cwd()}
369
+ Platform: ${process.platform}
370
+ Date: ${new Date().toDateString()}`}function bD($){M3=$}function U3($){if(!M3)console.error($)}function AD($,f,Z,z={}){return BD({description:`Launch a sub-agent to execute a task independently. The sub-agent has its own context and tools. Use this for:
371
+ - Parallel execution: call multiple tasks at once for independent work
372
+ - Context isolation: keep the main conversation clean while the sub-agent explores
373
+ - Delegation: hand off well-defined subtasks (search, analysis, file operations)
374
+
375
+ The sub-agent can read/write files, run commands, search, and use all available tools.
376
+ Call multiple tasks in parallel when the work is independent.`,inputSchema:VD({type:"object",properties:{description:{type:"string",description:"Short description of the task (shown to user)"},prompt:{type:"string",description:"Detailed instructions for the sub-agent"}},required:["description","prompt"]}),execute:async({description:J,prompt:K},Q)=>{let G=Q?.toolCallId;U3(`\x1B[90m ┌─ Sub-agent: ${J}\x1B[0m`);try{let Y=await jD(K,$,f,G,z);if(Y.usage)Z?.(Y.usage);return U3("\x1B[90m └─ ✓ Done\x1B[0m"),B0(Y.text,{direction:"tail"}).content}catch(Y){if(f?.aborted)return"Sub-agent cancelled by user.";let P=Y instanceof Error?Y.message:String(Y);return Z0("error",`sub-agent failed: ${P}`),U3(`\x1B[90m └─ ✗ Failed: ${P}\x1B[0m`),`Sub-agent error: ${P}`}}})}async function jD($,f,Z,z,J={}){let K=p$(f),Q=f3();Q.todo=q6({silent:!0});let G=V4(),Y=O2(),P=await J3(),X={...Q,...P,...G,...Y},W=T2(X);delete X.task,delete X.explore;let H=[{role:"user",content:$}],M=J.loopGuard??new T4,F=DD(J.maxSteps),q=new AbortController,U=Z?AbortSignal.any([Z,q.signal]):q.signal,N=LD({model:K,system:W?`${WX()}
377
+
378
+ ${W}`:WX(),messages:H,tools:X,stopWhen:_D(F),maxRetries:2,abortSignal:U,onError({error:b}){Z0("warn",`sub-agent step failed (will retry): ${String(b)}`)}}),B="";for await(let b of N.fullStream)switch(b.type){case"text-delta":B+=b.text;break;case"tool-call":{let C=M.observe(b.toolName,b.input);if(C==="halt"||C==="cap"){q.abort();let S=C==="halt"?"[Sub-agent stopped: repeated the same action too many times]":"[Sub-agent stopped: too many web searches. Summarize what was found.]";return{text:W1(B)+`
379
+
380
+ `+S}}M3?.({parentToolCallId:z,name:b.toolName,input:b.input,phase:"call"}),U3(`\x1B[90m │ ⚡ ${b.toolName}\x1B[0m`);break}case"tool-result":{if(M3?.({parentToolCallId:z,name:b.toolName,output:b.output,phase:"result"}),M.observeResult(b.toolName,b.output)==="cap")return q.abort(),{text:W1(B)+`
381
+
382
+ [Sub-agent stopped: research budget spent. Summarize what was found.]`};if(J.shouldStop?.())return Z0("warn","sub-agent stopped: parent budget reached"),q.abort(),{text:W1(B)+`
383
+
384
+ [Sub-agent stopped: run budget reached]`};break}case"error":return Z0("error",`sub-agent stream error: ${String(b.error)}`),q.abort(),{text:W1(B)+`
385
+
386
+ [Sub-agent error: ${b.error}]`}}let D=W1(Qf(B)),V;try{V=await N.usage}catch{}return{text:D||"(sub-agent produced no output)",usage:V}}var XX=15,M3=null;var LZ=O(()=>{Rf();GZ();S$();v$();YZ();Y3();Tf();d();P3();d2();b$();wf()});var AZ={};U0(AZ,{runOnceWithSystem:()=>bZ,runOnce:()=>yX,runAgent:()=>DZ,pushTurn:()=>_X,parseContextOverflow:()=>bX,loadImageParts:()=>q3,emptyRetryDelay:()=>BX,emptyResponseMessage:()=>VX,buildUserContent:()=>e2,WRAP_UP_PROMPT_TEXT:()=>gD,WRAP_UP_MESSAGE:()=>LX,SESSION_STATE_HEADER:()=>DX});import{streamText as CD,stepCountIs as OD}from"ai";import{readFileSync as wD,existsSync as yD,statSync as TD}from"fs";import HX from"path";function hD($){if(typeof $!=="number"||!Number.isFinite($)||$<1)return{cap:ID,bounded:!1};return{cap:Math.floor($),bounded:!0}}function BX($,f=FX){if($<=1||f<=0)return 0;return Math.min(RD,f*2**($-2))}function cD($){if($<=0)return Promise.resolve();return new Promise((f)=>setTimeout(f,$))}function VX($){return`模型连续 ${$} 次返回空响应(provider 可能超时或被限流),本轮已停止。发送消息可重试`}function UX(...$){for(let f of $)if(typeof f==="number"&&Number.isFinite(f)&&f>=0)return f;return}function mD(){let{dim:$,reset:f}=k4;console.log(`${$}⟳ 正在初始化(MCP、技能、规则)…${f}`)}function rD(){let{dim:$,reset:f}=k4;console.log(`${$}✓ 就绪${f}`)}function q3($,f){let Z=[];for(let z of $){let J=HX.resolve(process.cwd(),z);if(!yD(J)){f?.("not_found",z);continue}let K=TD(J).size;if(K>NX){f?.("too_large",z,K);continue}let Q=wD(J),G=HX.extname(J).toLowerCase();Z.push({type:"image",image:Q,mimeType:xD[G]??"image/png"}),f?.("attached",z)}return Z}async function e2($,f){if(!f||f.length===0)return $;let Z=q3(f,(z,J,K)=>{if(z==="not_found")console.error(`\x1B[33m Warning: Image not found: ${J}\x1B[0m`);else if(z==="too_large")console.error(`\x1B[33m Warning: Image skipped (${((K??0)/1024/1024).toFixed(1)} MB exceeds ${NX/1024/1024} MB limit): ${J}\x1B[0m`);else console.log(`\x1B[90m \uD83D\uDCCE ${J}\x1B[0m`)});return[{type:"text",text:$},...Z]}async function DZ($,f,Z,z,J){eP(f),H3(),mD(),await nf();try{A$();let K=await X1(),{loadExecHistory:Q,saveSession:G}=await Promise.resolve().then(() => (n$(),yf)),Y=Q(J);if(!Y.ok)return console.error(Y.error),!0;rD(),console.log(`\x1B[36m> ${$}\x1B[0m
387
+ `);let P=await e2($,Z),X=[...Y.messages,{role:"user",content:P}],W=new zf,H=k$();if(Y.taskState)B2(Y.taskState,H);let{createSaveThrottle:M}=await Promise.resolve().then(() => BZ),F=Y.sessionId,q=()=>{try{F=G(X,F,void 0,void 0,H)}catch{}},U=M(q),{hasError:N}=await yX(X,K,f,void 0,void 0,W,{providerName:z,taskState:H,onStepPersist:()=>U.request()});if(U.cancel(),q(),F)console.log(`
388
+ Resume with: min-agent exec --resume ${F}`);return N}finally{await ff()}}function _X($,f,Z,z){let J=Qf(f),K=new Set(z.map((G)=>G.toolCallId)),Q=[];if(J.trim())Q.push({type:"text",text:J});for(let G of Z){if(!K.has(G.toolCallId))continue;Q.push({type:"tool-call",toolCallId:G.toolCallId,toolName:G.toolName,input:G.input})}if(Q.length>0)$.push({role:"assistant",content:Q});for(let G of z){let Y=F3(G.output);$.push({role:"tool",content:[{type:"tool-result",toolCallId:G.toolCallId,toolName:G.toolName,output:{type:"text",value:Y}}]})}}async function oD($,f,Z,z,J,K,Q){let G=f3();G.todo=q6({store:J});let Y=V4(),P=O2(),X=f1(Q)?n9():{},W=await J3(),H={...G,...X,...W,...Y,...P},M=z?(U)=>z.add(U):void 0,{createExploreTool:F}=await Promise.resolve().then(() => (PX(),YX));H.explore=F($,f,M,{shouldStop:K.shouldStop});let{createTaskTool:q}=await Promise.resolve().then(() => (LZ(),VZ));if(H.task=q($,f,M,{loopGuard:K.loopGuard,shouldStop:K.shouldStop}),Z){for(let B of["bash","write","edit","apply_patch"])delete H[B];let U=N7();for(let B of Object.keys(Y))if(!U.has(B))delete H[B];let N=xP();for(let B of Object.keys(W))if(!N.has(B))delete H[B]}return H}function pD($,f,Z,z,J){return{stable:[T2($,b4(f))].filter((Q)=>Q.length>0),volatile:[k9(J),NG(Z),z.promptHint()].filter((Q)=>Q.length>0)}}function dD($){if($.length===0)return null;return{role:"system",content:[DX,...$].join(`
389
+
390
+ `)}}function bX($){if(!a2($))return null;let f=$.match(/n_prompt_tokens["\s:=]+(\d+)/i)?.[1]??$.match(/request\s*\((\d+)\s*tokens?\)/i)?.[1],Z=$.match(/n_ctx["\s:=]+(\d+)/i)?.[1]??$.match(/context size\s*\((\d+)\s*tokens?\)/i)?.[1];return{...f?{promptTokens:Number(f)}:{},...Z?{ctxTokens:Number(Z)}:{}}}function iD($){let f=bX($),Z=f?.promptTokens!=null?i1(f.promptTokens):null,z=f?.ctxTokens!=null?i1(f.ctxTokens):null;if(Z&&z)return`请求内容约 ${Z} token,超过当前上下文窗口 ${z}。请把窗口调大后再试。`;return"请求内容超过当前上下文窗口。请把窗口调大后再试。"}function n4($){if(a2($))return iD($);if($.includes("API key")||$.includes("Unauthorized")||$.includes("Forbidden"))return"Authentication error: Check your API key.";if($.includes("429")||$.includes("rate limit")||$.includes("Rate limit"))return"Rate limited after retries. Please wait and try again.";if($.includes("timeout")||$.includes("ETIMEDOUT"))return`Network error (retries exhausted): ${$}`;return $}function F3($){if(typeof $==="string")return $;try{return JSON.stringify($)??String($)}catch{return String($)}}function a2($){return/exceed_context_size_error|context[\s_-]*(length|window|size)|context_length_exceeded|maximum context|too many tokens|prompt (is )?too long|reduce the (prompt )?length|token limit exceeded/i.test($)}function o0($,...f){if(!$)return;try{$(...f)}catch(Z){Z0("error",`callback failed: ${Z instanceof Error?Z.message:String(Z)}`)}}function tD($,f){let Z=new Set(f.map((Q)=>Q.toolCallId)),z=new Set($.map((Q)=>Q.toolCallId)),J=f.filter((Q)=>z.has(Q.toolCallId)),K=$.filter((Q)=>!Z.has(Q.toolCallId)).map((Q)=>({toolCallId:Q.toolCallId,toolName:Q.toolName,output:lD}));return{calls:$,results:[...J,...K]}}async function MX($){try{return await $.usage}catch{return}}function s2($){return($?.inputTokens??0)>0||($?.outputTokens??0)>0}function AX($,f){if(!s2(f))return $??f;if(!s2($))return f;let Z=($.inputTokens??0)+(f.inputTokens??0),z=($.outputTokens??0)+(f.outputTokens??0);return{...$,...f,inputTokens:Z,outputTokens:z,totalTokens:($.totalTokens??0)+(f.totalTokens??0)||Z+z}}function aD(...$){let f=$.filter((J)=>J!=null);if(f.length===0)return;let Z=f.filter(s2);return(Z.length>0?Z:f).reduce((J,K)=>{let Q=(K.outputTokens??0)-(J.outputTokens??0);if(Q!==0)return Q>0?K:J;return(K.inputTokens??0)>(J.inputTokens??0)?K:J})}function _Z($,f){let Z=$[$.length-1];if(Z&&F4(Z)&&Z.role==="user"){Z.content=f;return}let z={role:"user",content:f};$.push(z),MG(z)}function sD($){if($.researchCapped)return K3;if($.webResearchCount>=6)return XZ;return ED}function eD($){for(let f of y4){let Z=$[f];if(!Z)continue;$[f]={...Z,execute:async()=>Q3}}}function $b($){let f=[];for(let Z of y4){if(!$[Z])continue;delete $[Z],f.push(Z)}return f}async function t2($,f,Z,z,J,K,Q={}){S2($,Q);try{if(!await m7($,Z,K))return!1;if(z.onCompaction)o0(z.onCompaction,"compacting_start");else if(!J)console.log("\x1B[90m⟳ Compacting context...\x1B[0m");let G=await v2($,f,K);if(!G.compacted)return!1;if(G.usage&&Z)Z.add(G.usage);if($.length=0,$.push(...G.messages),Z)Z.resetContext();if(C7(),z.onCompaction)o0(z.onCompaction,`compacted_ok estimated_tokens=${y1($)}`);else if(!J)console.log(`\x1B[90m ✓ Compacted (${y1($)} tokens estimated)\x1B[0m`);return!0}catch(G){return Z0("warn",`compaction failed: ${G instanceof Error?G.message:String(G)}`),o0(z.onCompaction,"compacted_failed"),!1}}async function jX($,f,Z,z,J,K,Q){return A7(()=>fb($,f,Z,z,J,K,Q))}async function fb($,f,Z,z,J,K,Q){let G=p$(Z,Q?.providerName);Z7(),Z0("info",`run start messages=${$.length} model=${typeof G==="string"?G:G.modelId}`);let Y=J??{},P=J0(),X=P.sampling??{},W=Q?.temperature??X.temperature,H=Q?.maxTokens??X.maxTokens,M=Q?.topP??X.topP,F=Q?.taskState??k$();qG(F,$);let{cap:q,bounded:U}=hD(Q?.maxSteps??P.agent?.maxSteps),N=Q?.maxContinues??P.agent?.maxContinues??kD,B=Q?.autoContinue??P.agent?.autoContinue??P.compaction?.autoContinue??!0,D=Math.max(1,Q?.maxEmptyAttempts??P.agent?.maxEmptyAttempts??nD),V=Q?.emptyRetryDelayMs??P.agent?.emptyRetryDelayMs??FX,b=UX(Q?.turnTimeLimitMs,P.agent?.turnTimeLimitMs)??SD,C=UX(Q?.softStepLimit,P.agent?.softStepLimit)??vD,S=Date.now(),I=(A)=>b>0&&Date.now()-S>=b||C>0&&A>=C,j=new T4({steerAfter:Q?.researchSteerAfter??P.agent?.researchSteerAfter,stopAfter:Q?.researchStopAfter??P.agent?.researchStopAfter,totalCap:Q?.researchTotalCap??P.agent?.researchTotalCap}),w={tokens:0},E={abortSignal:z,modelId:Z,taskGoal:F.goal||void 0,get overheadTokens(){return w.tokens}},h=(await d$(Z)).tokens,t=h*T6,v=()=>({pressureTokens:h*h7,targetTokens:h*c7,overheadTokens:w.tokens}),T=P.budget?.maxCostUSD,r=null;if(T!=null&&T>0){let A=Q?.providerName?P.providers?.find((o)=>o.name===Q.providerName):e(P);r=await u2(Z??A?.defaultModel??"")}let R=!1,m=()=>{if(!K||T==null||T<=0)return!1;let A=E2({inputTokens:K.totalInputTokens,outputTokens:K.totalOutputTokens},r);if(A!=null&&A>T)return R=!0,!0;return!1};await t2($,G,K,Y,J,E,v());let K0=0,x=0,y=0,n0=!1,P0=!1,F0,f0=!0,Q0=await oD(Z,z,Q?.planMode??!1,K,F,{loopGuard:j,shouldStop:()=>m()||I(K0)},Q?.memory),Y0=async(A)=>{if(Z0("info",`run end steps=${K0} continues=${x} tokens_in=${F0?.inputTokens??0} tokens_out=${F0?.outputTokens??0}`),vG(),Y.onRunFinish){try{await Y.onRunFinish({stepCount:K0,usage:F0,contextTokens:K?.lastInputTokens??0,hasError:P0,aborted:A.aborted,maxStepsReached:A.maxStepsReached,budgetExceeded:R,continues:x,incomplete:A.incomplete??!1,stopped:A.stopped??!1,emptyResponse:A.emptyResponse??!1,emptyAttempts:y,wrapUp:A.wrapUp??!1})}catch(o){Z0("error",`onRunFinish failed: ${o instanceof Error?o.message:String(o)}`)}return{hasError:P0}}if(P0)return H3(),{hasError:P0};if(H3(),$X(K0,F0,h,K?.lastInputTokens),R)console.log(`\x1B[33m⚠ 已达到预算上限 ($${T}),运行已中断\x1B[0m`);if(A.stopped)console.log(`\x1B[33m⚠ ${G3}\x1B[0m`);if(A.emptyResponse)console.log(`\x1B[33m⚠ ${VX(y)}\x1B[0m`);else if(A.wrapUp)console.log(`\x1B[33m⚠ ${LX}\x1B[0m`);else if(A.maxStepsReached)console.log("\x1B[33m⚠ 已达到自动续跑上限,发送消息继续\x1B[0m");else if(A.incomplete)console.log("\x1B[33m⚠ 还没有完整回复,发送消息可继续\x1B[0m");return{hasError:P0}};while(!0){if(z?.aborted)return Y0({aborted:!0,maxStepsReached:!1});if(m())return Y0({aborted:!0,maxStepsReached:!1});let A;SG();try{A=await Zb({messages:$,systemPrompt:f,model:G,abortSignal:z,callbacks:J,cbs:Y,tracker:K,taskState:F,allTools:Q0,maxSteps:q,stepBounded:U,temperature:W,maxTokens:H,topP:M,thinking:Q?.thinking,memory:Q?.memory,providerType:(Q?.providerName?P.providers?.find((z0)=>z0.name===Q.providerName):e(P))?.type,modelId:Z,checkBudget:m,overTurnBudget:(z0)=>I(K0+z0),pruneBudget:v,overhead:w,compactThreshold:t,allowContextAbort:f0,loopGuard:j,onStepPersist:Q?.onStepPersist})}catch(z0){let w0=z0 instanceof Error?z0.message:String(z0);if(Z0("error",w0),P0=!0,Y.onStreamError)o0(Y.onStreamError,n4(w0));else console.error(`\x1B[31m${n4(w0)}\x1B[0m`);return Y0({aborted:Boolean(z?.aborted),maxStepsReached:!1})}if(K0+=A.stepCount,F0=AX(F0,A.usage),A.hasError)P0=!0;if(A.budgetExceeded)R=!0;if(A.userAborted)return Y0({aborted:!0,maxStepsReached:!1});if(A.doomLoop)return Y0({aborted:!1,maxStepsReached:!1,stopped:!0});if(A.hasError&&!A.contextPressure&&!A.toolPressure)return Y0({aborted:!1,maxStepsReached:!1});if(R)return Y0({aborted:!0,maxStepsReached:!1});if(A.toolPressure){S2($,v());continue}if(A.contextPressure&&A.stepCount===0&&!A.lastStepHadTools){if(await t2($,G,K,Y,J,{...E,force:!0},v())){if(x++,x>N)return Y0({aborted:!1,maxStepsReached:!0,incomplete:!0});continue}P0=!0;let w0=n4(A.overflowError??"");if(Y.onStreamError)o0(Y.onStreamError,w0);else console.error(`\x1B[31m${w0}\x1B[0m`);return Y0({aborted:!1,maxStepsReached:!1})}if(A.emptyCompletion){if(y++,y>=D)return Z0("warn",`empty response from provider ${y}x, ending run`),Y0({aborted:!1,maxStepsReached:!1,incomplete:!0,emptyResponse:!0});if(x++,x>N)return Y0({aborted:!1,maxStepsReached:!0,incomplete:!0});let z0=BX(y,V);if(Z0("warn",`empty response from provider, retry ${y}/${D-1} after ${z0}ms`),Y.onRetryNotice)o0(Y.onRetryNotice,{kind:"empty_response",attempt:y,maxAttempts:D-1,delayMs:z0});else if(!J)console.log(`\x1B[90m⟳ 模型返回空响应,重试 ${y}/${D-1}…\x1B[0m`);await cD(z0);continue}let o=A.researchCap||A.researchSteer,i=!j.producedArtifact&&(o||A.lastStepHadTools&&(j.researchCapped||!B&&j.webResearchCount>0)),u=A.lastStepHadTools||A.xmlToolFollowUp||A.providerStall,G0=A.xmlToolFollowUp||B&&(A.contextPressure||A.lastStepHadTools||A.providerStall);if(!i&&!G0){let z0=!B&&A.maxStepsReached&&A.lastStepHadTools;if(z0&&!J)console.log(`\x1B[33m⚠ 本轮已达到步数上限(${q}),发送消息继续\x1B[0m`);return Y0({aborted:!1,maxStepsReached:z0,incomplete:u&&!z0})}if(A.wrapUp||I(K0)){if(n0)return Z0("warn",`turn budget spent after wrap-up (steps=${K0})`),Y0({aborted:!1,maxStepsReached:!1,incomplete:!0,wrapUp:!0});if(n0=!0,x++,x>N)return Y0({aborted:!1,maxStepsReached:!0,incomplete:!0});if(Z0("info",`auto-continue reason=wrap_up steps=${K0} elapsed=${Date.now()-S}ms`),Y.onRetryNotice)o0(Y.onRetryNotice,{kind:"wrap_up",attempt:1,maxAttempts:1,delayMs:0});else if(!J)console.log("\x1B[90m⟳ 本轮预算用尽,正在收尾…\x1B[0m");await t2($,G,K,Y,J,E,v()),_Z($,qX);continue}if(i){if(x++,x>N)return Y0({aborted:!1,maxStepsReached:!0,incomplete:!0});$b(Q0),j.markCapped(),Z0("info",`auto-continue reason=${o?A.researchCap?"research_cap":"research_steer":"awaiting_deliverable"}`),await t2($,G,K,Y,J,E,v()),_Z($,K3);continue}if(x++,x>N)return Y0({aborted:!1,maxStepsReached:!0,incomplete:u});Z0("info",`auto-continue reason=${A.xmlToolFollowUp?"xml_search":A.contextPressure?"context":A.providerStall?"provider_stall":"tools_without_reply"}`);let O0=await t2($,G,K,Y,J,{...E,force:A.contextPressure},v());if(A.contextPressure&&!O0)f0=!1;_Z($,sD(j))}}class CX{messages;onFlush;stepText="";toolCalls=[];toolResults=[];innerSteps=0;lastStepHadTools=!1;hadTools=!1;hadAssistantText=!1;producedTokens=0;constructor($,f){this.messages=$;this.onFlush=f}get pendingResults(){return this.toolResults.length}get hasUnpairedCalls(){let $=new Set(this.toolResults.map((f)=>f.toolCallId));return this.toolCalls.some((f)=>!$.has(f.toolCallId))}appendText($){this.stepText+=$}recordCall($){this.toolCalls.push($)}recordResult($){this.toolResults.push($)}nextMissingCallId(){return`missing-${this.innerSteps}-${this.toolCalls.length}`}flushStep(){let $=this.toolCalls.length>0||this.toolResults.length>0,f=Boolean(this.stepText.trim());if(!f&&!$)return;if(this.lastStepHadTools=$,$)this.hadTools=!0;if(f)this.hadAssistantText=!0;this.producedTokens+=I6(this.stepText);for(let z of this.toolCalls)this.producedTokens+=I6(F3(z.input));let Z=tD(this.toolCalls,this.toolResults);_X(this.messages,this.stepText,Z.calls,Z.results),this.innerSteps++,this.stepText="",this.toolCalls=[],this.toolResults=[],this.onFlush?.({steps:this.innerSteps})}}class OX{cbs;interactive;md=new W2;thinkingSplit=new HZ;xmlSplit=new X3;rawText="";hadThinking=!1;thinkingOpen=!1;constructor($,f){this.cbs=$;this.interactive=f}emitThinking($){if(!$)return;if(this.hadThinking=!0,this.cbs.onThinkingDelta){o0(this.cbs.onThinkingDelta,$);return}if(process.env.MIN_AGENT_SHOW_THINKING==="0"||process.env.MIN_AGENT_SHOW_THINKING==="false")return;if(!this.thinkingOpen)this.thinkingOpen=!0,process.stderr.write(`
391
+ ${k4.dim}\uD83D\uDCAD 思考${k4.reset}
392
+ `);process.stderr.write(`${k4.dim}${$}${k4.reset}`)}emitDisplay($){try{if(this.cbs.onAssistantDisplayDelta){this.cbs.onAssistantDisplayDelta($);return}let f=this.md.write($);if(f)process.stdout.write(f)}catch(f){Z0("error",`display callback failed: ${f instanceof Error?f.message:String(f)}`)}}feedReasoning($){this.emitThinking($)}mirror($){if(!$)return;this.rawText+=$,this.emitDisplay($)}pipeXml($,f){let Z=$?this.xmlSplit.feed($):[];if(f)Z.push(...this.xmlSplit.flush());let z=[];for(let J of Z)if(J.type==="display"){if(!J.text)continue;this.mirror(J.text),z.push(J)}else z.push(J);return z}feedText($){let{display:f,thinking:Z}=this.thinkingSplit.feed($);return this.emitThinking(Z),this.pipeXml(f,!1)}flushSplitText(){let $=this.thinkingSplit.flush();return this.emitThinking($.thinking),this.pipeXml($.display,!0)}flushMarkdown(){if(this.interactive){try{let $=this.md.flush();if($)process.stdout.write($)}catch{}if(this.rawText.trim())console.log()}this.rawText=""}flushOutput(){let $=this.flushSplitText();return this.flushMarkdown(),$}flushOnError(){if(this.interactive&&this.rawText.trim())console.log();let $=this.flushSplitText();if(this.interactive)try{process.stdout.write(this.md.flush())}catch{}return this.rawText="",$}}class wX{params;stop={budget:!1,doom:!1,steer:!1,cap:!1,context:!1,tools:!1,stall:!1,wrapUp:!1};hasError=!1;assembler;renderer;usageSteps=0;innerController=new AbortController;forwardAbort=()=>this.innerController.abort();xmlSearchRecovered=!1;answerAfterXml=!1;pendingLoop=null;stepFinishSeen=!1;stepUsage;totalUsage;overflowError;constructor($){this.params=$;this.assembler=new CX($.messages,(f)=>{if($.onStepPersist)o0($.onStepPersist,f)}),this.renderer=new OX($.cbs,!$.callbacks)}get signal(){return this.innerController.signal}attachAbort(){this.params.abortSignal?.addEventListener("abort",this.forwardAbort,{once:!0})}detachAbort(){this.params.abortSignal?.removeEventListener("abort",this.forwardAbort)}onStepFinish($){let{tracker:f,checkBudget:Z,allowContextAbort:z,compactThreshold:J,messages:K,overTurnBudget:Q}=this.params;if($&&f)f.update($);if(this.usageSteps++,Z())this.stop.budget=!0,this.innerController.abort();else if(Q(this.assembler.innerSteps))this.stop.wrapUp=!0,this.innerController.abort();else if(z&&this.usageSteps>=2&&f&&f.lastInputTokens>J)this.stop.context=!0,this.innerController.abort();else if(this.usageSteps>=uD&&R2(K,this.params.pruneBudget())!==K)this.stop.tools=!0,this.innerController.abort()}noteStepUsage($){this.stepUsage=AX(this.stepUsage,$)}resolvedUsage($){let f=aD($,this.totalUsage,this.stepUsage);if(s2(f))return f;let Z=this.estimateUsage();if(!Z)return f;if(this.params.tracker)this.params.tracker.update(Z);return Z0("info",`usage estimated for aborted pass in=${Z.inputTokens} out=${Z.outputTokens}`),Z}estimateUsage(){let $=this.assembler.producedTokens;if($===0)return;let f=y1(this.params.messages)+this.params.overhead.tokens;return{inputTokens:f,outputTokens:$,totalTokens:f+$,inputTokenDetails:{noCacheTokens:f,cacheReadTokens:void 0,cacheWriteTokens:void 0},outputTokenDetails:{textTokens:$,reasoningTokens:void 0}}}onStepError($){let f=String($);if(a2(f))this.stop.context=!0;Z0("warn",`step failed (will retry): ${f}`)}async applySlices($){for(let f of $)if(f.type==="display"){if(!f.text)continue;if(this.assembler.pendingResults>0)this.assembler.flushStep();if(this.assembler.appendText(f.text),this.xmlSearchRecovered&&f.text.trim())this.answerAfterXml=!0}else if(await this.materializeXmlSearch(f.block))return!0;return!1}applyLoopAction($){if($==="ok")return!1;if($==="halt")return this.stop.doom=!0,this.innerController.abort(),!0;return this.pendingLoop=$,eD(this.params.allTools),!1}settlePendingLoop(){if(!this.pendingLoop)return!1;if(this.assembler.hasUnpairedCalls)return!1;return this.stop.steer=this.pendingLoop==="steer",this.stop.cap=this.pendingLoop==="cap",this.pendingLoop=null,this.innerController.abort(),!0}async flushAndSettleLoop(){if(this.assembler.hasUnpairedCalls)return!1;if(await this.flushOutputAndStep())return!0;return this.settlePendingLoop()}async materializeXmlSearch($){let{cbs:f,loopGuard:Z}=this.params,z="search_web",J=$.query.trim(),K={query:J},Q=this.assembler.nextMissingCallId();if(this.renderer.flushMarkdown(),this.assembler.recordCall({toolCallId:Q,toolName:"search_web",input:K}),z7("search_web",K),f.onToolCall)o0(f.onToolCall,"search_web",K,Q);else qZ("search_web",K);if(Z.researchCapped){let P=Q3;if(this.assembler.recordResult({toolCallId:Q,toolName:"search_web",output:P}),A2("search_web",P),f.onToolResult)o0(f.onToolResult,"search_web",P,{toolCallId:Q,isError:!1});else l2("search_web",P,!1);return this.xmlSearchRecovered=!0,!1}if(this.applyLoopAction(Z.observe("search_web",K))){let P=G3;if(this.assembler.recordResult({toolCallId:Q,toolName:"search_web",output:P}),A2("search_web",P),f.onToolResult)o0(f.onToolResult,"search_web",P,{toolCallId:Q,isError:!1});else l2("search_web",P,!1);return!0}let G=$.kind==="results"?$.body:await this.executeSearchWeb(J,Q),Y=typeof G==="string"&&/^(error|search error)\b/i.test(G);if(this.assembler.recordResult({toolCallId:Q,toolName:"search_web",output:G}),A2("search_web",G),f.onToolResult)o0(f.onToolResult,"search_web",G,{toolCallId:Q,isError:Y});else l2("search_web",G,Y);return this.xmlSearchRecovered=!0,this.applyLoopAction(Z.observeResult("search_web",Y?"error":G)),!1}async executeSearchWeb($,f){if(!$)return'Search error: "query" must be a non-empty string.';let Z=this.params.allTools.search_web;if(typeof Z?.execute!=="function")return"Search error: search_web is unavailable.";try{let z=await Z.execute({query:$},{toolCallId:f,messages:this.params.messages,abortSignal:this.signal});return typeof z==="string"?z:F3(z)}catch(z){return`Search error: ${z instanceof Error?z.message:String(z)}`}}async flushOutputAndStep(){let $=await this.applySlices(this.renderer.flushOutput());return this.assembler.flushStep(),$}async handleEvent($){let{cbs:f,loopGuard:Z}=this.params;switch($.type){case"start-step":if(this.stepFinishSeen=!1,!this.assembler.hasUnpairedCalls)this.assembler.flushStep();return!1;case"finish-step":return this.stepFinishSeen=!0,this.noteStepUsage($.usage),await this.flushAndSettleLoop();case"finish":if(s2($.totalUsage))this.totalUsage=$.totalUsage;return!1;case"reasoning-delta":{let z=typeof $.text==="string"?$.text:"";if(z)this.renderer.feedReasoning(z);return!1}case"text-delta":{if(this.assembler.pendingResults>0&&await this.flushOutputAndStep())return!0;return await this.applySlices(this.renderer.feedText($.text))}case"tool-call":{if(this.assembler.pendingResults>0&&await this.flushOutputAndStep())return!0;if(await this.applySlices(this.renderer.flushOutput()))return!0;let z=$.toolName||"unknown",J=$.toolCallId||this.assembler.nextMissingCallId();if(this.assembler.recordCall({toolCallId:J,toolName:z,input:$.input}),z7(z,$.input),f.onToolCall)o0(f.onToolCall,z,$.input,J);else qZ(z,$.input);if(this.applyLoopAction(Z.observe(z,$.input)))return await this.flushOutputAndStep(),!0;return!1}case"tool-result":case"tool-error":{let z=$.type==="tool-error",J=z?$.error:$.output,K=z?`Error: ${F3($.error)}`:$.output;if(this.assembler.recordResult({toolCallId:$.toolCallId,toolName:$.toolName||"unknown",output:J}),A2($.toolName,K),f.onToolResult)o0(f.onToolResult,$.toolName,K,{toolCallId:$.toolCallId,isError:z});else l2($.toolName,K,z);if(this.applyLoopAction(Z.observeResult($.toolName||"unknown",z?"error":J)),this.stepFinishSeen||this.pendingLoop)return await this.flushAndSettleLoop();return!1}case"error":{let z=String($.error);if(y7($.error))return this.stop.stall=!0,Z0("warn",`provider stall: ${O6($.error)}`),await this.flushOutputAndStep(),this.innerController.abort(),!0;if(a2(z))return this.stop.context=!0,this.overflowError=z,Z0("warn",`context overflow: ${z}`),await this.flushOutputAndStep(),this.innerController.abort(),!0;if(this.hasError=!0,Z0("error",`stream error: ${z}`),f.onStreamError)o0(f.onStreamError,n4(z));else console.error(`\x1B[31m${n4(z)}\x1B[0m`);return!1}}return!1}snapshot($,f={}){return{hasError:this.hasError,userAborted:Boolean(this.params.abortSignal?.aborted),budgetExceeded:this.stop.budget,doomLoop:this.stop.doom,researchSteer:this.stop.steer,researchCap:this.stop.cap,contextPressure:this.stop.context,toolPressure:this.stop.tools,maxStepsReached:this.params.stepBounded&&this.assembler.innerSteps>=this.params.maxSteps&&this.assembler.lastStepHadTools,wrapUp:this.stop.wrapUp,lastStepHadTools:this.assembler.lastStepHadTools,xmlToolFollowUp:this.xmlSearchRecovered&&!this.answerAfterXml&&!this.stop.doom,emptyCompletion:!this.stop.context&&!this.assembler.hadAssistantText&&!this.assembler.hadTools&&!this.xmlSearchRecovered,overflowError:this.overflowError,providerStall:this.stop.stall,stepCount:this.assembler.innerSteps,usage:$,...f}}async finalize($){return await this.flushOutputAndStep(),this.settlePendingLoop(),this.snapshot(this.resolvedUsage($?await MX($):void 0))}async handleException($,f){await this.applySlices(this.renderer.flushOnError()),this.assembler.flushStep(),this.settlePendingLoop();let Z=this.resolvedUsage(f?await MX(f):void 0);if(this.params.abortSignal?.aborted)return this.snapshot(Z,{userAborted:!0});if(y7($)){let K=this.assembler.hadAssistantText||this.assembler.hadTools||this.renderer.hadThinking;return Z0("warn",`provider stall: ${O6($)}`),this.stop.stall=!0,this.snapshot(Z,{hasError:!1,userAborted:!1,emptyCompletion:!K})}if($ instanceof Error&&$.name==="AbortError")return this.snapshot(Z,{userAborted:!1});let z=$ instanceof Error?$.message:String($);if(Z0("error",z),a2(z))return this.stop.context=!0,this.overflowError=z,this.snapshot(Z,{hasError:!1,contextPressure:!0,userAborted:!1});this.hasError=!0;let J=n4(z);if(this.params.cbs.onStreamError)o0(this.params.cbs.onStreamError,J);else if(J!==z)console.error(`\x1B[31m${J}\x1B[0m`);else console.error(`\x1B[31mError: ${z}\x1B[0m`);return this.snapshot(Z,{hasError:!0,userAborted:!1,contextPressure:!1})}}async function Zb($){let f=new wX($),Z;try{f.attachAbort();let z=pD($.allTools,$.messages,$.taskState,$.loopGuard,$.memory),J=[$.systemPrompt,...z.stable].join(`
393
+
394
+ `);S2($.messages,$.pruneBudget());let K=dD(z.volatile),Q=K?[...$.messages,K]:$.messages;$.overhead.tokens=k6(J,$.allTools)+(K?k6(String(K.content)):0);let G=A9({runOverride:$.thinking,providerType:$.providerType,modelId:$.modelId}),Y=()=>CD({model:$.model,system:J,messages:Q,tools:$.allTools,stopWhen:OD($.maxSteps),maxRetries:3,abortSignal:f.signal,...$.temperature!=null?{temperature:$.temperature}:{},...$.maxTokens!=null?{maxOutputTokens:$.maxTokens}:{},...$.topP!=null?{topP:$.topP}:{},onStepFinish({usage:P}){f.onStepFinish(P)},onError({error:P}){f.onStepError(P)}});Z=e4.run(G,Y);for await(let P of Z.fullStream)if(await f.handleEvent(P))break;return await f.finalize(Z)}catch(z){return f.handleException(z,Z)}finally{f.detachAbort()}}async function yX($,f,Z,z,J,K,Q){let G=I1(),Y=Ef(G,f);return jX($,Y,Z,z,J,K,Q)}async function bZ($,f,Z,z,J,K,Q){return jX($,f,Z,z,J,K,Q)}var ID=1e5,kD=40,nD=4,FX=1000,RD=8000,SD=1200000,vD=120,uD=4,ED="Continue the task from where you left off. Do not wait for another user message. If the work is complete, give a brief summary and stop.",qX="You are out of time budget for this turn. Stop starting new work: finish or save what is already in progress, then reply with a short summary of what is done, what is not, and the exact next step. Do not call more tools than needed to leave things in a consistent state.",gD,NX=5242880,xD,k4,LX="本轮已达时间或步数预算,已让模型收尾并停止。发送消息可继续",DX="## Session state (reference only — not a to-do list, not part of the conversation)",lD="Error: tool call was interrupted before a result was returned.";var gf=O(()=>{Rf();T7();d();C4();GZ();r2();S$();v$();Zf();$1();V1();T1();YZ();b5();Y3();P3();d2();fX();wf();Sf();Tf();F6();Zf();gD=qX,xD={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},k4="NO_COLOR"in process.env?{dim:"",reset:""}:{dim:"\x1B[90m",reset:"\x1B[0m"}});var B3={};U0(B3,{pushTurn:()=>zb,popTurn:()=>Jb,createUndoStack:()=>jZ,clearStack:()=>N3});function jZ(){return[]}function zb($,f,Z,z){return[...$,{start:f,end:Z,uiEnd:z}]}function Jb($){if($.length===0)return null;return{turn:$[$.length-1],stack:$.slice(0,-1)}}function N3($){return[]}var IX={};U0(IX,{getWorkingTreeDiff:()=>CZ});import{execFile as Kb}from"child_process";import{promisify as Qb}from"util";async function CZ($=process.cwd(),f=Yb){try{await f("git rev-parse --is-inside-work-tree",$)}catch{return{ok:!1,reason:"not_git",message:"当前目录不是 git 仓库"}}let Z="",z="";try{Z=await f("git diff --stat",$),z=await f("git diff",$)}catch(K){return{ok:!1,reason:"error",message:K instanceof Error?K.message:String(K)}}if(!z.trim())return{ok:!1,reason:"no_changes",message:"工作区无未提交变更"};let J=z.length>TX?z.slice(0,TX)+`
395
+ … [diff 过长,已截断]`:z;return{ok:!0,diff:Z?`${Z}
396
+
397
+ ${J}`:J}}async function Yb($,f){let Z=Pb($),{stdout:z}=await Gb(Z[0],Z.slice(1),{cwd:f,encoding:"utf-8",timeout:1e4,maxBuffer:10485760});return z}function Pb($){let f=[],Z="",z=null;for(let J of $)if(z)if(J===z)z=null;else Z+=J;else if(J==='"'||J==="'")z=J;else if(J===" "){if(Z)f.push(Z),Z=""}else Z+=J;if(Z)f.push(Z);return f}var TX=8000,Gb;var OZ=O(()=>{Gb=Qb(Kb)});var V3={};U0(V3,{snapshotTokenInfo:()=>Xb});async function Xb($,f,Z){let z=await d$(f);return gQ($,z.tokens,y1(Z))}var L3=O(()=>{T1();Sf()});function n($,f){$.addMessage({id:`sys-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,role:"system",content:f,timestamp:Date.now()})}async function kX($,f,Z,z,J,K,Q,G){let{parseSlashArgs:Y}=await Promise.resolve().then(() => (t8(),TK)),P=Y($),X=$.slice(1).trim().split(/\s+/),W=(P?.command||X[0]||"").toLowerCase(),H=P?[...P.tokens,...P.partial?[P.partial]:[]]:X.slice(1),M=H.join(" "),{truncateDisplay:F}=await Promise.resolve().then(() => FZ);switch(W){case"exit":case"quit":case"q":Q();break;case"new":G.startNewSession();break;case"undo":{let{popTurn:q}=await Promise.resolve().then(() => B3),U=q(G.undoStack);if(!U){n(f,"没有可撤销的内容");break}G.setUndoStack(U.stack),Z.splice(U.turn.start,U.turn.end-U.turn.start),f.truncateMessages(U.turn.uiEnd),n(f,"✓ 已撤销 1 轮");break}case"redo":{if(!G.lastUserMessage){n(f,"没有可重发的消息");break}let q=G.lastUserMessage;return f.addMessage({id:`user-${Date.now()}`,role:"user",content:q,timestamp:Date.now()}),Z.push({role:"user",content:q}),"run"}case"diff":{let{getWorkingTreeDiff:q}=await Promise.resolve().then(() => (OZ(),IX)),U=await q();if(!U.ok){let N=U.reason==="not_git"?"非 git 仓库,无法显示 diff":U.reason==="no_changes"?"工作区无未提交变更":`diff 失败: ${U.message}`;n(f,N)}else n(f,U.diff);break}case"plan":{G.togglePlanMode(),n(f,G.planMode?"✓ 计划模式已开启:仅只读工具可用,输出计划后再次输入 /plan 确认并执行":"✓ 已退出计划模式");break}case"reload":await G.reloadSystemPrompt();break;case"resume":case"sessions":{let q=M.trim();if(!q){G.openSessionPicker();break}G.applySession(q);break}case"rename":{let q=M.trim();if(!q){n(f,"用法: /rename <标题>");break}let{saveSession:U,renameSession:N}=await Promise.resolve().then(() => (n$(),yf)),B=G.sessionId;if(!B)B=U(Z,void 0,void 0,void 0,G.taskState),G.setSessionId(B);if(N(B,q))n(f,`✓ 会话已重命名为: ${q}`);else n(f,"重命名失败: 会话不存在");break}case"attach":case"image":{let q=M;if(!q){n(f,"用法: /attach <图片路径>");break}let{loadImageParts:U}=await Promise.resolve().then(() => (gf(),AZ)),B=[{type:"text",text:""},...U([q],(D,V)=>{if(D==="not_found")n(f,`⚠ 图片不存在: ${V}`);else if(D==="too_large")n(f,`⚠ 图片超过 5MB 限制: ${V}`)})];if(B.length<=1)break;return Z.push({role:"user",content:B}),f.addMessage({id:`user-${Date.now()}`,role:"user",content:`[\uD83D\uDCCE 图片] ${q}`,timestamp:Date.now()}),"run"}case"compact":{let{compactMessages:q}=await Promise.resolve().then(() => (T1(),n6)),{estimateTokens:U}=await Promise.resolve().then(() => (T1(),n6)),{resolveModel:N}=await Promise.resolve().then(() => (Rf(),OY)),{clearStack:B}=await Promise.resolve().then(() => B3);if(Z.length<4)n(f,"消息太少,无需压缩");else{n(f,"⟳ 正在压缩上下文...");let D=N(z);G.setUndoStack(B(G.undoStack));let V=await q(Z,D,{keepRecentTurns:2,taskGoal:G.taskState.goal||void 0});if(Z.length=0,Z.push(...V.messages),J)J.resetContext();n(f,`✓ 已压缩 (约 ${U(Z)} tokens)`);let{snapshotTokenInfo:b}=await Promise.resolve().then(() => (L3(),V3));f.setTokenInfo(await b(J,z,Z))}break}case"provider":{let{applyProviderSwitch:q,listProviderChoices:U}=await Promise.resolve().then(() => (M6(),GG));if(M){let N=q(M);if(!N.ok){n(f,N.message);break}K(N.defaultModel),G.setProvider(N.name),n(f,`✓ 当前服务商已切换为: ${N.name}`);break}if(U().length===0){n(f,"无已配置服务商,运行: min-agent setup");break}f.showProviderPicker();break}case"model":{if(M){let q=await Promise.resolve().then(() => (d(),B1)),U=q.loadConfig(),N=q.getActiveProvider(U);if(N)N.defaultModel=M,q.saveConfig(U);K(M),n(f,`✓ 默认模型已设为: ${M}`)}else f.showModelPicker();break}case"models":{let{fetchModels:q}=await Promise.resolve().then(() => (d(),B1)),{loadConfig:U,getActiveProvider:N}=await Promise.resolve().then(() => (d(),B1)),B=U(),D=N(B);if(!D?.baseURL||!D?.apiKey){n(f,"未配置 Provider,运行: min-agent setup");break}n(f,"正在获取模型列表...");let V=await q(D.baseURL,D.apiKey);if(V.length===0)n(f,"无法获取模型列表");else{let b=V.map((C)=>{let S=C===D.defaultModel?" ← 默认":"";return` ${C}${S}`});n(f,`可用模型 (${V.length}):
398
+ ${b.join(`
399
+ `)}`)}break}case"memory":{let{takeScopeFlags:q}=await Promise.resolve().then(() => z4),{addMemory:U,loadMemories:N,defaultMemoryScope:B,formatMemoryLine:D,parseMemoryMode:V,resolveMemoryMode:b,setMemoryMode:C,setMemoryOverride:S,isMemoryEnabled:I}=await Promise.resolve().then(() => (V1(),R9)),{scope:j,rest:w}=q(H),E=w.length===1?V(w[0]):void 0;if(E){let h=j==="project"?"project":"global";C(E,h),S(E),n(f,`✓ 记忆已${E==="on"?"开启":"关闭"}(${h==="project"?"项目":"全局"})`);break}let l=w.join(" ").trim();if(l){let h=j??B();U(l,[],h);let t=I()?"":"(当前未开启,下一轮对话不会用到;可用 /memory on 开启)";n(f,`✓ 已保存${h==="project"?"项目":"全局"}记忆: "${l}"${t}`)}else{let h=b(),t=h.source==="cli"?"本次启动参数":h.source==="project"?"项目":h.source==="global"?"全局":"默认",v=`记忆:${h.memory==="on"?"开":"关"}(${t})`,r=(j?[j]:["project","global"]).map((m)=>{let K0=N(m),x=m==="project"?"项目记忆":"全局记忆";if(K0.length===0)return`${x}: 无`;let y=K0.map((n0,P0)=>D(n0,P0));return`${x} (${K0.length}):
400
+ ${y.join(`
401
+ `)}`}),R=!j&&N("project").length===0&&N("global").length===0;n(f,[v,R?"无已保存的记忆":r.join(`
402
+ `),"设置: /memory on|off [--project]","保存: /memory <文本> [--project]"].join(`
403
+ `))}break}case"path":case"pwd":n(f,process.cwd());break;case"paste":{let{getClipboardImage:q}=await Promise.resolve().then(() => (Z6(),xK)),U=q();if(!U){n(f,"剪贴板中未找到图片");break}n(f,`\uD83D\uDCCE 剪贴板图片 (${(U.data.length/1024).toFixed(1)} KB)`);let N=M||"What's in this image?",B=[{type:"text",text:N},{type:"image",image:U.data,mimeType:U.mimeType}];return Z.push({role:"user",content:B}),f.addMessage({id:`user-${Date.now()}`,role:"user",content:`${N} [\uD83D\uDCCE 图片]`,timestamp:Date.now()}),"run"}case"tokens":{let{getContextWindowInfo:q}=await Promise.resolve().then(() => (Sf(),v7)),{getModelPrice:U,estimateCost:N,formatCost:B}=await Promise.resolve().then(() => (C4(),R6)),{estimateTokens:D}=await Promise.resolve().then(() => (T1(),n6)),V=await q(z),b=D(Z),C=J.lastInputTokens>0?J.lastInputTokens:b,S=V.tokens>0&&C>0?Math.round(C/V.tokens*100):0,I=await U(z??""),j=N({inputTokens:J.totalInputTokens,outputTokens:J.totalOutputTokens},I),w=J.lastInputTokens>0?"":",按对话内容估算",E=V.source==="fallback"?`,未读到接口窗口,按 ${V.tokens} 默认`:"";n(f,[`上下文: ${C} / ${V.tokens} tokens (${S}%${w}${E})`,`累计: ${J.totalInputTokens} in / ${J.totalOutputTokens} out`,...j!=null?[`成本: 约 ${B(j)}`]:[],`消息: ${Z.length}`].join(`
404
+ `));break}case"budget":{let{takeScopeFlags:q}=await Promise.resolve().then(() => z4),{getBudgetSnapshot:U,setBudgetMaxCost:N}=await Promise.resolve().then(() => (d(),B1)),{getModelPrice:B,estimateCost:D,formatCost:V}=await Promise.resolve().then(() => (C4(),R6)),{scope:b,rest:C}=q(H),S=C.join(" ").trim();if(S){let v=parseFloat(S);if(Number.isNaN(v)||v<=0){n(f,"用法: /budget <USD 金额> [--project]");break}let T=b==="project"?"project":"global";N(v,T),n(f,`✓ 预算上限已设为: $${v}(${T==="project"?"项目":"全局"})`);break}let I=U(),j=I.maxCostUSD,w=I.source==="project"?"项目":I.source==="global"?"全局":null,E=await B(z??""),l=D({inputTokens:J.totalInputTokens,outputTokens:J.totalOutputTokens},E),h=l!=null?`约 ${V(l)}`:"--",t=j!=null?`上限 $${j}${w?`(${w})`:""}`:"未设置上限";n(f,`预算: 已用${h} / ${t}
405
+ 设置: /budget <金额> 或 /budget <金额> --project`);break}case"permission":{let{takeScopeFlags:q}=await Promise.resolve().then(() => z4),{getPermissionSnapshot:U,parsePermissionMode:N,permissionModeLabel:B,setPermissionMode:D}=await Promise.resolve().then(() => (d(),B1)),{getPermissionOverride:V,setPermissionOverride:b}=await Promise.resolve().then(() => (G$(),Q9)),{scope:C,rest:S}=q(H),I=(E)=>E==="cli"?"本次启动参数":E==="project"?"项目":E==="global"?"全局":"默认";if(S.length===0){let E=U(),l=V(),h=l??E.permission,t=l?"cli":E.source;n(f,[`当前确认: ${B(h)}(${I(t)})`,"设置: /permission ask|accept-edits|allow-all [--project]"].join(`
406
+ `));break}let j=N(S[0]);if(!j||S.length>1){n(f,"用法: /permission ask|accept-edits|allow-all [--project]");break}let w=C==="project"?"project":"global";D(j,w),b(j),n(f,`✓ 确认已设为${B(j)}(${w==="project"?"项目":"全局"})`);break}case"think":case"thinking":{let{takeScopeFlags:q}=await Promise.resolve().then(() => z4),{parseThinkingEffort:U,thinkingEffortLabel:N,thinkingChoicesForModel:B,setThinkingEffort:D,setThinkingOverride:V}=await Promise.resolve().then(() => ($1(),j9)),{scope:b,rest:C}=q(H);if(C.length===0){f.showThinkPicker(b==="project"?"project":"global");break}let S=U(C[0]),I=B(z);if(!S||C.length>1){n(f,`用法: /think [${I.join("|")}] [--project]`);break}if(!I.includes(S)){n(f,`该模型支持: ${I.join(", ")}`);break}let j=b==="project"?"project":"global";D(S,j),V(S),n(f,`✓ 思考强度已设为 ${N(S)}(${j==="project"?"项目":"全局"})`);break}case"ctx":{let{getActiveProvider:q,getEffectiveConfig:U}=await Promise.resolve().then(() => (d(),B1)),{CTX_CHOICES:N,parseCtxChoice:B,setOllamaContextChoice:D,ctxChoiceLabel:V}=await Promise.resolve().then(() => (H4(),fG));if(q(U())?.type!=="ollama"){n(f,"窗口档位仅本地模型可用");break}if(H.length===0){f.showCtxPicker();break}let b=B(H[0]);if(!b||H.length>1){n(f,`用法: /ctx [${N.join("|")}]`);break}if(!D(b).ok){n(f,"窗口档位仅本地模型可用");break}G.refreshTokenBar(),n(f,`✓ 上下文窗口已设为${V(b)}`);break}case"mcp":{let{loadMcpConfig:q}=await Promise.resolve().then(() => (S$(),L4)),{getMcpStatus:U}=await Promise.resolve().then(() => (S$(),L4)),N=q(),B=Object.entries(N.mcpServers);if(B.length===0)n(f,"无 MCP 服务器配置");else{let D=U(),V=B.map(([b,C])=>{let S=C.enabled===!1,I=D[b],j=I?.connected??!1,w=I?.tools.length??0,E=[w>0?`${w} tools`:"",(I?.resource_count??0)>0?`${I.resource_count} resources`:"",(I?.prompt_count??0)>0?`${I.prompt_count} prompts`:""].filter(Boolean).join(", "),l=S?"disabled":j?"connected":"disconnected",h=!S&&!j&&I?.error?` — ${I.error}`:"";return` ${b}: ${l}${E?` (${E})`:""}${h}`});n(f,`MCP 服务器 (${B.length}):
407
+ ${V.join(`
408
+ `)}`)}break}case"skills":{let{discoverSkills:q,getAllSkills:U,getSkill:N,getStaleDisabledSkills:B,setSkillEnabled:D}=await Promise.resolve().then(() => (v$(),I2));q({silent:!0});let V=H.filter(Boolean),b=V[0],C=U().sort((j,w)=>j.name.localeCompare(w.name));if(b==="enable"||b==="disable"){let j=V.includes("--project")?"project":"global",w=V.slice(1).filter((v)=>v!=="--project"&&v!=="--global");if(w.length===0){n(f,`用法: /skills ${b} <name...> [--project]`);break}let E=new Set(C.map((v)=>v.name)),l=w.filter((v)=>!E.has(v));if(l.length>0){n(f,`未找到 skill: ${l.join(", ")}
409
+ 可用: ${E.size?[...E].join(", "):"无"}`);break}let t=D(w,b==="enable",j).filter((v)=>v.blockedBy).map((v)=>` ⚠ ${v.name} 仍为${v.enabled?"启用":"禁用"}(被 ${v.blockedBy} 范围覆盖)`);n(f,[`✓ 已${b==="enable"?"启用":"禁用"}(${j}): ${w.join(", ")}`,...t].join(`
410
+ `));break}if(b==="info"){let j=V[1],w=j?N(j):void 0;if(!w){n(f,`未找到 skill: ${j??"(未指定)"}
411
+ 可用: ${C.length?C.map((t)=>t.name).join(", "):"无"}`);break}let E=w.enabled?"enabled":`disabled(${w.disabledScope==="project"?"proj":"glob"})`,l=[`Name: ${w.name}`,`Status: ${E}`,...w.builtin?["Source: 内置"]:[],...w.version?[`Version: ${w.version}`]:[],`Description: ${w.description.replace(/\s+/g," ")}`,`Location: ${w.location}`,...w.allowedTools.length?[`Tools: ${w.allowedTools.join(", ")}`]:[],...w.requiredBins.length?[`Requires: ${w.requiredBins.join(", ")}`]:[]],h=w.content.trim();n(f,[...l,...h?["","--- Content ---","",h.slice(0,4000)]:[]].join(`
412
+ `));break}if(b&&b!=="list"){n(f,"用法: /skills [list|info <name>|enable <name...> [--project]|disable <name...> [--project]]");break}let S=B();if(C.length===0&&S.length===0){n(f,"无可用 skills。添加 SKILL.md 到 .min-agent/skills/<name>/");break}let I=C.map((j)=>{let w=j.enabled?"enabled":`disabled(${j.disabledScope==="project"?"proj":"glob"})`,E=j.builtin?" 内置":"";return` ${j.name} ${w}${E} ${F(j.description.replace(/\s+/g," "),56)}`});if(S.length>0)I.push(` ⚠ disabledSkills/enabledSkills 中无对应 skill: ${S.join(", ")}`);n(f,`Skills (${C.filter((j)=>j.enabled).length} enabled / ${C.length}):
413
+ ${I.join(`
414
+ `)}
415
+ 切换: /skills disable <name> [--project]`);break}case"sandbox":{let{takeScopeFlags:q}=await Promise.resolve().then(() => z4),{getSandboxSnapshot:U,setSandboxConfig:N}=await Promise.resolve().then(() => (d(),B1)),{parseSandboxMode:B,parseNetworkPolicy:D,getEffectiveSandboxPolicy:V,sandboxEnforcementCaveat:b,sandboxModeLabel:C,setSandboxOverride:S}=await Promise.resolve().then(() => (E0(),p3)),{scope:I,rest:j}=q(H),w=(v)=>v==="cli"?"本次启动参数":v==="env"?"环境变量":v==="project"?"项目":v==="global"?"全局":"默认";if(j.length===0){let v=U(),T=[...v.extraWriteRoots.length>0?[`额外可写目录: ${v.extraWriteRoots.join(", ")}`]:[],...v.extraReadRoots.length>0?[`额外可读目录: ${v.extraReadRoots.join(", ")}`]:[]],r=b(V().mode);n(f,[`当前隔离: ${v.label}(${w(v.source)})`,...T,...r?[r]:[],"设置: /sandbox off|workspace|strict [--project]"," /sandbox network allow|deny [--project]"].join(`
416
+ `));break}let E=I==="project"?"project":"global",l=E==="project"?"项目":"全局";if(j[0]==="network"){let v=D(j[1]);if(!v||j.length>2){n(f,"用法: /sandbox network allow|deny [--project]");break}N({network:v},E),S({network:v}),n(f,`✓ 联网已设为${v==="deny"?"禁止":"允许"}(${l})`);break}let h=B(j[0]);if(!h||j.length>1){n(f,`用法: /sandbox off|workspace|strict [--project]
417
+ /sandbox network allow|deny [--project]`);break}N({mode:h},E),S({mode:h});let t=b(h);n(f,[`✓ 隔离已设为${C(h)}(${l})`,...t?[t]:[]].join(`
418
+ `));break}case"help":n(f,["命令:"," 输入 / 弹出命令菜单 (输入过滤, ↑↓ 选择, Tab/Enter 执行, Esc 关闭)"," /new 新建会话(保留当前)"," /compact 压缩上下文"," /model [n] 交互式选择/切换模型"," /models 列出可用模型"," /provider 交互式选择服务商(也可 /provider <name>)"," /memory 查看记忆开关与已保存内容(/memory on|off 开关;也可 /memory 文本 保存)"," /tokens 显示上下文占用、累计用量与成本"," /ctx 选择本地模型上下文窗口(也可 /ctx 2k|4k|8k|12k|16k|32k|64k|128k|256k|auto)"," /budget [n] 查看/设置预算上限(--project 写入当前项目)"," /permission 查看/设置确认模式(ask|accept-edits|allow-all,--project 写入当前项目)"," /think 交互式选择思考强度(档位随当前模型;也可 /think off|low|medium|high|max)"," /sandbox 查看/设置隔离(off|workspace|strict,--project 写入当前项目)"," /undo 撤销上一轮"," /redo 重发最后一条消息"," /diff 显示工作区未提交变更"," /plan 切换只读计划模式"," /sessions 列出/切换已保存会话"," /resume [id] 同 /sessions"," /reload 重新加载规则"," /rename <t> 重命名当前会话"," /attach <p> 附加本地图片"," /mcp 显示 MCP 状态"," /skills 显示/启用/禁用 skills(/skills info <name> 查看详情)"," /path 显示工作目录"," /paste [t] 粘贴剪贴板图片 + 可选提示"," /help 显示帮助"," /exit 退出","","快捷键:"," Esc 取消当前任务"," Ctrl+J 输入框换行"," Ctrl+V 粘贴剪贴板图片到输入框"," 多行粘贴 收成片段,发送时带上全文"," Ctrl+C 清空输入(↑↓ 可找回);生成中则中断,空输入连按两次退出"," Ctrl+B 消息区选择模式"," Home/End 行首/行尾"," PageUp/Down 滚动消息"," 鼠标滚轮 滚动消息"," 鼠标拖拽 选择文本并自动复制"," 鼠标双击 选词并复制"," 鼠标三击 选中该条消息并复制"," 鼠标点击 工具调用行展开/收起"," ↑↓ 菜单中选择;否则翻阅输入历史"," ← → 移动输入框光标"," 选项提问 ↑↓ 移动 · 单选 Enter 确认 · 多选空格勾选后 Enter · Esc 取消"," 鼠标点击 输入框内定位光标"].join(`
419
+ `));break;default:n(f,`未知命令: /${W},输入 /help 查看可用命令`)}}function nX($){let f=null;return{run:async()=>{let K=$.messages.length,Q=$.tui.messageCount(),G=!1;f=new AbortController,$.tui.setRunning(!0,"思考中...");let{summarizeToolCall:Y,summarizeToolResult:P,toolResultText:X}=await Promise.resolve().then(() => FZ),{getContextWindowInfo:W}=await Promise.resolve().then(() => (Sf(),v7)),{getModelPrice:H,estimateCost:M,formatCost:F}=await Promise.resolve().then(() => (C4(),R6)),{runOnceWithSystem:q,emptyResponseMessage:U,WRAP_UP_MESSAGE:N}=await Promise.resolve().then(() => (gf(),AZ)),{clearStack:B,pushTurn:D}=await Promise.resolve().then(() => B3),{setSubAgentListener:V}=await Promise.resolve().then(() => (LZ(),VZ)),{LOOP_HALT_MESSAGE:b}=await Promise.resolve().then(() => (Y3(),rP)),{createSaveThrottle:C}=await Promise.resolve().then(() => BZ),{snapshotTokenInfo:S}=await Promise.resolve().then(() => (L3(),V3)),I=C(()=>$.persist?.()),j=$.tracker.totalInputTokens,w=$.tracker.totalOutputTokens,E=null,l=0,h=async()=>{let R=++l,m=await S($.tracker,$.getModel(),$.messages);if(R!==l)return;$.tui.setTokenInfo(m)},t=()=>{if(E!=null)return;E=setTimeout(()=>{E=null,h()},50)},v=async()=>{if(E!=null)clearTimeout(E),E=null;await h()},T=$.tracker.subscribe(t);h();let r={onAssistantDisplayDelta:(R)=>$.tui.appendToLast(R),onThinkingDelta:(R)=>{$.tui.setRunning(!0,"推理中..."),$.tui.appendToThinking(R)},onToolCall:(R,m,K0)=>{$.tui.setRunning(!0,`执行 ${R}...`),$.tui.addMessage({id:`tool-${K0||`${Date.now()}-${Math.random().toString(36).slice(2,6)}`}`,role:"tool",content:Y(R,m),toolName:R,toolCallId:K0,timestamp:Date.now()})},onToolResult:(R,m,K0)=>{$.tui.setRunning(!0,"思考中..."),$.tui.setToolResult(K0.toolCallId,R,P(R,m,K0.isError),X(m),K0.isError)},onStreamError:(R)=>{$.tui.addMessage({id:`err-${Date.now()}`,role:"system",content:`错误: ${R}`,timestamp:Date.now()})},onCompaction:(R)=>{if(G=!0,$.setUndoStack(B($.getUndoStack())),R==="compacting_start")$.tui.addMessage({id:`compact-${Date.now()}`,role:"system",content:"正在整理过长的对话记录…",timestamp:Date.now()});else if(R.startsWith("compacted_ok"))$.tui.addMessage({id:`compact-ok-${Date.now()}`,role:"system",content:"✓ 已整理对话记录,继续执行",timestamp:Date.now()})},onRetryNotice:(R)=>{$.tui.addMessage({id:`retry-${Date.now()}`,role:"system",content:R.kind==="wrap_up"?"⟳ 本轮预算用尽,正在收尾…":`⟳ 模型返回空响应,重试 ${R.attempt}/${R.maxAttempts}…`,timestamp:Date.now()})},onRunFinish:async(R)=>{if(f=null,$.tui.setRunning(!1),await v(),R.aborted)return;if(R.budgetExceeded)$.tui.addMessage({id:`budget-${Date.now()}`,role:"system",content:"⚠ 已达到预算上限。/budget 查看或调高",timestamp:Date.now()});let m=Math.max(0,$.tracker.totalInputTokens-j),K0=Math.max(0,$.tracker.totalOutputTokens-w),x=$.tracker.lastInputTokens;if(m>0||K0>0||x>0){let y=await W($.getModel()),n0=y.tokens>0&&x>0?Math.round(x/y.tokens*100):null,P0=await H($.getModel()??""),F0=M({inputTokens:m,outputTokens:K0},P0),f0=[`Done in ${R.stepCount} step(s)`,`Tokens: ${m} in / ${K0} out / ${m+K0} total`,...n0!=null?[`Context: ${n0}%`]:[],...F0!=null?[`约 ${F(F0)}`]:[]];$.tui.addMessage({id:`done-${Date.now()}`,role:"system",content:f0.join(" | "),timestamp:Date.now()})}if(R.maxStepsReached)$.tui.addMessage({id:`maxsteps-${Date.now()}`,role:"system",content:"⚠ 已达到自动续跑上限,发送消息继续",timestamp:Date.now()});if(R.stopped)$.tui.addMessage({id:`stopped-${Date.now()}`,role:"system",content:`⚠ ${b}`,timestamp:Date.now()});else if(R.wrapUp)$.tui.addMessage({id:`wrapup-${Date.now()}`,role:"system",content:`⚠ ${N}`,timestamp:Date.now()});else if(R.emptyResponse)$.tui.addMessage({id:`empty-${Date.now()}`,role:"system",content:`⚠ ${U(R.emptyAttempts??0)}`,timestamp:Date.now()});else if(R.incomplete)$.tui.addMessage({id:`incomplete-${Date.now()}`,role:"system",content:"还没有完整回复,发送消息可继续",timestamp:Date.now()})}};try{V((m)=>{if(m.phase!=="call")return;$.tui.appendToolChild(m.parentToolCallId,{name:m.name,summary:Y(m.name,m.input)})});let R={providerName:$.getProvider(),taskState:$.getTaskState(),onStepPersist:()=>I.request(),...$.getPlanMode()?{planMode:!0}:{}};await q($.messages,$.getSystemPrompt(),$.getModel(),f?.signal,r,$.tracker,R)}catch(R){if(!f)return;let m=R instanceof Error?R.message:String(R);r.onStreamError(m)}finally{if(T(),E!=null)clearTimeout(E),E=null;if(V(null),I.cancel(),!G)$.setUndoStack(D($.getUndoStack(),K,$.messages.length,Q));f=null,$.tui.setRunning(!1),await v()}},abort:(K)=>{if(!f)return!1;return Promise.resolve().then(() => (g2(),sY)).then((Q)=>Q.killActiveProcesses()).catch(()=>{}),f.abort(),f=null,K.setRunning(!1),K.addMessage({id:`sys-${Date.now()}`,role:"system",content:"(已取消)",timestamp:Date.now()}),!0},getController:()=>f}}function _3($){return typeof $==="object"&&$!==null}function $8($){if(typeof $==="string")return $;if(!Array.isArray($))return"";let f=[];for(let Z of $)if(_3(Z)&&Z.type==="text"&&typeof Z.text==="string")f.push(Z.text);return f.join("")}function Wb($){if(!Array.isArray($))return!1;return $.some((f)=>_3(f)&&(f.type==="image"||f.type==="file"))}function Hb($){if(!_3($))return $;if(($.type==="text"||$.type==="json")&&"value"in $)return $.value;return $}function Ub($){if($8($).trim())return $8($);if(Wb($))return"[\uD83D\uDCCE 图片]";return null}function D3($){for(let f=$.length-1;f>=0;f--){let Z=$[f];if(Z?.role!=="user")continue;if($8(Z.content).trim())return $8(Z.content)}return null}function wZ($){let f=[];for(let Z=0;Z<$.length;Z++){let z=$[Z];if(z.role==="assistant"){f.push(...Mb(z,Z));continue}let J=Fb(z,Z);if(J)f.push(J)}return f}function Mb($,f){let Z=$8($.content);if(!Z)return[];let{slices:z}=UZ(Z);if(z.every((Q)=>Q.type==="display"))return[{id:`hyd-${f}-assistant`,role:"assistant",content:Z,timestamp:0}];let J=[],K=0;for(let Q of z){if(Q.type==="display"){if(!Q.text.trim())continue;J.push({id:`hyd-${f}-assistant-${K++}`,role:"assistant",content:Q.text,timestamp:0});continue}let G=Q.block.query,Y=Q.block.kind==="results"?Q.block.body:Q.block.query,P={query:G};J.push({id:`hyd-${f}-search-${K++}`,role:"tool",content:i2("search_web",P),toolName:"search_web",toolCallId:`xml-search-hyd-${f}-${K}`,toolResult:Y,toolResultSummary:W3("search_web",Y),timestamp:0})}return J}function Fb($,f){if($.role==="user"){let Z=Ub($.content);if(Z==null)return null;return{id:`hyd-${f}-user`,role:"user",content:Z,timestamp:0}}if($.role==="tool"){if(!Array.isArray($.content))return null;for(let Z of $.content){if(!_3(Z)||Z.type!=="tool-result")continue;let z=typeof Z.toolName==="string"?Z.toolName:"";if(!z)continue;let J=Hb(Z.output),K=I4(J),Q=typeof Z.toolCallId==="string"?Z.toolCallId:void 0;return{id:`hyd-${f}-tool`,role:"tool",content:z,toolName:z,toolCallId:Q,toolResult:K,toolResultSummary:W3(z,J),timestamp:0}}return null}return null}var yZ=O(()=>{d2()});function RX(){let $=Promise.resolve(),f=0,Z=0,z=()=>{return};return{run(J,K){let Q=f;Z++;let G=()=>Q!==f?Promise.resolve(K()):J(),Y=$.then(G,G);return $=Y.then(z,z),Y.finally(()=>{Z--})},cancelAll(){f++},get size(){return Z}}}function SX($){if($.running)return{ok:!1,reason:"running"};if($.currentId===$.targetId)return{ok:!1,reason:"current"};if(!$.exists)return{ok:!1,reason:"missing"};return{ok:!0}}function TZ($){if($==="running")return"请先等待当前回合结束或按 Esc 取消";if($==="current")return"已是当前会话";return"会话不存在"}function vX($){if($.running)return{ok:!1,reason:"running"};if(!$.sessionId&&$.messageCount===0)return{ok:!1,reason:"already_new"};return{ok:!0}}function uX($){if($==="running")return"请先等待当前回合结束或按 Esc 取消";return"已是新会话"}var EX={};U0(EX,{runTui:()=>Ab});function qb(){w$("provider",($)=>{if($.length>0)return[];return M4().map((f)=>({value:f.name,description:f.current?`${f.baseURL}(当前)`:f.baseURL}))})}function Nb(){let $=()=>a1().map((f)=>({value:f.id,description:f.title}));w$("sessions",$),w$("resume",$)}function Bb(){w$("ctx",($)=>{if($.length>0)return[];return H$.map((f)=>f==="auto"?{value:f,description:"按模型探测"}:{value:f})})}function Vb(){let $=(f)=>{let Z=[{value:"--project",description:"写入当前项目"},{value:"--global",description:"写入全局配置"}],z=new Set(f),J=Z.filter((K)=>!z.has(K.value));if(f.length===0){let K=e(J0())?.defaultModel;return[...c1(K).map((Q)=>({value:Q})),...J]}return J};w$("think",$),w$("thinking",$)}function Lb(){w$("memory",($)=>{let f=[{value:"--project",description:"写入当前项目"},{value:"--global",description:"写入全局配置"}],Z=new Set($),z=f.filter((J)=>!Z.has(J.value));if($.length===0)return[{value:"on",description:"开启记忆(跨会话保留)"},{value:"off",description:"关闭记忆(默认)"},...z];return z})}function _b(){w$("permission",($)=>{let f=[{value:"--project",description:"写入当前项目"},{value:"--global",description:"写入全局配置"}],Z=new Set($),z=f.filter((J)=>!Z.has(J.value));if($.length===0)return[{value:"ask",description:"危险操作前询问"},{value:"accept-edits",description:"自动允许改文件,危险命令仍询问(默认)"},{value:"allow-all",description:"全部自动允许"},...z];return z})}function Db(){w$("sandbox",($)=>{let f=[{value:"--project",description:"写入当前项目"},{value:"--global",description:"写入全局配置"}],Z=new Set($),z=f.filter((J)=>!Z.has(J.value));if($.length===0)return[{value:"off",description:"不隔离(默认)"},{value:"workspace",description:"只允许写入工作目录"},{value:"strict",description:"读写都限制在工作目录"},{value:"network",description:"设置是否允许联网"},...z];if($[0]==="network")return[...[{value:"allow",description:"允许联网"},{value:"deny",description:"禁止联网"}].filter((K)=>!Z.has(K.value)),...z];return z})}function bb(){w$("skills",($)=>{let f=$[0];if(f===void 0)return[{value:"list",description:"列出全部 skills"},{value:"info",description:"查看 skill 详情"},{value:"enable",description:"启用 skill"},{value:"disable",description:"禁用 skill"}];if(f==="info")return P1().map((J)=>({value:J.name,description:J.description}));if(f!=="enable"&&f!=="disable")return[];let Z=P1();return[...(f==="enable"?[...Z.filter((J)=>!J.enabled).map((J)=>({value:J.name,description:J.description})),...D4().map((J)=>({value:J,description:"(配置中的孤儿条目)"}))]:Z.filter((J)=>J.enabled).map((J)=>({value:J.name,description:J.description}))).filter((J)=>!$.includes(J.value)),...$.includes("--project")?[]:[{value:"--project",description:"仅对当前项目生效"}]]})}async function Ab($){let{modelId:f,resumeSessionId:Z,images:z,providerName:J,initialPrompt:K}=$;await nf(),A$(),bb(),_b(),Vb(),Bb(),qb(),Lb(),Db(),Nb();let Q=await X1(),G=$0(),Y=I1(),P=Ef(Y,Q),X=[],W=Z,H=f??e(G)?.defaultModel,M=J;if(H)f4(H);let F=new zf,q=k$(),U=jZ(),N=null,B=!1;if(Z){let T=Z$(Z);if(T)X=T.messages,W=Z,B2(T.taskState,q)}let D=null,V=new t5({onSubmit:async(T)=>{let r=T.display;if(r.trim().startsWith("/")){if(await kX(r,V,X,H,F,(m)=>{H=m,V.setModel(m),C()},l,{undoStack:U,setUndoStack:(m)=>{U=m},lastUserMessage:N,setLastUserMessage:(m)=>{N=m},sessionId:W,setSessionId:(m)=>{W=m},planMode:B,togglePlanMode:()=>{B=!B},reloadSystemPrompt:async()=>{let m=await X1();P=Ef(I1(),m),n(V,`✓ 已重载规则(${m.join("").length} 字符)`)},applySession:S,startNewSession:I,openSessionPicker:j,taskState:q,refreshTokenBar:C,setProvider:(m)=>{M=m}})==="run"&&D)await D.run(),b();return}if(N=r,V.addMessage({id:`user-${Date.now()}`,role:"user",content:r,timestamp:Date.now()}),X.push({role:"user",content:T.content}),D)await D.run(),b()},onNotice:(T)=>{n(V,T)},onConfirm:(T)=>{if(V.hideConfirm(),xf)xf(T),xf=null},onQuestionAnswer:(T)=>{if(V.hideQuestion(),hf)hf(T),hf=null},onModelPick:(T)=>{V.hideModelPicker();let r=$0(),R=e(r);if(R)R.defaultModel=T,Promise.resolve().then(() => (d(),B1)).then((m)=>m.saveConfig(r));H=T,V.setModel(T),C(),n(V,`✓ 默认模型已设为: ${T}`)},onModelCancel:()=>{V.hideModelPicker()},onThinkPick:(T,r)=>{m1(T,r),$4(T),V.hideThinkPicker(),n(V,`✓ 思考强度已设为 ${B$(T)}(${r==="project"?"项目":"全局"})`)},onThinkCancel:()=>{V.hideThinkPicker()},onCtxPick:(T)=>{let r=Of(T);if(V.hideCtxPicker(),!r.ok){n(V,"窗口档位仅本地模型可用");return}C(),n(V,`✓ 上下文窗口已设为${l1(T)}`)},onCtxCancel:()=>{V.hideCtxPicker()},onProviderPick:(T)=>{V.hideProviderPicker();let r=x5(T);if(!r.ok){n(V,r.message);return}if(M=r.name,H=r.defaultModel,V.setModel(r.defaultModel),C(),r.defaultModel)f4(r.defaultModel);n(V,`✓ 当前服务商已切换为: ${r.name}`)},onProviderCancel:()=>{V.hideProviderPicker()},onSessionPick:(T)=>{V.hideSessionPicker(),S(T)},onSessionCancel:()=>{V.hideSessionPicker()},onToggleSelectionMode:()=>{V.toggleSelectionMode()},onExitSelectionMode:()=>{V.setSelectionMode(!1)},onExit:()=>{l()}},f??e(G)?.defaultModel,W);D=nX({tui:V,messages:X,tracker:F,getModel:()=>H,getProvider:()=>M,getPlanMode:()=>B,getUndoStack:()=>U,setUndoStack:(T)=>{U=T},getSystemPrompt:()=>P,getTaskState:()=>q,persist:()=>b()});function b(){if(X.length===0)return;try{W=D$(X,W,void 0,void 0,q)}catch{}}async function C(){let{snapshotTokenInfo:T}=await Promise.resolve().then(() => (L3(),V3));V.setTokenInfo(await T(F,H,X))}function S(T){let r=SX({running:Boolean(D?.getController()),currentId:W,targetId:T,exists:Boolean(Z$(T))});if(!r.ok){n(V,TZ(r.reason));return}if(X.length>0)W=D$(X,W,void 0,void 0,q);let R=Z$(T);if(!R){n(V,TZ("missing"));return}X.length=0,X.push(...R.messages),B2(R.taskState,q),W=T,U=N3(U),F.reset(),N=D3(R.messages),V.setSessionId(T),V.update({messages:wZ(R.messages)}),C(),n(V,`✓ 已切换到: ${R.meta.title}`)}function I(){let T=vX({running:Boolean(D?.getController()),sessionId:W,messageCount:X.length});if(!T.ok){n(V,uX(T.reason));return}if(X.length>0)W=D$(X,W,void 0,void 0,q);X.length=0,m5(q),W=void 0,U=N3(U),F.reset(),N=null,V.setSessionId(void 0),V.update({messages:[]}),C(),n(V,"✓ 已新建会话")}function j(){if(a1().length===0){n(V,"无已保存的会话");return}V.showSessionPicker()}B8((T)=>IZ.run(()=>new Promise((r)=>{xf=r,V.showConfirm(T)}),()=>!1)),V8((T,r,R)=>IZ.run(()=>new Promise((m)=>{hf=m,V.showQuestion(T,r,Boolean(R))}),()=>null));let w,E=new Promise((T)=>{w=T}),l=()=>{if(V.setSelectionMode(!1),b(),D?.getController()){if(i7(),IZ.cancelAll(),xf)xf(!1),xf=null,V.hideConfirm();if(hf)hf(null),hf=null,V.hideQuestion();D.getController().abort(),V.setRunning(!1),V.addMessage({id:`sys-${Date.now()}`,role:"system",content:"(已取消)",timestamp:Date.now()})}else w?.()};if(V.start(),X.length>0)V.update({messages:wZ(X)});await C();let h=K?.trim()??"",t=(T,r)=>{if(T==="not_found")n(V,`⚠ 图片不存在: ${r}`);else if(T==="too_large")n(V,`⚠ 图片超过 5 MB 限制: ${r}`);else n(V,`\uD83D\uDCCE ${r}`)};if(z&&z.length>0){let T=[{type:"text",text:h},...q3(z,t)];if(T.length>1||h){if(X.push({role:"user",content:T}),V.addMessage({id:`user-${Date.now()}`,role:"user",content:h?h:`[\uD83D\uDCCE 图片] ${z.join(", ")}`,timestamp:Date.now()}),h)N=h;await D.run(),b()}}else if(h)N=h,V.addMessage({id:`user-${Date.now()}`,role:"user",content:h,timestamp:Date.now()}),X.push({role:"user",content:h}),await D.run(),b();let v=()=>{if(D?.getController())l()};process.on("SIGINT",v),await E,process.off("SIGINT",v);try{b()}finally{B8(null),V8(null),V.destroy(),await ff()}}var xf=null,hf=null,IZ;var gX=O(()=>{IG();S$();v$();t8();Zf();T1();wf();gf();g2();G$();d();r2();n$();yZ();$1();H4();M6();IZ=RX()});var xX={};U0(xX,{startTuiSession:()=>kZ});async function kZ($){if(!a$()){let z=Boolean(process.stdin.isTTY&&process.stdout.isTTY);if(!aJ(!1,z))throw new a("Not configured.",{hint:"Run: min-agent setup"});let{offerInteractiveSetup:J}=await Promise.resolve().then(() => (i9(),GK));if(await J("session-gate"),!a$())throw new a("Not configured.",{hint:"Run: min-agent setup"})}let{runTui:f}=await Promise.resolve().then(() => (gX(),EX)),Z=$.positionals.join(" ").trim();await f({modelId:$.model,providerName:$.provider,resumeSessionId:$.resume,images:$.images,initialPrompt:Z||void 0})}var nZ=O(()=>{d();Y$();c9()});function pX($=300000){let f=new Map,Z=(z)=>{let J=f.get(z);if(!J)return;return clearTimeout(J.timer),f.delete(z),J};return{waitConfirm(z){return new Promise((J)=>{let K=setTimeout(()=>{f.delete(z),J(!1)},$);f.set(z,{kind:"confirm",resolve:J,timer:K})})},waitQuestion(z){return new Promise((J)=>{let K=setTimeout(()=>{f.delete(z),J(null)},$);f.set(z,{kind:"question",resolve:J,timer:K})})},resolveConfirm(z,J){let K=f.get(z);if(!K||K.kind!=="confirm")return!1;return Z(z),K.resolve(J),!0},resolveQuestion(z,J){let K=f.get(z);if(!K||K.kind!=="question")return!1;return Z(z),K.resolve(J),!0},cancel(z){let J=Z(z);if(!J)return;if(J.kind==="confirm")J.resolve(!1);else J.resolve(null)},has(z){return f.has(z)}}}import{randomUUID as dX}from"crypto";function RZ(){let $=process.env.MIN_AGENT_SERVE_CORS;return $==="1"||$==="true"}function j3(){if(RZ())return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization"};return{}}function C3($){return{name:$.name,description:$.description,location:$.location,enabled:$.enabled,...$.disabledScope?{disabled_scope:$.disabledScope}:{},...$.version?{version:$.version}:{},...$.allowedTools.length?{allowed_tools:$.allowedTools}:{},...$.requiredBins.length?{requires_bins:$.requiredBins}:{},...$.builtin?{builtin:!0}:{},...$.alwaysLoad?{always_load:!0}:{}}}function L($,f,Z){let z={"Content-Type":"application/json; charset=utf-8",...j3()};$.writeHead(f,z),$.end(JSON.stringify(Z))}function M$($){try{return decodeURIComponent($)}catch{return null}}function Rb($){return new Promise((f,Z)=>{let z=[],J=0,K=setTimeout(()=>{$.destroy(),Z(Error("body_timeout"))},nb);$.on("data",(Q)=>{if(J+=Q.length,J>iX){clearTimeout(K),$.removeAllListeners("data"),$.pause(),Z(Error("body_too_large"));return}z.push(Q)}),$.on("end",()=>{clearTimeout(K),f(Buffer.concat(z).toString("utf-8"))}),$.on("error",(Q)=>{clearTimeout(K),Z(Q)})})}async function D0($){let f;try{f=await Rb($)}catch(Z){if(Z?.message==="body_too_large")return{ok:!1,status:413,error:"payload_too_large"};if(Z?.message==="body_timeout")return{ok:!1,status:408,error:"payload_timeout"};throw Z}try{return{ok:!0,value:JSON.parse(f)}}catch{return{ok:!1,status:400,error:"invalid_json"}}}function C0($,f){if(f.status===413)$.shouldKeepAlive=!1;L($,f.status,f.status===413?{error:f.error,max_bytes:iX}:{error:f.error})}function i$($,f){try{if($.writableEnded)return;$.write(`data: ${JSON.stringify(f)}
420
+
421
+ `)}catch{}}function A3($,f){if(typeof $==="string"&&$.length>f)return $.slice(0,f)+`
422
+ … [truncated ${$.length-f} chars]`;return $}function Sb($){return{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no",...$}}function vb($,f,Z={}){return{onAssistantDisplayDelta(z){i$($,{type:"assistant",text:z})},onThinkingDelta(z){i$($,{type:"thinking",text:z})},onToolCall(z,J){i$($,{type:"tool_call",name:z,input:A3(J,b3)})},onToolResult(z,J){i$($,{type:"tool_result",name:z,output:A3(J,b3)})},onCompaction(z){i$($,{type:"compaction",line:z})},onRetryNotice(z){i$($,{type:"notice",kind:z.kind,attempt:z.attempt,max_attempts:z.maxAttempts,delay_ms:z.delayMs})},onStreamError(z){i$($,{type:"error",message:z})},onRunFinish(z){let J;if(Z.sessionId&&f.length>0)try{J=D$(f,Z.sessionId,void 0,void 0,Z.taskState)}catch{J=void 0}if(i$($,{type:"done",step_count:z.stepCount,usage:z.usage,context_tokens:z.contextTokens??0,has_error:z.hasError,aborted:z.aborted,max_steps_reached:z.maxStepsReached,incomplete:z.incomplete??!1,budget_exceeded:z.budgetExceeded??!1,continues:z.continues??0,stopped:z.stopped??!1,empty_response:z.emptyResponse??!1,empty_attempts:z.emptyAttempts??0,wrap_up:z.wrapUp??!1,session_id:J,messages:b2(f),task_state:Z.taskState,project:Z.project}),!$.writableEnded)$.end()}}}function ub(){let $=[],f=[],Z=null;return{callbacks:{onToolCall(J,K){$.push({name:J,input:A3(K,b3)})},onToolResult(J,K){f.push({name:J,output:A3(K,b3)})},onRunFinish(J){Z=J}},toolCalls:$,toolResults:f,finishInfo:()=>Z}}function O3($){let f={};if($.sandbox!==void 0){let Z=O$($.sandbox);if(!Z)return{ok:!1,error:"invalid_sandbox",detail:"sandbox must be off, workspace, or strict"};f.mode=Z}if($.network!==void 0){let Z=g$($.network);if(!Z)return{ok:!1,error:"invalid_network",detail:"network must be allow or deny"};f.network=Z}return{ok:!0,policy:f}}function SZ($){if($===void 0)return{ok:!0};if(!Array.isArray($)||$.some((f)=>typeof f!=="string"||f.length===0))return{ok:!1};return{ok:!0,value:$}}function w3(){let $=r4();return{mode:$.mode,network:$.network,extraWriteRoots:$.extraWriteRoots,extraReadRoots:$.extraReadRoots,source:$.source,label:$.label}}function y3(){let $=i4(),f=m4(),Z=$??f.permission,z=$?"cli":f.source;return{permission:Z,source:z,label:Hf(Z)}}function T3($){if($.thinking===void 0)return{ok:!0};let f=R0($.thinking);if(!f)return{ok:!1,error:"invalid_thinking",detail:"thinking must be off, low, medium, high, or max"};return{ok:!0,thinking:f}}function lX($){if($.memory===void 0)return{ok:!0};let f=g0($.memory);if(!f)return{ok:!1,error:"invalid_memory",detail:"memory must be on or off"};return{ok:!0,memory:f}}function tX($){if($.messages&&Array.isArray($.messages)){if($.messages.length===0)return{ok:!1,error:"messages must be non-empty"};return{ok:!0,messages:[...$.messages]}}if(typeof $.message==="string"&&$.message.length>0)return{ok:!0,messages:[{role:"user",content:$.message}]};return{ok:!1,error:"Provide `message` (string) or non-empty `messages` array"}}function J8($){return{temperature:typeof $.temperature==="number"?$.temperature:void 0,maxTokens:typeof $.maxTokens==="number"?$.maxTokens:void 0,topP:typeof $.topP==="number"?$.topP:void 0,thinking:R0($.thinking),memory:g0($.memory),providerName:typeof $.provider==="string"?$.provider:void 0,...$.plan_mode===!0?{planMode:!0}:{}}}function Eb($,f,Z,z){if(Z)return{autoApprove:!0};return{autoApprove:!1,onConfirm:async(J)=>{let K=dX();return z.push(K),i$(f,{type:"confirm",id:K,message:J}),$.approvalGate.waitConfirm(K)},onQuestion:async(J,K,Q)=>{let G=dX();return z.push(G),i$(f,{type:"question",id:G,prompt:J,...K&&K.length>0?{options:K}:{},...Q?{multiple:!0}:{}}),$.approvalGate.waitQuestion(G)}}}async function K8($,f){let{res:Z,messages:z,modelId:J,stream:K,sessionId:Q,runOptions:G,autoApprove:Y}=f,P=f.taskState??k$();if(!Y&&!K){L(Z,400,{error:"auto_approve_requires_stream",detail:"Set stream: true when auto_approve is false, then answer via POST /v1/approvals and POST /v1/answers"});return}let X=new AbortController,W=[],H=()=>{X.abort();for(let w of W)$.approvalGate.cancel(w)};Z.on("close",H);let M=new zf,F=I1(),q=Ef(F,$.instructions),U=Eb($,Z,Y,W),N=f.sandboxTighten,B=(w)=>{let E=Q!=null?NZ(()=>{try{D$(z,Q,void 0,void 0,P)}catch{}}):null,l=()=>z9(U,()=>bZ(z,q,J,X.signal,w,M,{...G,taskState:P,...E?{onStepPersist:()=>E.request()}:{}})),h=(t)=>t.finally(()=>{E?.cancel()});if(N&&(N.mode||N.network))return h(h3(N,l));return h(l())};if(K){Z.writeHead(200,Sb(j3())),Z.flushHeaders?.();let w=vb(Z,z,{sessionId:Q,project:F,taskState:P});try{await B(w)}catch(E){let l=E instanceof Error?E.message:String(E);if(!Z.writableEnded)i$(Z,{type:"fatal",message:l}),Z.end()}return}let{callbacks:D,toolCalls:V,toolResults:b,finishInfo:C}=ub();await B(D);let S=[...z].reverse().find((w)=>w.role==="assistant"),I;if(Q&&z.length>0)try{I=D$(z,Q,void 0,void 0,P)}catch{I=void 0}let j=C();L(Z,200,{messages:b2(z),assistant:S??null,tool_calls:V,tool_results:b,session_id:I,step_count:j?.stepCount??0,usage:j?.usage??null,context_tokens:j?.contextTokens??0,has_error:j?.hasError??!1,aborted:j?.aborted??!1,max_steps_reached:j?.maxStepsReached??!1,incomplete:j?.incomplete??!1,budget_exceeded:j?.budgetExceeded??!1,continues:j?.continues??0,stopped:j?.stopped??!1,empty_response:j?.emptyResponse??!1,empty_attempts:j?.emptyAttempts??0,wrap_up:j?.wrapUp??!1,task_state:P,project:F})}var iX=2097152,nb=30000,b3=48000,cf=8;var Gf=O(()=>{d();E0();G$();$1();V1();gf();n$();r2();T1();wf();t4()});async function gb($,f,Z){if(f.headers["content-type"]?.split(";")[0]?.trim()!=="application/json"){L(Z,415,{error:"unsupported_media_type",detail:"Use Content-Type: application/json"});return}if($.activeChats>=cf){L(Z,429,{error:"too_many_concurrent_requests",detail:`Max ${cf} concurrent chats`});return}$.activeChats++;try{let z=await D0(f);if(!z.ok){C0(Z,z);return}let J=z.value,K=O3(J);if(!K.ok){L(Z,400,{error:K.error,detail:K.detail});return}let Q=K.policy,G=T3(J);if(!G.ok){L(Z,400,{error:G.error,detail:G.detail});return}let Y=lX(J);if(!Y.ok){L(Z,400,{error:Y.error,detail:Y.detail});return}let P=typeof J.model==="string"?J.model:void 0,X=J.stream===!0,W=typeof J.session_id==="string"?J.session_id:void 0,H;if(W){await L2(W,async()=>{let M=Z$(W);if(!M){L(Z,404,{error:"session_not_found",session_id:W});return}if(typeof J.message!=="string"||!J.message.trim()){L(Z,400,{error:"session_requires_message",detail:"With `session_id`, send a non-empty `message` for the new user turn"});return}let F=[...M.messages],q=J.images&&J.images.length>0?await e2(J.message,J.images):J.message;F.push({role:"user",content:q}),await K8($,{res:Z,messages:F,modelId:P,stream:X,sessionId:W,runOptions:J8(J),autoApprove:J.auto_approve!==!1,taskState:M.taskState??k$(),sandboxTighten:Q})});return}else{let M=tX(J);if(!M.ok){L(Z,400,{error:"invalid_body",detail:M.error});return}if(H=M.messages,J.images&&J.images.length>0){let F=H[H.length-1];if(!F||F.role!=="user"||typeof J.message!=="string"){L(Z,400,{error:"images_require_message",detail:"With `images`, send a top-level `message` string for the user turn"});return}H[H.length-1]={role:"user",content:await e2(J.message,J.images)}}}await K8($,{res:Z,messages:H,modelId:P,stream:X,sessionId:W,runOptions:J8(J),autoApprove:J.auto_approve!==!1,sandboxTighten:Q})}finally{$.activeChats--}}var aX=async($,f,Z,z,J)=>{if($.method==="POST"&&J==="/v1/chat/reload-instructions")return Z.instructions=await X1(),L(f,200,{ok:!0,instructions_chars:Z.instructions.join(`
423
+ `).length}),!0;if($.method==="POST"&&(J==="/v1/chat"||J==="/v1/code"))return await gb(Z,$,f),!0;if($.method==="POST"&&J==="/v1/chat/redo"){let K=await D0($);if(!K.ok)return C0(f,K),!0;let Q=K.value,G=typeof Q.session_id==="string"?Q.session_id:void 0;if(!G)return L(f,400,{error:"missing_session_id"}),!0;let Y=O3(Q);if(!Y.ok)return L(f,400,{error:Y.error,detail:Y.detail}),!0;let P=T3(Q);if(!P.ok)return L(f,400,{error:P.error,detail:P.detail}),!0;if(Z.activeChats>=cf)return L(f,429,{error:"too_many_concurrent_requests",detail:`Max ${cf} concurrent chats`}),!0;Z.activeChats++;try{await L2(G,async()=>{let X=Z$(G);if(!X){L(f,404,{error:"session_not_found",session_id:G});return}let W=D3(X.messages);if(!W){L(f,400,{error:"no_user_message"});return}await K8(Z,{res:f,messages:[...X.messages,{role:"user",content:W}],modelId:typeof Q.model==="string"?Q.model:void 0,stream:Q.stream===!0,sessionId:G,runOptions:J8(Q),autoApprove:Q.auto_approve!==!1,taskState:X.taskState??k$(),sandboxTighten:Y.policy})})}finally{Z.activeChats--}return!0}if($.method==="POST"&&J==="/v1/approvals"){let K=await D0($);if(!K.ok)return C0(f,K),!0;let Q=K.value.id?.trim();if(!Q)return L(f,400,{error:"missing_id"}),!0;if(typeof K.value.accepted!=="boolean")return L(f,400,{error:"missing_accepted"}),!0;if(!Z.approvalGate.resolveConfirm(Q,K.value.accepted))return L(f,404,{error:"unknown_approval_id",id:Q}),!0;return L(f,200,{ok:!0,id:Q,accepted:K.value.accepted}),!0}if($.method==="POST"&&J==="/v1/answers"){let K=await D0($);if(!K.ok)return C0(f,K),!0;let Q=K.value.id?.trim();if(!Q)return L(f,400,{error:"missing_id"}),!0;let G=K.value.answer===void 0?null:K.value.answer;if(G!==null&&typeof G!=="string")return L(f,400,{error:"invalid_answer"}),!0;if(!Z.approvalGate.resolveQuestion(Q,G))return L(f,404,{error:"unknown_answer_id",id:Q}),!0;return L(f,200,{ok:!0,id:Q}),!0}if($.method==="POST"&&J==="/v1/paste"){if($.headers["content-type"]?.split(";")[0]?.trim()!=="application/json")return L(f,415,{error:"unsupported_media_type"}),!0;if(Z.activeChats>=cf)return L(f,429,{error:"too_many_concurrent_requests",detail:`Max ${cf} concurrent chats`}),!0;let K=await D0($);if(!K.ok)return C0(f,K),!0;let Q=K.value;if(!Q.image_base64)return L(f,400,{error:"missing_image_base64"}),!0;let G=O3(Q);if(!G.ok)return L(f,400,{error:G.error,detail:G.detail}),!0;let Y=T3(Q);if(!Y.ok)return L(f,400,{error:Y.error,detail:Y.detail}),!0;let P=Buffer.from(Q.image_base64,"base64"),X=Q.mime_type??"image/png",W=Q.message??"What's in this image?",H=Q.model,M=Q.session_id,F=Q.stream===!0;Z.activeChats++;try{await L2(M,async()=>{let q=[],U;if(M){let N=Z$(M);if(!N){L(f,404,{error:"session_not_found",session_id:M});return}q=[...N.messages],U=N.taskState}q.push({role:"user",content:[{type:"text",text:W},{type:"image",image:P,mimeType:X}]}),await K8(Z,{res:f,messages:q,modelId:H,stream:F,sessionId:M,runOptions:J8(Q),autoApprove:Q.auto_approve!==!1,taskState:U??k$(),sandboxTighten:G.policy})})}finally{Z.activeChats--}return!0}if($.method==="POST"&&J==="/v1/chat/compact"){let K=await D0($);if(!K.ok)return C0(f,K),!0;let Q=K.value;if(!Q.session_id)return L(f,400,{error:"missing_session_id"}),!0;let G=Z$(Q.session_id);if(!G)return L(f,404,{error:"session_not_found"}),!0;let Y=p$(),P=await v2(G.messages,Y,{taskGoal:G.taskState?.goal});if(P.compacted)D$(P.messages,Q.session_id);return L(f,200,{ok:!0,compacted:P.compacted,message_count:P.messages.length}),!0}if($.method==="POST"&&J==="/v1/chat/undo"){let K=await D0($);if(!K.ok)return C0(f,K),!0;let Q=K.value;if(!Q.session_id)return L(f,400,{error:"missing_session_id"}),!0;let G=Z$(Q.session_id);if(!G)return L(f,404,{error:"session_not_found"}),!0;let Y=-1;for(let P=G.messages.length-1;P>=0;P--)if(G.messages[P].role==="user"){Y=P;break}if(Y===-1)return L(f,400,{error:"no_user_message"}),!0;return G.messages=G.messages.slice(0,Y+1),D$(G.messages,Q.session_id),L(f,200,{ok:!0,message_count:G.messages.length,messages:G.messages}),!0}return!1};var sX=O(()=>{Zf();n$();gf();yZ();T1();Rf();wf();Gf()});var eX=async($,f,Z,z,J)=>{if($.method==="GET"&&J==="/v1/sessions"){let K=a1();return L(f,200,{sessions:K}),!0}if($.method==="DELETE"&&J.startsWith("/v1/sessions/")){let K=M$(J.slice(13));if(!K)return L(f,400,{error:"missing_session_id"}),!0;if(!d5(K))return L(f,404,{error:"session_not_found",session_id:K}),!0;return L(f,200,{ok:!0,deleted:K}),!0}if($.method==="GET"&&J.startsWith("/v1/sessions/")){let K=M$(J.slice(13));if(!K)return L(f,400,{error:"missing_session_id"}),!0;let Q=Z$(K);if(!Q)return L(f,404,{error:"session_not_found",session_id:K}),!0;return L(f,200,{session:Q}),!0}if($.method==="POST"&&J.startsWith("/v1/sessions/")&&J.endsWith("/rename")){let K=M$(J.slice(13,-7));if(!K)return L(f,400,{error:"missing_session_id"}),!0;let Q=await D0($);if(!Q.ok)return C0(f,Q),!0;let G=Q.value.title?.trim();if(!G)return L(f,400,{error:"missing_title"}),!0;if(!i5(K,G))return L(f,404,{error:"session_not_found",session_id:K}),!0;return L(f,200,{ok:!0,session_id:K,title:G}),!0}return!1};var $W=O(()=>{n$();Gf()});var fW=async($,f,Z,z,J)=>{if($.method==="GET"&&J==="/v1/memory/mode")return L(f,200,o1()),!0;if($.method==="POST"&&J==="/v1/memory/mode"){let K=await D0($);if(!K.ok)return C0(f,K),!0;let Q=g0(K.value.memory);if(!Q)return L(f,400,{error:"invalid_memory",detail:"memory must be on or off"}),!0;let G=V$(K.value.scope);if(!G.ok)return L(f,400,{error:"invalid_scope",allowed:["global","project"]}),!0;let Y=G.scope??"global";return J4(Q,Y),L(f,200,{ok:!0,scope:Y,...o1()}),!0}if($.method==="GET"&&J==="/v1/memory")return L(f,200,{...o1(),memories:L$("global"),project_memories:L$("project")}),!0;if($.method==="POST"&&J==="/v1/memory"){let K=await D0($);if(!K.ok)return C0(f,K),!0;let Q=K.value;if(!Q.content)return L(f,400,{error:"missing_content"}),!0;let G=V$(Q.scope);if(!G.ok)return L(f,400,{error:"invalid_scope",allowed:["global","project"]}),!0;let Y=G.scope??"global",P=K4(Q.content,Q.tags??[],Y);return L(f,201,{ok:!0,memory:P,scope:Y}),!0}if($.method==="GET"&&J==="/v1/memory/search"){let K=z.searchParams.get("q")??"";if(!K)return L(f,400,{error:"missing_query_param_q"}),!0;let Q=V$(z.searchParams.get("scope"));if(!Q.ok)return L(f,400,{error:"invalid_scope",allowed:["global","project"]}),!0;let G=Q.scope==="project"?[]:_f(K,"global"),Y=Q.scope==="global"?[]:_f(K,"project");return L(f,200,{results:G,project_results:Y}),!0}if($.method==="DELETE"&&J.startsWith("/v1/memory/")){let K=parseInt(J.slice(11),10);if(Number.isNaN(K))return L(f,400,{error:"invalid_index"}),!0;let Q=V$(z.searchParams.get("scope"));if(!Q.ok)return L(f,400,{error:"invalid_scope",allowed:["global","project"]}),!0;let G=Q.scope??"global";if(!Q4(K-1,G))return L(f,404,{error:"memory_not_found",index:K,scope:G}),!0;return L(f,200,{ok:!0,deleted:K,scope:G}),!0}return!1};var ZW=O(()=>{V1();Gf()});var zW=async($,f,Z,z,J)=>{if($.method==="GET"&&J==="/v1/mcp"){let X=o$();return L(f,200,{servers:X}),!0}let K=J.match(/^\/v1\/mcp\/([^/]+)\/resources$/);if($.method==="GET"&&K){let X=M$(K[1]);if(!X)return L(f,400,{error:"missing_name"}),!0;let W=o$()[X];if(!W)return L(f,404,{error:"mcp_not_found",name:X}),!0;if(!W.connected)return L(f,404,{error:"mcp_not_connected",name:X}),!0;let H=$f(X).servers[0];return L(f,200,{name:X,resources:H.resources,templates:H.templates}),!0}let Q=J.match(/^\/v1\/mcp\/([^/]+)\/prompts$/);if($.method==="GET"&&Q){let X=M$(Q[1]);if(!X)return L(f,400,{error:"missing_name"}),!0;let W=o$()[X];if(!W)return L(f,404,{error:"mcp_not_found",name:X}),!0;if(!W.connected)return L(f,404,{error:"mcp_not_connected",name:X}),!0;let H=$f(X).servers[0];return L(f,200,{name:X,prompts:H.prompts}),!0}let G=J.match(/^\/v1\/mcp\/([^/]+)\/resources\/read$/);if($.method==="POST"&&G){let X=M$(G[1]);if(!X)return L(f,400,{error:"missing_name"}),!0;let W=await D0($);if(!W.ok)return C0(f,W),!0;let H=W.value.uri?.trim();if(!H)return L(f,400,{error:"missing_uri"}),!0;let M=o$()[X];if(!M)return L(f,404,{error:"mcp_not_found",name:X}),!0;if(!M.connected)return L(f,404,{error:"mcp_not_connected",name:X}),!0;let F=await _6(H,X);return L(f,200,{ok:!0,name:X,uri:H,content:F}),!0}let Y=J.match(/^\/v1\/mcp\/([^/]+)\/prompts\/get$/);if($.method==="POST"&&Y){let X=M$(Y[1]);if(!X)return L(f,400,{error:"missing_name"}),!0;let W=await D0($);if(!W.ok)return C0(f,W),!0;let H=W.value.prompt?.trim();if(!H)return L(f,400,{error:"missing_prompt"}),!0;let M=o$()[X];if(!M)return L(f,404,{error:"mcp_not_found",name:X}),!0;if(!M.connected)return L(f,404,{error:"mcp_not_connected",name:X}),!0;let F=await D6(H,W.value.arguments,X);return L(f,200,{ok:!0,name:X,prompt:H,content:F}),!0}if($.method==="POST"&&J==="/v1/mcp"){let X=await D0($);if(!X.ok)return C0(f,X),!0;let W=X.value;if(!W.name)return L(f,400,{error:"missing_name"}),!0;if(W.remoteTransport&&!["streamable-http","sse","auto"].includes(W.remoteTransport))return L(f,400,{error:"invalid_remote_transport",allowed:["streamable-http","sse","auto"]}),!0;let H=W.project?"project":"global",{loadMcpConfigFile:M,saveMcpConfig:F}=await Promise.resolve().then(() => (S$(),L4)),q=M(H),U={...W.environment?{environment:W.environment}:{},...W.headers?{headers:W.headers}:{},...W.remoteTransport?{remoteTransport:W.remoteTransport}:{},...W.timeout!==void 0?{timeout:W.timeout}:{},...W.connectTimeout!==void 0?{connectTimeout:W.connectTimeout}:{},...W.callTimeout!==void 0?{callTimeout:W.callTimeout}:{},enabled:W.enabled!==!1};if(W.url)q.mcpServers[W.name]={url:W.url,...W.token?{token:W.token}:{},...U};else if(typeof W.command==="string"&&W.command.length>0)q.mcpServers[W.name]={command:W.command,...W.args?{args:W.args}:{},...U};else if(Array.isArray(W.command)&&W.command.length>0)q.mcpServers[W.name]={command:W.command,...U};else return L(f,400,{error:"provide command or url"}),!0;F(q,H),await B4();let N=o$()[W.name];return L(f,201,{ok:!0,name:W.name,scope:H,connected:N?.connected??!1,...N?.error?{error:N.error}:{},...N?.tools?.length?{tools:N.tools}:{}}),!0}if($.method==="DELETE"&&J.startsWith("/v1/mcp/")){let X=M$(J.slice(8));if(!X)return L(f,400,{error:"missing_name"}),!0;let W=z.searchParams.get("project")==="1"?"project":"global",{loadMcpConfigFile:H,saveMcpConfig:M}=await Promise.resolve().then(() => (S$(),L4)),F=H(W);if(!F.mcpServers[X])return L(f,404,{error:"mcp_not_found",name:X,scope:W,available:Object.keys(F.mcpServers)}),!0;return delete F.mcpServers[X],M(F,W),await B4(),L(f,200,{ok:!0,deleted:X,scope:W}),!0}let P=J.match(/^\/v1\/mcp\/([^/]+)\/(enable|disable)$/);if($.method==="POST"&&P){let X=M$(P[1]);if(!X)return L(f,400,{error:"missing_name"}),!0;let W=P[2]==="enable",H=await D0($),M=H.ok&&H.value.scope==="project"?"project":"global",{loadMcpConfigFile:F,saveMcpConfig:q}=await Promise.resolve().then(() => (S$(),L4)),U=F(M);if(!U.mcpServers[X]){let N=G1().some((B)=>B.name===X);return L(f,404,{error:"mcp_not_found",name:X,scope:M,...N?{hint:"server exists in another scope; pass the matching scope"}:{available:Object.keys(U.mcpServers)}}),!0}return U.mcpServers[X].enabled=W,q(U,M),await B4(),L(f,200,{ok:!0,name:X,enabled:W,scope:M,connected:o$()[X]?.connected??!1}),!0}return!1};var JW=O(()=>{S$();Gf()});var KW=async($,f,Z,z,J)=>{if($.method==="GET"&&J==="/v1/skills"){let G=P1();return L(f,200,{count:G.length,enabled_count:G.filter((Y)=>Y.enabled).length,stale_disabled:D4(),skills:G.map(C3)}),!0}if($.method==="POST"&&J==="/v1/skills/reload"){A$({silent:!0});let G=P1();return L(f,200,{ok:!0,count:G.length,enabled_count:G.filter((Y)=>Y.enabled).length,stale_disabled:D4(),skills:G.map(C3)}),!0}let K=J.match(/^\/v1\/skills\/([^/]+)$/);if($.method==="GET"&&K){let G=M$(K[1]);if(!G)return L(f,400,{error:"invalid_skill_name"}),!0;let Y=A6(G);if(!Y)return L(f,404,{error:"skill_not_found",name:G,available:P1().map((P)=>P.name)}),!0;return L(f,200,{skill:{...C3(Y),content:Y.content}}),!0}let Q=J.match(/^\/v1\/skills\/([^/]+)\/(enable|disable)$/);if($.method==="POST"&&Q){let G=M$(Q[1]);if(!G)return L(f,400,{error:"invalid_skill_name"}),!0;let Y=Q[2]==="enable";if(!A6(G))return L(f,404,{error:"skill_not_found",name:G,available:P1().map((H)=>H.name)}),!0;let P=await D0($),X=P.ok?P.value.scope:void 0;if(X!==void 0&&X!=="global"&&X!=="project")return L(f,400,{error:"invalid_scope",allowed:["global","project"]}),!0;let[W]=L7([G],Y,X??"global");return L(f,200,{ok:!0,name:G,enabled:W.enabled,scope:X??"global",...W.blockedBy?{blocked_by:W.blockedBy}:{}}),!0}return!1};var QW=O(()=>{v$();Gf()});var GW=async($,f,Z,z,J)=>{if($.method==="GET"&&J==="/health")return L(f,200,{ok:!0,service:"min-agent",version:Z.version}),!0;if($.method==="GET"&&J==="/v1/meta")return L(f,200,{version:Z.version,cwd:process.cwd(),instructions_chars:Z.instructions.join(`
424
+ `).length,sandbox:w3(),permission:y3(),thinking:Z4(),memory:o1()}),!0;if($.method==="GET"&&J==="/v1/update"){let K=await rz({currentVersion:Z.version});return L(f,200,{current:K.current,latest:K.latest,update_available:K.updateAvailable,...K.latest===null?{error:"registry_unavailable"}:{}}),!0}if($.method==="GET"&&J==="/v1/models"){let K=J0(),Q=e(K),G=Q?.baseURL,Y=Q?.apiKey;if(!G||!Y)return L(f,500,{error:"provider_not_configured"}),!0;let P=await Ff(G,Y);return L(f,200,{default_model:Q?.defaultModel??null,models:P}),!0}if($.method==="GET"&&J==="/v1/budget"){let K=M8();return L(f,200,{maxCostUSD:K.maxCostUSD??null,source:K.source}),!0}if($.method==="POST"&&J==="/v1/budget"){let K=await D0($);if(!K.ok)return C0(f,K),!0;let Q=K.value.maxCostUSD;if(typeof Q!=="number"||!Number.isFinite(Q)||Q<=0)return L(f,400,{error:"invalid_max_cost",detail:"maxCostUSD must be a positive number"}),!0;let G=V$(K.value.scope);if(!G.ok)return L(f,400,{error:"invalid_scope",allowed:["global","project"]}),!0;let Y=G.scope??"global";a3(Q,Y);let P=M8();return L(f,200,{ok:!0,maxCostUSD:P.maxCostUSD??Q,source:P.source,scope:Y}),!0}if($.method==="GET"&&J==="/v1/sandbox")return L(f,200,w3()),!0;if($.method==="GET"&&J==="/v1/permission")return L(f,200,y3()),!0;if($.method==="POST"&&J==="/v1/permission"){let K=await D0($);if(!K.ok)return C0(f,K),!0;let Q=N$(K.value.permission);if(!Q)return L(f,400,{error:"invalid_permission",detail:"permission must be ask, accept-edits, or allow-all"}),!0;let G=V$(K.value.scope);if(!G.ok)return L(f,400,{error:"invalid_scope",allowed:["global","project"]}),!0;let Y=G.scope??"global";return lf(Q,Y),L(f,200,{ok:!0,scope:Y,...y3()}),!0}if($.method==="GET"&&J==="/v1/thinking")return L(f,200,Z4()),!0;if($.method==="POST"&&J==="/v1/thinking"){let K=await D0($);if(!K.ok)return C0(f,K),!0;let Q=R0(K.value.thinking);if(!Q)return L(f,400,{error:"invalid_thinking",detail:"thinking must be off, low, medium, high, or max"}),!0;let G=V$(K.value.scope);if(!G.ok)return L(f,400,{error:"invalid_scope",allowed:["global","project"]}),!0;let Y=G.scope??"global";return m1(Q,Y),L(f,200,{ok:!0,scope:Y,...Z4()}),!0}if($.method==="POST"&&J==="/v1/sandbox"){let K=await D0($);if(!K.ok)return C0(f,K),!0;let Q=K.value,G=Q.mode===void 0?void 0:O$(Q.mode);if(Q.mode!==void 0&&!G)return L(f,400,{error:"invalid_sandbox",detail:"mode must be off, workspace, or strict"}),!0;let Y=Q.network===void 0?void 0:g$(Q.network);if(Q.network!==void 0&&!Y)return L(f,400,{error:"invalid_network",detail:"network must be allow or deny"}),!0;let P=SZ(Q.extraWriteRoots),X=SZ(Q.extraReadRoots);if(!P.ok||!X.ok)return L(f,400,{error:"invalid_roots",detail:"extraWriteRoots and extraReadRoots must be arrays of non-empty strings"}),!0;if(!G&&!Y&&P.value===void 0&&X.value===void 0)return L(f,400,{error:"invalid_body",detail:"Provide mode, network, extraWriteRoots, or extraReadRoots"}),!0;let W=V$(Q.scope);if(!W.ok)return L(f,400,{error:"invalid_scope",allowed:["global","project"]}),!0;let H=W.scope??"global";return Uf({...G?{mode:G}:{},...Y?{network:Y}:{},...P.value?{extraWriteRoots:P.value}:{},...X.value?{extraReadRoots:X.value}:{}},H),L(f,200,{ok:!0,scope:H,...w3()}),!0}if($.method==="GET"&&J==="/v1/diff"){let K=await CZ();if(!K.ok)return L(f,200,{ok:!1,reason:K.reason,message:K.message}),!0;return L(f,200,{ok:!0,diff:K.diff}),!0}if($.method==="GET"&&J==="/v1/rules")return L(f,200,{count:Z.instructions.length,rules:Z.instructions.map((K)=>{return{source:(K.split(`
425
+ `)[0]??"").replace("Instructions from: ",""),chars:K.length}})}),!0;if($.method==="GET"&&J==="/v1/project"){let K=I1();return L(f,200,{project:K}),!0}if($.method==="GET"&&J==="/v1/context"){let K=J0(),Q=e(K),G=await d$(Q?.defaultModel);return L(f,200,{context_window:G.tokens,source:G.source,model:Q?.defaultModel??null,...U6()}),!0}if($.method==="POST"&&J==="/v1/context"){let K=await D0($);if(!K.ok)return C0(f,K),!0;let Q=typeof K.value.level==="string"?q2(K.value.level):null;if(!Q)return L(f,400,{error:"invalid_context_level",detail:`level must be one of: ${H$.join(", ")}`}),!0;if(!Of(Q).ok)return L(f,400,{error:"ctx_not_supported",detail:"context levels are only available for an Ollama provider"}),!0;let Y=e(J0()),P=await d$(Y?.defaultModel);return L(f,200,{ok:!0,context_window:P.tokens,source:P.source,model:Y?.defaultModel??null,...U6()}),!0}if($.method==="GET"&&J==="/v1/cost"){let K=J0(),Q=e(K),G=z.searchParams.get("model")??Q?.defaultModel??null,Y=z.searchParams.get("input"),P=z.searchParams.get("output"),X=Y?parseInt(Y,10):0,W=P?parseInt(P,10):0;if(Number.isNaN(X)||Number.isNaN(W)||X<0||W<0)return L(f,400,{error:"invalid_tokens",detail:"input/output must be non-negative integers"}),!0;let H=G?await u2(G):null,M=H?E2({inputTokens:X,outputTokens:W},H):null;return L(f,200,{model:G,price:H,cost_usd:M}),!0}return!1};var YW=O(()=>{d();$1();E0();OZ();r2();Sf();H4();C4();t4();Gf()});var PW={};U0(PW,{runServe:()=>rb});import{createServer as xb}from"http";import{timingSafeEqual as hb}from"crypto";function cb($){if(process.env.MIN_AGENT_SERVE_TOKEN?.trim())return!0;let f=$.headers.origin?.trim();if(!f||f==="null")return!0;try{let Z=new URL(f).hostname;if(Z==="localhost"||Z==="127.0.0.1"||Z==="[::1]")return!0}catch{return!1}return!1}function mb($){let f=process.env.MIN_AGENT_SERVE_TOKEN?.trim();if(!f)return!0;let Z=$.headers.authorization?.trim();if(!Z?.startsWith("Bearer "))return!1;let z=Buffer.from(Z.slice(7)),J=Buffer.from(f);return z.length===J.length&&hb(z,J)}async function rb($={}){if(!a$())console.error("Not configured. Run: min-agent setup"),process.exit(1);let f=$.host??process.env.MIN_AGENT_SERVE_HOST??"127.0.0.1",Z=$.port??parseInt(process.env.MIN_AGENT_SERVE_PORT??"8787",10);if(!(f==="127.0.0.1"||f==="::1"||f==="localhost")&&!process.env.MIN_AGENT_SERVE_TOKEN?.trim())console.error("Refusing to serve on a non-loopback address without MIN_AGENT_SERVE_TOKEN. Set the token (Authorization: Bearer <token>) or bind to 127.0.0.1."),process.exit(1);console.error("\x1B[33m⚠ min-agent serve: confirmations are auto-approved by default (same as -y). Set auto_approve: false with stream: true to require callbacks.\x1B[0m"),d4(!0),console.error("\x1B[90m⟳ Initializing MCP, skills, instructions…\x1B[0m"),await nf(),A$();let J={host:f,version:Bf(),instructions:await X1(),approvalGate:pX(),activeChats:0},K=[GW,aX,eX,fW,zW,KW],Q=xb(async(P,X)=>{let W=j3();if(P.method==="OPTIONS"){X.writeHead(204,W),X.end();return}if(!mb(P)){L(X,401,{error:"unauthorized",detail:"Set Authorization: Bearer <MIN_AGENT_SERVE_TOKEN> when MIN_AGENT_SERVE_TOKEN is set"});return}if(RZ()&&!cb(P)){L(X,403,{error:"origin_not_allowed",detail:"CORS is enabled without a token; only localhost origins are allowed. Set MIN_AGENT_SERVE_TOKEN or disable CORS."});return}let H=new URL(P.url??"/",`http://${f}`),M=H.pathname.replace(/\/$/,"")||"/";try{for(let F of K)if(await F(P,X,J,H,M))return;L(X,404,{error:"not_found",path:M})}catch(F){L(X,500,{error:"internal_error",message:F?.message??String(F)})}});await new Promise((P,X)=>{Q.once("error",X),Q.listen(Z,f,()=>{console.error(`\x1B[32m✓ min-agent serve\x1B[0m http://${f}:${Z} (API: docs/API.md)`),P()})});let G=async()=>{await ff(),Q.closeAllConnections?.(),await new Promise((P)=>Q.close(()=>P()))},Y=async()=>{await G(),process.exit(0)};return process.on("SIGINT",Y),process.on("SIGTERM",Y),{close:G}}var XW=O(()=>{S$();v$();Zf();d();G$();Gf();sX();$W();ZW();JW();QW();YW()});G$();Y$();_8();t4();import{Command as jb,Option as f8}from"commander";function Cb($,f){return[...f,$]}function Ob($){return $.option("-m, --model <model>","override model for this request").option("--provider <name>","use a specific configured provider").option("--resume <id>","resume a previous session by id").option("-i, --image <path>","attach an image (repeatable)",Cb,[]).addOption(new f8("--sandbox <mode>","isolation mode (off, workspace, strict)").argParser(Rz)).addOption(new f8("--network <policy>","network policy (allow, deny)").argParser(Sz)).addOption(new f8("--permission <mode>","confirmation mode (ask, accept-edits, allow-all)").argParser(vz)).addOption(new f8("--think <level>","thinking intensity (off, low, medium, high, max)").argParser(uz)).addOption(new f8("--memory <mode>","memory across sessions (on, off; default off)").argParser(Ez)).option("--project","write --permission/--sandbox/--think/--memory to this repo's config").option("--global","write --permission/--sandbox/--think/--memory to the global config").option("-y, --yes","this session only: same as --permission allow-all")}function wb(){let $=new jb("min-agent");return $.description("min-agent - Minimal AI coding agent").version(Bf(),"-v, --version","show version number").helpOption("-h, --help","show help").allowUnknownOption().enablePositionalOptions().configureOutput({writeErr:(f)=>process.stderr.write(f),outputError:(f)=>process.stderr.write(f)}).exitOverride(),Ob($),$.argument("[prompt...]","prompt to send in an interactive session"),$.addHelpText("after",`
426
+ session:
427
+ min-agent start interactive session
428
+ min-agent <message> start interactive session and send message
429
+ min-agent --resume <id> resume a previous interactive session
430
+ min-agent chat | code same as interactive session (compat)
431
+ min-agent exec <message> run one message non-interactively
432
+ min-agent exec --resume <id> <msg> continue a saved exec session
433
+
434
+ setup & config:
435
+ min-agent setup [--type T] configure providers (interactively, or with flags)
436
+ min-agent init initialize .min-agent/ in current directory
437
+ min-agent models list available models
438
+ min-agent rules [edit] show or edit instruction rules
439
+ min-agent memory [on|off] show or set memory (off by default)
440
+ min-agent memory <add|search|delete> manage saved memories
441
+ min-agent sandbox [off|workspace|strict] show or set isolation mode
442
+ min-agent sandbox network <allow|deny> show or set network policy
443
+ min-agent permission [ask|accept-edits|allow-all] show or set confirmation mode
444
+ min-agent think [off|low|medium|high|max] show or set thinking intensity
445
+ min-agent ctx [2k|4k|8k|12k|16k|32k|64k|128k|256k|auto] show or set Ollama context window
446
+
447
+ integrations:
448
+ min-agent mcp <list|add|remove|info|check|enable|disable> manage MCP servers
449
+ min-agent skills <list|info|new|enable|disable> manage skills
450
+
451
+ operations:
452
+ min-agent serve [--host H] [--port P] start the HTTP API (see docs/API.md)
453
+ min-agent history [delete|rename|export] manage saved sessions
454
+ min-agent update upgrade to the latest npm release
455
+
456
+ confirmation modes (default: accept-edits; independent of isolation):
457
+ ask prompt before dangerous operations
458
+ accept-edits auto-approve file writes; still prompt for dangerous commands
459
+ allow-all auto-approve everything
460
+
461
+ thinking intensity (default: medium):
462
+ off disable thinking
463
+ low light reasoning
464
+ medium standard reasoning
465
+ high strong reasoning
466
+ max highest reasoning
467
+
468
+ ollama context window:
469
+ 2k … 256k loaded window size
470
+ auto use the model's default
471
+
472
+ memory (default: off):
473
+ off do not inject memories or expose memory tools
474
+ on remember facts across sessions
475
+
476
+ isolation modes (default: off; independent of confirmation):
477
+ off no sandboxing
478
+ workspace restrict file writes to the project workspace
479
+ strict restrict file writes and deny risky commands
480
+ env: MIN_AGENT_SANDBOX, MIN_AGENT_SANDBOX_NETWORK
481
+
482
+ rules (loaded as system instructions):
483
+ global: ~/.min-agent/rules.md
484
+ project: ./AGENTS.md or ./RULES.md or ./.min-agent/AGENTS.md
485
+ config: "instructions" array in ~/.min-agent/config.json
486
+
487
+ examples:
488
+ min-agent setup
489
+ min-agent setup --type ollama
490
+ min-agent
491
+ min-agent "hello"
492
+ min-agent exec "hello"
493
+ min-agent exec --resume <id> "continue"
494
+ min-agent --resume <id>
495
+ min-agent --permission ask
496
+ min-agent --think max
497
+ min-agent --memory on
498
+ min-agent serve --port 8787
499
+ min-agent update
500
+ min-agent rules edit
501
+ min-agent mcp add filesystem npx -y @modelcontextprotocol/server-filesystem /tmp
502
+ min-agent mcp add remote --url https://example.com/mcp --token "$TOKEN"
503
+ `),$}function Z8($){if($.yes)d4(!0)}async function z8($){if($.sandbox!==void 0||$.network!==void 0){let{setSandboxOverride:f}=await Promise.resolve().then(() => (E0(),p3));if($.sandbox!==void 0)f({mode:$.sandbox});if($.network!==void 0)f({network:$.network})}if($.permission!==void 0){let{setPermissionOverride:f}=await Promise.resolve().then(() => (G$(),Q9));f($.permission)}if($.think!==void 0){let{setThinkingOverride:f}=await Promise.resolve().then(() => ($1(),j9));f($.think)}if($.memory!==void 0){let{setMemoryOverride:f}=await Promise.resolve().then(() => (V1(),R9));f($.memory)}}function yb($,f){return f.length>0||Boolean($.resume)||$.image.length>0||Boolean($.model)||Boolean($.provider)}function Tb($){let f=[],Z=[];for(let z of $)if(z.startsWith("--"))Z.push(`Unknown option: ${z}`);else f.push(z);return{rest:f,errors:Z}}async function Ib($,f){Z8(f);let{rest:Z,errors:z}=Tb($),J=yb(f,Z);if((f.sandbox!==void 0||f.network!==void 0||f.permission!==void 0||f.think!==void 0||f.memory!==void 0)&&!J){let{runWriteConfig:G}=await Promise.resolve().then(() => (oJ(),rJ));await G({sandbox:f.sandbox,network:f.network,permission:f.permission,think:f.think,memory:f.memory,scope:f.project?"project":f.global?"global":void 0});return}if(await z8(f),z.length>0){console.error(z[0]),process.exitCode=1;return}let{startTuiSession:Q}=await Promise.resolve().then(() => (nZ(),xX));await Q({model:f.model,provider:f.provider,resume:f.resume,images:f.image,positionals:Z})}async function hX($,f){let Z=wb();Z.action((z,J)=>Ib(z,J)),f(Z);try{await Z.parseAsync($,{from:"user"})}catch(z){if(z instanceof a){console.error(L8(z)),process.exitCode=Y9(z);return}if(kb(z)){process.exitCode=z.exitCode;return}console.error(L8(z)),process.exitCode=2}}function kb($){return typeof $==="object"&&$!==null&&"exitCode"in $&&"code"in $}_8();i9();import{Option as xW}from"commander";d();Y$();async function cX($){let f=$0(),Z=$.provider?f.providers?.find((J)=>J.name===$.provider):e(f);if(!Z?.baseURL||!Z?.apiKey)throw new a("Not configured.",{hint:"Run: min-agent setup"});console.log(`Fetching models (${Z.name??"default"})...`);let z=await Ff(Z.baseURL,Z.apiKey);if(z.length===0)console.log("No models found or unable to fetch model list.");else{console.log(`
504
+ Available models (${z.length}):`);for(let J of z){let K=J===Z.defaultModel?" ← default":"";console.log(` ${J}${K}`)}}}nZ();async function mX($,f){Z8(f),await z8(f),await kZ({model:f.model,provider:f.provider,resume:f.resume,images:f.image,positionals:$})}gf();d();function rX($,f,Z){let z=$.join(" "),J=f.length>0;if(z==="-"){let K=f;if(!K.trim())return{ok:!1,error:"Usage: min-agent exec <message>"};return{ok:!0,prompt:K}}if(!z){if(Z||!J)return{ok:!1,error:"Usage: min-agent exec <message>"};return{ok:!0,prompt:f}}if(J&&!Z)return{ok:!0,prompt:`${z}
505
+
506
+ ${f}`};return{ok:!0,prompt:z}}Y$();async function oX($,f){if(!a$())throw new a("Not configured.",{hint:"Run: min-agent setup"});Z8(f),await z8(f);let Z=Boolean(process.stdin.isTTY),J=$.join(" ")==="-"||!Z,K="";if(J)try{let Y=[];for await(let P of process.stdin)Y.push(Buffer.isBuffer(P)?P:Buffer.from(P));K=Buffer.concat(Y).toString("utf-8")}catch{throw new a("Failed to read stdin")}let Q=rX($,K,Z);if(!Q.ok)throw new a(Q.error);if(await DZ(Q.prompt,f.model,f.image.length>0?f.image:void 0,f.provider,f.resume))process.exitCode=1}d();Y$();async function WW($){if(!a$())throw new a("Not configured.",{hint:"Run: min-agent setup"});let{runServe:f}=await Promise.resolve().then(() => (XW(),PW));await f({port:$.port,host:$.host})}S9();async function vZ($,f,Z){let z=f.project?"project":f.global?"global":void 0,J=k8({positionals:$,flagMode:Z.sandbox,flagNetwork:Z.network??f.network,scope:z});if(console.log(J.lines.join(`
507
+ `)),!J.ok)process.exitCode=1}v9();async function HW($,f,Z){let z=f.project?"project":f.global?"global":void 0,J=R8({positionals:$,flagMode:Z.permission,scope:z});if(console.log(J.lines.join(`
508
+ `)),!J.ok)process.exitCode=1}u9();async function UW($,f,Z){let z=f.project?"project":f.global?"global":void 0,J=v8({positionals:$,flagEffort:Z.think,scope:z});if(console.log(J.lines.join(`
509
+ `)),!J.ok)process.exitCode=1}H4();var R4=["Usage: min-agent ctx [2k|4k|8k|12k|16k|32k|64k|128k|256k|auto]"," Context levels are only available for an Ollama provider."].join(`
510
+ `);function MW($){if($.positionals[0]==="--help"||$.positionals[0]==="-h")return{ok:!0,lines:[R4]};if(!E5())return{ok:!1,lines:["Context levels are only available for an Ollama provider.",R4]};if($.positionals.length===0){let z=g5();return{ok:!0,lines:[`Current context window: ${z.choice==="auto"&&z.tokens!=null?`${z.tokens}`:z.choice}`,R4]}}if($.positionals.length>1)return{ok:!1,lines:[R4]};let f=q2($.positionals[0]);if(!f)return{ok:!1,lines:[R4]};let Z=Of(f);if(!Z.ok)return{ok:!1,lines:["Context levels are only available for an Ollama provider.",R4]};return{ok:!0,lines:[`✓ Context window set to ${Z.choice==="auto"?"auto":l1(Z.choice)}`]}}async function FW($){let f=MW({positionals:$});if(console.log(f.lines.join(`
511
+ `)),!f.ok)process.exitCode=1}import{existsSync as qW,writeFileSync as ob,mkdirSync as NW}from"fs";import uZ from"path";function pb(){let $=uZ.join(process.cwd(),".min-agent"),f=uZ.join($,"skills"),Z=uZ.join($,"mcp.json");if(!qW(f))NW(f,{recursive:!0});if(!qW(Z))NW($,{recursive:!0}),ob(Z,JSON.stringify({mcpServers:{}},null,2),"utf-8")}async function BW(){pb(),console.log(`✓ Initialized .min-agent/ in ${process.cwd()}`)}d();import{existsSync as db,writeFileSync as ib,mkdirSync as lb}from"fs";async function VW(){let{loadInstructions:$}=await Promise.resolve().then(() => (Zf(),NY)),f=await $();if(f.length===0)console.log("No instruction rules loaded."),console.log(""),console.log("Add rules by creating:"),console.log(` Global: ${df()}`),console.log(" Project: ./AGENTS.md or ./RULES.md"),console.log(""),console.log("Or add paths/URLs in ~/.min-agent/config.json:"),console.log(' { "instructions": ["./docs/rules.md", "https://..."] }');else{console.log(`Loaded ${f.length} instruction source(s):
512
+ `);for(let Z of f){let z=Z.split(`
513
+ `)[0];console.log(` ${z}`)}}}async function LW(){let $=df();if(!db($))lb(X0(),{recursive:!0}),ib($,`# Global Agent Rules
514
+
515
+ <!-- Add your custom instructions here. They will be included in every conversation. -->
516
+ `,"utf-8");let f=process.env.EDITOR||"vi",{execSync:Z}=await import("child_process");Z(`${f} "${$}"`,{stdio:"inherit"})}t4();async function _W(){let $=await oz();if($.status==="check-failed"||$.status==="install-failed")process.exitCode=1}Y$();import{writeFileSync as tb}from"fs";async function DW(){let{listSessions:$}=await Promise.resolve().then(() => (n$(),yf)),f=$();if(f.length===0)console.log("No saved sessions."),console.log("Sessions are auto-saved when you exit interactive chat.");else{console.log(`Sessions (${f.length}):`);for(let Z of f.slice(0,20)){let z=Z.updated.split("T")[0];console.log(` ${Z.id} ${z} ${Z.title} (${Z.messageCount} msgs)`)}console.log(`
517
+ Resume with: min-agent --resume <id>`)}}async function bW($){let{deleteSession:f}=await Promise.resolve().then(() => (n$(),yf));if(f($))console.log(`✓ Session ${$} deleted`);else throw new a(`Session ${$} not found`)}async function AW($,f){let Z=f.join(" ");if(!Z)throw new a("Usage: min-agent history rename <id> <title>");let{renameSession:z}=await Promise.resolve().then(() => (n$(),yf));if(z($,Z))console.log(`✓ Session ${$} renamed to: ${Z}`);else throw new a(`Session ${$} not found`)}async function jW($,f){let{loadSession:Z}=await Promise.resolve().then(() => (n$(),yf)),z=Z($);if(!z)throw new a(`Session ${$} not found`);let J=JSON.stringify(z,null,2);if(f.output)try{tb(f.output,J,"utf-8"),console.log(`✓ Session ${$} exported to ${f.output}`)}catch(K){throw new a(`Export failed: ${K.message}`,{exitCode:2})}else console.log(J)}V1();E9();Y$();function ab($){let f=L$($),Z=$==="project"?"Project memories":"Global memories";if(f.length===0){console.log(`${Z}: none`);return}console.log(`${Z} (${f.length}):`);for(let z of f.map((J,K)=>I9(J,K,{date:!0})))console.log(z)}async function CW($,f,Z){if(!$&&Z===void 0)return!1;if($&&$!=="list"&&!g0($))return!1;if($==="list")return!1;let z=E8({positionals:$?[$]:[],flagMode:Z,scope:f});if(console.log(z.lines.join(`
518
+ `)),!z.ok)process.exitCode=1;return!0}async function OW($){let{memory:f,source:Z}=Lf();if(console.log(`Current memory: ${r1(f)} (${$2(Z)})`),!$&&L$("project").length===0&&L$("global").length===0){if(console.log("No memories stored."),!f1())console.log("Turn on with: min-agent memory on");console.log('Or add manually: min-agent memory add "prefer TypeScript over JavaScript"');return}let z=$?[$]:["project","global"];for(let J of z)ab(J);if(!f1())console.log("Memories are stored but not used in chat until you run: min-agent memory on")}async function wW($,f){let Z=$.join(" ");if(!Z)throw new a("Usage: min-agent memory add <text> [--project|--global]");let z=f??f2();K4(Z,[],z);let J=f1()?"":" (memory is off — turn on with: min-agent memory on)";console.log(`✓ ${z==="project"?"Project":"Global"} memory saved: "${Z}"${J}`)}async function yW($,f){let Z=$.join(" ");if(!Z)throw new a("Usage: min-agent memory search <query> [--project|--global]");let J=(f?[f]:["project","global"]).flatMap((K)=>_f(Z,K).map((Q)=>{let G=Q.tags.length>0?` [${Q.tags.join(", ")}]`:"";return` [${K}] #${Q.index+1}: ${Q.content}${G}`}));if(J.length===0)console.log(`No memories matching "${Z}"`);else{console.log(`Found ${J.length} memory(s):`);for(let K of J)console.log(K)}}async function TW($,f){let Z=Number.parseInt($,10);if(Number.isNaN(Z))throw new a("Usage: min-agent memory delete <number> [--project|--global]");let z=f??f2();if(Q4(Z-1,z))console.log(`✓ ${z==="project"?"Project":"Global"} memory #${Z} deleted`);else throw new a(`${z==="project"?"Project":"Global"} memory #${Z} not found`)}S$();Y$();function sb($){let f={};for(let Z of $??[]){let z=Z.indexOf("=");if(z<=0)throw new a(`Invalid --env format: ${Z}`,{hint:"use KEY=VALUE"});f[Z.slice(0,z)]=Z.slice(z+1)}return f}async function IW($,f,Z){let z=Z.project?"project":"global";if(Z.sse&&Z.streamableHttp)throw new a("--sse and --streamable-http are mutually exclusive");let J=`Usage: min-agent mcp add <name> [--project] [--skip-check] <command...>
519
+ or: min-agent mcp add <name> --url <https://host/mcp> [--sse|--streamable-http] [--token <bearer>] [--project] [--skip-check]`,K;if(Z.url?.trim()){if(K={url:Z.url.trim(),enabled:!0,remoteTransport:Z.streamableHttp?"streamable-http":Z.sse?"sse":"auto",...Z.timeout?{timeout:Z.timeout}:{}},Z.token?.trim())K.token=Z.token.trim()}else if(f.length>0)K={command:f,enabled:!0,...Z.timeout?{timeout:Z.timeout}:{}};else throw new a(J);let Q=sb(Z.env);if(Object.keys(Q).length>0)K.environment=Q;let G=0;if(!Z.skipCheck){console.log(`Validating MCP server "${$}"...`);let W=await L6($,K);if(!W.ok)throw new a(`MCP server "${$}" validation failed: ${W.error??"unknown error"}`,{exitCode:2});G=W.toolCount}else console.log(`Skipping MCP validation for "${$}" (--skip-check).`);let Y=C1(z);Y.mcpServers[$]=K,C2(Y,z);let P=Z.skipCheck?"":` (${G} tools detected)`,X=Z.project?" [project]":"";console.log(`✓ MCP server "${$}" added${X}: ${V6(K)}${P}`)}async function kW($,f){let Z=f.project?"project":"global",z=C1(Z);if(!z.mcpServers[$]){let J=G1().find((K)=>K.name===$);throw new a(J?`MCP server "${$}" is defined in ${J.scope} scope, not ${Z}.`:`MCP server "${$}" not found`)}delete z.mcpServers[$],C2(z,Z),console.log(`✓ MCP server "${$}" removed${f.project?" [project]":""}`)}async function nW(){let $=G1();if($.length===0){console.log("No MCP servers configured."),console.log("Add one with: min-agent mcp add <name> <command...>");return}console.log("MCP Servers:");for(let{name:f,config:Z,scope:z}of $){let J=Z.enabled===!1?"\x1B[90mdisabled\x1B[0m":"\x1B[32menabled\x1B[0m";console.log(` ${f} ${J}${z==="project"?" \x1B[90m[project]\x1B[0m":""}`)}console.log(`
520
+ Use: min-agent mcp info <name> for details`)}async function RW($){let f=G1().find((J)=>J.name===$);if(!f)throw new a(`MCP server "${$}" not found`);let Z=f.config;if(console.log(`Name: ${$}`),console.log(`Scope: ${f.scope}`),console.log(`Status: ${Z.enabled===!1?"disabled":"enabled"}`),console.log(`Binding: ${V6(Z)}`),Z.command)console.log(`Command: ${Array.isArray(Z.command)?Z.command.join(" "):`${Z.command} ${(Z.args??[]).join(" ")}`.trim()}`);if(Z.url){if(console.log(`URL: ${Z.url}`),Z.remoteTransport)console.log(`Transport: ${Z.remoteTransport}`);if(Z.oauth===!1)console.log("OAuth: disabled");else if(Z.oauth)console.log(`OAuth: enabled${Z.oauth.clientId?" (clientId set)":""}`)}if(Z.headers)console.log(`Headers: ${Object.keys(Z.headers).join(", ")} (values hidden)`);if(Z.token)console.log("Token: ***");if(Z.environment)console.log(`Env: ${Object.keys(Z.environment).join(", ")}`);if(Z.timeout)console.log(`Timeout: ${Z.timeout}ms`);if(Z.connectTimeout)console.log(`ConnectTimeout: ${Z.connectTimeout}ms`);if(Z.callTimeout)console.log(`CallTimeout: ${Z.callTimeout}ms`);let z=o$()[$];if(z?.connected){let J=$f($).servers[0];if(J)console.log(`Tools: ${z.tools.join(", ")||"(none)"}`),console.log(`Resources: ${J.resources.length===0?"(none)":J.resources.map((K)=>K.uri).join(", ")}`),console.log(`Prompts: ${J.prompts.length===0?"(none)":J.prompts.map((K)=>K.name).join(", ")}`)}}async function SW(){let $=await q7();if($.length===0){console.log("No MCP servers configured."),console.log("Add one with: min-agent mcp add <name> <command...> or --url <https://...>");return}let f=0;console.log("MCP Check Results:");for(let Z of $){if(!Z.enabled){console.log(` ${Z.name}: skipped (disabled)`);continue}if(Z.ok)console.log(` ${Z.name}: ok (${Z.toolCount} tools)`);else f++,console.log(` ${Z.name}: failed${Z.error?` - ${Z.error}`:""}`)}if(f>0)throw new a(`${f} MCP server(s) failed.`,{exitCode:1});console.log(`
521
+ All enabled MCP servers are available.`)}async function EZ($,f,Z){let z=Z.project?"project":"global",J=f?"enable":"disable";if($.length===0)throw new a(`Usage: min-agent mcp ${J} <name...> [--project]`);let K=C1(z);for(let Q of $){if(!K.mcpServers[Q]){console.error(`MCP server "${Q}" not found${Z.project?" in project scope":""}`);continue}K.mcpServers[Q].enabled=f,console.log(`✓ MCP server "${Q}" ${J}d${Z.project?" [project]":""}`)}C2(K,z)}v$();Y$();import{existsSync as vW,writeFileSync as eb,mkdirSync as $A}from"fs";import mf from"path";import fA from"os";function ZA($,f){let Z=$.replace(/\s+/g," ").trim();return Z.length<=f?Z:`${Z.slice(0,f-1)}…`}async function uW($){A$({silent:!0});let{getAllSkills:f,getStaleDisabledSkills:Z}=await Promise.resolve().then(() => (v$(),I2)),z=f().sort((K,Q)=>K.name.localeCompare(Q.name)),J=Z();if($){console.log(JSON.stringify({count:z.length,enabled_count:z.filter((K)=>K.enabled).length,stale_disabled:J,skills:z.map((K)=>({name:K.name,description:K.description,location:K.location,enabled:K.enabled,...K.disabledScope?{disabled_scope:K.disabledScope}:{},...K.version?{version:K.version}:{},...K.allowedTools.length?{allowed_tools:K.allowedTools}:{},...K.requiredBins.length?{requires_bins:K.requiredBins}:{},...K.builtin?{builtin:!0}:{},...K.alwaysLoad?{always_load:!0}:{}}))},null,2));return}if(z.length===0&&J.length===0){console.log("No skills found. Add SKILL.md files in .min-agent/skills/<name>/");return}console.log(`Skills (${z.filter((K)=>K.enabled).length} enabled, ${z.filter((K)=>!K.enabled).length} disabled):`);for(let K of z){let Q=K.enabled?"\x1B[32menabled \x1B[0m":`\x1B[90mdisabled(${K.disabledScope==="project"?"proj":"glob"})\x1B[0m`,G=K.builtin?" \x1B[90mbuiltin\x1B[0m":"";console.log(` ${K.name} ${Q}${G} \x1B[90m${ZA(K.description,60)}\x1B[0m`),console.log(` \x1B[90m${K.location}\x1B[0m`)}if(J.length>0)console.log(`
522
+ \x1B[33m⚠ disabledSkills/enabledSkills entries matching no skill: ${J.join(", ")}\x1B[0m`),console.log(`\x1B[33m Remove them with: min-agent skills enable ${J.join(" ")} (add --project if the entry is project-scoped)\x1B[0m`);console.log(`
523
+ Use: min-agent skills info <name> for details`)}async function EW($,f){A$({silent:!0});let{getSkill:Z,getAllSkills:z}=await Promise.resolve().then(() => (v$(),I2)),J=Z($);if(!J){let K=z().map((Q)=>Q.name);throw new a(`Skill "${$}" not found.${K.length?` Available: ${K.join(", ")}`:" No skills discovered."}`)}if(f){console.log(JSON.stringify(J,null,2));return}if(console.log(`Name: ${J.name}`),console.log(`Status: ${J.enabled?"enabled":`disabled (${J.disabledScope} scope)`}`),J.builtin)console.log("Source: builtin");if(J.version)console.log(`Version: ${J.version}`);if(console.log(`Description: ${J.description}`),console.log(`Location: ${J.location}`),J.allowedTools.length>0)console.log(`Tools: ${J.allowedTools.join(", ")}`);if(J.requiredBins.length>0)console.log(`Requires: ${J.requiredBins.join(", ")}`);if(J.content.trim())console.log(`
524
+ --- Content ---
525
+ `),console.log(J.content.trim())}async function gZ($,f,Z){let z=f?"enable":"disable";if($.length===0)throw new a(`Usage: min-agent skills ${z} <name...> [--project]`);A$({silent:!0});let{getAllSkills:J,setSkillEnabled:K,getStaleDisabledSkills:Q}=await Promise.resolve().then(() => (v$(),I2)),G=new Set(J().map((X)=>X.name)),Y=new Set(Q()),P=$.filter((X)=>!G.has(X)&&!(f&&Y.has(X)));if(P.length>0)throw new a(`Skill${P.length>1?"s":""} not found: ${P.join(", ")}`,{hint:G.size?`Available: ${[...G].join(", ")}`:"No skills discovered."});for(let X of K($,f,Z))if(console.log(`✓ Skill "${X.name}" ${z}d (${Z} scope)`),X.blockedBy)console.log(`\x1B[33m ⚠ still ${X.enabled?"enabled":"disabled"} — overridden by ${X.blockedBy} scope\x1B[0m`)}async function gW($,f){if(!/^[\w-]+$/.test($))throw new a("Invalid skill name",{hint:"use letters, digits, _ or -"});if(!f&&!vW(mf.join(process.cwd(),".min-agent")))throw new a("当前目录没有 .min-agent/,无法创建项目级 skill。",{hint:"先运行: min-agent init"});let Z=f?mf.join(fA.homedir(),".agents","skills"):mf.join(process.cwd(),".min-agent","skills"),z=mf.join(Z,$);if(vW(mf.join(z,"SKILL.md")))throw new a(`Skill "${$}" already exists at ${z}`);$A(z,{recursive:!0}),eb(mf.join(z,"SKILL.md"),`---
526
+ name: ${$}
527
+ description: What this skill does
528
+ # version: 1.0.0
529
+ # allowed-tools: [read, grep]
530
+ # metadata:
531
+ # requires:
532
+ # bins: ["some-cli"]
533
+ ---
534
+
535
+ # ${$}
536
+
537
+ Write the skill instructions here.
538
+ `,"utf-8"),console.log(`✓ Created skill "${$}" at ${mf.join(z,"SKILL.md")}`)}function hW($){let f=()=>$.opts();for(let Y of["chat","code"])$.command(Y).description("same as interactive session (compat)").argument("[prompt...]","prompt to send").allowUnknownOption().action(async(P)=>{await mX(P,f())});$.command("exec").description("run one message non-interactively").argument("[message...]",'message to send (use "-" to read from stdin)').allowUnknownOption().action(async(Y)=>{await oX(Y,f())}),d9($,f),$.command("init").description("initialize .min-agent/ in current directory").action(BW),$.command("models").description("list available models").action(async()=>{await cX(f())});let Z=$.command("rules").description("show or edit instruction rules");Z.action(VW),Z.command("edit").description("edit the global rules file").action(LW);let z=$.command("memory").description("show or set memory, and manage saved memories");z.argument("[state]","on or off"),z.action(async(Y)=>{let P=f(),X=P.project?"project":P.global?"global":void 0;if(await CW(Y,X,P.memory))return;if(Y&&Y!=="list"){let{CliError:W}=await Promise.resolve().then(() => (Y$(),nz));throw new W("Usage: min-agent memory [on|off|list|add|search|delete] [--project|--global]")}await OW(X)}),z.command("add").argument("<text...>").description("add a memory").action(async(Y)=>{let P=f();await wW(Y,P.project?"project":P.global?"global":void 0)}),z.command("search").argument("<query...>").description("search memories").action(async(Y)=>{let P=f();await yW(Y,P.project?"project":P.global?"global":void 0)}),z.command("delete").argument("<index>").description("delete a memory by index").action(async(Y)=>{let P=f();await TW(Y,P.project?"project":P.global?"global":void 0)});let J=$.command("sandbox").description("show or set isolation mode (uses --project/--global)").argument("[mode]","off, workspace, or strict");J.action(async(Y)=>{let P=f();await vZ(Y?[Y]:[],P,P)}),J.command("network").description("show or set network policy").argument("[policy]","allow or deny").action(async(Y)=>{let P=f();await vZ(["network",...Y?[Y]:[]],P,P)}),$.command("permission").description("show or set confirmation mode (uses --project/--global)").argument("[mode]","ask, accept-edits, or allow-all").action(async(Y)=>{let P=f();await HW(Y?[Y]:[],P,P)}),$.command("think").description("show or set thinking intensity (uses --project/--global)").argument("[level]","off, low, medium, high, or max").action(async(Y)=>{let P=f();await UW(Y?[Y]:[],P,P)}),$.command("ctx").description("show or set the Ollama context window level").argument("[level]","2k, 4k, 8k, 12k, 16k, 32k, 64k, 128k, 256k, or auto").action(async(Y)=>{await FW(Y?[Y]:[])});let K=$.command("mcp").description("manage MCP servers");K.command("add").description("add a new MCP server (stdio or remote)").usage("[options] <name> [command...]").argument("<name>").argument("[cmd...]","command to launch a stdio server (npx, node, ...)").option("--url <url>","remote server URL").option("--sse","use SSE transport for the remote server").option("--streamable-http","use streamable-http transport for the remote server").option("--token <token>","bearer token for remote servers").option("--env <KEY=VALUE>","extra env for stdio servers (repeatable)",(Y,P)=>[...P,Y],[]).addOption(new xW("--timeout <ms>","connection/call timeout").argParser(l4("--timeout"))).option("--skip-check","skip validation before saving").addHelpText("after","\nall options above must come before <name>. Everything after <name> (including flags meant for the\nlaunched command, like `npx -y`) is passed through as-is.\nscope: pass --project on `min-agent` before `mcp add` to write to .min-agent/mcp.json.").allowUnknownOption().passThroughOptions().action(async(Y,P,X)=>{await IW(Y,P,{...X,project:f().project})}),K.command("remove").argument("<name>").description("remove a server").action(async(Y)=>{await kW(Y,{project:f().project})}),K.command("list").description("list configured MCP servers").action(nW),K.command("info").argument("<name>").description("show details of a server").action(RW),K.command("check").description("test connectivity of all servers").action(SW),K.command("enable").argument("<names...>").description("enable disabled servers (use --project to target project scope)").action(async(Y)=>{await EZ(Y,!0,{project:f().project})}),K.command("disable").argument("<names...>").description("disable servers (use --project to target project scope)").action(async(Y)=>{await EZ(Y,!1,{project:f().project})});let Q=$.command("skills").description("manage skills");Q.command("list").option("--json","machine-readable JSON output").description("list skills").action(async(Y)=>{await uW(Boolean(Y.json))}),Q.command("info").argument("<name>").option("--json","machine-readable JSON output").description("show details of a skill").action(async(Y,P)=>{await EW(Y,Boolean(P.json))}),Q.command("new").argument("<name>").description("create a new skill scaffold (use --global on `min-agent` for ~/.agents/skills/)").action(async(Y)=>{await gW(Y,Boolean(f().global))}),Q.command("enable").argument("<names...>").description("enable disabled skills (use --project to target this project only)").action(async(Y)=>{await gZ(Y,!0,P9(f()))}),Q.command("disable").argument("<names...>").description("disable skills (use --project to target this project only)").action(async(Y)=>{await gZ(Y,!1,P9(f()))}),$.command("serve").description("start the HTTP API (see docs/API.md)").option("--host <host>","bind host").addOption(new xW("--port <port>","bind port").argParser(l4("--port"))).action(async(Y)=>{await WW(Y)});let G=$.command("history").description("manage saved sessions");G.action(DW),G.command("delete").argument("<id>").description("delete a saved session").action(bW),G.command("rename").argument("<id>").argument("<title...>").description("rename a saved session").action(async(Y,P)=>{await AW(Y,P)}),G.command("export").argument("<id>").option("-o, --output <file>","write to a file instead of stdout").description("export a session as JSON").action(async(Y,P)=>{await jW(Y,P)}),$.command("update").description("upgrade to the latest npm release").action(_W)}Tf();async function zA(){RG(),Z0("info","min-agent started"),await hX(process.argv.slice(2),hW)}zA().catch(($)=>{console.error(`\x1B[31mFatal error: ${$.message}\x1B[0m`),process.exitCode=1});