min-agent 0.6.5 → 0.6.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +264 -261
- package/package.json +1 -2
- package/docs/API.md +0 -757
package/dist/cli.js
CHANGED
|
@@ -1,54 +1,55 @@
|
|
|
1
|
-
import{createRequire as
|
|
2
|
-
`),
|
|
1
|
+
import{createRequire as Yq}from"node:module";var zq=Object.defineProperty;var Gq=($)=>$;function Qq($,Z){this[$]=Gq.bind(null,Z)}var M0=($,Z)=>{for(var J in Z)zq($,J,{get:Z[J],enumerable:!0,configurable:!0,set:Qq.bind(Z,J)})};var C=($,Z)=>()=>($&&(Z=$($=0)),Z);var Kq=Yq(import.meta.url);import{writeFile as Xq,rename as Pq,unlink as Wq}from"fs/promises";import{writeFileSync as Hq,renameSync as qq,unlinkSync as Uq}from"fs";import{randomBytes as Mq}from"crypto";import a9 from"path";function f8($){return a9.join(a9.dirname($),`.${a9.basename($)}.${process.pid}.${Mq(4).toString("hex")}.tmp`)}async function a4($,Z){let J=f8($);try{await Xq(J,Z,"utf-8"),await Pq(J,$)}catch(z){throw await Wq(J).catch(()=>{}),z}}function T0($,Z){let J=f8($);try{Hq(J,Z,"utf-8"),qq(J,$)}catch(z){try{Uq(J)}catch{}throw z}}var L$=()=>{};var X5={};M0(X5,{writeRoots:()=>d2,workspaceRoot:()=>G5,tightenSandbox:()=>Vz,setSandboxOverride:()=>o2,sandboxStatusLabel:()=>i2,sandboxNetworkLabel:()=>bz,sandboxModeLabel:()=>l2,sandboxLaunchSource:()=>J5,sandboxEnforcementCaveat:()=>r2,runWithSandboxPolicy:()=>z5,resolveCheckedPath:()=>fz,resetSandboxBackendCache:()=>Lq,readRoots:()=>jz,planSandboxedSpawn:()=>K5,pathAccessError:()=>j$,parseSandboxMode:()=>y$,parseSandboxConfig:()=>D1,parseNetworkPolicy:()=>o$,networkDeniedMessage:()=>m1,mergeSandboxConfig:()=>Z5,isNetworkCommand:()=>Az,isInsideRoot:()=>_8,getSandboxOverride:()=>Bq,getEffectiveSandboxPolicy:()=>t0,detectSandboxBackend:()=>Y5,clearSandboxOverride:()=>Nq,checkPathAccess:()=>Q5,bwrapBin:()=>Oz,buildSeatbeltProfile:()=>Dz,buildBwrapArgs:()=>Cz,DEFAULT_SANDBOX_MODE:()=>e9,DEFAULT_NETWORK_POLICY:()=>$5});import{AsyncLocalStorage as Fq}from"async_hooks";import{existsSync as s4,realpathSync as L8}from"fs";import s9 from"os";import L0 from"path";function y$($){if($==="off"||$==="workspace"||$==="strict")return $;return}function o$($){if($==="allow"||$==="deny")return $;return}function D1($){if($==null)return;if(typeof $==="string"){let Y=y$($);return Y?{mode:Y}:void 0}if(typeof $!=="object")return;let Z=$,J=y$(Z.mode),z=o$(Z.network),G=Array.isArray(Z.extraWriteRoots)?Z.extraWriteRoots.filter((Y)=>typeof Y==="string"&&Y.length>0):void 0,Q=Array.isArray(Z.extraReadRoots)?Z.extraReadRoots.filter((Y)=>typeof Y==="string"&&Y.length>0):void 0;if(!J&&!z&&!G&&!Q)return;return{mode:J,network:z,extraWriteRoots:G,extraReadRoots:Q}}function Z5($,Z){if(!$&&!Z)return;let J=Z?.extraWriteRoots??$?.extraWriteRoots,z=Z?.extraReadRoots??$?.extraReadRoots;return{mode:Z?.mode??$?.mode,network:Z?.network??$?.network,...J?{extraWriteRoots:J}:{},...z?{extraReadRoots:z}:{}}}function o2($){J1={...J1,...$}}function Nq(){J1={}}function Bq(){return{...J1}}function J5(){if(J1.mode!=null||J1.network!=null)return"cli";if(Nz()!=null||Bz()!=null)return"env";return null}function z5($,Z){return Fz.run($,Z)}function G5(){try{return L8(process.cwd())}catch{return L0.resolve(process.cwd())}}function Nz(){return y$(process.env.MIN_AGENT_SANDBOX)}function Bz(){return o$(process.env.MIN_AGENT_SANDBOX_NETWORK)}function Vq(){let $=D1(G0().sandbox);return{mode:J1.mode??Nz()??$?.mode??e9,network:J1.network??Bz()??$?.network??$5,extraWriteRoots:J1.extraWriteRoots??$?.extraWriteRoots??[],extraReadRoots:J1.extraReadRoots??$?.extraReadRoots??[],workspaceRoot:G5()}}function Vz($,Z){let J=Z.mode&&Wz[Z.mode]>Wz[$.mode]?Z.mode:$.mode,z=Z.network==="deny"||$.network==="deny"?"deny":"allow";return{...$,mode:J,network:z}}function t0(){let $=Vq(),Z=Fz.getStore();if(!Z)return $;if(Z.replace)return{mode:Z.mode??e9,network:Z.network??$5,extraWriteRoots:Z.extraWriteRoots??[],extraReadRoots:Z.extraReadRoots??[],workspaceRoot:Z.workspaceRoot??G5()};return Vz($,Z)}function _8($,Z){let J=(Y)=>{let K=L0.resolve(Y);return process.platform==="win32"?K.toLowerCase():K},z=J($),G=J(Z);if(z===G)return!0;let Q=G.endsWith(L0.sep)?G:G+L0.sep;return z.startsWith(Q)}function fz($,Z=process.cwd()){let J=L0.resolve(Z,$),z=[],G=J;for(;;)try{let Q=L8(G);return{lexical:J,real:z.length===0?Q:L0.resolve(Q,...z)}}catch{let Q=L0.dirname(G);if(Q===G)return{lexical:J,real:J};z.unshift(L0.basename(G)),G=Q}}function Z1(...$){return L0.join(s9.homedir(),...$)}function _z(){return[Z1(".ssh"),Z1(".gnupg"),Z1(".aws"),L0.join(Z1(".min-agent"),"config.json"),Z1(".netrc"),Z1(".npmrc"),Z1(".pypirc"),Z1(".git-credentials"),L0.join(Z1(".config"),"gh"),L0.join(Z1(".config"),"git","credentials"),"/etc/shadow","/etc/sudoers","/etc/master.passwd"]}function fq($){return _z().some((Z)=>{try{let J=s4(Z)?L8(Z):L0.resolve(Z);return _8($,J)||L0.resolve($)===L0.resolve(Z)}catch{return _8($,Z)}})}function Lz($){let Z=[],J=new Set;for(let z of $){let G=L0.resolve(z),Q=[G];try{Q.push(L8(G))}catch{}for(let Y of Q){let K=process.platform==="win32"?Y.toLowerCase():Y;if(J.has(K))continue;J.add(K),Z.push(Y)}}return Z}function _q(){let $=s9.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 d2($=t0()){return Lz([$.workspaceRoot,s9.tmpdir(),"/tmp","/var/tmp","/private/tmp","/private/var/tmp",..._q(),...$.extraWriteRoots.map((Z)=>L0.resolve($.workspaceRoot,Z))])}function jz($=t0()){return Lz([$.workspaceRoot,...d2($),...$.extraReadRoots.map((Z)=>L0.resolve($.workspaceRoot,Z))])}function Hz($,Z){return Z.some((J)=>_8($,J))}function Q5($,Z,J=process.cwd(),z=t0()){let{real:G}=fz($,J);if(fq(G))return{ok:!1,message:"该路径受保护,无法访问。"};if(z.mode==="off")return{ok:!0,real:G};if(Z==="write"){if(!Hz(G,d2(z)))return{ok:!1,message:`无法写入工作区以外的路径: ${$}`};return{ok:!0,real:G}}if(z.mode==="strict"&&!Hz(G,jz(z)))return{ok:!1,message:`当前隔离级别不允许读取工作区以外的文件: ${$}`};return{ok:!0,real:G}}function j$($,Z,J){let z=Q5($,Z,J);return z.ok?null:z.message}function Az($){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 m1(){return"当前设置不允许访问网络。"}function Y5(){if(A1)return A1;let $=process.env.MIN_AGENT_SANDBOX_BACKEND;if($==="seatbelt"||$==="bwrap"||$==="none")return A1=$,A1;if(process.platform==="darwin"&&s4("/usr/bin/sandbox-exec"))A1="seatbelt";else if(process.platform==="linux"&&(s4("/usr/bin/bwrap")||s4("/usr/local/bin/bwrap")))A1="bwrap";else A1="none";return A1}function Lq(){A1=void 0}function qz($){return`"${$.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function Dz($){let Z=d2($).map((G)=>`(subpath ${qz(G)})`).join(`
|
|
2
|
+
`),J=_z().map((G)=>`(subpath ${qz(L0.resolve(G))})`).join(`
|
|
3
3
|
`),z=$.network==="deny"?"(deny network*)":"";return`(version 1)
|
|
4
4
|
(allow default)
|
|
5
5
|
(deny file-write*)
|
|
6
6
|
(allow file-write-data (literal "/dev/null"))
|
|
7
7
|
(allow file-write*
|
|
8
|
-
${
|
|
8
|
+
${Z}
|
|
9
9
|
)
|
|
10
10
|
(deny file-read*
|
|
11
|
-
${
|
|
11
|
+
${J}
|
|
12
12
|
)
|
|
13
13
|
${z}
|
|
14
|
-
`}function
|
|
15
|
-
${qz}`:Mz,P}function l2($){return $==="off"?"off":$==="strict"?"strict":"workspace"}function wz($){return $==="deny"?"network denied":"network allowed"}function i2($=t0()){return`${l2($.mode)}, ${wz($.network)}`}var $9="off",f9="allow",Wz,Fz,Z1,_1,Mz="⚠ 当前平台不支持命令级隔离(需要 macOS 的 sandbox-exec 或 Linux 的 bwrap),bash 命令未在隔离环境中执行,工作区写入限制对它不生效(read/write/edit 等文件工具仍会校验路径)。",qz="⚠ 当前平台不支持系统级网络隔离,禁止联网仅按命令名拦截,脚本或解释器仍可能访问网络。",DH="当前平台不支持命令级隔离(需要 macOS 的 sandbox-exec 或 Linux 的 bwrap),严格隔离模式下无法安全执行 bash 命令,已拒绝执行。可将隔离级别设为 workspace(文件工具仍会校验路径)或 off。";var g0=C(()=>{l();Wz={off:0,workspace:1,strict:2},Fz=new qH,Z1={}});var b1={};M0(b1,{withBuiltinProvider:()=>bf,setSandboxConfig:()=>V4,setPermissionMode:()=>f2,setBudgetMaxCost:()=>M9,saveProjectConfig:()=>W$,saveConfig:()=>I0,permissionModeLabel:()=>B4,parseThinkingEffort:()=>S0,parsePermissionMode:()=>A$,parseMemoryMode:()=>n0,normalizeOllamaBaseURL:()=>A1,migrateLegacyConfig:()=>Sz,mergeProjectOverGlobal:()=>U9,loadStoredConfig:()=>c1,loadProjectConfig:()=>w0,loadConfigFile:()=>Rz,loadConfig:()=>t,isProviderLocked:()=>$2,isConfigured:()=>z1,isBuiltinProvider:()=>h1,getSandboxSnapshot:()=>a2,getRulesFile:()=>e4,getProjectConfigFile:()=>Df,getProjectConfigDir:()=>n1,getPermissionSnapshot:()=>t2,getEffectiveConfig:()=>K0,getConfigDir:()=>P0,getBudgetSnapshot:()=>jf,getActiveProvider:()=>s,fetchModelsLive:()=>L4,fetchModels:()=>_4,DEFAULT_PERMISSION_MODE:()=>Af,BUILTIN_PROVIDER:()=>X$,BUILTIN_MODEL:()=>s4});import{readFileSync as W9,mkdirSync as yz,existsSync as Iz,statSync as kz}from"fs";import N4 from"path";import AH from"os";function P0(){return process.env.MIN_AGENT_CONFIG_DIR??jH}function e4(){return N4.join(P0(),CH)}function n1(){return N4.join(process.cwd(),".min-agent")}function Df(){return N4.join(n1(),H9)}function w0(){let $=Df(),f;try{f=kz($)}catch{return{}}let Z=X9.get($);if(Z&&Z.mtimeMs===f.mtimeMs&&Z.size===f.size)return Z.config;let z;try{z=JSON.parse(W9($,"utf-8"))}catch{return console.warn(`\x1B[33m ⚠ Project config ${$} is not valid JSON; ignoring\x1B[0m`),{}}return X9.set($,{mtimeMs:f.mtimeMs,size:f.size,config:z}),z}function W$($){let f=n1();if(!Iz(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}=$;y0(Df(),JSON.stringify({...J,...Z?.length?{disabledSkills:Z}:{},...z?.length?{enabledSkills:z}:{}},null,2)),X9.delete(Df())}function Rz($){let f;try{f=kz($)}catch{return{}}if(F4&&F4.file===$&&F4.mtimeMs===f.mtimeMs&&F4.size===f.size)return F4.config;let Z;try{Z=JSON.parse(W9($,"utf-8"))}catch{return console.warn(`\x1B[33m ⚠ Config file ${$} is not valid JSON; using defaults\x1B[0m`),{}}return F4={file:$,mtimeMs:f.mtimeMs,size:f.size,config:Z},Z}function OH(){let $=process.env[bH]?.trim().toLowerCase();return $!=="1"&&$!=="true"}function wH($){return($.providers??[]).some((f)=>Boolean(f.baseURL?.trim()&&f.apiKey?.trim()))}function bf($){if(!OH())return $;if(wH($))return $;if(($.providers??[]).length>0)return $;return{...$,providers:[{...X$}],activeProvider:$.activeProvider??X$.name}}function h1($){if(!$)return!1;return $.name===X$.name&&$.type===X$.type&&$.baseURL===X$.baseURL&&$.apiKey===X$.apiKey}function $2($){return h1(s($))}function TH($){let f=$.providers??[];if(f.length!==1)return!1;let Z=f[0];if(!Z)return!1;return Z.name===X$.name&&Z.type===X$.type&&Z.baseURL===X$.baseURL&&Z.apiKey===X$.apiKey&&Z.defaultModel===X$.defaultModel&&Z.contextWindow==null}function yH($){if(!TH($))return $;let{providers:f,activeProvider:Z,...z}=$;return z}function c1(){let $=Rz(N4.join(P0(),H9)),{config:f,migrated:Z}=Sz($);if(Z)try{I0(f)}catch{}return f}function t(){return bf(c1())}function Sz($){if(!$.provider)return{config:$,migrated:!1};let{provider:Z,...z}=$;return{config:{...z,providers:[{name:"default",...Z}],activeProvider:"default"},migrated:!0}}function U9($,f){let Z=f.activeProvider??$.activeProvider,z=f.sampling?{...$.sampling,...f.sampling}:$.sampling,J=f.budget?{...$.budget,...f.budget}:$.budget,K=A$(f.permission)??A$($.permission),G=S0(f.thinking)??S0($.thinking),Q=n0(f.memory)??n0($.memory),Y=Z9(D1($.sandbox),D1(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((M)=>M.name===Z):0,U=H>=0?H:0;W=W.map((M,N)=>N===U?{...M,defaultModel:f.defaultModel}:M)}return{...$,activeProvider:Z,sampling:z,budget:J,permission:K,...G?{thinking:G}:{},...Q?{memory:Q}:{},...Y?{sandbox:Y}:{},compaction:P,agent:X,...W?{providers:W}:{}}}function K0(){return U9(t(),w0())}function jf(){let $=t(),f=w0(),Z=U9($,f).budget?.maxCostUSD,z=f.budget?.maxCostUSD!=null?"project":$.budget?.maxCostUSD!=null?"global":null;return{maxCostUSD:Z,source:z}}function A$($){if($==="ask"||$==="accept-edits"||$==="allow-all")return $;return}function S0($){if(typeof $!=="string")return;return IH[$.trim().toLowerCase()]}function n0($){if($===!0)return"on";if($===!1)return"off";if(typeof $!=="string")return;return kH[$.trim().toLowerCase()]}function B4($){if($==="allow-all")return"allow all";if($==="accept-edits")return"accept edits";return"ask"}function t2(){let $=t(),f=w0(),Z=A$(f.permission)??A$($.permission)??Af,z=A$(f.permission)!=null?"project":A$($.permission)!=null?"global":null;return{permission:Z,source:z}}function f2($,f){if(f==="project"){let Z=w0();W$({...Z,permission:$});return}I0({...t(),permission:$})}function V4($,f){if(f==="project"){let J=w0(),K=D1(J.sandbox)??{};W$({...J,sandbox:{...K,...$}});return}let Z=t(),z=D1(Z.sandbox)??{};I0({...Z,sandbox:{...z,...$}})}function a2(){let $=t0(),f=z9(),Z=D1(w0().sandbox),z=D1(t().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),G=f??(J?"project":K?"global":null);return{mode:$.mode,network:$.network,extraWriteRoots:$.extraWriteRoots,extraReadRoots:$.extraReadRoots,source:G,label:i2($)}}function M9($,f){if(f==="project"){let z=w0();W$({...z,budget:{...z.budget,maxCostUSD:$}});return}let Z=t();I0({...Z,budget:{...Z.budget,maxCostUSD:$}})}function s($){if(!$.providers||$.providers.length===0)return;if($.activeProvider){let f=$.providers.find((Z)=>Z.name===$.activeProvider);if(f)return f}return $.providers[0]}function A1($){let f=$.replace(/\/$/,"");return f.endsWith("/v1")?f:`${f}/v1`}function I0($){let f=P0();yz(f,{recursive:!0}),y0(N4.join(f,H9),JSON.stringify(yH($),null,2)),F4=null}function z1(){let $=t(),f=s($);return!!(f?.baseURL&&f?.apiKey)}async function Tz($,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:RH(J),ok:!0,status:z.status}}function RH($){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 Ez(){return N4.join(P0(),SH)}function q9($){return $.replace(/\/$/,"")}function vz(){let $=Ez();if(!Iz($))return{};try{let f=JSON.parse(W9($,"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 EH($){return vz()[q9($)]??[]}function vH($,f){let Z=vz();Z[q9($)]=f,yz(P0(),{recursive:!0}),y0(Ez(),JSON.stringify(Z))}async function L4($,f){if($===X$.baseURL&&f===X$.apiKey)return{models:[s4],ok:!0};try{let Z=q9($),z=await Tz(`${Z}/models`,f);if(z.models.length===0&&!Z.endsWith("/v1"))z=await Tz(`${Z}/v1/models`,f);if(z.ok&&z.models.length>0)return vH(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 _4($,f){let Z=await L4($,f);if(Z.models.length>0)return Z.models;let z=EH($);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 Af="accept-edits",s4="openrouter/free",X$,bH="MIN_AGENT_NO_BUILTIN_PROVIDER",jH,H9="config.json",CH="rules.md",F4=null,X9,IH,kH,SH="models-cache.json";var l=C(()=>{_$();g0();X$={name:"openrouter",type:"openai-compatible",baseURL:"https://openrouter.ai/api/v1",apiKey:"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",defaultModel:s4},jH=N4.join(AH.homedir(),".min-agent");X9=new Map;IH={off:"off",none:"off",low:"low",minimal:"low",medium:"medium",high:"high",max:"max",xhigh:"max","extra-high":"max",extra_high:"max",extrahigh:"max"};kH={on:"on",true:"on",enable:"on",enabled:"on",off:"off",false:"off",disable:"off",disabled:"off"}});function xH($,f){let Z=[],z=new Set;for(let J of f){let K=$[J];if(typeof K!=="string")continue;let G=K.trim();if(!G||z.has(G))continue;z.add(G),Z.push(G)}return Z}function xz($){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=xH(f,uH);if(Z.length>0)return Z.join(" — ");let z=f.key;return typeof z==="string"&&z.trim()?z.trim():null}function m1($){if(typeof $==="string")return $;return xz($)??""}function p1($){if($==null)return[];let f=Array.isArray($)?$:[$],Z=[],z=new Set;for(let J of f){let K=xz(J);if(!K||z.has(K))continue;z.add(K),Z.push(K)}return Z}function s2($){let f=$.trim().toLowerCase();return f==="其他"||f==="其它"||f==="other"}function r1($){if($.length===0)return[];let f=$.filter((z)=>!s2(z));if(f.length===0)return[uz];let Z=$.find((z)=>s2(z));return[...f,Z??uz]}function gz($){let{multiple:f,choices:Z,index:z,checked:J,otherText:K}=$;if(Z.length===0){let X=K.trim();return X?[X]:null}let G=Z.findIndex((X)=>s2(X)),Q=K.trim();if(!f){if(z<0||z>=Z.length)return null;if(z===G)return Q?[Q]: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===G){if(!Q)return null;Y.push(Q);continue}Y.push(Z[X])}return Y.length>0?Y:null}function nz($){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 hz($){if($.length===0)return"User cancelled the question";if($.length===1)return`User chose: ${$[0]}`;return`User chose: ${$.join("; ")}`}var uH,uz="其他";var e2=C(()=>{uH=["label","description","title","text","value","content","prompt"]});var Sf={};M0(Sf,{setTuiQuestion:()=>kf,setTuiConfirm:()=>If,setPermissionOverride:()=>yf,setExecPermissiveDefault:()=>hH,setConfirmReadline:()=>cH,setAutoApprove:()=>Z6,runWithConfirmContext:()=>L9,isExecPermissive:()=>B9,isEditAutoApprove:()=>A4,isDestructiveCommand:()=>Rf,isDangerousCommand:()=>D9,isAutoApprove:()=>D4,getPermissionOverride:()=>z6,getPermissionMode:()=>V9,confirm:()=>o$,askQuestion:()=>_9});import{AsyncLocalStorage as gH}from"async_hooks";import nH from"readline";function Z6($){mz=$}function hH($){N9=$}function B9(){return N9}function D4(){let $=J6.getStore();if($)return $.autoApprove;if(mz)return!0;if(N9)return!0;return V9()==="allow-all"}function yf($){wf=$}function z6(){return wf}function V9(){if(wf)return wf;let $=K0();return $.permission==="allow-all"||$.permission==="accept-edits"||$.permission==="ask"?$.permission:Af}function A4(){let $=J6.getStore();if($)return $.autoApprove;if(D4())return!0;return V9()==="accept-edits"}function L9($,f){return J6.run($,f)}function cH($){f6=$}function If($){Tf=$}function kf($){F9=$}async function _9($,f,Z=!1){let z=m1($),J=r1(p1(f)),K=J.length>0?J:void 0,G=J6.getStore();if(G){if(G.autoApprove)return null;if(G.onQuestion)return G.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`),
|
|
17
|
-
\x1B[33m⚠ Rejected (no interactive terminal): ${$}\x1B[0m`),!1;return
|
|
14
|
+
`}function Oz(){if(s4("/usr/bin/bwrap"))return"/usr/bin/bwrap";return"/usr/local/bin/bwrap"}function Cz($,Z,J){let z=["--die-with-parent","--ro-bind","/","/","--dev","/dev","--proc","/proc"],G=new Set;for(let Q of d2($)){let Y=process.platform==="win32"?Q.toLowerCase():Q;if(G.has(Y))continue;if(G.add(Y),s4(Q))z.push("--bind",Q,Q)}if($.network==="deny")z.push("--unshare-net");return z.push("--chdir",Z,"/bin/sh","-c",J),z}function r2($){if($==="off"||Y5()!=="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 K5($,Z,J,z=t0()){if(z.mode!=="off"){if(!Q5(Z,"write",process.cwd(),z).ok)return{error:`无法在工作区以外的目录执行命令: ${Z}`}}let G=Y5();if(z.network==="deny"&&G==="none"&&Az($))return{error:m1()};let Q=process.platform==="win32",Y=Q?`chcp 65001 >nul && ${$}`:$,K={...J,...Q?{PYTHONIOENCODING:"utf-8"}:{}},X=()=>({file:Y,args:[],shell:!0,cwd:Z,env:K});if(z.mode==="off"){let W=X();if(z.network==="deny"&&G==="none")W.warning=Mz;return W}if(G==="seatbelt")return{file:"/usr/bin/sandbox-exec",args:["-p",Dz(z),"/bin/sh","-c",Y],shell:!1,cwd:Z,env:K};if(G==="bwrap")return{file:Oz(),args:Cz(z,Z,Y),shell:!1,cwd:Z,env:K};if(z.mode==="strict")return{error:jq};let P=X();return P.warning=z.network==="deny"?`${Uz}
|
|
15
|
+
${Mz}`:Uz,P}function l2($){return $==="off"?"off":$==="strict"?"strict":"workspace"}function bz($){return $==="deny"?"network denied":"network allowed"}function i2($=t0()){return`${l2($.mode)}, ${bz($.network)}`}var e9="off",$5="allow",Wz,Fz,J1,A1,Uz="⚠ 当前平台不支持命令级隔离(需要 macOS 的 sandbox-exec 或 Linux 的 bwrap),bash 命令未在隔离环境中执行,工作区写入限制对它不生效(read/write/edit 等文件工具仍会校验路径)。",Mz="⚠ 当前平台不支持系统级网络隔离,禁止联网仅按命令名拦截,脚本或解释器仍可能访问网络。",jq="当前平台不支持命令级隔离(需要 macOS 的 sandbox-exec 或 Linux 的 bwrap),严格隔离模式下无法安全执行 bash 命令,已拒绝执行。可将隔离级别设为 workspace(文件工具仍会校验路径)或 off。";var u0=C(()=>{l();Wz={off:0,workspace:1,strict:2},Fz=new Fq,J1={}});var C1={};M0(C1,{withBuiltinProvider:()=>D8,setSandboxConfig:()=>_4,setPermissionMode:()=>J2,setBudgetMaxCost:()=>U5,saveProjectConfig:()=>H$,saveConfig:()=>R0,permissionModeLabel:()=>f4,parseThinkingEffort:()=>S0,parsePermissionMode:()=>A$,parseMemoryMode:()=>h0,normalizeOllamaBaseURL:()=>O1,migrateLegacyConfig:()=>yz,mergeProjectOverGlobal:()=>q5,loadStoredConfig:()=>c1,loadProjectConfig:()=>w0,loadConfigFile:()=>kz,loadConfig:()=>a,isProviderLocked:()=>Z2,isConfigured:()=>G1,isBuiltinProvider:()=>z1,getSandboxSnapshot:()=>a2,getRulesFile:()=>$2,getProjectConfigFile:()=>j8,getProjectConfigDir:()=>n1,getPermissionSnapshot:()=>t2,getEffectiveConfig:()=>G0,getConfigDir:()=>P0,getBudgetSnapshot:()=>O8,getActiveProvider:()=>s,fetchModelsLive:()=>L4,fetchModels:()=>j4,DEFAULT_PERMISSION_MODE:()=>A8,BUILTIN_PROVIDER:()=>W$,BUILTIN_MODEL:()=>e4});import{readFileSync as W5,mkdirSync as Iz,existsSync as Tz,statSync as Rz}from"fs";import V4 from"path";import Aq from"os";function P0(){return process.env.MIN_AGENT_CONFIG_DIR??Oq}function $2(){return V4.join(P0(),Cq)}function n1(){return V4.join(process.cwd(),".min-agent")}function j8(){return V4.join(n1(),H5)}function w0(){let $=j8(),Z;try{Z=Rz($)}catch{return{}}let J=P5.get($);if(J&&J.mtimeMs===Z.mtimeMs&&J.size===Z.size)return J.config;let z;try{z=JSON.parse(W5($,"utf-8"))}catch{return console.warn(`\x1B[33m ⚠ Project config ${$} is not valid JSON; ignoring\x1B[0m`),{}}return P5.set($,{mtimeMs:Z.mtimeMs,size:Z.size,config:z}),z}function H$($){let Z=n1();if(!Tz(Z)){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:J,enabledSkills:z,...G}=$;T0(j8(),JSON.stringify({...G,...J?.length?{disabledSkills:J}:{},...z?.length?{enabledSkills:z}:{}},null,2)),P5.delete(j8())}function kz($){let Z;try{Z=Rz($)}catch{return{}}if(B4&&B4.file===$&&B4.mtimeMs===Z.mtimeMs&&B4.size===Z.size)return B4.config;let J;try{J=JSON.parse(W5($,"utf-8"))}catch{return console.warn(`\x1B[33m ⚠ Config file ${$} is not valid JSON; using defaults\x1B[0m`),{}}return B4={file:$,mtimeMs:Z.mtimeMs,size:Z.size,config:J},J}function bq(){let $=process.env[Dq]?.trim().toLowerCase();return $!=="1"&&$!=="true"}function wq($){return($.providers??[]).some((Z)=>Boolean(Z.baseURL?.trim()&&Z.apiKey?.trim()))}function D8($){if(!bq())return $;if(wq($))return $;if(($.providers??[]).length>0)return $;return{...$,providers:[{...W$}],activeProvider:$.activeProvider??W$.name}}function z1($){if(!$)return!1;return $.name===W$.name&&$.type===W$.type&&$.baseURL===W$.baseURL&&$.apiKey===W$.apiKey}function Z2($){return z1(s($))}function Iq($){let Z=$.providers??[];if(Z.length!==1)return!1;let J=Z[0];if(!J)return!1;return J.name===W$.name&&J.type===W$.type&&J.baseURL===W$.baseURL&&J.apiKey===W$.apiKey&&J.defaultModel===W$.defaultModel&&J.contextWindow==null}function Tq($){if(!Iq($))return $;let{providers:Z,activeProvider:J,...z}=$;return z}function c1(){let $=kz(V4.join(P0(),H5)),{config:Z,migrated:J}=yz($);if(J)try{R0(Z)}catch{}return Z}function a(){return D8(c1())}function yz($){if(!$.provider)return{config:$,migrated:!1};let{provider:J,...z}=$;return{config:{...z,providers:[{name:"default",...J}],activeProvider:"default"},migrated:!0}}function q5($,Z){let J=Z.activeProvider??$.activeProvider,z=Z.sampling?{...$.sampling,...Z.sampling}:$.sampling,G=Z.budget?{...$.budget,...Z.budget}:$.budget,Q=A$(Z.permission)??A$($.permission),Y=S0(Z.thinking)??S0($.thinking),K=h0(Z.memory)??h0($.memory),X=Z5(D1($.sandbox),D1(Z.sandbox)),P=Z.compaction?{...$.compaction,...Z.compaction}:$.compaction,W=Z.agent?{...$.agent,...Z.agent}:$.agent,H=$.providers;if(Z.defaultModel&&H&&H.length>0){let q=J?H.findIndex((M)=>M.name===J):0,U=q>=0?q:0;H=H.map((M,F)=>F===U?{...M,defaultModel:Z.defaultModel}:M)}return{...$,activeProvider:J,sampling:z,budget:G,permission:Q,...Y?{thinking:Y}:{},...K?{memory:K}:{},...X?{sandbox:X}:{},compaction:P,agent:W,...H?{providers:H}:{}}}function G0(){return q5(a(),w0())}function O8(){let $=a(),Z=w0(),J=q5($,Z).budget?.maxCostUSD,z=Z.budget?.maxCostUSD!=null?"project":$.budget?.maxCostUSD!=null?"global":null;return{maxCostUSD:J,source:z}}function A$($){if($==="ask"||$==="accept-edits"||$==="allow-all")return $;return}function S0($){if(typeof $!=="string")return;return Rq[$.trim().toLowerCase()]}function h0($){if($===!0)return"on";if($===!1)return"off";if(typeof $!=="string")return;return kq[$.trim().toLowerCase()]}function f4($){if($==="allow-all")return"allow all";if($==="accept-edits")return"accept edits";return"ask"}function t2(){let $=a(),Z=w0(),J=A$(Z.permission)??A$($.permission)??A8,z=A$(Z.permission)!=null?"project":A$($.permission)!=null?"global":null;return{permission:J,source:z}}function J2($,Z){if(Z==="project"){let J=w0();H$({...J,permission:$});return}R0({...a(),permission:$})}function _4($,Z){if(Z==="project"){let G=w0(),Q=D1(G.sandbox)??{};H$({...G,sandbox:{...Q,...$}});return}let J=a(),z=D1(J.sandbox)??{};R0({...J,sandbox:{...z,...$}})}function a2(){let $=t0(),Z=J5(),J=D1(w0().sandbox),z=D1(a().sandbox),G=Boolean(J?.mode||J?.network||J?.extraWriteRoots?.length||J?.extraReadRoots?.length),Q=Boolean(z?.mode||z?.network||z?.extraWriteRoots?.length||z?.extraReadRoots?.length),Y=Z??(G?"project":Q?"global":null);return{mode:$.mode,network:$.network,extraWriteRoots:$.extraWriteRoots,extraReadRoots:$.extraReadRoots,source:Y,label:i2($)}}function U5($,Z){if(Z==="project"){let z=w0();H$({...z,budget:{...z.budget,maxCostUSD:$}});return}let J=a();R0({...J,budget:{...J.budget,maxCostUSD:$}})}function s($){if(!$.providers||$.providers.length===0)return;if($.activeProvider){let Z=$.providers.find((J)=>J.name===$.activeProvider);if(Z)return Z}return $.providers[0]}function O1($){let Z=$.replace(/\/$/,"");return Z.endsWith("/v1")?Z:`${Z}/v1`}function R0($){let Z=P0();Iz(Z,{recursive:!0}),T0(V4.join(Z,H5),JSON.stringify(Tq($),null,2)),B4=null}function G1(){let $=a(),Z=s($);return!!(Z?.baseURL&&Z?.apiKey)}async function wz($,Z){let J=new URL($);J.searchParams.set("_t",Date.now().toString());let z=await fetch(J.toString(),{headers:{Authorization:`Bearer ${Z}`,"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 G=await z.json();return{models:yq(G),ok:!0,status:z.status}}function yq($){return(Array.isArray($)?$:$!==null&&typeof $==="object"&&("data"in $)&&Array.isArray($.data)?$.data:[]).map((J)=>J!==null&&typeof J==="object"&&("id"in J)&&typeof J.id==="string"?J.id:null).filter((J)=>J!=null).sort()}function Sz(){return V4.join(P0(),Sq)}function M5($){return $.replace(/\/$/,"")}function Ez(){let $=Sz();if(!Tz($))return{};try{let Z=JSON.parse(W5($,"utf-8"));if(!Z||typeof Z!=="object"||Array.isArray(Z))return{};return Object.fromEntries(Object.entries(Z).filter((J)=>Array.isArray(J[1])&&J[1].every((z)=>typeof z==="string")))}catch{return{}}}function Eq($){return Ez()[M5($)]??[]}function vq($,Z){let J=Ez();J[M5($)]=Z,Iz(P0(),{recursive:!0}),T0(Sz(),JSON.stringify(J))}async function L4($,Z){if($===W$.baseURL&&Z===W$.apiKey)return{models:[e4],ok:!0};try{let J=M5($),z=await wz(`${J}/models`,Z);if(z.models.length===0&&!J.endsWith("/v1"))z=await wz(`${J}/v1/models`,Z);if(z.ok&&z.models.length>0)return vq(J,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 j4($,Z){let J=await L4($,Z);if(J.models.length>0)return J.models;let z=Eq($);if(z.length>0){let G=J.status==null&&!J.ok?" — network unavailable":"";console.log(`\x1B[90m (using cached model list${G})\x1B[0m`)}return z}var A8="accept-edits",e4="openrouter/free",W$,Dq="MIN_AGENT_NO_BUILTIN_PROVIDER",Oq,H5="config.json",Cq="rules.md",B4=null,P5,Rq,kq,Sq="models-cache.json";var l=C(()=>{L$();u0();W$={name:"openrouter",type:"openai-compatible",baseURL:"https://openrouter.ai/api/v1",apiKey:"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",defaultModel:e4},Oq=V4.join(Aq.homedir(),".min-agent");P5=new Map;Rq={off:"off",none:"off",low:"low",minimal:"low",medium:"medium",high:"high",max:"max",xhigh:"max","extra-high":"max",extra_high:"max",extrahigh:"max"};kq={on:"on",true:"on",enable:"on",enabled:"on",off:"off",false:"off",disable:"off",disabled:"off"}});function gq($,Z){let J=[],z=new Set;for(let G of Z){let Q=$[G];if(typeof Q!=="string")continue;let Y=Q.trim();if(!Y||z.has(Y))continue;z.add(Y),J.push(Y)}return J}function xz($){if($==null)return null;if(typeof $==="string"){let G=$.trim();return G.length>0?G:null}if(typeof $==="number"||typeof $==="boolean")return String($);if(typeof $!=="object"||Array.isArray($))return null;let Z=$,J=gq(Z,xq);if(J.length>0)return J.join(" — ");let z=Z.key;return typeof z==="string"&&z.trim()?z.trim():null}function p1($){if(typeof $==="string")return $;return xz($)??""}function o1($){if($==null)return[];let Z=Array.isArray($)?$:[$],J=[],z=new Set;for(let G of Z){let Q=xz(G);if(!Q||z.has(Q))continue;z.add(Q),J.push(Q)}return J}function s2($){let Z=$.trim().toLowerCase();return Z==="其他"||Z==="其它"||Z==="other"}function d1($){if($.length===0)return[];let Z=$.filter((z)=>!s2(z));if(Z.length===0)return[vz];let J=$.find((z)=>s2(z));return[...Z,J??vz]}function gz($){let{multiple:Z,choices:J,index:z,checked:G,otherText:Q}=$;if(J.length===0){let W=Q.trim();return W?[W]:null}let Y=J.findIndex((W)=>s2(W)),K=Q.trim();if(!Z){if(z<0||z>=J.length)return null;if(z===Y)return K?[K]:null;return[J[z]]}let X=[],P=[...G].sort((W,H)=>W-H);for(let W of P){if(W<0||W>=J.length)continue;if(W===Y){if(!K)return null;X.push(K);continue}X.push(J[W])}return X.length>0?X:null}function uz($){let Z=$.trim();if(Z.startsWith("["))try{let J=JSON.parse(Z);if(Array.isArray(J)&&J.length>0&&J.every((z)=>typeof z==="string")){let z=J.map((G)=>G.trim()).filter(Boolean);if(z.length>0)return z}}catch{}return Z?[Z]:[]}function hz($){if($.length===0)return"User cancelled the question";if($.length===1)return`User chose: ${$[0]}`;return`User chose: ${$.join("; ")}`}var xq,vz="其他";var e2=C(()=>{xq=["label","description","title","text","value","content","prompt"]});var S8={};M0(S8,{setTuiQuestion:()=>k8,setTuiConfirm:()=>R8,setPermissionOverride:()=>T8,setExecPermissiveDefault:()=>mq,setConfirmReadline:()=>nq,setAutoApprove:()=>J6,runWithConfirmContext:()=>f5,isExecPermissive:()=>B5,isEditAutoApprove:()=>D4,isDestructiveCommand:()=>y8,isDangerousCommand:()=>L5,isAutoApprove:()=>A4,getPermissionOverride:()=>z6,getPermissionMode:()=>V5,confirm:()=>d$,askQuestion:()=>_5});import{AsyncLocalStorage as uq}from"async_hooks";import hq from"readline";function J6($){nz=$}function mq($){N5=$}function B5(){return N5}function A4(){let $=G6.getStore();if($)return $.autoApprove;if(nz)return!0;if(N5)return!0;return V5()==="allow-all"}function T8($){w8=$}function z6(){return w8}function V5(){if(w8)return w8;let $=G0();return $.permission==="allow-all"||$.permission==="accept-edits"||$.permission==="ask"?$.permission:A8}function D4(){let $=G6.getStore();if($)return $.autoApprove;if(A4())return!0;return V5()==="accept-edits"}function f5($,Z){return G6.run($,Z)}function nq($){Z6=$}function R8($){I8=$}function k8($){F5=$}async function _5($,Z,J=!1){let z=p1($),G=d1(o1(Z)),Q=G.length>0?G:void 0,Y=G6.getStore();if(Y){if(Y.autoApprove)return null;if(Y.onQuestion)return Y.onQuestion(z,Q,J);return null}if(F5)return F5(z,Q,J);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`),Q){for(let K=0;K<Q.length;K++)console.log(`\x1B[90m ${K+1}. ${Q[K]}\x1B[0m`);if(J)console.log("\x1B[90m (可勾选多项;最后一项可自己输入)\x1B[0m")}return new Promise((K)=>{let X=hq.createInterface({input:process.stdin,output:process.stdout});X.question("\x1B[36m → \x1B[0m",(P)=>{if(X.close(),!Z6)process.stdin.pause();K(P.trim()||"(no answer)")})})}async function d$($){let Z=G6.getStore();if(Z){if(Z.autoApprove)return!0;if(Z.onConfirm)return Z.onConfirm($);return!1}if(A4())return!0;if(!I8&&!process.stdin.isTTY)return console.log(`
|
|
17
|
+
\x1B[33m⚠ Rejected (no interactive terminal): ${$}\x1B[0m`),!1;return pq($)}function pq($){return new Promise((Z)=>{$6.push({message:$,resolve:Z}),cz()})}function cz(){if(b8||C8)return;C8=setTimeout(()=>{C8=null,oq()},cq),C8.unref?.()}async function oq(){if(b8)return;b8=!0;try{while($6.length>0){let $=$6;$6=[];let Z=$.map((z)=>z.message),J=await dq(Z);for(let z of $)z.resolve(J)}}finally{if(b8=!1,$6.length>0)cz()}}async function dq($){if(I8)return I8(mz($));return rq(mz($))}function mz($){if($.length===1)return $[0];let Z=$.map((J,z)=>`${z+1}. ${J.replace(/\n/g,`
|
|
18
18
|
`)}`);return`${$.length} 个操作待确认(允许将全部执行,拒绝将全部取消):
|
|
19
|
-
${
|
|
20
|
-
`)}`}function
|
|
19
|
+
${Z.join(`
|
|
20
|
+
`)}`}function rq($){Z6?.pause(),process.stdout.write(`
|
|
21
21
|
\x1B[90m┌─ 即将执行 ─────────────────────────────────\x1B[0m
|
|
22
|
-
`);for(let
|
|
23
|
-
`))process.stdout.write(`\x1B[90m│\x1B[0m ${
|
|
22
|
+
`);for(let Z of $.split(`
|
|
23
|
+
`))process.stdout.write(`\x1B[90m│\x1B[0m ${Z}
|
|
24
24
|
`);return process.stdout.write(`\x1B[90m└────────────────────────────────────────────\x1B[0m
|
|
25
25
|
`),process.stdout.write(`
|
|
26
|
-
`),new Promise((
|
|
27
|
-
|
|
28
|
-
`),
|
|
29
|
-
`&&!
|
|
30
|
-
`){if(!
|
|
31
|
-
→ ${$.hint}`:`✖ ${$.message}`;return`✖ ${$ instanceof Error?$.message:String($)}`}function b9($){if($ instanceof a)return $.exitCode;return 2}var a;var H$=C(()=>{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 rb}from"commander";function j9($,f="global"){if($.project)return"project";if($.global)return"global";return f}function oz($){let f=R$($);if(!f)throw J1(`Invalid --sandbox value: "${$}"`,"use one of: off, workspace, strict");return f}function dz($){let f=r$($);if(!f)throw J1(`Invalid --network value: "${$}"`,"use one of: allow, deny");return f}function lz($){let f=A$($);if(!f)throw J1(`Invalid --permission value: "${$}"`,"use one of: ask, accept-edits, allow-all");return f}function iz($){let f=S0($);if(!f)throw J1(`Invalid --think value: "${$}"`,"use one of: off, low, medium, high, max");return f}function tz($){let f=n0($);if(!f)throw J1(`Invalid --memory value: "${$}"`,"use one of: on, off");return f}function K6($){return(f)=>{let Z=Number.parseInt(f,10);if(!Number.isFinite(Z)||Z<=0)throw J1(`Invalid ${$} value: "${f}"`,"use a positive integer");return Z}}var vf=C(()=>{g0();l();H$()});import{existsSync as lH,readFileSync as iH}from"fs";import uf from"path";import{fileURLToPath as tH}from"url";function xf(){let $=uf.dirname(tH(import.meta.url)),f=$;for(;;){let Z=uf.join(f,"package.json");if(lH(Z))try{if(JSON.parse(iH(Z,"utf-8")).name===aH)return f}catch{}let z=uf.dirname(f);if(z===f)return uf.resolve($,"..");f=z}}var aH="min-agent";var C9=()=>{};import{readFileSync as sH}from"fs";import eH from"path";import{spawnSync as $U}from"child_process";function JU(){return[sz,...ez].join(" ")}function b4(){try{let $=eH.join(xf(),"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 $J($,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,G=z[J]??0,Q=Number.isFinite(K)?K:0,Y=Number.isFinite(G)?G:0;if(Q!==Y)return Q-Y}return 0}function KU($){if(typeof $!=="string"||!ZU.test($))return null;return $}async function fJ($=fetch){let f;try{f=await $(fU,{signal:AbortSignal.timeout(zU),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 KU(Z.version)}async function ZJ($){let f=$?.currentVersion??b4(),Z=await fJ($?.fetchFn);return{current:f,latest:Z,updateAvailable:Z!==null&&$J(f,Z)<0}}function GU(){let $=$U(sz,[...ez],{stdio:"inherit",shell:process.platform==="win32",env:process.env});if($.error)return{ok:!1,missing:$.error.code==="ENOENT"};return{ok:$.status===0}}async function zJ($={}){let f=$.log??((Q)=>console.log(Q)),Z=$.error??((Q)=>console.error(Q)),z=$.currentVersion?.()??b4(),J=JU();f(`当前版本: ${z}`);let K=$.fetchLatest?await $.fetchLatest():await fJ();if(!K)return Z(`无法检查新版本(网络不可用)。请稍后重试,或手动执行: ${J}`),{status:"check-failed",current:z,latest:null};if($J(z,K)>=0)return f(`已是最新版本 (${K})`),{status:"up-to-date",current:z,latest:K};f(`发现新版本: ${K}`),f(`正在执行 ${J} ...`);let G=($.install??GU)();if(!G.ok){if(G.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 az="min-agent",fU,sz="npm",ez,ZU,zU=1e4;var G6=C(()=>{C9();fU=`https://registry.npmjs.org/${az}/latest`,ez=["install","-g",az],ZU=/^\d+\.\d+\.\d+/});import{readFileSync as QU,mkdirSync as YU,existsSync as PU}from"fs";import PJ from"path";function UU(){let $=process.env.MIN_AGENT_MODELS_API_URL?.trim();if(!$)return XU;return $.replace(/\/$/,"")}function XJ(){return PJ.join(P0(),"model-catalog-cache.json")}function WJ(){let $=XJ();if(!PU($))return{};try{return JSON.parse(QU($,"utf-8"))}catch{return{}}}function MU($){let f=XJ();YU(PJ.dirname(f),{recursive:!0}),y0(f,JSON.stringify($))}function Z2($){let f=y9.get($);if(f&&f.version===T9&&Date.now()-f.timestamp<=JJ)return f;let Z=WJ()[$];if(!Z||Z.version!==T9||Date.now()-Z.timestamp>JJ)return null;return y9.set($,Z),Z}function qU($,f){y9.set($,f);let Z=WJ();Z[$]=f,MU(Z)}function o1($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function HJ($){if(!Array.isArray($))return{toggle:!1,efforts:[]};let f=!1,Z=new Set;for(let z of $){if(!o1(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 FU($,f){let Z=f.toLowerCase(),z=$.find((K)=>K.id.toLowerCase()===Z);if(z)return z;let J=$.find((K)=>{let G=K.id.toLowerCase();return G.endsWith(`/${Z}`)||Z.endsWith(`/${G}`)});if(J)return J;return $.find((K)=>K.name?.toLowerCase()===Z)}function NU($,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 VU($){return $.efforts.some((f)=>{let Z=S0(f);return Boolean(Z&&Z!=="off")})}function LU($){let f=$.map((X)=>HJ(X.reasoningOptions)).filter((X)=>X.toggle||X.efforts.length>0);if(f.length===0)return{toggle:!1,efforts:[]};let Z=f.filter(VU),z=f.length/2,J=Z.length===0?Number.POSITIVE_INFINITY:Z.length/2,K=0,G=0,Q=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")G++;let U=S0(H);if(!U||U==="off"||W.has(U))continue;W.add(U),Q.set(U,(Q.get(U)??0)+1)}}let Y=K>=z,P=[];if(Y)P.push("none");for(let X of BU)if((Q.get(X)??0)>=J)P.push(X);if(P.includes("max")&&G>0)P.push("xhigh");return{toggle:Y,efforts:P}}function GJ($){let f=$?.context;if(typeof f==="number"&&Number.isFinite(f)&&f>=4096)return Math.floor(f);return}function _U($,f,Z){let z=$.offerings??[],J=NU(z,Z),K=J?HJ(J.reasoningOptions):LU(z),G=GJ(J?.limit)??GJ($.limit);return{version:T9,modelId:f,lonaeId:$.id,...G!=null?{contextWindow:G}:{},reasoning:K,timestamp:Date.now()}}async function w9($){try{let f=await fetch($,{signal:AbortSignal.timeout(HU)});if(!f.ok)return null;return await f.json()}catch{return null}}function QJ($){let f=o1($)?$:null,Z=f&&o1(f.data)?f.data:f;if(!Z||typeof Z.id!=="string")return null;let z=o1(Z.limit)?{context:typeof Z.limit.context==="number"?Z.limit.context:void 0}:void 0,J=Array.isArray(Z.offerings)?Z.offerings.filter(o1).map((K)=>({providerId:typeof K.providerId==="string"?K.providerId:void 0,limit:o1(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 DU($){let f=o1($)?$:null;return(f&&Array.isArray(f.data)?f.data:Array.isArray($)?$:[]).flatMap((z)=>{if(!o1(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 YJ($){return $.split("/").map((f)=>encodeURIComponent(f)).join("/")}async function AU($){let f=UU();if($.includes("/")){let J=QJ(await w9(`${f}/api/v1/models/${YJ($)}`));if(J)return J}let Z=DU(await w9(`${f}/api/v1/models?q=${encodeURIComponent($)}&page_size=20`)),z=FU(Z,$);if(!z)return null;return QJ(await w9(`${f}/api/v1/models/${YJ(z.id)}`))}async function gf($,f){let Z=Z2($);if(Z)return Z;let z=KJ.get($);if(z!==void 0&&Date.now()-z<=WU)return null;let J=O9.get($);if(J)return J;let K=AU($).then((G)=>{if(!G)return KJ.set($,Date.now()),null;let Q=_U(G,$,f);return qU($,Q),Q});O9.set($,K);try{return await K}finally{O9.delete($)}}var XU="https://models.lonae.com",JJ=604800000,T9=3,WU=3600000,HU=1e4,y9,O9,KJ,BU;var I9=C(()=>{_$();l();y9=new Map,O9=new Map,KJ=new Map;BU=["low","medium","high","max"]});import{readFileSync as bU,mkdirSync as jU,existsSync as CU}from"fs";import qJ from"path";function J2($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function hf($){return $.replace(/\/$/,"").replace(/\/v1$/i,"")}function NJ($,f){let Z="";try{Z=new URL($).hostname.toLowerCase()}catch{Z=hf($).toLowerCase()}let z=f.trim().toLowerCase();return Z?`${Z}::${z}`:z}function z2($){let f=typeof $==="string"&&$.trim()!==""?Number($):$;if(typeof f!=="number"||!Number.isFinite(f)||f<FJ)return;return Math.floor(f)}function TU($){let f=[];for(let[Z,z]of Object.entries($))if(Z==="context_length"||Z.endsWith(".context_length")){let J=z2(z);if(J!=null)f.push(J)}if(f.length===0)return;return Math.max(...f)}function yU($){if(typeof $==="number")return z2($);if(J2($))return z2($.num_ctx);if(typeof $!=="string")return;let f=$.match(/(?:^|\n)\s*num_ctx\s+(\d+)/);if(f?.[1])return z2(Number(f[1]));return z2($)}function IU($){if(!Array.isArray($))return null;return $.some((f)=>String(f).toLowerCase()==="thinking")}function kU($,f){if($!=null)return $;if(f!=null)return Math.min(f,S9);return}function BJ($,f){let Z=J2($.options)?$.options:{};return{...$,options:{...Z,num_ctx:f}}}function VJ($,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 LJ($,f){let Z=s(K0());if(typeof Z?.contextWindow==="number"&&Number.isFinite(Z.contextWindow)&&Z.contextWindow>=FJ)return Math.floor(Z.contextWindow);return d1($,f??Z?.baseURL)?.contextWindow??nf}function RU($,f){let Z=J2($)?$:{},z=J2(Z.model_info)?Z.model_info:{},J=kU(yU(Z.parameters),TU(z));return{version:Q6,modelId:f,...J!=null?{contextWindow:J}:{},thinking:IU(Z.capabilities),timestamp:Date.now()}}function _J($){if($.thinking===!1)return["off"];return["off","low","medium","high","max"]}function DJ(){return qJ.join(P0(),"ollama-model-cache.json")}function AJ(){let $=DJ();if(!CU($))return{};try{let f=JSON.parse(bU($,"utf-8"));if(!J2(f))return{};let Z={};for(let[z,J]of Object.entries(f)){if(!J2(J)||J.version!==Q6)continue;if(typeof J.modelId!=="string")continue;let K=J.thinking===!0||J.thinking===!1?J.thinking:null,G=z2(J.contextWindow),Q=typeof J.timestamp==="number"?J.timestamp:0;Z[z]={version:Q6,modelId:J.modelId,...G!=null?{contextWindow:G}:{},thinking:K,timestamp:Q}}return Z}catch{return{}}}function SU($){let f=DJ();jU(qJ.dirname(f),{recursive:!0}),y0(f,JSON.stringify($))}function d1($,f){let Z=NJ(f??"",$),z=R9.get(Z);if(z&&z.version===Q6&&Date.now()-z.timestamp<=UJ)return z;let J=AJ()[Z];if(!J||J.version!==Q6||Date.now()-J.timestamp>UJ)return null;return R9.set(Z,J),J}function EU($,f){R9.set($,f);let Z=AJ();Z[$]=f,SU(Z)}async function vU($,f){try{let Z=await fetch(`${hf($)}/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 Y6($,f){let Z=f??"",z=NJ(Z,$),J=d1($,Z);if(J)return J;let K=MJ.get(z);if(K!==void 0&&Date.now()-K<=OU)return null;let G=k9.get(z);if(G)return G;let Q=vU(Z,$).then((Y)=>{if(!Y)return MJ.set(z,Date.now()),null;let P=RU(Y,$);return EU(z,P),P});k9.set(z,Q);try{return await Q}finally{k9.delete(z)}}var Q6=2,UJ=604800000,OU=3600000,wU=8000,FJ=512,nf=2048,S9=32768,R9,k9,MJ;var cf=C(()=>{l();_$();R9=new Map,k9=new Map,MJ=new Map});function Z$($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function uU($){return typeof $==="string"?$:$ instanceof URL?$.href:$.url}function xU($){try{return/\/chat\/completions\/?$/i.test(new URL($).pathname)}catch{return/\/chat\/completions\/?$/i.test($)}}function gU($){let f=$.replace(/\/v1\/chat\/completions\/?$/i,"").replace(/\/chat\/completions\/?$/i,"");return`${hf(f)}/api/chat`}async function OJ($){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:G,value:Q}=await f.read();if(G)break;if(Q)Z.push(Q)}let z=Z.reduce((G,Q)=>G+Q.length,0),J=new Uint8Array(z),K=0;for(let G of Z)J.set(G,K),K+=G.length;return new TextDecoder().decode(J)}return null}function nU($){return $.match(/^data:[^;]+;base64,(.+)$/s)?.[1]??null}function hU($){if(typeof $==="string")return{text:$,images:[]};if(!Array.isArray($))return{text:$==null?"":JSON.stringify($),images:[]};let f=[],Z=[];for(let z of $){if(!Z$(z))continue;if(z.type==="text"&&typeof z.text==="string")f.push(z.text);else if(z.type==="image_url"){let J=Z$(z.image_url)?z.image_url.url:void 0;if(typeof J==="string"){let K=nU(J);if(K)Z.push(K)}}else if(typeof z.text==="string")f.push(z.text)}return{text:f.join(`
|
|
32
|
-
`),images:Z}}function cU($){if(Z$($))return $;if(typeof $!=="string"||!$.trim())return{};try{let f=JSON.parse($);return Z$(f)?f:{value:f}}catch{return{value:$}}}function mU($){if(typeof $==="string")return $;try{return JSON.stringify($??{})}catch{return"{}"}}function pU($){if(!Array.isArray($)||$.length===0)return;return $.map((f)=>{let Z=Z$(f)?f:{},z=Z$(Z.function)?Z.function:Z;return{function:{name:typeof z.name==="string"?z.name:"",arguments:cU(z.arguments)}}})}function rU($){if(!Array.isArray($))return[];return $.map((f)=>{let Z=Z$(f)?f:{},{text:z,images:J}=hU(Z.content),K={role:typeof Z.role==="string"?Z.role:"user",content:z};if(J.length>0)K.images=J;let G=pU(Z.tool_calls);if(G)K.tool_calls=G;return K})}function oU($){let f=Z$($.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 dU($,f){let Z={model:$.model,messages:rU($.messages),stream:$.stream!==!1,options:oU($)};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 BJ(Z,f.numCtx)}function wJ($,f){if(Array.isArray(f)&&f.length>0)return"tool_calls";if($==="length"||$==="max_tokens")return"length";return"stop"}function TJ($){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 yJ($){if(!Array.isArray($)||$.length===0)return;return $.map((f,Z)=>{let z=Z$(f)?f:{},J=Z$(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:mU(J.arguments)}}})}function bJ($,f){let Z=Z$($.message)?$.message:{},z=typeof Z.content==="string"?Z.content:"",J=typeof Z.thinking==="string"?Z.thinking:"",K=yJ(Z.tool_calls),G=$.done===!0,Q={};if(!f.sentRole)Q.role="assistant",f.sentRole=!0;if(J)Q.reasoning=J;if(z)Q.content=z;if(K)Q.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:Q,finish_reason:G?wJ($.done_reason,Z.tool_calls):null}]},P=TJ($);if(P)Y.usage=P;return Y}function jJ($){let f=Z$($.message)?$.message:{},Z=typeof f.content==="string"?f.content:"",z=typeof f.thinking==="string"?f.thinking:"",J=yJ(f.tool_calls),K={role:"assistant",content:Z};if(z)K.reasoning=z;if(J)K.tool_calls=J;let G={id:"chatcmpl-ollama",object:"chat.completion",created:Math.floor(Date.now()/1000),model:typeof $.model==="string"?$.model:"",choices:[{index:0,message:K,finish_reason:wJ($.done_reason,f.tool_calls)}]},Q=TJ($);if(Q)G.usage=Q;return G}function CJ($){return`data: ${JSON.stringify($)}
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
`)
|
|
38
|
-
`)){let U=H.trim();if(!U)continue;try{let M=JSON.parse(U);if(Z$(M))W.push(CJ(bJ(M,J)))}catch{}}if(W.length>0){G.enqueue(Z.encode(W.join("")));return}}},cancel(G){return z.cancel(G)}})}function iU($){let f=new Headers($);return f.set("content-type","application/json"),f}function tU($){let f=new Headers($);return f.set("content-type","text/event-stream"),f.delete("content-length"),f}async function IJ($,f,Z,z,J){let K=uU(f);if(!xU(K))return $(f,{...Z,body:JSON.stringify(z)});let G=typeof z.model==="string"?z.model:"",Q=d1(G,K),Y=dU(z,{numCtx:LJ(G,K),think:VJ(J,Q?.thinking??null)}),P=await $(gU(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=Z$(W)?jJ(W):jJ({});return new Response(JSON.stringify(H),{status:P.status,statusText:P.statusText,headers:iU(P.headers)})}catch{return P}if(!P.body)return P;return new Response(lU(P.body),{status:P.status,statusText:P.statusText,headers:tU(P.headers)})}var kJ=C(()=>{cf()});import{AsyncLocalStorage as aU}from"async_hooks";import{readFileSync as sU,mkdirSync as eU,existsSync as $M}from"fs";import EJ from"path";function vJ($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function ZM($){return $==="enabled-disabled"||$==="adaptive-disabled"||$==="omit"}function zM($){return $==="reasoning_effort"||$==="omit"}function JM($){if(!vJ($))return!1;return $.version===K2&&ZM($.thinkingType)&&zM($.effort)&&typeof $.timestamp==="number"&&Number.isFinite($.timestamp)}function uJ(){return EJ.join(P0(),"thinking-wire-cache.json")}function xJ(){let $=uJ();if(!$M($))return{};try{let f=JSON.parse(sU($,"utf-8"));if(!vJ(f))return{};let Z={};for(let[z,J]of Object.entries(f))if(JM(J))Z[z]=J;return Z}catch{return{}}}function KM($){let f=uJ();eU(EJ.dirname(f),{recursive:!0}),y0(f,JSON.stringify($))}function RJ($,f){if($.version!==K2)return null;if(f-$.timestamp>fM)return null;return $}function gJ($,f){let Z=$.trim().toLowerCase(),z=f.trim().toLowerCase();if(!Z)return z;if(!z)return Z;return`${Z}::${z}`}function GM($,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:E9.thinkingType,effort:E9.effort}}function QM($,f){let Z=mf.get($);if(Z){let K=RJ(Z,f);if(K)return K;mf.delete($)}let z=xJ()[$];if(!z)return null;let J=RJ(z,f);if(!J)return null;return mf.set($,J),J}function YM($,f,Z,z=Date.now()){let J=QM(gJ($,f),z);if(J)return J;return{version:K2,...GM(f,$,Z),timestamp:z}}function PM($,f,Z,z=Date.now()){let J={version:K2,thinkingType:Z.thinkingType,effort:Z.effort,timestamp:Z.timestamp??z},K=gJ($,f);mf.set(K,J);let G=xJ();return G[K]=J,KM(G),J}function pf($,f,Z=E9){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 XM($){return new Set($.split(",").map((f)=>f.trim().replace(/^['"]|['"]$/g,"").toLowerCase()).filter(Boolean))}function WM($){let f=$.match(/thinking\.type[\s\S]*?allowed:\s*([^)]+)/i);if(f?.[1]){let Z=XM(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 HM($){try{let f=typeof $==="string"?$:$ instanceof URL?$.href:$.url;return new URL(f).hostname}catch{return""}}function SJ($,f){return new Response(f,{status:400,statusText:$.statusText,headers:$.headers})}function UM($,f){return $.thinkingType===f.thinkingType&&$.effort===f.effort}async function nJ($,f,Z,z){if(!Z?.body)return $(f,Z);let J=await OJ(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 G=P6.getStore(),Q=z?.providerType??s(K0())?.type,Y=K;if(Q==="ollama")return IJ($,f,Z,Y,G);if(!G)return $(f,Z);let P=HM(f),X=typeof Y.model==="string"?Y.model:"",W=YM(P,X,Q),H=await $(f,{...Z,body:JSON.stringify(pf(Y,G,W))});if(H.status!==400)return H;let U=await H.text(),M=WM(U);if(!M)return SJ(H,U);let N={version:K2,thinkingType:M.thinkingType??W.thinkingType,effort:M.effort??W.effort,timestamp:Date.now()};if(UM(W,N))return SJ(H,U);return PM(P,X,N),$(f,{...Z,body:JSON.stringify(pf(Y,G,N))})}var P6,K2=1,fM=604800000,E9,mf;var v9=C(()=>{l();kJ();_$();P6=new aU,E9={version:K2,thinkingType:"enabled-disabled",effort:"reasoning_effort"},mf=new Map});var h9={};M0(h9,{toWireEffort:()=>rJ,thinkingSourceLabel:()=>g9,thinkingRequestStore:()=>P6,thinkingPayload:()=>Y2,thinkingEffortLabel:()=>b$,thinkingChoicesFromReasoning:()=>mJ,thinkingChoicesForModel:()=>l1,thinkingChoiceIndex:()=>rf,setThinkingOverride:()=>G2,setThinkingEffort:()=>i1,resolveThinkingRequest:()=>n9,resolveThinkingEffort:()=>K1,refreshThinkingChoices:()=>Q2,parseThinkingEffort:()=>S0,getThinkingSnapshot:()=>pJ,getThinkingOverride:()=>cJ,clampThinkingEffort:()=>x9,applyThinkingToChatBody:()=>pf,THINKING_EFFORTS:()=>d$,DEFAULT_THINKING_EFFORT:()=>u9});function G2($){hJ=$}function cJ(){return hJ}function b$($){return $}function rf($,f=d$){let Z=f.length>0?f:d$,z=x9($,Z),J=Z.indexOf(z);return J>=0?J:0}function mJ($){let f=new Set;if($.toggle||$.efforts.includes("none"))f.add("off");for(let z of $.efforts){let J=S0(z);if(J)f.add(J)}if(d$.filter((z)=>z!=="off"&&f.has(z)).length===0)return[...d$];return d$.filter((z)=>f.has(z))}function l1($){let f=s(K0());if(f?.type==="ollama"){if(!$)return[...d$];let z=d1($,f.baseURL);if(!z)return[...d$];return _J(z)}if(!$)return[...d$];let Z=Z2($);if(!Z)return[...d$];return mJ(Z.reasoning)}async function Q2($,f){let Z=s(K0()),z=f?.type??Z?.type,J=f?.baseURL??Z?.baseURL;if($)if(z==="ollama")await Y6($,J);else await gf($,J);return l1($)}function x9($,f=d$){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 u9}function g9($){if($==="cli")return"本次启动参数";if($==="project")return"项目";if($==="global")return"全局";return"默认"}function K1($,f){let Z,z;if($)Z=$,z="cli";else{let K=cJ();if(K)Z=K,z="cli";else{let G=pJ();Z=G.thinking??u9,z=G.source}}let J=f??s(K0())?.defaultModel;return{thinking:x9(Z,l1(J)),source:z}}function pJ(){let $=S0(w0().thinking);if($!==void 0)return{thinking:$,source:"project"};let f=S0(t().thinking);if(f!==void 0)return{thinking:f,source:"global"};return{thinking:void 0,source:null}}function MM(){let $=w0();if($.thinking===void 0)return;let{thinking:f,...Z}=$;W$(Z)}function i1($,f){if(f==="project"){W$({...w0(),thinking:$});return}I0({...t(),thinking:$}),MM()}function Y2(){let{thinking:$,source:f}=K1();return{thinking:$,source:f,label:b$($)}}function rJ($,f,Z){if($==="off")return"none";if($!=="max")return $;let J=(Z?Z2(Z):void 0)?.reasoning.efforts??[];if(J.includes("max"))return"max";if(J.includes("xhigh")||f==="openai")return"xhigh";return"max"}function n9($){let{thinking:f}=K1($?.runOverride,$?.modelId),Z=$?.providerType??s(K0())?.type;return{reasoningEffort:rJ(f,Z,$?.modelId),thinkingEnabled:f!=="off"}}var d$,u9="medium",hJ;var G1=C(()=>{l();I9();cf();v9();d$=["off","low","medium","high","max"]});var P2={};M0(P2,{takeScopeFlags:()=>l$,scopeLabel:()=>U$,readScope:()=>j$});function j$($){if($===void 0||$===null||$==="")return{ok:!0,scope:void 0};if($==="global"||$==="project")return{ok:!0,scope:$};return{ok:!1}}function l$($){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 U$($){return $==="project"?"project":"global"}var t9={};M0(t9,{takeScopeFlags:()=>l$,setMemoryOverride:()=>of,setMemoryMode:()=>X2,searchMemories:()=>O4,resolveMemoryMode:()=>C4,readMemoryScope:()=>j$,parseMemoryMode:()=>n0,memorySourceLabel:()=>X6,memoryPayload:()=>a1,memoryModeLabel:()=>t1,loadMemories:()=>C$,isMemoryEnabled:()=>Q1,getMemoryTools:()=>i9,getMemorySystemPrompt:()=>l9,getMemorySnapshot:()=>eJ,getMemoryOverride:()=>sJ,formatMemoryLine:()=>d9,deleteMemory:()=>H2,defaultMemoryScope:()=>W6,addMemory:()=>W2,DEFAULT_MEMORY_MODE:()=>tJ});import{readFileSync as qM,mkdirSync as FM,existsSync as o9,renameSync as NM,statSync as iJ}from"fs";import r9 from"path";import{tool as c9,jsonSchema as m9}from"ai";function of($){aJ=$}function sJ(){return aJ}function t1($){return $}function X6($){if($==="cli")return"this run";if($==="project")return"project";if($==="global")return"global";return"default"}function eJ(){let $=n0(w0().memory);if($!==void 0)return{memory:$,source:"project"};let f=n0(t().memory);if(f!==void 0)return{memory:f,source:"global"};return{memory:void 0,source:null}}function C4($){if($)return{memory:$,source:"cli"};let f=sJ();if(f)return{memory:f,source:"cli"};let Z=eJ();return{memory:Z.memory??tJ,source:Z.source}}function Q1($){return C4($).memory==="on"}function BM(){let $=w0();if($.memory===void 0)return;let{memory:f,...Z}=$;W$(Z)}function X2($,f){if(f==="project"){W$({...w0(),memory:$});return}I0({...t(),memory:$}),BM()}function a1(){let{memory:$,source:f}=C4();return{memory:$,source:f,label:t1($)}}function W6(){return o9(n1())?"project":"global"}function oJ($){return $==="global"||$==="project"?$:W6()}function $K($){if($==="project")return r9.join(n1(),"memory.json");return r9.join(P0(),"memory.json")}function VM($){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 dJ($){try{NM($,`${$}.corrupt-${Date.now()}`)}catch{}}function LM($,f){try{let Z=iJ($);j4.set($,{mtimeMs:Z.mtimeMs,size:Z.size,memories:f})}catch{j4.delete($)}}function C$($="global"){let f=$K($),Z;try{Z=iJ(f)}catch{return j4.delete(f),[]}let z=j4.get(f);if(z&&z.mtimeMs===Z.mtimeMs&&z.size===Z.size)return z.memories;let J;try{J=JSON.parse(qM(f,"utf-8"))}catch{return dJ(f),j4.delete(f),[]}if(!Array.isArray(J))return dJ(f),j4.delete(f),[];let K=J.flatMap((G)=>{let Q=VM(G);return Q?[Q]:[]});return j4.set(f,{mtimeMs:Z.mtimeMs,size:Z.size,memories:K}),K}function fK($,f){let Z=$K(f);if(f==="project"&&!o9(n1())){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}FM(r9.dirname(Z),{recursive:!0}),y0(Z,JSON.stringify($,null,2)),LM(Z,$)}function W2($,f=[],Z="global"){let z=C$(Z),J={content:$,tags:f,created:new Date().toISOString()};return z.push(J),fK(z,Z),J}function H2($,f="global"){let Z=C$(f);if($<0||$>=Z.length)return!1;return Z.splice($,1),fK(Z,f),!0}function O4($,f="global"){let Z=C$(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 d9($,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 lJ($,f){if($.length===0)return"";let Z=Math.max(0,$.length-p9),z=$.slice(Z).map((K,G)=>({m:K,num:Z+G+1})).reverse().map(({m:K,num:G})=>{let Q=K.tags.length>0?` [${K.tags.join(", ")}]`:"";return` ${G}. ${K.content}${Q}`}),J=$.length>p9?`
|
|
39
|
-
(${$.length-p9} older memories not shown — use memory_search to find them.)`:"";return[f,...z,J].filter(Boolean).join(`
|
|
40
|
-
|
|
41
|
-
`)}function
|
|
42
|
-
`)}
|
|
43
|
-
`)});function
|
|
44
|
-
`)});function AM($){return $==="cli"?"this run":$==="project"?"project":$==="global"?"global":"default"}function
|
|
45
|
-
`)});function $
|
|
46
|
-
`)});
|
|
47
|
-
`)),!Z)process.exitCode=1}var zK=C(()=>{a9();s9();e9();$5()});function f8($,f,Z){let z=$==="openai"?"openai":$==="ollama"?"ollama":jM(f)??"provider";return CM(z,Z)}function Z8($){let f=$.trim();if(!f||f.includes("/")||f.includes(":"))return"名称不能为空,且不能包含 / 或 :。";return null}function f5($){if($.length<4)return"****";return`…${$.slice(-4)}`}function JK($,f){let Z=$.trim().toLowerCase();if(!Z)return[...f];return f.filter((z)=>z.toLowerCase().includes(Z))}function z8($,f,Z){let z=Z8(f.name);if(z)return{error:z};let J=f.name.trim(),K=[...$.providers??[]],G=K.findIndex((Y)=>Y.name===J);if(G>=0&&!Z.overwrite)return{error:`已存在同名服务商 "${J}"。`};let Q=GK(f,J);if(G>=0)K[G]=Q;else K.push(Q);return{...$,providers:K,activeProvider:J}}function U2($,f){if(!($.providers??[]).find((z)=>z.name===f))return{error:`找不到服务商 "${f}"。`};return{...$,activeProvider:f}}function KK($,f,Z){let z=Z8(Z.name);if(z)return{error:z};let J=Z.name.trim(),K=[...$.providers??[]],G=K.findIndex((Y)=>Y.name===f);if(G<0)return{error:`找不到服务商 "${f}"。`};if(J!==f&&K.some((Y)=>Y.name===J))return{error:`已存在同名服务商 "${J}"。`};K[G]=GK(Z,J);let Q=$.activeProvider===f?J:$.activeProvider;return{...$,providers:K,activeProvider:Q}}function J8($,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,...G}=$;return{...G,providers:[]}}let J=$.activeProvider===f?z[0]?.name:$.activeProvider;return{...$,providers:z,activeProvider:J}}function GK($,f){return{name:f,type:$.type,baseURL:$.baseURL,apiKey:$.apiKey,defaultModel:$.defaultModel,...$.contextWindow!=null?{contextWindow:$.contextWindow}:{}}}function jM($){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 CM($,f){if(!f.includes($))return $;let Z=2;while(f.includes(`${$}-${Z}`))Z+=1;return`${$}-${Z}`}function QK($){if($==="openai-compatible"||$==="openai"||$==="ollama")return $;throw J1(`Invalid --type value: "${$}"`,"use one of: openai-compatible, openai, ollama")}function YK($){return[$.type,$.switch,$.remove].filter(Boolean).length}var K8=C(()=>{H$()});function PK($,f){return!$&&f}async function Z5($,f,Z){if(YK($)>1)throw new a("一次只能执行一种操作。");if($2(bf(f.load()))&&($.type||$.switch||$.remove))throw new a("内置 OpenRouter 服务商已锁定,provider 配置不允许修改。",{hint:"设置 MIN_AGENT_NO_BUILTIN_PROVIDER=1 关闭预设后再配置"});if($.remove){await IM($.remove,$.yes===!0,f);return}if($.switch){z5(U2(f.load(),$.switch),f);return}if($.type){await kM($,f);return}if(!f.isTty)throw new a("无法在非交互环境完成配置。",{hint:TM});let z=f.load(),J=Z??(yM(z)?"hub":"first-run");await f.runWizard(J)}function yM($){let f=s($);return Boolean(f?.baseURL&&f?.apiKey)}async function IM($,f,Z){if(!f)throw new a("删除需要确认。",{hint:"加上 --yes"});z5(J8(Z.load(),$),Z)}async function kM($,f){let Z=$.type,z=RM(Z,$.url),J=SM(Z,$.apiKey),K=await EM(Z,z,J,$.defaultModel,f.fetchLive),G=f.load(),Q=(G.providers??[]).map((H)=>H.name).filter((H)=>Boolean(H)),P={name:($.name?.trim()||f8(Z,z,Q)).trim(),type:Z,baseURL:z,apiKey:J,defaultModel:K,...$.contextWindow!=null?{contextWindow:$.contextWindow}:{}},X=$.yes===!0,W=z8(G,P,{overwrite:X});if(XK(W)&&W.error.startsWith("已存在同名服务商")&&!X)throw new a(W.error,{hint:"加上 --yes 以覆盖"});z5(W,f)}function RM($,f){if($==="openai")return OM;if($==="ollama")return A1(f?.trim()||wM);let Z=f?.trim()??"";if(!Z)throw new a("API 地址不能为空。");return Z.replace(/\/$/,"")}function SM($,f){if($==="ollama")return f?.trim()||"ollama";let Z=f?.trim()??"";if(!Z)throw new a("API 密钥不能为空。");return Z}async function EM($,f,Z,z,J){let K=z?.trim()??"";if(K)return K;let G=await J(f,Z);if(G.models[0])return G.models[0];if($==="ollama")return"llama3";if(!G.ok&&G.status==null)throw A9("无法连接到该服务商。");throw new a("默认模型不能为空。")}function z5($,f){if(XK($))throw new a($.error);f.save($),f.log(`已保存到 ${f.configPath()}`)}function XK($){return Object.keys($).length===1&&"error"in $}var OM="https://api.openai.com/v1",wM="http://localhost:11434/v1",TM="使用 --type、--switch 或 --remove。例如: min-agent setup --type ollama";var J5=C(()=>{l();H$();K8();K8()});var D;var Y1=C(()=>{D={inputBorder:"cyan",inputBorderDisabled:"gray",confirmBorder:"blue",pickerBorder:"blue",questionBorder:"blue",accent:"cyan",muted:"gray",tool:"yellow",error:"red",success:"green"}});async function WK($){let f=$?.fetchImpl??fetch,Z=$?.timeoutMs??uM;try{if(!(await f(vM,{signal:AbortSignal.timeout(Z)})).ok)return{found:!1};return{found:!0,baseURL:A1(xM)}}catch{return{found:!1}}}var vM="http://localhost:11434/api/tags",uM=800,xM="http://localhost:11434/v1";var HK=C(()=>{l()});var MK={};M0(MK,{renderSetupWizard:()=>mM});import{useEffect as Y5,useRef as G8,useState as C1}from"react";import{Box as s1,Text as _0,render as gM,useInput as UK}from"ink";import nM from"ink-spinner";import hM from"path";import{jsxDEV as e}from"react/jsx-dev-runtime";async function mM($){return new Promise((f)=>{let Z=gM(e(pM,{mode:$,onDone:(z)=>{Z.unmount(),f(z)}},void 0,!1,void 0,this),{exitOnCtrlC:!1})})}function pM({mode:$,onDone:f}){let[Z,z]=C1(()=>{if($2(t()))return{id:"hub"};return $==="session-gate"?{id:"gate"}:$==="hub"?{id:"hub"}:{id:"type"}}),[J,K]=C1(null),[G,Q]=C1({found:!1}),[Y,P]=C1(""),[X,W]=C1(0),H=()=>W((F)=>F+1),U=c1(),M=$2(t()),N=M?t():U,q=()=>f("aborted"),L=()=>f("saved");return e(s1,{flexDirection:"column",paddingX:1,paddingY:1,children:[e(_0,{bold:!0,color:D.accent,children:"配置服务商"},void 0,!1,void 0,this),Z.id==="gate"&&e(M2,{items:[{label:"开始配置",value:"start"},{label:"退出",value:"exit"}],onSelect:(F)=>{if(F==="exit")f("aborted");else z({id:"type"})},onCancel:()=>f("aborted")},void 0,!1,void 0,this),Z.id==="hub"&&e(rM,{config:N,locked:M,onAdd:()=>{K({fromHub:!0,type:"openai-compatible",baseURL:Q5,apiKey:"",defaultModel:"",name:""}),P(""),z({id:"type"})},onPick:(F)=>{let V=U.providers??[];if(F==="switch"&&V.length<=1){z({id:"message",text:"当前只有一个服务商,无需切换。",back:"hub"});return}z({id:"pick",action:F})},onDone:L},void 0,!1,void 0,this),Z.id==="pick"&&e(oM,{config:N,onCancel:()=>z({id:"hub"}),onSelect:(F)=>{let V=F.name??"";if(Z.action==="switch"){let B=U2(U,V);if(G5(B)){z({id:"message",text:B.error,back:"hub"});return}I0(B),K5(),H(),z({id:"hub"});return}if(Z.action==="delete"){z({id:"delete-confirm",name:V});return}if(Z.action==="test"){(async()=>{let B=await L4(F.baseURL,F.apiKey);if(B.ok&&B.models.length>0){z({id:"message",text:`可访问,${B.models.length} 个模型`,back:"hub"});return}let A=B.status!=null?`HTTP ${B.status}。`:"",j=F.type==="ollama"?"请确认 Ollama 已启动。":"请检查 API 地址和密钥。";z({id:"message",text:Zq(`无法连接到该服务商。${A}${j}`),back:"hub"})})();return}K(eM(F,!0)),P(""),z({id:"type"})}},void 0,!1,void 0,this),Z.id==="delete-confirm"&&e(M2,{title:`确定删除服务商 "${Z.name}"?`,items:[{label:"删除",value:"yes"},{label:"取消",value:"no"}],onSelect:(F)=>{if(F!=="yes"){z({id:"hub"});return}let V=J8(c1(),Z.name);if(G5(V)){z({id:"message",text:V.error,back:"hub"});return}I0(V),K5(),H(),z({id:"hub"})},onCancel:()=>z({id:"hub"})},void 0,!1,void 0,this),Z.id==="message"&&e(aM,{text:Z.text,onClose:()=>{if(Z.back==="exit-saved")L();else z({id:"hub"})}},void 0,!1,void 0,this),Z.id==="type"&&e(dM,{detected:G,onDetected:Q,initial:J?.type,onCancel:()=>{if(J?.fromHub||$==="hub")z({id:"hub"});else q()},onSelect:(F)=>{let V=sM(F,J,G);if(K(V),P(""),F==="openai")z({id:"key"});else z({id:"url"})}},void 0,!1,void 0,this),Z.id==="url"&&J&&e(U6,{label:J.type==="ollama"?"Ollama 地址":"API 地址",value:J.baseURL,error:Y,onChange:(F)=>K({...J,baseURL:F}),onCancel:()=>{P(""),z({id:"type"})},onSubmit:()=>{let F=J.baseURL.trim();if(!F){P("API 地址不能为空。");return}let V=J.type==="ollama"?A1(F):F.replace(/\/$/,"");if(K({...J,baseURL:V}),P(""),J.type==="ollama")z({id:"fetch"});else z({id:"key"})}},void 0,!1,void 0,this),Z.id==="key"&&J&&e(U6,{label:"API 密钥",value:J.apiKey,mask:!0,placeholder:J.existingKey?`已保存 (${f5(J.existingKey)}),回车保留`:void 0,error:Y,onChange:(F)=>K({...J,apiKey:F}),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&&e(lM,{draft:J,onBack:()=>z(J.type==="ollama"?{id:"url"}:{id:"key"}),onList:(F)=>{K({...J,models:F}),P(""),z({id:"models",models:F})},onEmpty:()=>{P(""),z({id:"model-manual"})}},void 0,!1,void 0,this),Z.id==="models"&&J&&e(iM,{models:Z.models,current:J.defaultModel,onCancel:()=>z(J.type==="openai"?{id:"key"}:{id:"url"}),onSelect:(F)=>{K({...J,defaultModel:F}),P(""),z({id:"name"})}},void 0,!1,void 0,this),Z.id==="model-manual"&&J&&e(U6,{label:"无法获取模型列表,请手动输入默认模型",value:J.defaultModel,error:Y,onChange:(F)=>K({...J,defaultModel:F}),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&&e(U6,{label:"上下文窗口(token,回车跳过)",value:J.contextWindow!=null?String(J.contextWindow):"",error:Y,onChange:(F)=>{let V=F.trim();if(!V){K({...J,contextWindow:void 0});return}let B=Number.parseInt(V,10);K({...J,contextWindow:Number.isFinite(B)?B:void 0})},onCancel:()=>z({id:"model-manual"}),onSubmit:(F)=>{let V=F.trim();if(!V){K({...J,contextWindow:void 0}),P(""),z({id:"name"});return}let B=Number.parseInt(V,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&&e(U6,{label:"名称",value:J.name,error:Y,onChange:(F)=>K({...J,name:F}),onCancel:()=>{if(J.models&&J.models.length>0)z({id:"models",models:J.models});else z({id:"model-manual"})},onSubmit:()=>{let F=Z8(J.name);if(F){P(F);return}P(""),z({id:"summary"})}},void 0,!1,void 0,this),Z.id==="summary"&&J&&e(tM,{draft:J,error:Y,onCancel:()=>z({id:"name"}),onConfirm:()=>{let F=$q(J);if(G5(F)){P(F.error),z({id:"name"});return}if(I0(F),K5(),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 rM({config:$,locked:f,onAdd:Z,onPick:z,onDone:J}){let K=$.providers??[],G=f?[{label:"测试连接",value:"test"},{label:"完成",value:"done"}]:[{label:"添加",value:"add"},{label:"设为当前",value:"switch"},{label:"修改",value:"edit"},{label:"删除",value:"delete"},{label:"测试连接",value:"test"},{label:"完成",value:"done"}];return e(s1,{flexDirection:"column",children:[K.map((Q)=>e(_0,{color:Q.name===$.activeProvider?D.accent:D.muted,children:[Q.name===$.activeProvider?"* ":" ",Q.name??"(未命名)"," ",Q.baseURL," ",Q.defaultModel??"未设置模型"]},Q.name??Q.baseURL,!0,void 0,this)),f&&e(_0,{color:D.muted,children:["内置 OpenRouter 服务商(",K[0]?.defaultModel??"",")已锁定,不可修改或添加其它服务商。"]},void 0,!0,void 0,this),e(M2,{items:G,onSelect:(Q)=>{if(Q==="add")Z();else if(Q==="done")J();else z(Q)},onCancel:J},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function oM({config:$,onSelect:f,onCancel:Z}){let z=$.providers??[],J=s($)?.name;return e(M2,{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 G=z.find((Q)=>Q.name===K);if(G)f(G)},onCancel:Z},void 0,!1,void 0,this)}function dM({detected:$,onDetected:f,initial:Z,onSelect:z,onCancel:J}){Y5(()=>{let Q=!1;return WK().then((Y)=>{if(!Q)f(Y)}),()=>{Q=!0}},[f]);let K=[{label:"OpenAI 兼容接口",hint:"OpenRouter、DeepSeek、Groq 等",value:"openai-compatible"},{label:"OpenAI",hint:"官方接口",value:"openai"},{label:"Ollama(本地)",hint:$.found?"已检测到":"本机模型",value:"ollama"}],G=Z==="openai"?1:Z==="ollama"?2:$.found&&!Z?2:0;return e(M2,{items:K,initial:G,onSelect:(Q)=>z(Q),onCancel:J},`${Z??"auto"}-${$.found?"detected":"plain"}`,!1,void 0,this)}function lM({draft:$,onList:f,onEmpty:Z,onBack:z}){let J=G8(f),K=G8(Z);return J.current=f,K.current=Z,UK((G,Q)=>{if(Q.escape)z()}),Y5(()=>{let G=!1;return L4($.baseURL,$.apiKey||"ollama").then((Q)=>{if(G)return;if(Q.ok&&Q.models.length>0)J.current(Q.models);else K.current()}),()=>{G=!0}},[$.apiKey,$.baseURL]),e(s1,{children:[e(_0,{color:D.accent,children:e(nM,{type:"dots"},void 0,!1,void 0,this)},void 0,!1,void 0,this),e(_0,{color:D.muted,children:" 正在获取模型列表…"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function iM({models:$,current:f,onSelect:Z,onCancel:z}){let[J,K]=C1(""),[G,Q]=C1(0),Y=JK(J,$),P=J.trim();Q8((M,N,q)=>{if(N.escape){z();return}if(N.downArrow&&Y.length>0){Q((F)=>(F+1)%Y.length);return}if(N.upArrow&&Y.length>0){Q((F)=>(F-1+Y.length)%Y.length);return}if(q){if(Y.length>0)Z(Y[Math.min(G,Y.length-1)]);else if(P)Z(P);return}if(N.backspace||N.delete){K((F)=>Array.from(F).slice(0,-1).join("")),Q(0);return}if(N.ctrl||N.meta||N.tab)return;let L=M.replace(/[\r\n]+$/,"");if(L)K((F)=>F+L),Q(0)});let X=Math.min(G,Math.max(0,Y.length-1)),W=12,H=Math.min(X,Math.max(0,Y.length-W)),U=Y.slice(H,H+W);return e(s1,{flexDirection:"column",children:[e(_0,{color:D.muted,children:"输入可筛选"},void 0,!1,void 0,this),e(_0,{color:J?D.accent:D.muted,children:J||" "},void 0,!1,void 0,this),U.map((M,N)=>{let q=H+N===X;return e(_0,{color:q?D.accent:void 0,bold:q,children:[q?"▸ ":" ",M,M===f?" ← 当前":""]},M,!0,void 0,this)}),Y.length===0&&P!==""&&e(_0,{color:D.accent,children:["▸ 使用自定义模型: ",P]},void 0,!0,void 0,this),e(_0,{color:D.muted,children:"↑↓ 选择 · Enter 确认 · Esc 返回"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function U6({label:$,value:f,mask:Z,placeholder:z,error:J,onChange:K,onSubmit:G,onCancel:Q}){Q8((P,X,W)=>{if(X.escape){Q();return}if(W){G(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 e(s1,{flexDirection:"column",children:[e(_0,{children:$},void 0,!1,void 0,this),e(_0,{color:D.accent,children:Y||z||" "},void 0,!1,void 0,this),J?e(_0,{color:D.error,children:J},void 0,!1,void 0,this):null,e(_0,{color:D.muted,children:"Enter 确认 · Esc 返回"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function tM({draft:$,error:f,onConfirm:Z,onCancel:z}){return e(s1,{flexDirection:"column",children:[e(_0,{children:["类型 ",fq($.type)]},void 0,!0,void 0,this),e(_0,{children:["地址 ",$.baseURL]},void 0,!0,void 0,this),e(_0,{children:["密钥 ",f5($.apiKey)]},void 0,!0,void 0,this),e(_0,{children:["模型 ",$.defaultModel]},void 0,!0,void 0,this),e(_0,{children:["名称 ",$.name.trim()]},void 0,!0,void 0,this),f?e(_0,{color:D.error,children:f},void 0,!1,void 0,this):null,e(M2,{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 aM({text:$,onClose:f}){return Q8((Z,z,J)=>{if(z.escape||J)f()}),e(s1,{flexDirection:"column",children:[e(_0,{children:$},void 0,!1,void 0,this),e(_0,{color:D.muted,children:"Enter / Esc 继续"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function M2({title:$,items:f,initial:Z=0,onSelect:z,onCancel:J}){let[K,G]=C1(Math.min(Math.max(0,Z),Math.max(0,f.length-1))),[Q,Y]=C1("");return Q8((P,X,W)=>{if(X.escape){J();return}if(f.length===0)return;if(X.downArrow){Y(""),G((M)=>(M+1)%f.length);return}if(X.upArrow){Y(""),G((M)=>(M-1+f.length)%f.length);return}if(X.backspace||X.delete){Y((M)=>M.slice(0,-1));return}let H=()=>{let M=Q?Number.parseInt(Q,10):NaN;if(Number.isFinite(M)&&M>=1&&M<=f.length)return z(f[M-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 U=P.replace(/[\r\n]+$/,"");if(U&&/^[0-9]$/.test(U)){let M=Q+U,N=Number.parseInt(M,10);if(Number.isFinite(N)&&N>=1&&N<=f.length)Y(M),G(N-1);else if(Number.isFinite(N)&&N>f.length){Y(U);let q=Number.parseInt(U,10);if(Number.isFinite(q)&&q>=1&&q<=f.length)G(q-1)}}}),e(s1,{flexDirection:"column",children:[$?e(_0,{children:$},void 0,!1,void 0,this):null,f.map((P,X)=>e(_0,{color:X===K?D.accent:void 0,bold:X===K,children:[X===K?"▸ ":" ",X+1,". ",P.label,P.hint?e(_0,{color:D.muted,children:[" ",P.hint]},void 0,!0,void 0,this):null]},P.value,!0,void 0,this)),Q?e(_0,{color:D.accent,children:["输入: ",Q]},void 0,!0,void 0,this):null,e(_0,{color:D.muted,children:"↑↓ 选择 · 数字键跳转 · Enter/空格 确认 · Esc 返回"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Q8($){let f=G8(!1),Z=G8($);Z.current=$,Y5(()=>{let z=setTimeout(()=>{f.current=!0},0);return()=>clearTimeout(z)},[]),UK((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:Q5,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||cM,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:Q5,apiKey:"",existingKey:f?.existingKey,defaultModel:f?.defaultModel??"",name:f?.name??""}}function eM($,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 $q($){let f=c1(),Z=(f.providers??[]).map((K)=>K.name).filter((K)=>Boolean(K)),J={name:$.name.trim()||f8($.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 KK(f,$.editingName,J);return z8(f,J,{overwrite:!1})}function fq($){if($==="openai")return"OpenAI";if($==="ollama")return"Ollama";return"OpenAI 兼容接口"}function K5(){console.log(`已保存到 ${hM.join(P0(),"config.json")}`)}function Zq($){return $.replace(/Bearer\s+\S+/gi,"Bearer ****").replace(/\bsk-[A-Za-z0-9_-]+/g,"sk-****")}function G5($){return Object.keys($).length===1&&"error"in $}var Q5="https://api.openai.com/v1",cM="http://localhost:11434/v1";var qK=C(()=>{l();Y1();HK()});var VK={};M0(VK,{runSetupCommand:()=>BK,registerSetupCommand:()=>P5,offerInteractiveSetup:()=>Jq});import zq from"path";import{Option as FK}from"commander";function P5($,f){$.command("setup").description("configure providers (interactively, or with flags)").addOption(new FK("--type <type>","openai-compatible, openai, or ollama").argParser(QK)).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 FK("--context-window <n>","context window in tokens").argParser(K6("--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 BK(Z,{yes:Boolean(Z.yes||f().yes)})})}function NK(){return{isTty:Boolean(process.stdin.isTTY&&process.stdout.isTTY),load:c1,save:I0,fetchLive:L4,log:($)=>{console.log($)},configPath:()=>zq.join(P0(),"config.json"),runWizard:async($)=>{let{renderSetupWizard:f}=await Promise.resolve().then(() => (qK(),MK));return f($)}}}async function Jq($){await Z5({},{...NK(),isTty:!0},$)}async function BK($,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 Z5(Z,NK())}var X5=C(()=>{l();vf();K8();J5()});import{Box as Kq,Text as LK}from"ink";import Gq from"ink-spinner";import{jsxDEV as Y8}from"react/jsx-dev-runtime";function _K({label:$}){return Y8(Kq,{children:[Y8(LK,{color:"cyan",children:Y8(Gq,{type:"dots"},void 0,!1,void 0,this)},void 0,!1,void 0,this),$&&Y8(LK,{color:"gray",children:[" ",$]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var DK=()=>{};function w4($){AK=$}function bK($){let f=0,Z=(z,J,K)=>{let G=Buffer?.isBuffer(z),Q;if(typeof z==="string")Q=z;else if(G)Q=z.toString(J||"utf-8");else if(z!=null)Q=String(z);else return $.write(z,J,K);let Y="";if(f>0)Y+=`\x1B[${f}B\r`,f=0;Y+=Q;let P=AK;if(P){let W=P.rowsAbove+(Q.endsWith(`
|
|
48
|
-
`)?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 AK=null;function Yq($){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 Pq($){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 Xq($){let f=$.codePointAt(0);if(f===void 0)return 0;if(f<32||f>=127&&f<160)return 0;if(Yq(f))return 0;if(Pq(f)||jK.test($))return 2;return 1}function Wq($){if($.length===0)return 0;if(jK.test($)||$.includes(""))return 2;let f=0;for(let Z of $)f+=Xq(Z);return $.includes("️")?Math.max(f,2):f}function*O$($,f){for(let{segment:Z}of Qq.segment($))yield{text:Z,width:f?.(Z)??Wq(Z)}}function A0($,f){let Z=0;for(let{width:z}of O$($,f))Z+=z;return Z}function a0($,f,Z){let z=typeof $==="string"?$:$==null?"":String($);if(f<1)return[z];let J=[],K="",G=0;for(let{text:Q,width:Y}of O$(z,Z)){if(G+Y>f&&K.length>0)J.push(K),K="",G=0;K+=Q,G+=Y}return J.push(K),J}var Qq,jK;var P1=C(()=>{Qq=new Intl.Segmenter(void 0,{granularity:"grapheme"}),jK=/\p{Extended_Pictographic}/u});function W5($,f,Z){let z=[],J=0,K=$.split(`
|
|
49
|
-
`);
|
|
50
|
-
`)z
|
|
51
|
-
`)z
|
|
26
|
+
`),new Promise((Z)=>{let J=process.stdin.isRaw,z=process.stdin.readableEncoding;if(process.stdin.isTTY)process.stdin.setRawMode(!0);process.stdin.resume(),process.stdin.setEncoding("utf8");let G=1,Q="",Y=!1,K=setTimeout(()=>{Y=!0},0);K.unref?.();let X=(q)=>{if(q==="A"||q==="D")G=0;else if(q==="B"||q==="C")G=1;else return;P()},P=()=>{let q=G===0,U=G===1;process.stdout.write("\r\x1B[K"),process.stdout.write(q?"\x1B[1;32m▸ 允许\x1B[0m":"\x1B[90m 允许\x1B[0m"),process.stdout.write(" "),process.stdout.write(U?"\x1B[1;31m▸ 拒绝\x1B[0m":"\x1B[90m 拒绝\x1B[0m"),process.stdout.write(" \x1B[90m←→/↑↓ 选择 · Enter 确认 · y/n 快捷 · Esc 拒绝\x1B[0m")},W=(q)=>{if(clearTimeout(K),process.stdin.removeListener("data",H),process.stdin.isTTY)process.stdin.setRawMode(J??!1);if(z)process.stdin.setEncoding(z);if(process.stdout.write(`
|
|
27
|
+
|
|
28
|
+
`),Z6)Z6.resume();else process.stdin.pause();Z(q)};P();let H=(q)=>{Q+=q;while(Q.length>0){if(Q[0]==="\x03"||Q[0]==="\x04"){Q="",W(!1),process.exit(130);return}if(Q[0]==="\x1B"){if(Q[1]==="["){let M=Q.slice(2).search(/[A-Za-z~]/);if(M===-1)return;let F=Q[2+M];Q=Q.slice(3+M),X(F);continue}if(Q[1]==="O"){if(Q.length<3)return;let M=Q[2];Q=Q.slice(3),X(M);continue}if(Q.length===1){setTimeout(()=>{if(Q==="\x1B")Q="",W(!1)},50).unref?.();return}Q=Q.slice(1),W(!1);return}let U=Q[0];if(Q=Q.slice(1),U===`
|
|
29
|
+
`&&!Y)continue;if(U==="\r"||U===`
|
|
30
|
+
`){if(!Y)continue;W(G===0);return}if(U==="y"||U==="Y"){W(!0);return}if(U==="n"||U==="N"){W(!1);return}}};process.stdin.on("data",H)})}function y8($){return[/\brm\s+(-[a-z]*[rf][a-z]*|--recursive|--force)\s/,/\brm\s+-[a-z]*[rf]/,/\bfind\b[^|;&]*\s+-delete\b/,/\bfind\b[^|;&]*\s+-(exec|execdir|ok)\s+rm\b/,/\b(drop|truncate)\s+(table|database|schema)\b/i,/\bdelete\s+from\b/i,/\bmkfs\b/,/\bdd\s+/,/\b(shred|wipefs)\b/,/>+\s*\/dev\/(sd[a-z]+|nvme\d|disk\d)/,/\bformat\b.*\b[a-z]:\b/i,/\bgit\s+(reset\s+--hard|clean\s+-[a-z]*f)/,/\b(docker|podman)\s+(rm|rmi|prune|system\s+prune)\b/].some((J)=>J.test($))}function L5($){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,/\bdelete\s+from\b/i,/\bformat\b.*\b[a-z]:\b/i,/\bfind\b[^|;&]*\s+-delete\b/,/\bfind\b[^|;&]*\s+-(exec|execdir|ok)\s+rm\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((J)=>J.test($))}var nz=!1,N5=!1,w8,G6,Z6=null,I8=null,F5=null,cq=20,$6,C8=null,b8=!1;var Z$=C(()=>{l();e2();G6=new uq;$6=[]});var pz={};M0(pz,{userError:()=>Q1,runtimeError:()=>j5,formatCliError:()=>E8,exitCodeFor:()=>A5,CliError:()=>e});function Q1($,Z){return new e($,{exitCode:1,hint:Z})}function j5($,Z){return new e($,{exitCode:2,hint:Z})}function E8($){if($ instanceof e)return $.hint?`✖ ${$.message}
|
|
31
|
+
→ ${$.hint}`:`✖ ${$.message}`;return`✖ ${$ instanceof Error?$.message:String($)}`}function A5($){if($ instanceof e)return $.exitCode;return 2}var e;var q$=C(()=>{e=class e extends Error{exitCode;hint;constructor($,Z){super($);this.name="CliError",this.exitCode=Z?.exitCode??1,this.hint=Z?.hint}}});import{Option as rD}from"commander";function D5($,Z="global"){if($.project)return"project";if($.global)return"global";return Z}function oz($){let Z=y$($);if(!Z)throw Q1(`Invalid --sandbox value: "${$}"`,"use one of: off, workspace, strict");return Z}function dz($){let Z=o$($);if(!Z)throw Q1(`Invalid --network value: "${$}"`,"use one of: allow, deny");return Z}function rz($){let Z=A$($);if(!Z)throw Q1(`Invalid --permission value: "${$}"`,"use one of: ask, accept-edits, allow-all");return Z}function lz($){let Z=S0($);if(!Z)throw Q1(`Invalid --think value: "${$}"`,"use one of: off, low, medium, high, max");return Z}function iz($){let Z=h0($);if(!Z)throw Q1(`Invalid --memory value: "${$}"`,"use one of: on, off");return Z}function Q6($){return(Z)=>{let J=Number.parseInt(Z,10);if(!Number.isFinite(J)||J<=0)throw Q1(`Invalid ${$} value: "${Z}"`,"use a positive integer");return J}}var v8=C(()=>{u0();l();q$()});import{existsSync as lq,readFileSync as iq}from"fs";import x8 from"path";import{fileURLToPath as tq}from"url";function g8(){let $=x8.dirname(tq(import.meta.url)),Z=$;for(;;){let J=x8.join(Z,"package.json");if(lq(J))try{if(JSON.parse(iq(J,"utf-8")).name===aq)return Z}catch{}let z=x8.dirname(Z);if(z===Z)return x8.resolve($,"..");Z=z}}var aq="min-agent";var O5=()=>{};import{readFileSync as sq}from"fs";import eq from"path";import{spawnSync as $U}from"child_process";function GU(){return[sz,...ez].join(" ")}function QU($,Z=process.stderr){if(!Z.isTTY)return{stop:()=>{}};let J=0,z=()=>Z.write(`\r${tz[J++%tz.length]} ${$}`);z();let G=setInterval(z,80);return{stop:(Q)=>{if(clearInterval(G),Z.write("\r\x1B[2K"),Q)Z.write(`${Q}
|
|
32
|
+
`)}}}function r1(){try{let $=eq.join(g8(),"package.json"),Z=JSON.parse(sq($,"utf-8"));return typeof Z.version==="string"&&Z.version.length>0?Z.version:"0.0.0"}catch{return"0.0.0"}}function $G($,Z){let J=$.split("-")[0].split(".").map(Number),z=Z.split("-")[0].split(".").map(Number);for(let G=0;G<Math.max(J.length,z.length);G++){let Q=J[G]??0,Y=z[G]??0,K=Number.isFinite(Q)?Q:0,X=Number.isFinite(Y)?Y:0;if(K!==X)return K-X}return 0}function YU($){if(typeof $!=="string"||!JU.test($))return null;return $}async function ZG($=fetch){let Z;try{Z=await $(ZU,{signal:AbortSignal.timeout(zU),headers:{Accept:"application/json"}})}catch{return null}if(!Z.ok)return null;let J;try{J=await Z.json()}catch{return null}if(!J||typeof J!=="object"||!("version"in J))return null;return YU(J.version)}async function JG($){let Z=$?.currentVersion??r1(),J=await ZG($?.fetchFn);return{current:Z,latest:J,updateAvailable:J!==null&&$G(Z,J)<0}}function KU(){let $=$U(sz,[...ez],{stdio:"inherit",shell:process.platform==="win32",env:process.env});if($.error)return{ok:!1,missing:$.error.code==="ENOENT"};return{ok:$.status===0}}async function zG($={}){let Z=$.log??((P)=>console.log(P)),J=$.error??((P)=>console.error(P)),z=$.spinner??QU,G=$.currentVersion?.()??r1(),Q=GU();Z(`当前版本: ${G}`);let Y=z("正在检查最新版本…"),K=$.fetchLatest?await $.fetchLatest():await ZG();if(Y.stop(),!K)return J(`无法检查新版本(网络不可用)。请稍后重试,或手动执行: ${Q}`),{status:"check-failed",current:G,latest:null};if($G(G,K)>=0)return Z(`已是最新版本 (${K})`),{status:"up-to-date",current:G,latest:K};Z(`发现新版本: ${K}(当前 ${G})`),Z(`正在安装,可能需要一会儿…(${Q})`);let X=($.install??KU)();if(!X.ok){if(X.missing)J(`未找到 npm。请先安装 Node.js,然后执行: ${Q}`);else J(`自动升级失败。请手动执行: ${Q}`);return{status:"install-failed",current:G,latest:K}}return Z(`✓ 已升级到 ${K}`),{status:"updated",current:G,latest:K}}var az="min-agent",ZU,sz="npm",ez,JU,zU=1e4,tz;var Y6=C(()=>{O5();ZU=`https://registry.npmjs.org/${az}/latest`,ez=["install","-g",az],JU=/^\d+\.\d+\.\d+/;tz=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"]});import{readFileSync as XU,mkdirSync as PU,existsSync as WU}from"fs";import PG from"path";function MU(){let $=process.env.MIN_AGENT_MODELS_API_URL?.trim();if(!$)return HU;return $.replace(/\/$/,"")}function WG(){return PG.join(P0(),"model-catalog-cache.json")}function HG(){let $=WG();if(!WU($))return{};try{return JSON.parse(XU($,"utf-8"))}catch{return{}}}function FU($){let Z=WG();PU(PG.dirname(Z),{recursive:!0}),T0(Z,JSON.stringify($))}function z2($){let Z=I5.get($);if(Z&&Z.version===w5&&Date.now()-Z.timestamp<=GG)return Z;let J=HG()[$];if(!J||J.version!==w5||Date.now()-J.timestamp>GG)return null;return I5.set($,J),J}function NU($,Z){I5.set($,Z);let J=HG();J[$]=Z,FU(J)}function l1($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function qG($){if(!Array.isArray($))return{toggle:!1,efforts:[]};let Z=!1,J=new Set;for(let z of $){if(!l1(z))continue;if(z.type==="toggle")Z=!0;if(z.type==="effort"&&Array.isArray(z.values)){for(let G of z.values)if(typeof G==="string"&&G&&G!=="default")J.add(G)}}if(J.has("none"))Z=!0;return{toggle:Z,efforts:[...J]}}function BU($,Z){let J=Z.toLowerCase(),z=$.find((Q)=>Q.id.toLowerCase()===J);if(z)return z;let G=$.find((Q)=>{let Y=Q.id.toLowerCase();return Y.endsWith(`/${J}`)||J.endsWith(`/${Y}`)});if(G)return G;return $.find((Q)=>Q.name?.toLowerCase()===J)}function VU($,Z){if(!Z||$.length===0)return;let J="";try{J=new URL(Z).hostname.toLowerCase()}catch{return}return $.find((z)=>{let G=String(z.providerId??"").toLowerCase().replace(/_/g,"-");if(!G)return!1;if(J.includes(G))return!0;let Q=G.split("-")[0]??"";return Q.length>=4&&J.includes(Q)})}function _U($){return $.efforts.some((Z)=>{let J=S0(Z);return Boolean(J&&J!=="off")})}function LU($){let Z=$.map((W)=>qG(W.reasoningOptions)).filter((W)=>W.toggle||W.efforts.length>0);if(Z.length===0)return{toggle:!1,efforts:[]};let J=Z.filter(_U),z=Z.length/2,G=J.length===0?Number.POSITIVE_INFINITY:J.length/2,Q=0,Y=0,K=new Map;for(let W of Z)if(W.toggle||W.efforts.includes("none"))Q++;for(let W of J){let H=new Set;for(let q of W.efforts){if(q==="xhigh"||q==="extra-high")Y++;let U=S0(q);if(!U||U==="off"||H.has(U))continue;H.add(U),K.set(U,(K.get(U)??0)+1)}}let X=Q>=z,P=[];if(X)P.push("none");for(let W of fU)if((K.get(W)??0)>=G)P.push(W);if(P.includes("max")&&Y>0)P.push("xhigh");return{toggle:X,efforts:P}}function YG($){let Z=$?.context;if(typeof Z==="number"&&Number.isFinite(Z)&&Z>=4096)return Math.floor(Z);return}function jU($,Z,J){let z=$.offerings??[],G=VU(z,J),Q=G?qG(G.reasoningOptions):LU(z),Y=YG(G?.limit)??YG($.limit);return{version:w5,modelId:Z,lonaeId:$.id,...Y!=null?{contextWindow:Y}:{},reasoning:Q,timestamp:Date.now()}}async function b5($){try{let Z=await fetch($,{signal:AbortSignal.timeout(UU)});if(!Z.ok)return null;return await Z.json()}catch{return null}}function KG($){let Z=l1($)?$:null,J=Z&&l1(Z.data)?Z.data:Z;if(!J||typeof J.id!=="string")return null;let z=l1(J.limit)?{context:typeof J.limit.context==="number"?J.limit.context:void 0}:void 0,G=Array.isArray(J.offerings)?J.offerings.filter(l1).map((Q)=>({providerId:typeof Q.providerId==="string"?Q.providerId:void 0,limit:l1(Q.limit)?{context:typeof Q.limit.context==="number"?Q.limit.context:void 0}:void 0,reasoningOptions:Q.reasoningOptions})):[];return{id:J.id,limit:z,reasoning:J.reasoning===!0,offerings:G}}function AU($){let Z=l1($)?$:null;return(Z&&Array.isArray(Z.data)?Z.data:Array.isArray($)?$:[]).flatMap((z)=>{if(!l1(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 XG($){return $.split("/").map((Z)=>encodeURIComponent(Z)).join("/")}async function DU($){let Z=MU();if($.includes("/")){let G=KG(await b5(`${Z}/api/v1/models/${XG($)}`));if(G)return G}let J=AU(await b5(`${Z}/api/v1/models?q=${encodeURIComponent($)}&page_size=20`)),z=BU(J,$);if(!z)return null;return KG(await b5(`${Z}/api/v1/models/${XG(z.id)}`))}async function u8($,Z){let J=z2($);if(J)return J;let z=QG.get($);if(z!==void 0&&Date.now()-z<=qU)return null;let G=C5.get($);if(G)return G;let Q=DU($).then((Y)=>{if(!Y)return QG.set($,Date.now()),null;let K=jU(Y,$,Z);return NU($,K),K});C5.set($,Q);try{return await Q}finally{C5.delete($)}}var HU="https://models.lonae.com",GG=604800000,w5=3,qU=3600000,UU=1e4,I5,C5,QG,fU;var T5=C(()=>{L$();l();I5=new Map,C5=new Map,QG=new Map;fU=["low","medium","high","max"]});import{readFileSync as OU,mkdirSync as CU,existsSync as bU}from"fs";import FG from"path";function Q2($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function m8($){return $.replace(/\/$/,"").replace(/\/v1$/i,"")}function BG($,Z){let J="";try{J=new URL($).hostname.toLowerCase()}catch{J=m8($).toLowerCase()}let z=Z.trim().toLowerCase();return J?`${J}::${z}`:z}function G2($){let Z=typeof $==="string"&&$.trim()!==""?Number($):$;if(typeof Z!=="number"||!Number.isFinite(Z)||Z<NG)return;return Math.floor(Z)}function TU($){let Z=[];for(let[J,z]of Object.entries($))if(J==="context_length"||J.endsWith(".context_length")){let G=G2(z);if(G!=null)Z.push(G)}if(Z.length===0)return;return Math.max(...Z)}function RU($){if(typeof $==="number")return G2($);if(Q2($))return G2($.num_ctx);if(typeof $!=="string")return;let Z=$.match(/(?:^|\n)\s*num_ctx\s+(\d+)/);if(Z?.[1])return G2(Number(Z[1]));return G2($)}function kU($){if(!Array.isArray($))return null;return $.some((Z)=>String(Z).toLowerCase()==="thinking")}function yU($,Z){if($!=null)return $;if(Z!=null)return Math.min(Z,y5);return}function VG($,Z){let J=Q2($.options)?$.options:{};return{...$,options:{...J,num_ctx:Z}}}function fG($,Z){if(Z===!1)return!1;if(!$)return;if(!$.thinkingEnabled)return!1;let J=$.reasoningEffort;if(J==="low"||J==="medium"||J==="high")return J;if(J==="none")return!1;return"high"}function _G($,Z){let J=s(G0());if(typeof J?.contextWindow==="number"&&Number.isFinite(J.contextWindow)&&J.contextWindow>=NG)return Math.floor(J.contextWindow);return i1($,Z??J?.baseURL)?.contextWindow??h8}function SU($,Z){let J=Q2($)?$:{},z=Q2(J.model_info)?J.model_info:{},G=yU(RU(J.parameters),TU(z));return{version:K6,modelId:Z,...G!=null?{contextWindow:G}:{},thinking:kU(J.capabilities),timestamp:Date.now()}}function LG($){if($.thinking===!1)return["off"];return["off","low","medium","high","max"]}function jG(){return FG.join(P0(),"ollama-model-cache.json")}function AG(){let $=jG();if(!bU($))return{};try{let Z=JSON.parse(OU($,"utf-8"));if(!Q2(Z))return{};let J={};for(let[z,G]of Object.entries(Z)){if(!Q2(G)||G.version!==K6)continue;if(typeof G.modelId!=="string")continue;let Q=G.thinking===!0||G.thinking===!1?G.thinking:null,Y=G2(G.contextWindow),K=typeof G.timestamp==="number"?G.timestamp:0;J[z]={version:K6,modelId:G.modelId,...Y!=null?{contextWindow:Y}:{},thinking:Q,timestamp:K}}return J}catch{return{}}}function EU($){let Z=jG();CU(FG.dirname(Z),{recursive:!0}),T0(Z,JSON.stringify($))}function i1($,Z){let J=BG(Z??"",$),z=k5.get(J);if(z&&z.version===K6&&Date.now()-z.timestamp<=UG)return z;let G=AG()[J];if(!G||G.version!==K6||Date.now()-G.timestamp>UG)return null;return k5.set(J,G),G}function vU($,Z){k5.set($,Z);let J=AG();J[$]=Z,EU(J)}async function xU($,Z){try{let J=await fetch(`${m8($)}/api/show`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Z}),signal:AbortSignal.timeout(IU)});if(!J.ok)return null;return await J.json()}catch{return null}}async function X6($,Z){let J=Z??"",z=BG(J,$),G=i1($,J);if(G)return G;let Q=MG.get(z);if(Q!==void 0&&Date.now()-Q<=wU)return null;let Y=R5.get(z);if(Y)return Y;let K=xU(J,$).then((X)=>{if(!X)return MG.set(z,Date.now()),null;let P=SU(X,$);return vU(z,P),P});R5.set(z,K);try{return await K}finally{R5.delete(z)}}var K6=2,UG=604800000,wU=3600000,IU=8000,NG=512,h8=2048,y5=32768,k5,R5,MG;var n8=C(()=>{l();L$();k5=new Map,R5=new Map,MG=new Map});function J$($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function gU($){return typeof $==="string"?$:$ instanceof URL?$.href:$.url}function uU($){try{return/\/chat\/completions\/?$/i.test(new URL($).pathname)}catch{return/\/chat\/completions\/?$/i.test($)}}function hU($){let Z=$.replace(/\/v1\/chat\/completions\/?$/i,"").replace(/\/chat\/completions\/?$/i,"");return`${m8(Z)}/api/chat`}async function bG($){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 Z=$.getReader(),J=[];for(;;){let{done:Y,value:K}=await Z.read();if(Y)break;if(K)J.push(K)}let z=J.reduce((Y,K)=>Y+K.length,0),G=new Uint8Array(z),Q=0;for(let Y of J)G.set(Y,Q),Q+=Y.length;return new TextDecoder().decode(G)}return null}function mU($){return $.match(/^data:[^;]+;base64,(.+)$/s)?.[1]??null}function nU($){if(typeof $==="string")return{text:$,images:[]};if(!Array.isArray($))return{text:$==null?"":JSON.stringify($),images:[]};let Z=[],J=[];for(let z of $){if(!J$(z))continue;if(z.type==="text"&&typeof z.text==="string")Z.push(z.text);else if(z.type==="image_url"){let G=J$(z.image_url)?z.image_url.url:void 0;if(typeof G==="string"){let Q=mU(G);if(Q)J.push(Q)}}else if(typeof z.text==="string")Z.push(z.text)}return{text:Z.join(`
|
|
33
|
+
`),images:J}}function cU($){if(J$($))return $;if(typeof $!=="string"||!$.trim())return{};try{let Z=JSON.parse($);return J$(Z)?Z:{value:Z}}catch{return{value:$}}}function pU($){if(typeof $==="string")return $;try{return JSON.stringify($??{})}catch{return"{}"}}function oU($){if(!Array.isArray($)||$.length===0)return;return $.map((Z)=>{let J=J$(Z)?Z:{},z=J$(J.function)?J.function:J;return{function:{name:typeof z.name==="string"?z.name:"",arguments:cU(z.arguments)}}})}function dU($){if(!Array.isArray($))return[];return $.map((Z)=>{let J=J$(Z)?Z:{},{text:z,images:G}=nU(J.content),Q={role:typeof J.role==="string"?J.role:"user",content:z};if(G.length>0)Q.images=G;let Y=oU(J.tool_calls);if(Y)Q.tool_calls=Y;return Q})}function rU($){let Z=J$($.options)?{...$.options}:{};if(typeof $.temperature==="number")Z.temperature=$.temperature;if(typeof $.top_p==="number")Z.top_p=$.top_p;if(typeof $.seed==="number")Z.seed=$.seed;if(typeof $.max_tokens==="number")Z.num_predict=$.max_tokens;if(typeof $.max_completion_tokens==="number")Z.num_predict=$.max_completion_tokens;if(Array.isArray($.stop)||typeof $.stop==="string")Z.stop=$.stop;return Z}function lU($,Z){let J={model:$.model,messages:dU($.messages),stream:$.stream!==!1,options:rU($)};if(Array.isArray($.tools)&&$.tools.length>0)J.tools=$.tools;if($.format!=null)J.format=$.format;if(Z.think!==void 0)J.think=Z.think;return VG(J,Z.numCtx)}function wG($,Z){if(Array.isArray(Z)&&Z.length>0)return"tool_calls";if($==="length"||$==="max_tokens")return"length";return"stop"}function IG($){let Z=typeof $.prompt_eval_count==="number"?$.prompt_eval_count:void 0,J=typeof $.eval_count==="number"?$.eval_count:void 0;if(Z==null&&J==null)return;let z=Z??0,G=J??0;return{prompt_tokens:z,completion_tokens:G,total_tokens:z+G}}function TG($){if(!Array.isArray($)||$.length===0)return;return $.map((Z,J)=>{let z=J$(Z)?Z:{},G=J$(z.function)?z.function:z,Q=typeof z.id==="string"&&z.id?z.id:`ollama_call_${J}`;return{index:J,id:Q,type:"function",function:{name:typeof G.name==="string"?G.name:"",arguments:pU(G.arguments)}}})}function DG($,Z){let J=J$($.message)?$.message:{},z=typeof J.content==="string"?J.content:"",G=typeof J.thinking==="string"?J.thinking:"",Q=TG(J.tool_calls),Y=$.done===!0,K={};if(!Z.sentRole)K.role="assistant",Z.sentRole=!0;if(G)K.reasoning=G;if(z)K.content=z;if(Q)K.tool_calls=Q;let X={id:"chatcmpl-ollama",object:"chat.completion.chunk",created:Math.floor(Date.now()/1000),model:typeof $.model==="string"?$.model:"",choices:[{index:0,delta:K,finish_reason:Y?wG($.done_reason,J.tool_calls):null}]},P=IG($);if(P)X.usage=P;return X}function OG($){let Z=J$($.message)?$.message:{},J=typeof Z.content==="string"?Z.content:"",z=typeof Z.thinking==="string"?Z.thinking:"",G=TG(Z.tool_calls),Q={role:"assistant",content:J};if(z)Q.reasoning=z;if(G)Q.tool_calls=G;let Y={id:"chatcmpl-ollama",object:"chat.completion",created:Math.floor(Date.now()/1000),model:typeof $.model==="string"?$.model:"",choices:[{index:0,message:Q,finish_reason:wG($.done_reason,Z.tool_calls)}]},K=IG($);if(K)Y.usage=K;return Y}function CG($){return`data: ${JSON.stringify($)}
|
|
34
|
+
|
|
35
|
+
`}function iU($){let Z=new TextDecoder,J=new TextEncoder,z=$.getReader(),G={sentRole:!1},Q="";return new ReadableStream({async pull(Y){for(;;){let{done:K,value:X}=await z.read();if(K){Q+=Z.decode();let q=Q.trim();if(q)try{let U=JSON.parse(q);if(J$(U))Y.enqueue(J.encode(CG(DG(U,G))))}catch{}Y.enqueue(J.encode(`data: [DONE]
|
|
36
|
+
|
|
37
|
+
`)),Y.close();return}Q+=Z.decode(X,{stream:!0});let P=Q.lastIndexOf(`
|
|
38
|
+
`);if(P<0)continue;let W=Q.slice(0,P+1);Q=Q.slice(P+1);let H=[];for(let q of W.split(`
|
|
39
|
+
`)){let U=q.trim();if(!U)continue;try{let M=JSON.parse(U);if(J$(M))H.push(CG(DG(M,G)))}catch{}}if(H.length>0){Y.enqueue(J.encode(H.join("")));return}}},cancel(Y){return z.cancel(Y)}})}function tU($){let Z=new Headers($);return Z.set("content-type","application/json"),Z}function aU($){let Z=new Headers($);return Z.set("content-type","text/event-stream"),Z.delete("content-length"),Z}async function RG($,Z,J,z,G){let Q=gU(Z);if(!uU(Q))return $(Z,{...J,body:JSON.stringify(z)});let Y=typeof z.model==="string"?z.model:"",K=i1(Y,Q),X=lU(z,{numCtx:_G(Y,Q),think:fG(G,K?.thinking??null)}),P=await $(hU(Q),{...J,method:J.method??"POST",headers:{...Object.fromEntries(new Headers(J.headers).entries()),"Content-Type":"application/json"},body:JSON.stringify(X)});if(P.status>=400)return P;if(z.stream===!1)try{let H=await P.json(),q=J$(H)?OG(H):OG({});return new Response(JSON.stringify(q),{status:P.status,statusText:P.statusText,headers:tU(P.headers)})}catch{return P}if(!P.body)return P;return new Response(iU(P.body),{status:P.status,statusText:P.statusText,headers:aU(P.headers)})}var kG=C(()=>{n8()});import{AsyncLocalStorage as sU}from"async_hooks";import{readFileSync as eU,mkdirSync as $M,existsSync as ZM}from"fs";import EG from"path";function vG($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function zM($){return $==="enabled-disabled"||$==="adaptive-disabled"||$==="omit"}function GM($){return $==="reasoning_effort"||$==="omit"}function QM($){if(!vG($))return!1;return $.version===Y2&&zM($.thinkingType)&&GM($.effort)&&typeof $.timestamp==="number"&&Number.isFinite($.timestamp)}function xG(){return EG.join(P0(),"thinking-wire-cache.json")}function gG(){let $=xG();if(!ZM($))return{};try{let Z=JSON.parse(eU($,"utf-8"));if(!vG(Z))return{};let J={};for(let[z,G]of Object.entries(Z))if(QM(G))J[z]=G;return J}catch{return{}}}function YM($){let Z=xG();$M(EG.dirname(Z),{recursive:!0}),T0(Z,JSON.stringify($))}function yG($,Z){if($.version!==Y2)return null;if(Z-$.timestamp>JM)return null;return $}function uG($,Z){let J=$.trim().toLowerCase(),z=Z.trim().toLowerCase();if(!J)return z;if(!z)return J;return`${J}::${z}`}function KM($,Z,J){if(J==="ollama")return{thinkingType:"omit",effort:"reasoning_effort"};if(`${$} ${Z}`.toLowerCase().includes("minimax"))return{thinkingType:"adaptive-disabled",effort:"reasoning_effort"};if(J==="openai")return{thinkingType:"omit",effort:"reasoning_effort"};return{thinkingType:S5.thinkingType,effort:S5.effort}}function XM($,Z){let J=c8.get($);if(J){let Q=yG(J,Z);if(Q)return Q;c8.delete($)}let z=gG()[$];if(!z)return null;let G=yG(z,Z);if(!G)return null;return c8.set($,G),G}function PM($,Z,J,z=Date.now()){let G=XM(uG($,Z),z);if(G)return G;return{version:Y2,...KM(Z,$,J),timestamp:z}}function WM($,Z,J,z=Date.now()){let G={version:Y2,thinkingType:J.thinkingType,effort:J.effort,timestamp:J.timestamp??z},Q=uG($,Z);c8.set(Q,G);let Y=gG();return Y[Q]=G,YM(Y),G}function p8($,Z,J=S5){let z={...$};if(J.effort==="omit")delete z.reasoning_effort;else z.reasoning_effort=Z.reasoningEffort;if(J.thinkingType==="omit")delete z.thinking;else{let G=J.thinkingType==="adaptive-disabled"?"adaptive":"enabled";z.thinking={type:Z.thinkingEnabled?G:"disabled"}}return z}function HM($){return new Set($.split(",").map((Z)=>Z.trim().replace(/^['"]|['"]$/g,"").toLowerCase()).filter(Boolean))}function qM($){let Z=$.match(/thinking\.type[\s\S]*?allowed:\s*([^)]+)/i);if(Z?.[1]){let J=HM(Z[1]);if(J.has("adaptive")&&J.has("disabled"))return{thinkingType:"adaptive-disabled"};if(J.has("enabled")&&J.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 UM($){try{let Z=typeof $==="string"?$:$ instanceof URL?$.href:$.url;return new URL(Z).hostname}catch{return""}}function SG($,Z){return new Response(Z,{status:400,statusText:$.statusText,headers:$.headers})}function MM($,Z){return $.thinkingType===Z.thinkingType&&$.effort===Z.effort}async function hG($,Z,J,z){if(!J?.body)return $(Z,J);let G=await bG(J.body);if(G==null)return $(Z,J);let Q;try{Q=JSON.parse(G)}catch{return $(Z,J)}if(!Q||typeof Q!=="object"||Array.isArray(Q))return $(Z,J);let Y=P6.getStore(),K=z?.providerType??s(G0())?.type,X=Q;if(K==="ollama")return RG($,Z,J,X,Y);if(!Y)return $(Z,J);let P=UM(Z),W=typeof X.model==="string"?X.model:"",H=PM(P,W,K),q=await $(Z,{...J,body:JSON.stringify(p8(X,Y,H))});if(q.status!==400)return q;let U=await q.text(),M=qM(U);if(!M)return SG(q,U);let F={version:Y2,thinkingType:M.thinkingType??H.thinkingType,effort:M.effort??H.effort,timestamp:Date.now()};if(MM(H,F))return SG(q,U);return WM(P,W,F),$(Z,{...J,body:JSON.stringify(p8(X,Y,F))})}var P6,Y2=1,JM=604800000,S5,c8;var E5=C(()=>{l();kG();L$();P6=new sU,S5={version:Y2,thinkingType:"enabled-disabled",effort:"reasoning_effort"},c8=new Map});var h5={};M0(h5,{toWireEffort:()=>oG,thinkingSourceLabel:()=>g5,thinkingRequestStore:()=>P6,thinkingPayload:()=>P2,thinkingEffortLabel:()=>D$,thinkingChoicesFromReasoning:()=>cG,thinkingChoicesForModel:()=>t1,thinkingChoiceIndex:()=>o8,setThinkingOverride:()=>K2,setThinkingEffort:()=>a1,resolveThinkingRequest:()=>u5,resolveThinkingEffort:()=>Y1,refreshThinkingChoices:()=>X2,parseThinkingEffort:()=>S0,getThinkingSnapshot:()=>pG,getThinkingOverride:()=>nG,clampThinkingEffort:()=>x5,applyThinkingToChatBody:()=>p8,THINKING_EFFORTS:()=>r$,DEFAULT_THINKING_EFFORT:()=>v5});function K2($){mG=$}function nG(){return mG}function D$($){return $}function o8($,Z=r$){let J=Z.length>0?Z:r$,z=x5($,J),G=J.indexOf(z);return G>=0?G:0}function cG($){let Z=new Set;if($.toggle||$.efforts.includes("none"))Z.add("off");for(let z of $.efforts){let G=S0(z);if(G)Z.add(G)}if(r$.filter((z)=>z!=="off"&&Z.has(z)).length===0)return[...r$];return r$.filter((z)=>Z.has(z))}function t1($){let Z=s(G0());if(Z?.type==="ollama"){if(!$)return[...r$];let z=i1($,Z.baseURL);if(!z)return[...r$];return LG(z)}if(!$)return[...r$];let J=z2($);if(!J)return[...r$];return cG(J.reasoning)}async function X2($,Z){let J=s(G0()),z=Z?.type??J?.type,G=Z?.baseURL??J?.baseURL;if($)if(z==="ollama")await X6($,G);else await u8($,G);return t1($)}function x5($,Z=r$){if(Z.length===0||Z.includes($))return $;if(Z.includes("medium"))return"medium";if(Z.includes("high"))return"high";let J=Z.filter((z)=>z!=="off");if(J.length>0)return J[Math.floor((J.length-1)/2)];if(Z.includes("off"))return"off";return v5}function g5($){if($==="cli")return"本次启动参数";if($==="project")return"项目";if($==="global")return"全局";return"默认"}function Y1($,Z){let J,z;if($)J=$,z="cli";else{let Q=nG();if(Q)J=Q,z="cli";else{let Y=pG();J=Y.thinking??v5,z=Y.source}}let G=Z??s(G0())?.defaultModel;return{thinking:x5(J,t1(G)),source:z}}function pG(){let $=S0(w0().thinking);if($!==void 0)return{thinking:$,source:"project"};let Z=S0(a().thinking);if(Z!==void 0)return{thinking:Z,source:"global"};return{thinking:void 0,source:null}}function FM(){let $=w0();if($.thinking===void 0)return;let{thinking:Z,...J}=$;H$(J)}function a1($,Z){if(Z==="project"){H$({...w0(),thinking:$});return}R0({...a(),thinking:$}),FM()}function P2(){let{thinking:$,source:Z}=Y1();return{thinking:$,source:Z,label:D$($)}}function oG($,Z,J){if($==="off")return"none";if($!=="max")return $;let G=(J?z2(J):void 0)?.reasoning.efforts??[];if(G.includes("max"))return"max";if(G.includes("xhigh")||Z==="openai")return"xhigh";return"max"}function u5($){let{thinking:Z}=Y1($?.runOverride,$?.modelId),J=$?.providerType??s(G0())?.type;return{reasoningEffort:oG(Z,J,$?.modelId),thinkingEnabled:Z!=="off"}}var r$,v5="medium",mG;var K1=C(()=>{l();T5();n8();E5();r$=["off","low","medium","high","max"]});var W2={};M0(W2,{takeScopeFlags:()=>l$,scopeLabel:()=>U$,readScope:()=>O$});function O$($){if($===void 0||$===null||$==="")return{ok:!0,scope:void 0};if($==="global"||$==="project")return{ok:!0,scope:$};return{ok:!1}}function l$($){let Z,J=[];for(let z of $)if(z==="--project")Z="project";else if(z==="--global")Z="global";else J.push(z);return{scope:Z,rest:J}}function U$($){return $==="project"?"project":"global"}var i5={};M0(i5,{takeScopeFlags:()=>l$,setMemoryOverride:()=>d8,setMemoryMode:()=>H2,searchMemories:()=>b4,resolveMemoryMode:()=>C4,readMemoryScope:()=>O$,parseMemoryMode:()=>h0,memorySourceLabel:()=>W6,memoryPayload:()=>e1,memoryModeLabel:()=>s1,loadMemories:()=>C$,isMemoryEnabled:()=>X1,getMemoryTools:()=>l5,getMemorySystemPrompt:()=>r5,getMemorySnapshot:()=>eG,getMemoryOverride:()=>sG,formatMemoryLine:()=>d5,deleteMemory:()=>U2,defaultMemoryScope:()=>H6,addMemory:()=>q2,DEFAULT_MEMORY_MODE:()=>tG});import{readFileSync as NM,mkdirSync as BM,existsSync as o5,renameSync as VM,statSync as iG}from"fs";import p5 from"path";import{tool as m5,jsonSchema as n5}from"ai";function d8($){aG=$}function sG(){return aG}function s1($){return $}function W6($){if($==="cli")return"this run";if($==="project")return"project";if($==="global")return"global";return"default"}function eG(){let $=h0(w0().memory);if($!==void 0)return{memory:$,source:"project"};let Z=h0(a().memory);if(Z!==void 0)return{memory:Z,source:"global"};return{memory:void 0,source:null}}function C4($){if($)return{memory:$,source:"cli"};let Z=sG();if(Z)return{memory:Z,source:"cli"};let J=eG();return{memory:J.memory??tG,source:J.source}}function X1($){return C4($).memory==="on"}function fM(){let $=w0();if($.memory===void 0)return;let{memory:Z,...J}=$;H$(J)}function H2($,Z){if(Z==="project"){H$({...w0(),memory:$});return}R0({...a(),memory:$}),fM()}function e1(){let{memory:$,source:Z}=C4();return{memory:$,source:Z,label:s1($)}}function H6(){return o5(n1())?"project":"global"}function dG($){return $==="global"||$==="project"?$:H6()}function $Q($){if($==="project")return p5.join(n1(),"memory.json");return p5.join(P0(),"memory.json")}function _M($){if(typeof $!=="object"||$===null)return;let Z=$;if(typeof Z.content!=="string")return;let J=Array.isArray(Z.tags)?Z.tags.filter((G)=>typeof G==="string"):[],z=typeof Z.created==="string"?Z.created:"";return{content:Z.content,tags:J,created:z}}function rG($){try{VM($,`${$}.corrupt-${Date.now()}`)}catch{}}function LM($,Z){try{let J=iG($);O4.set($,{mtimeMs:J.mtimeMs,size:J.size,memories:Z})}catch{O4.delete($)}}function C$($="global"){let Z=$Q($),J;try{J=iG(Z)}catch{return O4.delete(Z),[]}let z=O4.get(Z);if(z&&z.mtimeMs===J.mtimeMs&&z.size===J.size)return z.memories;let G;try{G=JSON.parse(NM(Z,"utf-8"))}catch{return rG(Z),O4.delete(Z),[]}if(!Array.isArray(G))return rG(Z),O4.delete(Z),[];let Q=G.flatMap((Y)=>{let K=_M(Y);return K?[K]:[]});return O4.set(Z,{mtimeMs:J.mtimeMs,size:J.size,memories:Q}),Q}function ZQ($,Z){let J=$Q(Z);if(Z==="project"&&!o5(n1())){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}BM(p5.dirname(J),{recursive:!0}),T0(J,JSON.stringify($,null,2)),LM(J,$)}function q2($,Z=[],J="global"){let z=C$(J),G={content:$,tags:Z,created:new Date().toISOString()};return z.push(G),ZQ(z,J),G}function U2($,Z="global"){let J=C$(Z);if($<0||$>=J.length)return!1;return J.splice($,1),ZQ(J,Z),!0}function b4($,Z="global"){let J=C$(Z),z=$.toLowerCase();return J.map((G,Q)=>({...G,index:Q})).filter((G)=>G.content.toLowerCase().includes(z)||G.tags.some((Q)=>Q.toLowerCase().includes(z)))}function d5($,Z,J){let z=$.tags.length>0?` [${$.tags.join(", ")}]`:"",G=J?.date?$.created.split("T")[0]:"",Q=G?` (${G})`:"";return` #${Z+1}: ${$.content}${z}${Q}`}function lG($,Z){if($.length===0)return"";let J=Math.max(0,$.length-c5),z=$.slice(J).map((Q,Y)=>({m:Q,num:J+Y+1})).reverse().map(({m:Q,num:Y})=>{let K=Q.tags.length>0?` [${Q.tags.join(", ")}]`:"";return` ${Y}. ${Q.content}${K}`}),G=$.length>c5?`
|
|
40
|
+
(${$.length-c5} older memories not shown — use memory_search to find them.)`:"";return[Z,...z,G].filter(Boolean).join(`
|
|
41
|
+
`)}function r5($){if(!X1($))return"";let Z=C$("project"),J=C$("global");if(Z.length===0&&J.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.',""],G=[lG(Z,"### This project"),lG(J,Z.length>0?"### Global":"")].filter((Q)=>Q.length>0);return[...z,...G].join(`
|
|
42
|
+
`)}function l5(){let $=m5({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:n5({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:G,scope:Q})=>{let Y=dG(Q);if(Y==="project"&&!o5(n1()))return`Cannot save project memory: no .min-agent/ in ${process.cwd()}. Run "min-agent init" first, or use scope global.`;let K=q2(z,G??[],Y);return`Saved ${Y} memory: "${z}" (tags: ${K.tags.length>0?K.tags.join(", "):"none"})`}}),Z=m5({description:"Search through saved memories by keyword. Use this to recall previously saved information.",inputSchema:n5({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:G})=>{let Y=(G==="global"||G==="project"?[G]:["project","global"]).flatMap((K)=>b4(z,K).map((X)=>{let P=X.tags.length>0?` [${X.tags.join(", ")}]`:"";return`${K} #${X.index+1}: ${X.content}${P} (${X.created.split("T")[0]})`}));if(Y.length===0)return`No memories found matching "${z}"`;return Y.join(`
|
|
43
|
+
`)}}),J=m5({description:"Delete a memory by its number. Use memory_search first to find the index and scope.",inputSchema:n5({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:G})=>{let Q=dG(G);if(U2(z-1,Q))return`${Q} memory #${z} deleted.`;return`${Q} memory #${z} not found.`}});return{memory_save:$,memory_search:Z,memory_delete:J}}var tG="off",c5=30,aG,O4;var b1=C(()=>{l();L$();O4=new Map});function jM($){return $==="cli"?"this run":$==="env"?"environment variable":$==="project"?"project":$==="global"?"global":"default"}function r8($){let{scope:Z,rest:J}=l$($.positionals),z=Z??$.scope??"global";if(J[0]==="--help"||J[0]==="-h")return{ok:!0,lines:[q6]};if(J[0]==="network"){let K=o$(J[1]);if(!K||J.length>2)return{ok:!1,lines:[q6]};return _4({network:K},z),o2({network:K}),{ok:!0,lines:[`✓ Network set to ${K==="deny"?"denied":"allowed"} (${U$(z)})`]}}if(J.length===1){let K=y$(J[0]);if(!K)return{ok:!1,lines:[q6]};_4({mode:K},z),o2({mode:K});let X=r2(K);return{ok:!0,lines:[`✓ Sandbox set to ${l2(K)} (${U$(z)})`,...X?[X]:[]]}}if(J.length>1)return{ok:!1,lines:[q6]};if($.flagMode||$.flagNetwork){_4({...$.flagMode?{mode:$.flagMode}:{},...$.flagNetwork?{network:$.flagNetwork}:{}},z),o2({...$.flagMode?{mode:$.flagMode}:{},...$.flagNetwork?{network:$.flagNetwork}:{}});let K=[...$.flagMode?[`sandbox set to ${l2($.flagMode)}`]:[],...$.flagNetwork?[`network set to ${$.flagNetwork==="deny"?"denied":"allowed"}`]:[]],X=$.flagMode?r2($.flagMode):null;return{ok:!0,lines:[`✓ ${K.join(", ")} (${U$(z)})`,...X?[X]:[]]}}let G=a2(),Q=[...G.extraWriteRoots.length>0?[`Extra writable dirs: ${G.extraWriteRoots.join(", ")}`]:[],...G.extraReadRoots.length>0?[`Extra readable dirs: ${G.extraReadRoots.join(", ")}`]:[]],Y=r2(t0().mode);return{ok:!0,lines:[`Current sandbox: ${i2()} (${jM(G.source)})`,...Q,...Y?[Y]:[],q6]}}var q6;var t5=C(()=>{l();u0();q6=["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(`
|
|
44
|
+
`)});function AM($){return $==="cli"?"this run":$==="project"?"project":$==="global"?"global":"default"}function i8($){let{scope:Z,rest:J}=l$($.positionals),z=Z??$.scope??"global";if(J[0]==="--help"||J[0]==="-h")return{ok:!0,lines:[l8]};if(J.length===1){let X=A$(J[0]);if(!X)return{ok:!1,lines:[l8]};return J2(X,z),T8(X),{ok:!0,lines:[`✓ Permission set to ${f4(X)} (${U$(z)})`]}}if(J.length>1)return{ok:!1,lines:[l8]};if($.flagMode)return J2($.flagMode,z),T8($.flagMode),{ok:!0,lines:[`✓ Permission set to ${f4($.flagMode)} (${U$(z)})`]};let G=t2(),Q=z6(),Y=Q??G.permission,K=Q?"cli":G.source;return{ok:!0,lines:[`Current permission: ${f4(Y)} (${AM(K)})`,l8]}}var l8;var a5=C(()=>{l();Z$();l8=["Usage: min-agent permission [ask|accept-edits|allow-all] [--project|--global]"," min-agent --permission ask|accept-edits|allow-all [--project|--global]"].join(`
|
|
45
|
+
`)});function DM($){return $==="cli"?"this run":$==="project"?"project":$==="global"?"global":"default"}function a8($){let{scope:Z,rest:J}=l$($.positionals),z=Z??$.scope??"global";if(J[0]==="--help"||J[0]==="-h")return{ok:!0,lines:[t8]};if(J.length===1){let Y=S0(J[0]);if(!Y)return{ok:!1,lines:[t8]};return a1(Y,z),K2(Y),{ok:!0,lines:[`✓ Thinking set to ${D$(Y)} (${U$(z)})`]}}if(J.length>1)return{ok:!1,lines:[t8]};if($.flagEffort)return a1($.flagEffort,z),K2($.flagEffort),{ok:!0,lines:[`✓ Thinking set to ${D$($.flagEffort)} (${U$(z)})`]};let{thinking:G,source:Q}=Y1();return{ok:!0,lines:[`Current thinking: ${D$(G)} (${DM(Q)})`,t8]}}var t8;var s5=C(()=>{K1();t8=["Usage: min-agent think [off|low|medium|high|max] [--project|--global]"," min-agent --think off|low|medium|high|max [--project|--global]"].join(`
|
|
46
|
+
`)});function e8($){let{scope:Z,rest:J}=l$($.positionals),z=Z??$.scope??"global";if(J[0]==="--help"||J[0]==="-h")return{ok:!0,lines:[s8]};if(J.length===1){let Y=h0(J[0]);if(!Y)return{ok:!1,lines:[s8]};return H2(Y,z),d8(Y),{ok:!0,lines:[`✓ Memory set to ${s1(Y)} (${U$(z)})`]}}if(J.length>1)return{ok:!1,lines:[s8]};if($.flagMode)return H2($.flagMode,z),d8($.flagMode),{ok:!0,lines:[`✓ Memory set to ${s1($.flagMode)} (${U$(z)})`]};let{memory:G,source:Q}=C4();return{ok:!0,lines:[`Current memory: ${s1(G)} (${W6(Q)})`,s8]}}var s8;var e5=C(()=>{b1();s8=["Usage: min-agent memory [on|off] [--project|--global]"," min-agent --memory on|off [--project|--global]"].join(`
|
|
47
|
+
`)});var JQ={};M0(JQ,{runWriteConfig:()=>OM});async function OM($){let Z=[],J=!0;if($.sandbox!==void 0||$.network!==void 0){let z=r8({positionals:[],flagMode:$.sandbox,flagNetwork:$.network,scope:$.scope});if(Z.push(...z.lines),!z.ok)J=!1}if($.permission!==void 0){let z=i8({positionals:[],flagMode:$.permission,scope:$.scope});if(Z.push(...z.lines),!z.ok)J=!1}if($.think!==void 0){let z=a8({positionals:[],flagEffort:$.think,scope:$.scope});if(Z.push(...z.lines),!z.ok)J=!1}if($.memory!==void 0){let z=e8({positionals:[],flagMode:$.memory,scope:$.scope});if(Z.push(...z.lines),!z.ok)J=!1}if(console.log(Z.join(`
|
|
48
|
+
`)),!J)process.exitCode=1}var zQ=C(()=>{t5();a5();s5();e5()});function $3($,Z,J){let z=$==="openai"?"openai":$==="ollama"?"ollama":CM(Z)??"provider";return bM(z,J)}function Z3($){let Z=$.trim();if(!Z||Z.includes("/")||Z.includes(":"))return"名称不能为空,且不能包含 / 或 :。";return null}function $7($){if($.length<4)return"****";return`…${$.slice(-4)}`}function GQ($,Z){let J=$.trim().toLowerCase();if(!J)return[...Z];return Z.filter((z)=>z.toLowerCase().includes(J))}function J3($,Z,J){let z=Z3(Z.name);if(z)return{error:z};let G=Z.name.trim(),Q=[...$.providers??[]],Y=Q.findIndex((X)=>X.name===G);if(Y>=0&&!J.overwrite)return{error:`已存在同名服务商 "${G}"。`};let K=YQ(Z,G);if(Y>=0)Q[Y]=K;else Q.push(K);return{...$,providers:Q,activeProvider:G}}function M2($,Z){if(!($.providers??[]).find((z)=>z.name===Z))return{error:`找不到服务商 "${Z}"。`};return{...$,activeProvider:Z}}function QQ($,Z,J){let z=Z3(J.name);if(z)return{error:z};let G=J.name.trim(),Q=[...$.providers??[]],Y=Q.findIndex((X)=>X.name===Z);if(Y<0)return{error:`找不到服务商 "${Z}"。`};if(G!==Z&&Q.some((X)=>X.name===G))return{error:`已存在同名服务商 "${G}"。`};Q[Y]=YQ(J,G);let K=$.activeProvider===Z?G:$.activeProvider;return{...$,providers:Q,activeProvider:K}}function z3($,Z){let J=$.providers??[];if(!J.some((Q)=>Q.name===Z))return{error:`找不到服务商 "${Z}"。`};let z=J.filter((Q)=>Q.name!==Z);if(z.length===0){let{activeProvider:Q,...Y}=$;return{...Y,providers:[]}}let G=$.activeProvider===Z?z[0]?.name:$.activeProvider;return{...$,providers:z,activeProvider:G}}function YQ($,Z){return{name:Z,type:$.type,baseURL:$.baseURL,apiKey:$.apiKey,defaultModel:$.defaultModel,...$.contextWindow!=null?{contextWindow:$.contextWindow}:{}}}function CM($){try{let Z=new URL($).hostname.toLowerCase(),J=Z.startsWith("www.")?Z.slice(4):Z;if(!J)return;return J.replace(/\./g,"-")}catch{return}}function bM($,Z){if(!Z.includes($))return $;let J=2;while(Z.includes(`${$}-${J}`))J+=1;return`${$}-${J}`}function KQ($){if($==="openai-compatible"||$==="openai"||$==="ollama")return $;throw Q1(`Invalid --type value: "${$}"`,"use one of: openai-compatible, openai, ollama")}function XQ($){return[$.type,$.switch,$.remove].filter(Boolean).length}var G3=C(()=>{q$()});function PQ($,Z){return!$&&Z}async function Z7($,Z,J){if(XQ($)>1)throw new e("一次只能执行一种操作。");if(Z2(D8(Z.load()))&&($.type||$.switch||$.remove))throw new e("内置 OpenRouter 服务商已锁定,provider 配置不允许修改。",{hint:"设置 MIN_AGENT_NO_BUILTIN_PROVIDER=1 关闭预设后再配置"});if($.remove){await kM($.remove,$.yes===!0,Z);return}if($.switch){J7(M2(Z.load(),$.switch),Z);return}if($.type){await yM($,Z);return}if(!Z.isTty)throw new e("无法在非交互环境完成配置。",{hint:TM});let z=Z.load(),G=J??(RM(z)?"hub":"first-run");await Z.runWizard(G)}function RM($){let Z=s($);return Boolean(Z?.baseURL&&Z?.apiKey)}async function kM($,Z,J){if(!Z)throw new e("删除需要确认。",{hint:"加上 --yes"});J7(z3(J.load(),$),J)}async function yM($,Z){let J=$.type,z=SM(J,$.url),G=EM(J,$.apiKey),Q=await vM(J,z,G,$.defaultModel,Z.fetchLive),Y=Z.load(),K=(Y.providers??[]).map((q)=>q.name).filter((q)=>Boolean(q)),P={name:($.name?.trim()||$3(J,z,K)).trim(),type:J,baseURL:z,apiKey:G,defaultModel:Q,...$.contextWindow!=null?{contextWindow:$.contextWindow}:{}},W=$.yes===!0,H=J3(Y,P,{overwrite:W});if(WQ(H)&&H.error.startsWith("已存在同名服务商")&&!W)throw new e(H.error,{hint:"加上 --yes 以覆盖"});J7(H,Z)}function SM($,Z){if($==="openai")return wM;if($==="ollama")return O1(Z?.trim()||IM);let J=Z?.trim()??"";if(!J)throw new e("API 地址不能为空。");return J.replace(/\/$/,"")}function EM($,Z){if($==="ollama")return Z?.trim()||"ollama";let J=Z?.trim()??"";if(!J)throw new e("API 密钥不能为空。");return J}async function vM($,Z,J,z,G){let Q=z?.trim()??"";if(Q)return Q;let Y=await G(Z,J);if(Y.models[0])return Y.models[0];if($==="ollama")return"llama3";if(!Y.ok&&Y.status==null)throw j5("无法连接到该服务商。");throw new e("默认模型不能为空。")}function J7($,Z){if(WQ($))throw new e($.error);Z.save($),Z.log(`已保存到 ${Z.configPath()}`)}function WQ($){return Object.keys($).length===1&&"error"in $}var wM="https://api.openai.com/v1",IM="http://localhost:11434/v1",TM="使用 --type、--switch 或 --remove。例如: min-agent setup --type ollama";var z7=C(()=>{l();q$();G3();G3()});var j;var P1=C(()=>{j={inputBorder:"cyan",inputBorderDisabled:"gray",confirmBorder:"blue",pickerBorder:"blue",questionBorder:"blue",accent:"cyan",muted:"gray",tool:"yellow",error:"red",success:"green"}});async function HQ($){let Z=$?.fetchImpl??fetch,J=$?.timeoutMs??gM;try{if(!(await Z(xM,{signal:AbortSignal.timeout(J)})).ok)return{found:!1};return{found:!0,baseURL:O1(uM)}}catch{return{found:!1}}}var xM="http://localhost:11434/api/tags",gM=800,uM="http://localhost:11434/v1";var qQ=C(()=>{l()});var MQ={};M0(MQ,{renderSetupWizard:()=>pM});import{useEffect as K7,useRef as Q3,useState as W1}from"react";import{Box as w1,Text as B0,render as hM,useInput as UQ}from"ink";import mM from"ink-spinner";import nM from"path";import{jsxDEV as i}from"react/jsx-dev-runtime";async function pM($){return new Promise((Z)=>{let J=hM(i(oM,{mode:$,onDone:(z)=>{J.unmount(),Z(z)}},void 0,!1,void 0,this),{exitOnCtrlC:!1})})}function oM({mode:$,onDone:Z}){let[J,z]=W1(()=>{if(Z2(a()))return{id:"hub"};return $==="session-gate"?{id:"gate"}:$==="hub"?{id:"hub"}:{id:"type"}}),[G,Q]=W1(null),[Y,K]=W1({found:!1}),[X,P]=W1(""),[W,H]=W1(0),q=()=>H((B)=>B+1),U=c1(),M=Z2(a()),F=M?a():U,N=()=>Z("aborted"),f=()=>Z("saved");return i(w1,{flexDirection:"column",paddingX:1,paddingY:1,children:[i(B0,{bold:!0,color:j.accent,children:"配置服务商"},void 0,!1,void 0,this),J.id==="gate"&&i(F2,{items:[{label:"开始配置",value:"start"},{label:"退出",value:"exit"}],onSelect:(B)=>{if(B==="exit")Z("aborted");else z({id:"type"})},onCancel:()=>Z("aborted")},void 0,!1,void 0,this),J.id==="hub"&&i(dM,{config:F,locked:M,onAdd:()=>{Q({fromHub:!0,type:"openai-compatible",baseURL:Y7,apiKey:"",defaultModel:"",name:""}),P(""),z({id:"type"})},onPick:(B)=>{let _=U.providers??[];if(B==="switch"&&_.length<=1){z({id:"message",text:"当前只有一个服务商,无需切换。",back:"hub"});return}z({id:"pick",action:B})},onDone:f},void 0,!1,void 0,this),J.id==="pick"&&i(rM,{config:F,onCancel:()=>z({id:"hub"}),onSelect:(B)=>{let _=B.name??"";if(J.action==="switch"){let V=M2(U,_);if(Q7(V)){z({id:"message",text:V.error,back:"hub"});return}R0(V),G7(),q(),z({id:"hub"});return}if(J.action==="delete"){z({id:"delete-confirm",name:_});return}if(J.action==="test"){(async()=>{let V=await L4(B.baseURL,B.apiKey);if(V.ok&&V.models.length>0){z({id:"message",text:`可访问,${V.models.length} 个模型`,back:"hub"});return}let A=V.status!=null?`HTTP ${V.status}。`:"",O=B.type==="ollama"?"请确认 Ollama 已启动。":"请检查 API 地址和密钥。";z({id:"message",text:zF(`无法连接到该服务商。${A}${O}`),back:"hub"})})();return}Q($F(B,!0)),P(""),z({id:"type"})}},void 0,!1,void 0,this),J.id==="delete-confirm"&&i(F2,{title:`确定删除服务商 "${J.name}"?`,items:[{label:"删除",value:"yes"},{label:"取消",value:"no"}],onSelect:(B)=>{if(B!=="yes"){z({id:"hub"});return}let _=z3(c1(),J.name);if(Q7(_)){z({id:"message",text:_.error,back:"hub"});return}R0(_),G7(),q(),z({id:"hub"})},onCancel:()=>z({id:"hub"})},void 0,!1,void 0,this),J.id==="message"&&i(sM,{text:J.text,onClose:()=>{if(J.back==="exit-saved")f();else z({id:"hub"})}},void 0,!1,void 0,this),J.id==="type"&&i(lM,{detected:Y,onDetected:K,initial:G?.type,onCancel:()=>{if(G?.fromHub||$==="hub")z({id:"hub"});else N()},onSelect:(B)=>{let _=eM(B,G,Y);if(Q(_),P(""),B==="openai")z({id:"key"});else z({id:"url"})}},void 0,!1,void 0,this),J.id==="url"&&G&&i(U6,{label:G.type==="ollama"?"Ollama 地址":"API 地址",value:G.baseURL,error:X,onChange:(B)=>Q({...G,baseURL:B}),onCancel:()=>{P(""),z({id:"type"})},onSubmit:()=>{let B=G.baseURL.trim();if(!B){P("API 地址不能为空。");return}let _=G.type==="ollama"?O1(B):B.replace(/\/$/,"");if(Q({...G,baseURL:_}),P(""),G.type==="ollama")z({id:"fetch"});else z({id:"key"})}},"url",!1,void 0,this),J.id==="key"&&G&&i(U6,{label:"API 密钥",value:G.apiKey,mask:!0,placeholder:G.existingKey?`已保存 (${$7(G.existingKey)}),回车保留`:"在此输入 API 密钥",error:X,onChange:(B)=>Q({...G,apiKey:B}),onCancel:()=>{if(P(""),G.type==="openai")z({id:"type"});else z({id:"url"})},onSubmit:()=>{if(!G.apiKey.trim()&&G.existingKey){Q({...G,apiKey:G.existingKey}),P(""),z({id:"fetch"});return}if(!G.apiKey.trim()){P("API 密钥不能为空。");return}P(""),z({id:"fetch"})}},"key",!1,void 0,this),J.id==="fetch"&&G&&i(iM,{draft:G,onBack:()=>z(G.type==="ollama"?{id:"url"}:{id:"key"}),onList:(B)=>{Q({...G,models:B}),P(""),z({id:"models",models:B})},onEmpty:()=>{P(""),z({id:"model-manual"})}},void 0,!1,void 0,this),J.id==="models"&&G&&i(tM,{models:J.models,current:G.defaultModel,onCancel:()=>z(G.type==="openai"?{id:"key"}:{id:"url"}),onSelect:(B)=>{Q({...G,defaultModel:B}),P(""),z({id:"name"})}},void 0,!1,void 0,this),J.id==="model-manual"&&G&&i(U6,{label:"无法获取模型列表,请手动输入默认模型",value:G.defaultModel,placeholder:"例如 gpt-4o、deepseek-chat",error:X,onChange:(B)=>Q({...G,defaultModel:B}),onCancel:()=>z(G.type==="openai"?{id:"key"}:{id:"url"}),onSubmit:()=>{if(!G.defaultModel.trim()){P("默认模型不能为空。");return}if(P(""),G.type==="openai-compatible")z({id:"context"});else z({id:"name"})}},"model-manual",!1,void 0,this),J.id==="context"&&G&&i(U6,{label:"上下文窗口(token,回车跳过)",value:G.contextWindow!=null?String(G.contextWindow):"",placeholder:"例如 128000(留空使用默认)",error:X,onChange:(B)=>{let _=B.trim();if(!_){Q({...G,contextWindow:void 0});return}let V=Number.parseInt(_,10);Q({...G,contextWindow:Number.isFinite(V)?V:void 0})},onCancel:()=>z({id:"model-manual"}),onSubmit:(B)=>{let _=B.trim();if(!_){Q({...G,contextWindow:void 0}),P(""),z({id:"name"});return}let V=Number.parseInt(_,10);if(!Number.isFinite(V)||V<=0){P("上下文窗口必须是大于 0 的整数。");return}Q({...G,contextWindow:V}),P(""),z({id:"name"})}},"context",!1,void 0,this),J.id==="name"&&G&&i(U6,{label:"名称",value:G.name,placeholder:"给这个服务商起个名字",error:X,onChange:(B)=>Q({...G,name:B}),onCancel:()=>{if(G.models&&G.models.length>0)z({id:"models",models:G.models});else z({id:"model-manual"})},onSubmit:()=>{let B=Z3(G.name);if(B){P(B);return}P(""),z({id:"summary"})}},"name",!1,void 0,this),J.id==="summary"&&G&&i(aM,{draft:G,error:X,onCancel:()=>z({id:"name"}),onConfirm:()=>{let B=ZF(G);if(Q7(B)){P(B.error),z({id:"name"});return}if(R0(B),G7(),G.fromHub||$==="hub"){q(),Q(null),z({id:"hub"});return}Z("saved")}},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function dM({config:$,locked:Z,onAdd:J,onPick:z,onDone:G}){let Q=$.providers??[],Y=Z?[{label:"测试连接",value:"test"},{label:"完成",value:"done"}]:[{label:"添加",value:"add"},{label:"设为当前",value:"switch"},{label:"修改",value:"edit"},{label:"删除",value:"delete"},{label:"测试连接",value:"test"},{label:"完成",value:"done"}];return i(w1,{flexDirection:"column",children:[Q.map((K)=>i(B0,{color:K.name===$.activeProvider?j.accent:j.muted,children:[K.name===$.activeProvider?"* ":" ",K.name??"(未命名)"," ",K.baseURL," ",K.defaultModel??"未设置模型"]},K.name??K.baseURL,!0,void 0,this)),Z&&i(B0,{color:j.muted,children:["内置 OpenRouter 服务商(",Q[0]?.defaultModel??"",")已锁定,不可修改或添加其它服务商。"]},void 0,!0,void 0,this),i(F2,{items:Y,onSelect:(K)=>{if(K==="add")J();else if(K==="done")G();else z(K)},onCancel:G},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function rM({config:$,onSelect:Z,onCancel:J}){let z=$.providers??[],G=s($)?.name;return i(F2,{items:z.map((Q)=>({label:`${Q.name??"(未命名)"}${Q.name===G?" *":""} ${Q.baseURL}`,value:Q.name??""})),initial:Math.max(0,z.findIndex((Q)=>Q.name===G)),onSelect:(Q)=>{let Y=z.find((K)=>K.name===Q);if(Y)Z(Y)},onCancel:J},void 0,!1,void 0,this)}function lM({detected:$,onDetected:Z,initial:J,onSelect:z,onCancel:G}){K7(()=>{let K=!1;return HQ().then((X)=>{if(!K)Z(X)}),()=>{K=!0}},[Z]);let Q=[{label:"OpenAI 兼容接口",hint:"OpenRouter、DeepSeek、Groq 等",value:"openai-compatible"},{label:"OpenAI",hint:"官方接口",value:"openai"},{label:"Ollama(本地)",hint:$.found?"已检测到":"本机模型",value:"ollama"}],Y=J==="openai"?1:J==="ollama"?2:$.found&&!J?2:0;return i(F2,{items:Q,initial:Y,onSelect:(K)=>z(K),onCancel:G},`${J??"auto"}-${$.found?"detected":"plain"}`,!1,void 0,this)}function iM({draft:$,onList:Z,onEmpty:J,onBack:z}){let G=Q3(Z),Q=Q3(J);return G.current=Z,Q.current=J,UQ((Y,K)=>{if(K.escape)z()}),K7(()=>{let Y=!1;return L4($.baseURL,$.apiKey||"ollama").then((K)=>{if(Y)return;if(K.ok&&K.models.length>0)G.current(K.models);else Q.current()}),()=>{Y=!0}},[$.apiKey,$.baseURL]),i(w1,{children:[i(B0,{color:j.accent,children:i(mM,{type:"dots"},void 0,!1,void 0,this)},void 0,!1,void 0,this),i(B0,{color:j.muted,children:" 正在获取模型列表…"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function tM({models:$,current:Z,onSelect:J,onCancel:z}){let[G,Q]=W1(""),[Y,K]=W1(0),X=GQ(G,$),P=G.trim();Y3((M,F,N)=>{if(F.escape){z();return}if(F.downArrow&&X.length>0){K((B)=>(B+1)%X.length);return}if(F.upArrow&&X.length>0){K((B)=>(B-1+X.length)%X.length);return}if(N){if(X.length>0)J(X[Math.min(Y,X.length-1)]);else if(P)J(P);return}if(F.backspace||F.delete){Q((B)=>Array.from(B).slice(0,-1).join("")),K(0);return}if(F.ctrl||F.meta||F.tab)return;let f=M.replace(/[\r\n]+$/,"");if(f)Q((B)=>B+f),K(0)});let W=Math.min(Y,Math.max(0,X.length-1)),H=12,q=Math.min(W,Math.max(0,X.length-H)),U=X.slice(q,q+H);return i(w1,{flexDirection:"column",children:[i(B0,{color:j.muted,children:"输入可筛选"},void 0,!1,void 0,this),i(B0,{color:G?j.accent:j.muted,children:G||" "},void 0,!1,void 0,this),U.map((M,F)=>{let N=q+F===W;return i(B0,{color:N?j.accent:void 0,bold:N,children:[N?"▸ ":" ",M,M===Z?" ← 当前":""]},M,!0,void 0,this)}),X.length===0&&P!==""&&i(B0,{color:j.accent,children:["▸ 使用自定义模型: ",P]},void 0,!0,void 0,this),i(B0,{color:j.muted,children:"↑↓ 选择 · Enter 确认 · Esc 返回"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function U6({label:$,value:Z,mask:J,placeholder:z,error:G,onChange:Q,onSubmit:Y,onCancel:K}){let[X,P]=W1(!1),W=()=>{if(!X)P(!0)};Y3((M,F,N)=>{if(F.escape){K();return}if(N){Y(Z);return}if(F.backspace||F.delete){W(),Q(Array.from(Z).slice(0,-1).join(""));return}if(F.ctrl||F.meta||F.tab)return;let f=M.replace(/[\r\n]+$/,"");if(f)W(),Q(Z+f)});let H=Z.length>0,q=H?J?"*".repeat(Array.from(Z).length):Z:z||"",U=H&&X?void 0:j.muted;return i(w1,{flexDirection:"column",children:[i(B0,{children:$},void 0,!1,void 0,this),i(w1,{borderStyle:"round",borderColor:j.inputBorder,paddingX:1,children:[i(B0,{color:U,children:q},void 0,!1,void 0,this),i(B0,{inverse:!0,children:" "},void 0,!1,void 0,this)]},void 0,!0,void 0,this),G?i(B0,{color:j.error,children:G},void 0,!1,void 0,this):null,i(B0,{color:j.muted,children:"Enter 确认 · Esc 返回"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function aM({draft:$,error:Z,onConfirm:J,onCancel:z}){return i(w1,{flexDirection:"column",children:[i(B0,{children:["类型 ",JF($.type)]},void 0,!0,void 0,this),i(B0,{children:["地址 ",$.baseURL]},void 0,!0,void 0,this),i(B0,{children:["密钥 ",$7($.apiKey)]},void 0,!0,void 0,this),i(B0,{children:["模型 ",$.defaultModel]},void 0,!0,void 0,this),i(B0,{children:["名称 ",$.name.trim()]},void 0,!0,void 0,this),Z?i(B0,{color:j.error,children:Z},void 0,!1,void 0,this):null,i(F2,{items:[{label:"保存",value:"save"},{label:"返回",value:"back"}],onSelect:(G)=>{if(G==="save")J();else z()},onCancel:z},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function sM({text:$,onClose:Z}){return Y3((J,z,G)=>{if(z.escape||G)Z()}),i(w1,{flexDirection:"column",children:[i(B0,{children:$},void 0,!1,void 0,this),i(B0,{color:j.muted,children:"Enter / Esc 继续"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function F2({title:$,items:Z,initial:J=0,onSelect:z,onCancel:G}){let[Q,Y]=W1(Math.min(Math.max(0,J),Math.max(0,Z.length-1))),[K,X]=W1("");return Y3((P,W,H)=>{if(W.escape){G();return}if(Z.length===0)return;if(W.downArrow){X(""),Y((M)=>(M+1)%Z.length);return}if(W.upArrow){X(""),Y((M)=>(M-1+Z.length)%Z.length);return}if(W.backspace||W.delete){X((M)=>M.slice(0,-1));return}let q=()=>{let M=K?Number.parseInt(K,10):NaN;if(Number.isFinite(M)&&M>=1&&M<=Z.length)return z(Z[M-1].value),!0;return!1};if(H){if(!q())z(Z[Q].value);return}if(P===" "){if(!q())z(Z[Q].value);return}if(W.ctrl||W.meta||W.tab)return;let U=P.replace(/[\r\n]+$/,"");if(U&&/^[0-9]$/.test(U)){let M=K+U,F=Number.parseInt(M,10);if(Number.isFinite(F)&&F>=1&&F<=Z.length)X(M),Y(F-1);else if(Number.isFinite(F)&&F>Z.length){X(U);let N=Number.parseInt(U,10);if(Number.isFinite(N)&&N>=1&&N<=Z.length)Y(N-1)}}}),i(w1,{flexDirection:"column",children:[$?i(B0,{children:$},void 0,!1,void 0,this):null,Z.map((P,W)=>i(B0,{color:W===Q?j.accent:void 0,bold:W===Q,children:[W===Q?"▸ ":" ",W+1,". ",P.label,P.hint?i(B0,{color:j.muted,children:[" ",P.hint]},void 0,!0,void 0,this):null]},P.value,!0,void 0,this)),K?i(B0,{color:j.accent,children:["输入: ",K]},void 0,!0,void 0,this):null,i(B0,{color:j.muted,children:"↑↓ 选择 · 数字键跳转 · Enter/空格 确认 · Esc 返回"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function Y3($){let Z=Q3(!1),J=Q3($);J.current=$,K7(()=>{let z=setTimeout(()=>{Z.current=!0},0);return()=>clearTimeout(z)},[]),UQ((z,G)=>{let Q=G.return||/[\r\n]+$/.test(z);if(Q&&!Z.current)return;J.current(z,G,Q)})}function eM($,Z,J){let z=Z?.fromHub===!0||Z?.editingName!=null,G=Z?.editingName;if($==="openai")return{fromHub:z,editingName:G,type:$,baseURL:Y7,apiKey:"",existingKey:Z?.type==="openai"?Z.existingKey??Z.apiKey:Z?.existingKey,defaultModel:Z?.type==="openai"?Z.defaultModel:"",name:Z?.name??""};if($==="ollama")return{fromHub:z,editingName:G,type:$,baseURL:J.baseURL||Z?.baseURL||cM,apiKey:"ollama",defaultModel:Z?.type==="ollama"?Z.defaultModel:"llama3",name:Z?.name??""};return{fromHub:z,editingName:G,type:$,baseURL:Z?.type==="openai-compatible"?Z.baseURL:Y7,apiKey:"",existingKey:Z?.existingKey,defaultModel:Z?.defaultModel??"",name:Z?.name??""}}function $F($,Z){let J=$.type??"openai-compatible";return{fromHub:Z,editingName:$.name,type:J,baseURL:$.baseURL,apiKey:"",existingKey:$.apiKey,defaultModel:$.defaultModel??"",contextWindow:$.contextWindow,name:$.name??""}}function ZF($){let Z=c1(),J=(Z.providers??[]).map((Q)=>Q.name).filter((Q)=>Boolean(Q)),G={name:$.name.trim()||$3($.type,$.baseURL,J.filter((Q)=>Q!==$.editingName)),type:$.type,baseURL:$.baseURL,apiKey:$.apiKey||$.existingKey||($.type==="ollama"?"ollama":""),defaultModel:$.defaultModel.trim(),...$.contextWindow!=null?{contextWindow:$.contextWindow}:{}};if($.editingName)return QQ(Z,$.editingName,G);return J3(Z,G,{overwrite:!1})}function JF($){if($==="openai")return"OpenAI";if($==="ollama")return"Ollama";return"OpenAI 兼容接口"}function G7(){console.log(`已保存到 ${nM.join(P0(),"config.json")}`)}function zF($){return $.replace(/Bearer\s+\S+/gi,"Bearer ****").replace(/\bsk-[A-Za-z0-9_-]+/g,"sk-****")}function Q7($){return Object.keys($).length===1&&"error"in $}var Y7="https://api.openai.com/v1",cM="http://localhost:11434/v1";var FQ=C(()=>{l();P1();qQ()});var fQ={};M0(fQ,{runSetupCommand:()=>VQ,registerSetupCommand:()=>X7,offerInteractiveSetup:()=>QF});import GF from"path";import{Option as NQ}from"commander";function X7($,Z){$.command("setup").description("configure providers (interactively, or with flags)").addOption(new NQ("--type <type>","openai-compatible, openai, or ollama").argParser(KQ)).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 NQ("--context-window <n>","context window in tokens").argParser(Q6("--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(J)=>{await VQ(J,{yes:Boolean(J.yes||Z().yes)})})}function BQ(){return{isTty:Boolean(process.stdin.isTTY&&process.stdout.isTTY),load:c1,save:R0,fetchLive:L4,log:($)=>{console.log($)},configPath:()=>GF.join(P0(),"config.json"),runWizard:async($)=>{let{renderSetupWizard:Z}=await Promise.resolve().then(() => (FQ(),MQ));return Z($)}}}async function QF($){await Z7({},{...BQ(),isTty:!0},$)}async function VQ($,Z){let J={type:$.type,url:$.url,apiKey:$.apiKey,name:$.name,defaultModel:$.defaultModel,contextWindow:$.contextWindow,switch:$.switch,remove:$.remove,yes:Boolean(Z.yes||$.yes)};await Z7(J,BQ())}var P7=C(()=>{l();v8();G3();z7()});import{Box as YF,Text as _Q}from"ink";import KF from"ink-spinner";import{jsxDEV as K3}from"react/jsx-dev-runtime";function LQ({label:$}){return K3(YF,{children:[K3(_Q,{color:"cyan",children:K3(KF,{type:"dots"},void 0,!1,void 0,this)},void 0,!1,void 0,this),$&&K3(_Q,{color:"gray",children:[" ",$]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var jQ=()=>{};function w4($){AQ=$}function DQ($){let Z=0,J=(z,G,Q)=>{let Y=Buffer?.isBuffer(z),K;if(typeof z==="string")K=z;else if(Y)K=z.toString(G||"utf-8");else if(z!=null)K=String(z);else return $.write(z,G,Q);let X="";if(Z>0)X+=`\x1B[${Z}B\r`,Z=0;X+=K;let P=AQ;if(P){let H=P.rowsAbove+(K.endsWith(`
|
|
49
|
+
`)?1:0);if(H>0)X+=`\x1B[${H}A\x1B[${P.column}G`,Z=H}let W=typeof z==="string"?X:Buffer.from(X,G||"utf-8");return $.write(W,G,Q)};return new Proxy($,{get(z,G){if(G==="write")return J;let Q=Reflect.get(z,G,z);return typeof Q==="function"?Q.bind(z):Q},set(z,G,Q){return Reflect.set(z,G,Q,z)}})}var AQ=null;function PF($){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 WF($){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 HF($){let Z=$.codePointAt(0);if(Z===void 0)return 0;if(Z<32||Z>=127&&Z<160)return 0;if(PF(Z))return 0;if(WF(Z)||OQ.test($))return 2;return 1}function qF($){if($.length===0)return 0;if(OQ.test($)||$.includes(""))return 2;let Z=0;for(let J of $)Z+=HF(J);return $.includes("️")?Math.max(Z,2):Z}function*b$($,Z){for(let{segment:J}of XF.segment($))yield{text:J,width:Z?.(J)??qF(J)}}function A0($,Z){let J=0;for(let{width:z}of b$($,Z))J+=z;return J}function a0($,Z,J){let z=typeof $==="string"?$:$==null?"":String($);if(Z<1)return[z];let G=[],Q="",Y=0;for(let{text:K,width:X}of b$(z,J)){if(Y+X>Z&&Q.length>0)G.push(Q),Q="",Y=0;Q+=K,Y+=X}return G.push(Q),G}var XF,OQ;var H1=C(()=>{XF=new Intl.Segmenter(void 0,{granularity:"grapheme"}),OQ=/\p{Extended_Pictographic}/u});function W7($,Z,J){let z=[],G=0,Q=$.split(`
|
|
50
|
+
`);for(let Y=0;Y<Q.length;Y++){for(let K of a0(Q[Y],Z,J))z.push({text:K,startIndex:G}),G+=Array.from(K).length;if(Y<Q.length-1)G+=1}return z}function I4($,Z,J){let z=Array.from($).length;return Math.min(Math.max(Z+J,0),z)}function H7($,Z,J,z,G){let Q=$[Z];if(!Q)return 0;let Y=J-z;if(Y<=0)return Q.startIndex;let K=0,X=0;for(let{text:P,width:W}of b$(Q.text,G)){if(K+W>Y){if(G?.(P)!==void 0)return Q.startIndex+X;return Q.startIndex+X+(Y-K<W/2?0:Array.from(P).length)}K+=W,X+=Array.from(P).length}return Q.startIndex+X}function z$($,Z,J){let z=Array.from($);return z.splice(Z,0,...Array.from(J)),{value:z.join(""),caretIndex:Z+Array.from(J).length}}function N2($,Z){if(Z<=0)return{value:$,caretIndex:Z};let J=Array.from($);return J.splice(Z-1,1),{value:J.join(""),caretIndex:Z-1}}function bQ($,Z){let J=Array.from($);if(Z>=J.length)return{value:$,caretIndex:Z};return J.splice(Z,1),{value:J.join(""),caretIndex:Z}}function q7($,Z,J,z,G){let Q=W7($,z,G),Y=0,K=0;for(let W=0;W<Q.length;W++){let H=Q[W],q=H.startIndex+Array.from(H.text).length;if(Z>=H.startIndex&&Z<=q){Y=W,K=Z-H.startIndex;break}if(W===Q.length-1)Y=W,K=Array.from(H.text).length}let X=Y+J;if(X<0||X>=Q.length)return Z;let P=A0(Array.from(Q[Y].text).slice(0,K).join(""),G);return H7(Q,X,P,0,G)}function M6($,Z){let J=Array.from($),z=Z-1;while(z>=0&&J[z]!==`
|
|
51
|
+
`)z--;return z+1}function F6($,Z){let J=Array.from($),z=Z;while(z<J.length&&J[z]!==`
|
|
52
|
+
`)z++;return z}function wQ($,Z){let J=M6($,Z);if(J===Z)return{value:$,caretIndex:Z};let z=Array.from($);return z.splice(J,Z-J),{value:z.join(""),caretIndex:J}}function IQ($,Z){let J=F6($,Z);if(J===Z)return{value:$,caretIndex:Z};let z=Array.from($);return z.splice(Z,J-Z),{value:z.join(""),caretIndex:Z}}function TQ($,Z){if(Z<=0)return{value:$,caretIndex:Z};let J=Array.from($),z=Z-1;while(z>=0&&/\s/.test(J[z]))z--;while(z>=0&&!/\s/.test(J[z]))z--;let G=z+1;return J.splice(G,Z-G),{value:J.join(""),caretIndex:G}}function RQ($,Z){let J=$+Z,z=[],G=/\x1b\[3(?:;\d+)?[~$^]|\x7f/g,Q=0,Y;while(Y=G.exec(J))Q=Y.index+Y[0].length,z.push(Y[0]===""?{kind:"backspace"}:{kind:"delete"});let K=J.slice(Q),X=K.lastIndexOf("\x1B");if(X===-1)return{buffer:"",actions:z};let P=K.slice(X);return{buffer:P.length>UF?"\x1B":P,actions:z}}function kQ($,Z){let J=$+Z,z=[],G=0;CQ.lastIndex=0;let Q;while(Q=CQ.exec(J)){G=Q.index+Q[0].length;let P=Q[0];z.push(P.endsWith("H")||P.endsWith("1~")||P.endsWith("7~")?{kind:"home"}:{kind:"end"})}let Y=J.slice(G),K=Y.lastIndexOf("\x1B");if(K===-1)return{buffer:"",actions:z};let X=Y.slice(K);return{buffer:X.length>MF?"\x1B":X,actions:z}}var UF=32,CQ,MF=8;var U7=C(()=>{H1();CQ=/\x1b\[(?:[HF]|[1478]~)/g});import{existsSync as FF,mkdirSync as NF,readFileSync as BF,renameSync as VF}from"fs";import SQ from"path";function EQ(){return SQ.join(P0(),"input-history.json")}function vQ($=[]){return{entries:$,index:-1,draft:""}}function fF($){let Z;try{Z=JSON.parse($)}catch{return null}if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;let J=Z.entries;if(!Array.isArray(J)||J.some((z)=>typeof z!=="string"))return null;return J}function _F($){return JSON.stringify({entries:$},null,2)}function LF($){if(!FF($))return[];let Z;try{Z=BF($,"utf-8")}catch{return[]}let J=fF(Z);if(J)return J;try{VF($,`${$}.corrupt-${Date.now()}`)}catch{}return[]}function jF($,Z){try{NF(SQ.dirname($),{recursive:!0}),T0($,_F(Z))}catch{}}function xQ(){return LF(EQ())}function M7($){jF(EQ(),$)}function F7($,Z){if(!Z)return $;if($.entries.length>0&&$.entries[$.entries.length-1]===Z)return $;let J=[...$.entries,Z];if(J.length>yQ)J.splice(0,J.length-yQ);return{entries:J,index:-1,draft:""}}function gQ($,Z){let J=Z.toLowerCase();if(!J)return null;for(let z=$.entries.length-1;z>=0;z--)if($.entries[z].toLowerCase().includes(J))return $.entries[z];return null}function uQ($,Z,J){let z=$.entries.length;if(z===0)return{text:$.draft,state:$};let G=z-1,Q=(K)=>K>=0&&K<=G&&!J?.($.entries[K]),Y=$.index===-1?-1:Math.max(0,Math.min(G,$.index));if(Z===1){let K=Y===-1?G:Y-1;for(let X=K;X>=0;X--)if(Q(X))return{text:$.entries[X],state:{...$,index:X}};if(Y!==-1)return{text:$.entries[Y],state:$};return{text:$.draft,state:$}}if(Y===-1)return{text:$.draft,state:$};for(let K=Y+1;K<=G;K++)if(Q(K))return{text:$.entries[K],state:{...$,index:K}};return{text:$.draft,state:{...$,index:-1}}}function N7($,Z){if($.index===-1&&$.draft===Z)return $;return{entries:$.entries,index:-1,draft:Z}}function X3($,Z){return Z.ctrl===!0&&$==="c"||$==="\x03"}function hQ($,Z,J=null,z=0){if(Z===""){if(J!==null&&z-J<=B7)return{state:$,value:"",exit:!0,armedAt:null};return{state:$,value:"",exit:!1,armedAt:z}}return{state:Z.trim()?F7($,Z):{entries:$.entries,index:-1,draft:""},value:"",exit:!1,armedAt:null}}var yQ=1000,B7=2000;var V7=C(()=>{l();L$()});var nQ={};M0(nQ,{slashMenuWindow:()=>W3,setSlashArgProvider:()=>S$,sessionSlashCommands:()=>_7,parseSlashArgs:()=>mQ,isKnownSlashCommandInput:()=>L7,getSlashArgOptions:()=>A7,filterSlashCommands:()=>f7,clearSlashArgProviders:()=>AF,applySlashArgCompletion:()=>D7,SLASH_COMMANDS:()=>P3});function f7($,Z=P3){let J=$.slice(1).trim().toLowerCase();if(J==="")return Z;return Z.filter((z)=>z.name.startsWith(J)||(z.aliases??[]).some((G)=>G.startsWith(J)))}function _7($,Z=P3){if($==="ollama")return Z;return Z.filter((J)=>J.name!=="ctx")}function W3($,Z,J){let z=Number.isFinite(J)?Math.max(1,Math.floor(J)):Math.max(1,$.length),G=$.length===0?0:Math.min(Math.max(0,Z),$.length-1);if($.length<=z)return{start:0,shown:[...$],extraAbove:0,extraBelow:0};let Q=Math.max(0,Math.min(G-z+1,$.length-z)),Y=$.slice(Q,Q+z);return{start:Q,shown:Y,extraAbove:Q,extraBelow:$.length-(Q+Y.length)}}function L7($,Z=P3){if(!$.startsWith("/"))return!1;let J=$.slice(1).trim().split(/\s/,1)[0]?.toLowerCase()??"";if(!J)return!0;return Z.some((z)=>z.name===J||(z.aliases??[]).some((G)=>G===J))}function S$($,Z){j7.set($,Z)}function AF(){j7.clear()}function DF($){let Z=[],J="",z=null;for(let G of $)if(z)if(G===z)z=null;else J+=G;else if(G==='"'||G==="'")z=G;else if(/\s/.test(G)){if(J)Z.push(J),J=""}else J+=G;if(J)Z.push(J);return Z}function mQ($){if(!$.startsWith("/"))return null;let Z=$.slice(1);if(!/\s/.test(Z))return null;let J=DF(Z.trim()),z=J[0]??"",G=J.slice(1),Q=/\s$/.test(Z)?"":G.pop()??"";return{command:z,tokens:G,partial:Q}}function A7($){let Z=mQ($);if(!Z)return[];let J=j7.get(Z.command);if(!J)return[];let z=Z.partial.toLowerCase();return J(Z.tokens,Z.partial).filter((G)=>G.value.toLowerCase().startsWith(z))}function D7($,Z){return/\s$/.test($)?`${$}${Z} `:`${$.replace(/\S+$/,Z)} `}var P3,j7;var H3=C(()=>{P3=[{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"]}];j7=new Map});function q3($){let Z=$.match(OF);if(!Z)return null;return{event:{button:parseInt(Z[1],10),col:parseInt(Z[2],10),row:parseInt(Z[3],10),press:Z[4]==="M"},rest:$.slice((Z.index??0)+Z[0].length)}}var cQ="\x1B[?1000h\x1B[?1002h\x1B[?1006h",pQ="\x1B[?1000l\x1B[?1002l\x1B[?1006l",OF,N6=64,O7=65,B2=32,oQ=31;var B6=C(()=>{OF=/\x1b\[<(\d+);(\d+);(\d+)([Mm])/});function M3($){return $?5:5}function dQ($){if($<=0)return 0;return Math.max(1,$-CF)}function F3($){return Math.max(1,$-5)}function rQ($){return Math.max(1,$-1-2)}function N3($){return Math.max(8,$-4-2)}function lQ($,Z,J){if($<=0)return;return Math.max(2,$-Z-2-J)}function f6($,Z){if($<=0)return Number.POSITIVE_INFINITY;return Math.max(Z,$-2-2)}function iQ($,Z){return Math.max(1,$)+Math.max(0,Z)+2}function tQ($,Z,J,z){let G=J>0?J+5:z>0?z+4:0;return iQ($,Z)+G}function I7($,Z,J,z){let G=f6($,3);if(!Number.isFinite(G))return Number.POSITIVE_INFINITY;return Math.max(4,G-iQ(Z,J)-z)}function s0($,Z,J){if(Z<=0)return{start:0,lines:[],above:0,below:$.length};if($.length<=Z)return{start:0,lines:$,above:0,below:0};let z=0,G=0,Q=0,Y=Z;for(let K=0;K<3;K++){let X=(z>0?1:0)+(G>0?1:0);Y=Math.max(1,Z-X);let P=Math.max(0,$.length-Y);Q=Math.max(0,Math.min(J,P)),z=Q,G=Math.max(0,$.length-(Q+Y))}return{start:Q,lines:$.slice(Q,Q+Y),above:z,below:G}}var C7=5,V6=3,b7=5,w7=4,U3=6,CF=1;var sQ={};M0(sQ,{writeClipboard:()=>k7,getClipboardImage:()=>R7});import{execSync as I1}from"child_process";import{readFileSync as bF,unlinkSync as wF}from"fs";import IF from"path";import TF from"os";function T7($){let Z=bF($);try{wF($)}catch{}return Z.length>0?Z:null}function aQ(){return IF.join(TF.tmpdir(),`min-agent-paste-${Date.now()}.png`)}function R7(){switch(process.platform){case"darwin":return RF();case"linux":return kF();case"win32":return yF();default:return null}}function k7($){switch(process.platform){case"darwin":try{return I1("pbcopy",{input:$,stdio:"pipe"}),!0}catch{return!1}case"linux":{try{return I1("xclip -selection clipboard",{input:$,stdio:"pipe"}),!0}catch{}try{return I1("xsel --clipboard --input",{input:$,stdio:"pipe"}),!0}catch{}return!1}case"win32":try{return I1('powershell -NoProfile -Command "Set-Clipboard -Value ([Console]::In.ReadToEnd())"',{input:$,stdio:"pipe"}),!0}catch{return!1}default:return!1}}function RF(){let $=aQ();try{I1(`pngpaste "${$}" 2>/dev/null`,{stdio:"pipe"});let Z=T7($);if(Z)return{data:Z,mimeType:"image/png"}}catch{}try{let Z=`
|
|
52
53
|
set tmpFile to POSIX file "${$}"
|
|
53
54
|
try
|
|
54
55
|
set imgData to the clipboard as «class PNGf»
|
|
@@ -59,47 +60,47 @@ ${f.join(`
|
|
|
59
60
|
on error
|
|
60
61
|
return "no_image"
|
|
61
62
|
end try
|
|
62
|
-
`;if(
|
|
63
|
+
`;if(I1(`osascript -e '${Z.replace(/'/g,"'\\''")}'`,{encoding:"utf-8"}).trim()==="ok"){let z=T7($);if(z)return{data:z,mimeType:"image/png"}}}catch{}return null}function kF(){try{let $=I1("xclip -selection clipboard -t image/png -o 2>/dev/null",{maxBuffer:10485760});if($.length>0)return{data:$,mimeType:"image/png"}}catch{}try{let $=I1("xsel --clipboard --output 2>/dev/null",{maxBuffer:10485760});if($.length>8&&$[0]===137&&$[1]===80)return{data:$,mimeType:"image/png"}}catch{}return null}function yF(){let $=aQ();try{let Z=`
|
|
63
64
|
Add-Type -AssemblyName System.Windows.Forms
|
|
64
65
|
$img = [System.Windows.Forms.Clipboard]::GetImage()
|
|
65
66
|
if ($img) { $img.Save('${$.replace(/\\/g,"\\\\")}', [System.Drawing.Imaging.ImageFormat]::Png); Write-Output 'ok' }
|
|
66
67
|
else { Write-Output 'no_image' }
|
|
67
|
-
`;if(
|
|
68
|
+
`;if(I1(`powershell -NoProfile -Command "${Z}"`,{encoding:"utf-8"}).trim()==="ok"){let z=T7($);if(z)return{data:z,mimeType:"image/png"}}}catch{}return null}var B3=()=>{};function ZY($,Z){let J=[],z=$+Z;while(!0){let G=z.indexOf("\x1B[200~");if(G===-1)return{buffer:J.length>0?z:SF(z),pastes:J,active:!1};let Q=z.slice(G+6),Y=Q.indexOf("\x1B[201~");if(Y===-1)return{buffer:"\x1B[200~"+Q,pastes:J,active:!0};J.push(Q.slice(0,Y)),z=Q.slice(Y+6)}}function JY($,Z){if(Z)return!0;return $.includes("\x1B[200~")||$.includes("\x1B[201~")||$.includes("[200~")||$.includes("[201~")}function SF($){let Z=$.lastIndexOf("\x1B");if(Z===-1)return"";let J=$.slice(Z);return"\x1B[200~".startsWith(J)?J:""}var eQ="\x1B[?2004h",$Y="\x1B[?2004l";function S7(){return{nextCodePoint:EF,nextImageId:1,nextSnippetId:1,attachments:new Map}}function V3(){return S7()}function nF($){return`[图片 #${$}]`}function cF($,Z){return`[粘贴 #${$} · ${Z} 行]`}function pF($){let Z=$.replace(/\r\n/g,`
|
|
68
69
|
`).replace(/\r/g,`
|
|
69
|
-
`);return
|
|
70
|
-
`)?
|
|
71
|
-
`))return{kind:"text",text:
|
|
72
|
-
`).length});return{kind:"snippet",char:z,draft:
|
|
73
|
-
${
|
|
74
|
-
--- 粘贴 #${$} ---`;if(
|
|
70
|
+
`);return Z.endsWith(`
|
|
71
|
+
`)?Z.slice(0,-1):Z}function zY($,Z){let J=pF(Z);if(J.length>vF)return{kind:"reject",notice:uF,draft:$};if(!J.includes(`
|
|
72
|
+
`))return{kind:"text",text:J,draft:$};let{char:z,draft:G}=KY($,{kind:"snippet",id:$.nextSnippetId,text:J,lineCount:J.split(`
|
|
73
|
+
`).length});return{kind:"snippet",char:z,draft:G}}function GY($,Z){if(Z==null)return{kind:"none",draft:$};if(Z.data.length>xF)return{kind:"reject",notice:gF,draft:$};let{char:J,draft:z}=KY($,{kind:"image",id:$.nextImageId,data:Z.data,mimeType:Z.mimeType});return{kind:"image",char:J,draft:z}}function QY($,Z){let J=new Set(Array.from(Z)),z=new Map([...$.attachments].filter(([G])=>J.has(G)));if(z.size===$.attachments.size)return $;return{...$,attachments:z}}function oF($,Z){return Array.from($).map((J)=>{let z=Z.attachments.get(J);if(z)return v7(z);return x7(J)?y7:J}).join("")}function dF($,Z){let J=[],z="",G=()=>{if(!z)return;J.push({type:"text",text:z}),z=""};for(let Q of Array.from($)){let Y=Z.attachments.get(Q);if(Y?.kind==="image"){G(),J.push({type:"image",image:Y.data,mimeType:Y.mimeType});continue}if(Y?.kind==="snippet"){G(),J.push({type:"text",text:lF(Y.id,Y.text,J)});continue}z+=x7(Q)?y7:Q}if(G(),!J.some((Q)=>Q.type==="image"))return J.map((Q)=>Q.type==="text"?Q.text:"").join("");return J}function YY($,Z){return{display:oF($,Z),content:dF($,Z)}}function f3($,Z,J){let z=Z.attachments.get($);if(!z)return;return Math.min(A0(v7(z)),J)}function rF($,Z,J){let z=Z.attachments.get($);if(!z)return;return iF(v7(z),J)}function E7($,Z,J){return rF($,Z,J)??(x7($)?y7:$)}function v7($){return $.kind==="image"?nF($.id):cF($.id,$.lineCount)}function lF($,Z,J){let z=`--- 粘贴 #${$} ---
|
|
74
|
+
${Z}
|
|
75
|
+
--- 粘贴 #${$} ---`;if(J.length===0)return z;let G=J[J.length-1];if(G?.type==="text"&&G.text.endsWith(`
|
|
75
76
|
`))return z;return`
|
|
76
|
-
${z}`}function
|
|
77
|
-
`&&!
|
|
78
|
-
`));return}if(l0){let
|
|
79
|
-
`));return}let
|
|
80
|
-
`),Zz
|
|
81
|
-
`));let{buffer:
|
|
82
|
-
`);if(z===-1)break;let
|
|
83
|
-
`;continue}if(this.isTableRow(
|
|
84
|
-
`}if(!this.inTable&&!this.inCodeBlock&&this.buffer.length>0){if(!this.buffer.startsWith("|")&&!this.buffer.startsWith("`")){let z=this.buffer;this.buffer="",
|
|
77
|
+
${z}`}function KY($,Z){let J=String.fromCodePoint($.nextCodePoint),z=new Map($.attachments);return z.set(J,Z),{char:J,draft:{nextCodePoint:$.nextCodePoint+1,nextImageId:Z.kind==="image"?$.nextImageId+1:$.nextImageId,nextSnippetId:Z.kind==="snippet"?$.nextSnippetId+1:$.nextSnippetId,attachments:z}}}function x7($){let Z=$.codePointAt(0);return Z!==void 0&&Z>=hF&&Z<=mF}function iF($,Z){if(Z<1)return"";if(A0($)<=Z)return $;let J="…",z=A0(J),G="",Q=0;for(let{text:Y,width:K}of b$($)){if(Q+K+z>Z)break;G+=Y,Q+=K}return G+=J,Q+=z,Q<Z?`${G}${" ".repeat(Z-Q)}`:G}var EF=57344,vF=1e6,xF=5242880,gF="图片超过 5MB,未附加",uF="粘贴内容过大,未附加",hF=57344,mF=63743,y7="�";var XY=C(()=>{H1()});import{useState as _6,useEffect as T4,useMemo as PY,useRef as C0,useCallback as _3}from"react";import{Box as E$,Text as e0,useInput as tF,useStdin as aF,useStdout as sF}from"ink";import{jsxDEV as V0}from"react/jsx-dev-runtime";function eF($){return/^\[\d{1,2}(;\d{0,2})?u?$/.test($)||/^\d{1,2};\d{1,2}u$/.test($)}function $N($,Z){let J=$+Z,z=!1,G;while((G=J.indexOf(HY))!==-1)J=J.slice(G+HY.length),z=!0;let Q=J.lastIndexOf("\x1B");return{buffer:Q===-1?"":J.slice(Q),shiftEnter:z}}function qY({onSubmit:$,disabled:Z,placeholder:J,columns:z,terminalRows:G,onSelectionMode:Q,onExit:Y,onRowsChange:K,onNotice:X}){let[P,W]=_6({value:"",caretIndex:0}),{value:H,caretIndex:q}=P,[U,M]=_6(0),[F,N]=_6(!1),{stdin:f}=aF(),{stdout:B}=sF(),_=C0(""),V=C0(""),A=C0(""),O=C0(""),v=C0(""),b=C0(!1),D=C0(S7()),I=C0(X);I.current=X;let R=z||80,[J0,m]=_6(()=>vQ(xQ())),$0=C0(J0),[x,T]=_6(!1),o=C0(null),S=C0(null),p=_3(()=>{if(o.current===null&&S.current===null)return;if(S.current!==null)clearTimeout(S.current),S.current=null;o.current=null,T(!1)},[]),z0=_3((n)=>{if(o.current=n,T(!0),S.current!==null)clearTimeout(S.current);S.current=setTimeout(()=>{S.current=null,o.current=null,T(!1)},B7)},[]);T4(()=>()=>p(),[p]);let u=C0(P),w=_3((n)=>{p();let g=n(u.current.value,u.current.caretIndex);u.current=g,W(g),D.current=QY(D.current,g.value);let W0=N7($0.current,g.value);if(W0!==$0.current)$0.current=W0,m(W0)},[p]),y0=(n)=>{$0.current=F7($0.current,n.display),m($0.current),M7($0.current.entries),$(n)},Y0=_3((n)=>{let g=zY(D.current,n);if(g.kind==="text"){if(g.text)w((W0,l0)=>z$(W0,l0,g.text));return}if(g.kind==="snippet"){D.current=g.draft,w((W0,l0)=>z$(W0,l0,g.char));return}I.current?.(g.notice)},[w]),q0=(n)=>{let{text:g,state:W0}=uQ($0.current,n,L7);if($0.current=W0,m(W0),g!==u.current.value){let l0={value:g,caretIndex:Array.from(g).length};u.current=l0,W(l0)}};T4(()=>()=>{w4(null)},[]);let Z0=s(G0())?.type,K0=PY(()=>f7(H,_7(Z0)),[H,Z0]),U0=H.startsWith("/")&&!/\s/.test(H.slice(1))&&!F&&K0.length>0,c=U0?Math.min(U,K0.length-1):0,c0=U0?K0[c]:void 0,f$=PY(()=>U0?[]:A7(H),[H,U0]),g0=!U0&&!F&&f$.length>0,_$=g0?Math.min(U,f$.length-1):0,h=g0?f$[_$]:void 0;T4(()=>{if(U0||g0)M(0)},[U0,g0]);let E=(n)=>{if(n.argHint)w(()=>({value:`/${n.name} `,caretIndex:n.name.length+2}));else y0({display:`/${n.name}`,content:`/${n.name}`}),D.current=V3(),w(()=>({value:"",caretIndex:0}))},t=(n)=>{w((g)=>{let W0=D7(g,n.value);return{value:W0,caretIndex:Array.from(W0).length}})},d=C0(E);d.current=E;let X0=C0(t);X0.current=t;let I0=C0(U0);I0.current=U0;let O0=C0(g0);O0.current=g0;let X$=C0(Y0);X$.current=Y0,tF((n,g)=>{if(Z)return;if(X3(n,g)){let y=u.current.value,r=hQ($0.current,y,o.current,Date.now());if(r.exit){p(),Y();return}if(r.state.entries!==$0.current.entries)M7(r.state.entries);if($0.current=r.state,m(r.state),r.armedAt!==null){z0(r.armedAt);return}p(),D.current=V3(),w(()=>({value:"",caretIndex:0}));return}if(p(),g.ctrl&&n==="b"){Q?.();return}if(g.ctrl&&n==="v"){let y=GY(D.current,R7());if(y.kind==="image")D.current=y.draft,w((r,i0)=>z$(r,i0,y.char));else if(y.kind==="reject")I.current?.(y.notice);return}if(JY(n,b.current))return;let W0=n.replace(/[\r\n]+$/,""),l0=g.return||/[\r\n]+$/.test(n);if(g.escape){if(U0||g0)N(!0);else if($0.current.index!==-1){let y=N7($0.current,$0.current.draft);if($0.current=y,m(y),y.draft!==u.current.value){let r={value:y.draft,caretIndex:Array.from(y.draft).length};u.current=r,W(r)}}return}if(N(!1),U0){if(g.upArrow){M((y)=>(y-1+K0.length)%K0.length);return}if(g.downArrow){M((y)=>(y+1)%K0.length);return}if(g.tab){if(K0.length===1&&c0){E(c0);return}M((y)=>g.shift?(y-1+K0.length)%K0.length:(y+1)%K0.length);return}if(l0){if(c0)E(c0);return}}if(g0){if(g.upArrow){M((y)=>(y-1+f$.length)%f$.length);return}if(g.downArrow){M((y)=>(y+1)%f$.length);return}if(g.tab){if(h)t(h);return}}let N4=g;if(N4.home){w((y,r)=>({value:y,caretIndex:M6(y,r)}));return}if(N4.end){w((y,r)=>({value:y,caretIndex:F6(y,r)}));return}if(g.upArrow){let{value:y,caretIndex:r}=u.current,i0=N3(z),h1=q7(y,r,-1,i0,(c$)=>f3(c$,D.current,i0));if(h1!==r){w(()=>({value:y,caretIndex:h1}));return}q0(1);return}if(g.downArrow){let{value:y,caretIndex:r}=u.current,i0=N3(z),h1=q7(y,r,1,i0,(c$)=>f3(c$,D.current,i0));if(h1!==r){w(()=>({value:y,caretIndex:h1}));return}q0(-1);return}if(n===`
|
|
78
|
+
`&&!g.return){w((y,r)=>z$(y,r,`
|
|
79
|
+
`));return}if(l0){let y=u.current.value;if(y.endsWith("\\")){w((i0,c2)=>z$(i0.slice(0,-1),c2,`
|
|
80
|
+
`));return}let r=YY(y,D.current);if(r.display.trim()||D.current.attachments.size>0)y0(r);D.current=V3(),w(()=>({value:"",caretIndex:0}));return}if(g.leftArrow){w((y,r)=>({value:y,caretIndex:I4(y,r,-1)}));return}if(g.rightArrow){w((y,r)=>({value:y,caretIndex:I4(y,r,1)}));return}if(g.backspace){w((y,r)=>N2(y,r));return}if(g.escape||g.pageUp||g.pageDown)return;if(g.ctrl&&n==="r"){let y=gQ($0.current,u.current.value);if(y){let r={value:y,caretIndex:Array.from(y).length};u.current=r,W(r)}return}if(g.ctrl&&n==="a"){w((y,r)=>({value:y,caretIndex:M6(y,r)}));return}if(g.ctrl&&n==="e"){w((y,r)=>({value:y,caretIndex:F6(y,r)}));return}if(g.ctrl&&n==="k"){w((y,r)=>IQ(y,r));return}if(g.ctrl&&n==="u"){w((y,r)=>wQ(y,r));return}if(g.ctrl&&n==="w"){w((y,r)=>TQ(y,r));return}if(g.meta&&n==="b"){w((y,r)=>({value:y,caretIndex:Math.max(0,r-1)}));return}if(g.meta&&n==="f"){w((y,r)=>({value:y,caretIndex:Math.min(Array.from(y).length,r+1)}));return}if(g.ctrl||g.meta)return;if(eF(n))return;if(/^\[<.*[Mm]$/.test(n)||n.startsWith("[<")||/^[\d;,]+[Mm]$/.test(n))return;if(g.tab){w((y,r)=>z$(y,r," "));return}if(n)w((y,r)=>z$(y,r,W0))},{isActive:!Z});let m2=H==="",eJ=x?"再按一次 Ctrl+C 退出":J,$z=H.split(`
|
|
81
|
+
`),Zz=$z.length>1,$q=Z?j.inputBorderDisabled:j.inputBorder,n2=N3(R),N8=(n)=>f3(n,D.current,n2),p0=W7(H,n2,N8),l9=Math.min(q,Array.from(H).length),L1=p0.length-1,B8=Array.from(p0[L1].text).length;for(let n=0;n<p0.length;n++){let g=p0[n],W0=g.startIndex+Array.from(g.text).length;if(l9>=g.startIndex&&l9<=W0){L1=n,B8=l9-g.startIndex;break}}let i9=A0(Array.from(p0[L1].text).slice(0,B8).join(""),N8);if(i9>=n2){if(L1===p0.length-1)p0.push({text:"",startIndex:p0[L1].startIndex+Array.from(p0[L1].text).length});L1++,B8=0,i9=0}let F4=Zz?1:0,Zq=I7(G,p0.length,F4,b7),Jq=I7(G,p0.length,F4,w7),R$=U0?W3(K0,c,Zq):null,k$=g0?W3(f$,_$,Jq):null,Jz=R$?R$.shown.length+b7:k$?k$.shown.length+w7:0,zz=tQ(p0.length,F4,R$?.shown.length??0,k$?.shown.length??0),Gz=G-p0.length-F4-Jz,V8=C0(p0);V8.current=p0;let t9=C0(Gz);t9.current=Gz;let Qz=C0(F4);Qz.current=F4;let Yz=C0(R$);Yz.current=R$;let Kz=C0(k$);Kz.current=k$;let Xz=C0(N8);Xz.current=N8,T4(()=>{K?.(zz)},[zz,K]),T4(()=>()=>K?.(V6),[K]),T4(()=>{if(!f||Z)return;let n=(g)=>{let W0=g.toString("utf-8"),l0=ZY(v.current,W0);v.current=l0.buffer,b.current=l0.active;for(let P$ of l0.pastes)X$.current(P$);let{buffer:N4,shiftEnter:y}=$N(_.current,W0);if(_.current=N4,y)w((P$,p$)=>z$(P$,p$,`
|
|
82
|
+
`));let{buffer:r,actions:i0}=RQ(A.current,W0);if(A.current=r,i0.length>0)for(let P$ of i0)w((p$,j1)=>P$.kind==="backspace"?N2(p$,j1):bQ(p$,j1));let{buffer:c2,actions:h1}=kQ(O.current,W0);if(O.current=c2,h1.length>0)for(let P$ of h1)w((p$,j1)=>({value:p$,caretIndex:P$.kind==="home"?M6(p$,j1):F6(p$,j1)}));V.current+=W0;let c$;while(c$=q3(V.current))if(V.current=c$.rest,c$.event.button===0&&c$.event.press){let P$=c$.event.row-t9.current;if(P$>=0&&P$<V8.current.length){let p$=c$.event.col;w((j1)=>({value:j1,caretIndex:H7(V8.current,P$,p$,C7,Xz.current)}))}else{let j1=I0.current?1:0,Pz=c$.event.row-(t9.current+V8.current.length+Qz.current+3+j1);if(I0.current){let p2=Yz.current?.shown[Pz];if(p2)d.current(p2)}else if(O0.current){let p2=Kz.current?.shown[Pz];if(p2)X0.current(p2)}}}if(V.current.length>64){let P$=V.current.lastIndexOf("\x1B");V.current=P$===-1?"":V.current.slice(P$)}};return f.on("data",n),()=>{f.off("data",n)}},[f,Z,w]),T4(()=>{return B.write(`${eQ}${cQ}`),()=>{B.write(`${pQ}${$Y}`)}},[B]);{let n=p0.length-1-L1;w4({rowsAbove:n+1+F4+Jz,column:C7+i9})}return V0(E$,{flexDirection:"column",flexShrink:0,width:"100%",children:[V0(E$,{flexDirection:"column",borderStyle:"round",borderColor:$q,paddingX:1,width:"100%",children:[m2&&eJ?V0(E$,{children:[V0(e0,{color:Z?j.inputBorderDisabled:j.inputBorder,children:WY},void 0,!1,void 0,this),V0(e0,{inverse:!0,children:" "},void 0,!1,void 0,this),V0(e0,{color:j.muted,dimColor:!0,wrap:"truncate-end",children:eJ},void 0,!1,void 0,this)]},void 0,!0,void 0,this):p0.map((n,g)=>{let W0=Array.from(n.text),l0=g===L1,N4=l0?B8:W0.length,y=W0.slice(0,N4).map((i0)=>E7(i0,D.current,n2)).join(""),r=W0.slice(N4).map((i0)=>E7(i0,D.current,n2)).join("");return V0(E$,{children:[V0(e0,{color:Z?j.inputBorderDisabled:j.inputBorder,children:g===0?WY:" "},void 0,!1,void 0,this),V0(e0,{wrap:"truncate-end",children:[y,l0&&V0(e0,{inverse:!0,children:" "},void 0,!1,void 0,this),r]},void 0,!0,void 0,this)]},g,!0,void 0,this)}),Zz&&V0(E$,{justifyContent:"flex-end",children:V0(e0,{color:j.muted,dimColor:!0,wrap:"truncate-end",children:[$z.length," 行 | Shift+Enter/Ctrl+J 换行 | Enter 发送"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),U0&&c0&&V0(E$,{flexDirection:"column",borderStyle:"round",borderColor:j.inputBorder,paddingX:1,marginTop:1,width:"100%",children:[V0(E$,{children:V0(e0,{color:j.muted,children:H.trim()==="/"?"命令":`/${H.slice(1)} 命令`},void 0,!1,void 0,this)},void 0,!1,void 0,this),R$?.shown.map((n,g)=>{let W0=R$.start+g===c;return V0(E$,{children:[V0(e0,{color:W0?j.accent:j.muted,children:W0?"❯ ":" "},void 0,!1,void 0,this),V0(e0,{bold:W0,color:W0?j.accent:void 0,children:["/",n.name,n.argHint?` ${n.argHint}`:""]},void 0,!0,void 0,this),V0(e0,{color:j.muted,dimColor:!0,wrap:"truncate-end",children:[" ",n.description]},void 0,!0,void 0,this)]},n.name,!0,void 0,this)}),V0(E$,{children:V0(e0,{color:j.muted,dimColor:!0,wrap:"truncate-end",children:[R$&&R$.extraAbove+R$.extraBelow>0?`还有 ${R$.extraAbove+R$.extraBelow} 项 · `:"","↑↓ 选择 · Tab/Enter 执行 · Esc 关闭"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),g0&&V0(E$,{flexDirection:"column",borderStyle:"round",borderColor:j.inputBorder,paddingX:1,marginTop:1,width:"100%",children:[k$?.shown.map((n,g)=>{let W0=k$.start+g===_$;return V0(E$,{children:[V0(e0,{color:W0?j.accent:j.muted,children:W0?"❯ ":" "},void 0,!1,void 0,this),V0(e0,{bold:W0,color:W0?j.accent:void 0,children:n.value},void 0,!1,void 0,this),n.description&&V0(e0,{color:j.muted,dimColor:!0,wrap:"truncate-end",children:[" ",n.description]},void 0,!0,void 0,this)]},n.value,!0,void 0,this)}),V0(E$,{children:V0(e0,{color:j.muted,dimColor:!0,wrap:"truncate-end",children:[k$&&k$.extraAbove+k$.extraBelow>0?`还有 ${k$.extraAbove+k$.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 WY="❯ ",HY="\x1B[13;2u";var UY=C(()=>{H1();U7();V7();H3();l();B6();B6();P1();B3();XY()});function MY(){if("NO_COLOR"in process.env)return!1;if(process.env.FORCE_COLOR==="0")return!1;return!0}class L6{buffer="";inCodeBlock=!1;codeLang="";tableRows=[];inTable=!1;write($){this.buffer+=$;let Z="",J=MY()?FY:NY;while(!0){let z=this.buffer.indexOf(`
|
|
83
|
+
`);if(z===-1)break;let G=this.buffer.slice(0,z);if(this.buffer=this.buffer.slice(z+1),this.inCodeBlock||G.startsWith("```")){if(this.inTable)Z+=this.renderTable(J),this.tableRows=[],this.inTable=!1;Z+=this.formatLine(G,J)+`
|
|
84
|
+
`;continue}if(this.isTableRow(G)){if(this.isTableSeparator(G)){this.inTable=!0;continue}this.inTable=!0,this.tableRows.push(this.parseTableRow(G));continue}if(this.inTable)Z+=this.renderTable(J),this.tableRows=[],this.inTable=!1;Z+=this.formatLine(G,J)+`
|
|
85
|
+
`}if(!this.inTable&&!this.inCodeBlock&&this.buffer.length>0){if(!this.buffer.startsWith("|")&&!this.buffer.startsWith("`")){let z=this.buffer;this.buffer="",Z+=this.formatInline(z,J)}}if(this.inTable&&this.buffer.length>0&&!this.buffer.startsWith("|")){if(Z+=this.renderTable(J),this.tableRows=[],this.inTable=!1,this.buffer.length>0&&!this.buffer.startsWith("`")){let z=this.buffer;this.buffer="",Z+=this.formatInline(z,J)}}return Z}flush(){let $=MY()?FY:NY,Z="";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)Z+=this.renderTable($),this.tableRows=[],this.inTable=!1;if(!this.buffer)return Z;return Z+=this.formatLine(this.buffer,$),this.buffer="",Z}isTableRow($){let Z=$.trim();return Z.startsWith("|")&&Z.endsWith("|")&&Z.includes("|",1)}isTableSeparator($){return/^\s*\|[\s:]*-+[\s:|-]*\|\s*$/.test($)}parseTableRow($){return $.trim().slice(1,-1).split("|").map((Z)=>Z.trim())}clipToWidth($,Z){let J=0,z="";for(let G of $){let Q=A0(G);if(J+Q>Z)break;z+=G,J+=Q}return z}padToWidth($,Z){let J=this.clipToWidth($,Z),z=Z-A0(J);return z>0?J+" ".repeat(z):J}renderTable($){if(this.tableRows.length===0)return"";let Z=Math.max(0,...this.tableRows.map((X)=>X.length));if(Z===0)return"";let J=Array(Z).fill(0),z=64;for(let X of this.tableRows)for(let P=0;P<X.length;P++)J[P]=Math.min(z,Math.max(J[P],A0(X[P]??"")));let G=[],Q=`${$.dim}┌${J.map((X)=>"─".repeat(Math.max(0,X+2))).join("┬")}┐${$.reset}`,Y=`${$.dim}├${J.map((X)=>"─".repeat(Math.max(0,X+2))).join("┼")}┤${$.reset}`,K=`${$.dim}└${J.map((X)=>"─".repeat(Math.max(0,X+2))).join("┴")}┘${$.reset}`;G.push(Q);for(let X=0;X<this.tableRows.length;X++){let P=this.tableRows[X],W=J.map((H,q)=>{let U=P[q]??"",M=this.padToWidth(U,H);return X===0?`${$.bold}${M}${$.reset}`:M});if(G.push(`${$.dim}│${$.reset} ${W.join(` ${$.dim}│${$.reset} `)} ${$.dim}│${$.reset}`),X===0)G.push(Y)}return G.push(K),G.join(`
|
|
85
86
|
`)+`
|
|
86
|
-
`}formatInline($,
|
|
87
|
-
`)}function
|
|
88
|
-
`);if(
|
|
89
|
-
`),
|
|
90
|
-
`).length,P=
|
|
91
|
-
`))
|
|
92
|
-
`))J.push(...a0(K,z));return J}}}function kG($){let f=0;for(let Z=0;Z<$.length;Z++)f=f*31+$.charCodeAt(Z)|0;return String(f)}function WF($,f,Z){return[$.id,String($.content.length),kG($.content.slice(0,64)+$.content.slice(-32)),String($.toolResult?.length??0),$.toolResult?kG($.toolResult.slice(0,64)):"",String(f),Z?"1":"0",$.toolName??"",$.toolResultSummary??"",($.toolChildren??[]).map((z)=>`${z.name}:${z.summary}`).join("|")].join("\x00")}function O8($,f,Z){let z=WF($,f,Z),J=A6.get(z);if(J!==void 0)return J;let K=PF($,f,Z);if(A6.size>=XF){let G=A6.keys().next().value;if(G!==void 0)A6.delete(G)}return A6.set(z,K),K}function HF($,f,Z){return O8($,f,Z).length+($.role==="user"?SG:0)}function UF($,f,Z,z){let J=f.reduce((H,U)=>H+U,0);if(Z<=0)return{winTop:0,winBottom:J,above:0,below:0,parts:$.map((H,U)=>({msg:H,start:0,count:f[U]??0}))};let K=0,G=0,Q=0,Y=Z;for(let H=0;H<3;H++){let U=(K>0?1:0)+(G>0?1:0);Y=Math.max(1,Z-U);let M=Math.max(0,J-Y);Q=z===null?M:Math.min(z,M),K=Q,G=Math.max(0,J-(Q+Y))}let P=Math.min(J,Q+Y),X=[],W=0;for(let H=0;H<$.length;H++){let U=f[H]??0;if(W<P&&W+U>Q){let M=Math.max(0,Q-W),N=Math.min(U-M,P-W-M);X.push({msg:$[H],start:M,count:N})}W+=U}return{winTop:Q,winBottom:P,above:K,below:G,parts:X}}function EG({messages:$,maxHeight:f,columns:Z=80,onCopyNotice:z,selectionMode:J,onExitSelectionMode:K,interactive:G=!0}){let[Q,Y]=j8(null),[P,X]=j8(new Set),[W,H]=j8(null),U=$[$.length-1],M=U?.role==="thinking"?U.id:null,N=$$(null);b8(()=>{if(M)N.current=M,H(M);else if(N.current!==null){let n=N.current;N.current=null,H((E)=>E===n?null:E)}},[M]);let[q,L]=j8(null),F=p5(()=>$.map((n)=>HF(n,Z,C8(n,P,W))),[$,Z,P,W]),V=p5(()=>UF($,F,f??0,Q),[$,F,f,Q]),B=$$(V);B.current=V;let A=p5(()=>qF(V,Z,P,W),[V,Z,P,W]),j=$$(A.rows);j.current=A.rows;let v=$$(A.kinds);v.current=A.kinds;let O=$$(A.partMeta);O.current=A.partMeta;let b=$$(z);b.current=z;let T=$$(Boolean(J));T.current=Boolean(J);let I=$$(null),Z0=$$(OG()),h=(n)=>D6(A.rows,n.row,n.col),$0=q?c5(A.rows,h(q.anchor),h(q.cur)):null,u=$0?DG($0,A.partMeta):null,y=JF((n)=>{let E=j.current,i=VG(E,v.current,c5(E,D6(E,n.anchor.row,n.anchor.col),D6(E,n.cur.row,n.cur.col)));if(i==="")b.current?.("未选中文本");else if(R5(i))b.current?.(`已复制 ${Array.from(i).length} 字`);else b.current?.("复制失败")},[]),r=$$(y);r.current=y;let S=$$(q);S.current=q;let p=$$(K);p.current=K;let z0=()=>{let n=S.current;if(n)return n;if(I.current)return{anchor:I.current,cur:I.current};let i=j.current.findIndex((Y0)=>Y0!=null),o=i>=0?{row:i+1,col:2}:{row:1,col:2};return{anchor:o,cur:o}},g=(n)=>{let E=Math.max(1,j.current.length);return{anchor:n.anchor,cur:{row:Math.max(1,Math.min(E,n.cur.row)),col:Math.max(1,n.cur.col)}}},w=(n,E)=>{let i=z0(),o=Math.max(1,j.current.length),Y0=Math.max(1,Math.min(o,i.cur.row+n));if(n!==0)while(Y0>=1&&Y0<=o&&j.current[Y0-1]==null){let h2=Y0+Math.sign(n);if(h2<1||h2>o)break;Y0=h2}let T0=j.current[Y0-1],j0=T0?A0(N2(T0)):0,Y$=Math.max(1,Math.min(2+j0,i.cur.col+E));L({anchor:i.anchor,cur:{row:Y0,col:Y$}})};b8(()=>{if(!J)return;L((n)=>n??z0())},[J,z0]);let R0=(n)=>{if(n.role==="thinking"){N.current=null,H((E)=>E===n.id?null:n.id);return}X((E)=>{let i=new Set(E);if(i.has(n.id))i.delete(n.id);else i.add(n.id);return i})},G0=$$(R0);G0.current=R0;let H0=(n)=>{Y((E)=>{let i=E??B.current.winTop;return Math.max(0,i-n)})},f0=(n)=>{Y((E)=>{if(E===null)return E;let i=B.current.winTop+B.current.below;return E+n>=i?null:E+n})},Q0=$$(bG());KF((n,E)=>{if(T.current){let i=E;if(E.escape){L(null),p.current?.();return}if(E.return){let o=S.current??z0();r.current(o),p.current?.();return}if(E.leftArrow){w(0,-1);return}if(E.rightArrow){w(0,1);return}if(E.upArrow){w(-1,0);return}if(E.downArrow){w(1,0);return}if(i.home){let o=z0();L({anchor:o.anchor,cur:{row:o.cur.row,col:1}});return}if(i.end){let o=z0(),Y0=j.current[o.cur.row-1],T0=Y0?A0(N2(Y0)):0;L({anchor:o.anchor,cur:{row:o.cur.row,col:2+T0}});return}if(E.pageUp)H0(V.winBottom-V.winTop),L((o)=>o?g(o):o);else if(E.pageDown)f0(V.winBottom-V.winTop),L((o)=>o?g(o):o);return}if(!n.startsWith("[<")&&!/^[\d;,]+[Mm]$/.test(n))m5(Q0.current),L(null);if(E.pageUp){let i=V.winBottom-V.winTop;H0(i)}else if(E.pageDown){let i=V.winBottom-V.winTop;f0(i)}if((n===" "||n==="o")&&!E.ctrl&&!E.meta){let i=Math.floor((V.winTop+V.winBottom)/2),o=0;for(let Y0=0;Y0<$.length;Y0++){let T0=F[Y0]??0;if(i>=o&&i<o+T0&&yG($[Y0])){G0.current($[Y0]);break}o+=T0}}},{isActive:Boolean(G&&f&&f>0)});let U0=$$($.length);b8(()=>{if($.length<U0.current)Y(null);U0.current=$.length},[$]);let m=(n)=>{let{above:E,parts:i}=B.current,o=n-1;if(o<0)return;if(E>0){if(o-=1,o<0)return}for(let Y0 of i){if(o<Y0.count){if(yG(Y0.msg))G0.current(Y0.msg);return}o-=Y0.count}},m0=(n,E)=>{let i=j.current,o=D6(i,n,E),Y0=i[o.row];if(!Y0)return;let T0=_G(N2(Y0),o.col);if(T0.end<=T0.start)return;let j0={anchor:{row:o.row+1,col:T0.start+2},cur:{row:o.row+1,col:T0.end+1}};L(j0),r.current(j0)},V$=(n)=>{let E=n-1,i=O.current[E];if(!i)return;let o=E,Y0=E;while(o>0&&O.current[o-1]?.part===i.part)o--;while(Y0<O.current.length-1&&O.current[Y0+1]?.part===i.part)Y0++;let T0=j.current[Y0],j0=T0?A0(N2(T0)):0,Y$={anchor:{row:o+1,col:2},cur:{row:Y0+1,col:Math.max(2,1+j0)}};L(Y$),r.current(Y$)},{stdin:x0}=GF(),L$=$$("");if(b8(()=>{if(!x0||!f||f<=0)return;let n=(E)=>{L$.current+=E.toString("utf-8");let i;while(i=U8(L$.current)){L$.current=i.rest;let{button:o,row:Y0}=i.event,T0=j.current.length;if(o===F6||o===C5||o===F6+F2||o===C5+F2){if(Y0>=1&&Y0<=T0+2){if(m5(Q0.current),!T.current)L(null);if(o===F6||o===F6+F2)H0(3);else f0(3);if(T.current)L((Y$)=>Y$?g(Y$):Y$)}continue}let j0=jG(Q0.current,i.event,f);if(j0?.type==="selection")L(j0.selection);else if(j0?.type==="copy")r.current(j0.selection);else if(j0?.type==="click"){I.current={row:j0.row,col:j0.col};let Y$=wG(Z0.current,{row:j0.row,col:j0.col,at:Date.now()});if(Y$>=3)V$(j0.row);else if(Y$===2)m0(j0.row,j0.col);else m(j0.row)}}if(L$.current.length>64){let o=L$.current.lastIndexOf("\x1B");L$.current=o===-1?"":L$.current.slice(o)}};return x0.on("data",n),()=>{x0.off("data",n)}},[x0,f,g,m,f0,H0,V$,m0]),!f||f<=0)return F0(J$,{flexDirection:"column",children:[$.length===0&&F0(J$,{paddingLeft:1,paddingTop:1,children:F0(v$,{color:"gray",children:"输入消息开始对话,输入 /help 查看命令,Esc 取消运行"},void 0,!1,void 0,this)},void 0,!1,void 0,this),$.map((n)=>F0(RG,{message:n,lines:O8(n,Z,C8(n,P,W))},n.id,!1,void 0,this))]},void 0,!0,void 0,this);return F0(J$,{flexDirection:"column",height:f,overflow:"hidden",width:"100%",children:[$.length===0&&F0(J$,{paddingLeft:1,paddingTop:1,children:F0(v$,{color:"gray",children:"输入消息开始对话,输入 /help 查看命令,Esc 取消运行"},void 0,!1,void 0,this)},void 0,!1,void 0,this),V.above>0&&F0(J$,{paddingLeft:1,flexShrink:0,children:F0(v$,{color:"gray",dimColor:!0,children:["… 以上 ",V.above," 行"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),V.parts.map(({msg:n,start:E,count:i},o)=>F0(RG,{message:n,lines:O8(n,Z,C8(n,P,W)),start:E,count:i,selection:u?.get(o)},n.id,!1,void 0,this)),V.below>0&&F0(J$,{paddingLeft:1,flexShrink:0,children:F0(v$,{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 vG($,f,Z,z=f.length){if($.role!=="user")return{lines:f.slice(Z,Z+z),marginTop:!1,lineOffset:Z};let J=SG;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 MF($,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 qF($,f,Z,z){let J=[],K=[],G=[];if($.above>0)J.push(null),K.push("plain"),G.push(null);for(let Q=0;Q<$.parts.length;Q++){let Y=$.parts[Q],P=O8(Y.msg,f,C8(Y.msg,Z,z)),{lines:X,marginTop:W,lineOffset:H}=vG(Y.msg,P,Y.start,Y.count);if(W)J.push(null),K.push("plain"),G.push(null);for(let U=0;U<X.length;U++)J.push(X[U]),K.push(MF(Y.msg,H+U)),G.push({part:Q,shown:U})}if($.below>0)J.push(null),K.push("plain"),G.push(null);return{rows:J,kinds:K,partMeta:G}}var r5="\x1B[0m",o5=120,XF=256,A6,SG=1,RG;var uG=C(()=>{g5();P1();N6();AG();CG();B8();A6=new Map;RG=zF.memo(function({message:f,lines:Z,start:z=0,count:J,selection:K}){let{lines:G,marginTop:Q}=vG(f,Z,z,J);if(G.length===0){if(!Q)return null;return F0(J$,{height:1,flexShrink:0},void 0,!1,void 0,this)}let Y=K,P=(U,M)=>{let N=Y?.[U];return N&&N.end>N.start?A8(M,N.start,N.end):M},X=(U)=>{let M=Y?.[0];if(!M)return{head:null,tail:null};return LG(M,A0(U))},W=(U,M)=>M?A8(U,M.start,M.end):U,H=(U,M)=>M?A8(U,M.start,M.end):U;switch(f.role){case"user":{let U=G[0]??"",M=G.slice(1),N=h5(U,"user"),q=N?X(N):null,L=N?H(U.slice(N.length),q.tail):P(0,U);return F0(J$,{flexDirection:"column",paddingLeft:1,marginTop:Q?1:0,flexShrink:0,children:[F0(J$,{flexWrap:"nowrap",children:[N!==""&&F0(J$,{flexShrink:0,children:F0(v$,{color:"cyan",bold:!0,children:W(N,q.head)},void 0,!1,void 0,this)},void 0,!1,void 0,this),F0(v$,{wrap:"truncate-end",children:L},void 0,!1,void 0,this)]},void 0,!0,void 0,this),M.map((F,V)=>F0(v$,{wrap:"truncate-end",children:P(V+1,F)},V,!1,void 0,this))]},void 0,!0,void 0,this)}case"assistant":return F0(J$,{flexDirection:"column",paddingLeft:1,flexShrink:0,children:G.map((U,M)=>F0(v$,{wrap:"truncate-end",children:P(M,U)},M,!1,void 0,this))},void 0,!1,void 0,this);case"thinking":case"tool":{let U=G[0]??"",M=G.slice(1),N=f.role==="thinking",q=h5(U,N?"thinking":"tool"),L=q?X(q):null,F=q?H(U.slice(q.length),L.tail):P(0,U),V=N?void 0:f.toolIsError?"red":q?"gray":void 0;return F0(J$,{flexDirection:"column",paddingLeft:1,flexShrink:0,children:[F0(J$,{flexWrap:"nowrap",children:[q!==""&&F0(J$,{flexShrink:0,children:F0(v$,{color:N?"gray":"yellow",dimColor:N,children:W(q,L.head)},void 0,!1,void 0,this)},void 0,!1,void 0,this),F0(v$,{color:V,dimColor:N,wrap:"truncate-end",children:F},void 0,!1,void 0,this)]},void 0,!0,void 0,this),M.map((B,A)=>F0(v$,{color:V,dimColor:N,wrap:"truncate-end",children:P(A+1,B)},A,!1,void 0,this))]},void 0,!0,void 0,this)}case"system":return F0(J$,{flexDirection:"column",paddingLeft:1,flexShrink:0,children:G.map((U,M)=>F0(v$,{wrap:"truncate-end",children:P(M,U)},M,!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 i$($,f,Z){if(!$)return!1;if(Z===`
|
|
93
|
-
`&&!
|
|
94
|
-
`).flatMap((z)=>a0(z,
|
|
95
|
-
`).flatMap((
|
|
96
|
-
`).flatMap((H)=>a0(H,Q))})),P=[...K.map((X)=>({text:X,kind:"prompt"})),...Y.flatMap((X,W)=>X.lines.map((H,U)=>({text:H,kind:"option",optionIndex:W,optionLead:U===0})))];return{promptLines:K,optionBlocks:Y,body:P,lines:P.map((X)=>X.text),hasOptions:G.length>0}}function dG($,f,Z,z=0,J=!1){let K=oG($,f,Z,J),G=q8(K.hasOptions),Q=K.lines.length+G;return Math.min(Q,V6(z,G))}function VF($,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 LF($,f,Z,z,J){if(f<=0||$<=0)return 0;let K=Array.from({length:$},()=>"x"),G=s0(K,f,Z),Q=G.start,Y=G.start+G.lines.length;if(z>=Q&&J<=Y)return G.start;if(z<Q)return s0(K,f,z).start;let P=Math.max(0,J-Math.max(1,G.lines.length));return s0(K,f,P).start}function _F($,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 lG($){return Array.from($.replace(/[\r\n]+$/,"")).filter((f)=>{let Z=f.codePointAt(0)??0;return Z>=32&&Z!==127}).join("")}function iG({prompt:$,options:f,multiple:Z=!1,onAnswer:z,columns:J,maxRows:K}){let G=l5(()=>oG($,f,J,Z),[$,f,J,Z]);if(G.hasOptions)return q0(DF,{layout:G,multiple:Z,onAnswer:z,maxRows:K},void 0,!1,void 0,this);return q0(AF,{layout:G,onAnswer:z,maxRows:K},void 0,!1,void 0,this)}function DF({layout:$,multiple:f,onAnswer:Z,maxRows:z}){let J=q8(!0),K=Math.max(0,z-J),[G,Q]=T1(0),[Y,P]=T1(0),[X,W]=T1(""),[H,U]=T1(()=>new Set),[M,N]=T1(""),[q,L]=T1(0),F=w1(0),V=w1(""),B=w1(H),A=w1(""),j=w1(0),v=w1(!1);F.current=G,V.current=X,B.current=H,A.current=M,j.current=q;let O=$.optionBlocks.length,b=$.optionBlocks.findIndex((g)=>s2(g.label)),T=G===b,I=_F($.body,Math.min(G,Math.max(0,O-1)));d5(()=>{let g=setTimeout(()=>{v.current=!0},0);return()=>clearTimeout(g)},[]),d5(()=>{P((g)=>LF($.body.length,K,g,I.start,I.end))},[$.body.length,K,I.start,I.end]);let Z0=l5(()=>s0($.lines,K,Y),[$.lines,K,Y]),h=Z0.above>0||Z0.below>0,$0=()=>{V.current="",W("")},u=(g)=>{let w=g(A.current,j.current);A.current=w.value,j.current=w.caretIndex,N(w.value),L(w.caretIndex)},y=(g)=>{let w=new Set(B.current);if(w.has(g))w.delete(g);else w.add(g);B.current=w,U(w)},r=()=>{let g=gz({multiple:f,choices:$.optionBlocks.map((w)=>w.label),index:F.current,checked:B.current,otherText:A.current});if(!g)return;Z(JSON.stringify(g))};pG((g,w)=>{if(w.escape){Z(null);return}if(O===0)return;if(w.downArrow){$0(),Q((f0)=>(f0+1)%O);return}if(w.upArrow){$0(),Q((f0)=>(f0-1+O)%O);return}let R0=new Set(Z0.lines.map((f0,Q0)=>$.body[Z0.start+Q0]?.optionIndex).filter((f0)=>f0!=null)).size,G0=Math.max(1,R0);if(w.pageDown){$0(),Q((f0)=>Math.min(O-1,f0+G0));return}if(w.pageUp){$0(),Q((f0)=>Math.max(0,f0-G0));return}if(i$(v.current,w,g)){r();return}if(f&&g===" "){if(T&&B.current.has(b)&&A.current.length>0){u((f0,Q0)=>z$(f0,Q0," "));return}y(F.current);return}if(!f&&g===" "){if(T)u((f0,Q0)=>z$(f0,Q0," "));return}if(T&&(w.leftArrow||w.rightArrow)){u((f0,Q0)=>({value:f0,caretIndex:T4(f0,Q0,w.leftArrow?-1:1)}));return}if(T&&(w.backspace||w.delete)){if(u((f0,Q0)=>q2(f0,Q0)),f&&A.current.length===0&&B.current.has(b))y(b);return}if(T&&w.ctrl&&g==="a"){u((f0)=>({value:f0,caretIndex:0}));return}if(T&&w.ctrl&&g==="e"){u((f0)=>({value:f0,caretIndex:Array.from(f0).length}));return}if(T&&w.ctrl&&g==="u"){u(()=>({value:"",caretIndex:0}));return}if(w.backspace||w.delete){W((f0)=>{let Q0=Array.from(f0).slice(0,-1).join("");return V.current=Q0,Q0});return}if(w.ctrl||w.meta||w.tab)return;let H0=lG(g);if(!H0)return;if(T){if(u((f0,Q0)=>z$(f0,Q0,H0)),f&&!B.current.has(b))y(b);return}if(H0.length===1&&/^[0-9]$/.test(H0)){let f0=VF(V.current,H0,O);if(f0)V.current=f0.buf,W(f0.buf),Q(f0.index);return}if(b>=0){if($0(),Q(b),u((f0,Q0)=>z$(f0,Q0,H0)),f&&!B.current.has(b))y(b)}});let S=[h?"↑↓/PgUpDn 移动":"↑↓ 移动",f?"空格 勾选":"","数字键跳转","Enter 确认","Esc 取消",X?`数字 ${X}`:""].filter(Boolean).join(" · "),p=T||f&&H.has(b)&&M.length>0,z0=T;return q0(M$,{flexDirection:"column",flexShrink:0,width:"100%",borderStyle:"round",borderColor:D.questionBorder,paddingX:1,children:[K>0&&q0(M$,{flexDirection:"column",height:K,overflow:"hidden",flexShrink:0,width:"100%",children:[Z0.above>0&&q0(M$,{flexShrink:0,children:q0(c0,{color:D.muted,dimColor:!0,children:["… 以上 ",Z0.above," 行"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Z0.lines.map((g,w)=>{let R0=Z0.start+w,G0=$.body[R0];if(!G0)return null;let H0=G0.kind==="prompt",f0=G0.optionIndex??-1,Q0=G0.kind==="option"&&f0===G,U0=f&&H.has(f0),m=H0?"":G0.optionLead?`${Q0?"❯ ":" "}${f?U0?"[x] ":"[ ] ":""}`:" ".repeat(rG(f));return q0(M$,{flexShrink:0,children:[!H0&&q0(c0,{color:Q0?D.accent:D.muted,children:m},void 0,!1,void 0,this),q0(c0,{bold:H0||Q0,color:H0?D.questionBorder:Q0?D.accent:D.muted,wrap:"truncate-end",children:g},void 0,!1,void 0,this)]},`${G0.kind}-${f0}-${R0}`,!0,void 0,this)}),Z0.below>0&&q0(M$,{flexShrink:0,children:q0(c0,{color:D.muted,dimColor:!0,children:["↓ 还有 ",Z0.below," 行"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),q0(M$,{marginTop:1,flexShrink:0,height:1,overflow:"hidden",width:"100%",children:p||z0?q0(bF,{children:[q0(c0,{bold:!0,color:D.questionBorder,children:["→"," "]},void 0,!0,void 0,this),q0(c0,{children:Array.from(M).slice(0,z0?q:M.length).join("")},void 0,!1,void 0,this),z0&&q0(c0,{color:D.muted,inverse:!0,children:" "},void 0,!1,void 0,this),z0&&q0(c0,{children:Array.from(M).slice(q).join("")},void 0,!1,void 0,this)]},void 0,!0,void 0,this):q0(c0,{color:D.muted,dimColor:!0,children:"→ 选「其他」后可输入"},void 0,!1,void 0,this)},void 0,!1,void 0,this),q0(M$,{flexShrink:0,children:q0(c0,{color:D.muted,dimColor:!0,wrap:"truncate-end",children:S},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function AF({layout:$,onAnswer:f,maxRows:Z}){let z=q8(!1),J=Math.max(0,Z-z),[K,G]=T1(""),[Q,Y]=T1(0),[P,X]=T1(0),W=w1(""),H=w1(0),U=w1(!1);W.current=K,H.current=Q,d5(()=>{let F=setTimeout(()=>{U.current=!0},0);return()=>clearTimeout(F)},[]);let M=l5(()=>s0($.lines,J,P),[$.lines,J,P]),N=M.above>0||M.below>0,q=(F)=>{let V=F(W.current,H.current);W.current=V.value,H.current=V.caretIndex,G(V.value),Y(V.caretIndex)};pG((F,V)=>{if(V.escape){f(null);return}if(V.return){if(!i$(U.current,V,F))return;f(W.current.trim());return}if(N){let A=Math.max(1,M.lines.length);if(V.upArrow){X((j)=>s0($.lines,J,j-1).start);return}if(V.downArrow){X((j)=>s0($.lines,J,j+1).start);return}if(V.pageUp){X((j)=>s0($.lines,J,j-A).start);return}if(V.pageDown){X((j)=>s0($.lines,J,j+A).start);return}}if(V.leftArrow){q((A,j)=>({value:A,caretIndex:T4(A,j,-1)}));return}if(V.rightArrow){q((A,j)=>({value:A,caretIndex:T4(A,j,1)}));return}if(V.backspace||V.delete){q((A,j)=>q2(A,j));return}if(V.ctrl&&F==="a"){q((A)=>({value:A,caretIndex:0}));return}if(V.ctrl&&F==="e"){q((A)=>({value:A,caretIndex:Array.from(A).length}));return}if(V.ctrl&&F==="u"){q(()=>({value:"",caretIndex:0}));return}if(V.ctrl&&F==="k"){q((A,j)=>{let v=Array.from(A);return v.splice(j),{value:v.join(""),caretIndex:j}});return}if(V.ctrl||V.meta)return;if(V.upArrow||V.downArrow||V.tab)return;let B=lG(F);if(!B)return;q((A,j)=>z$(A,j,B))});let L=N?"Enter 提交 · Esc 取消 · ↑↓ 滚动 · ←→ 光标":"Enter 提交 · Esc 取消 · ←→ 光标";return q0(M$,{flexDirection:"column",flexShrink:0,width:"100%",borderStyle:"round",borderColor:D.questionBorder,paddingX:1,children:[J>0&&q0(M$,{flexDirection:"column",height:J,overflow:"hidden",flexShrink:0,width:"100%",children:[M.above>0&&q0(M$,{flexShrink:0,children:q0(c0,{color:D.muted,dimColor:!0,children:["… 以上 ",M.above," 行"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),M.lines.map((F,V)=>q0(M$,{flexShrink:0,children:q0(c0,{bold:!0,color:D.questionBorder,wrap:"truncate-end",children:F},void 0,!1,void 0,this)},`${M.start+V}:${F}`,!1,void 0,this)),M.below>0&&q0(M$,{flexShrink:0,children:q0(c0,{color:D.muted,dimColor:!0,children:["↓ 还有 ",M.below," 行"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),q0(M$,{marginTop:1,flexShrink:0,height:1,overflow:"hidden",width:"100%",children:[q0(c0,{bold:!0,color:D.questionBorder,children:["→"," "]},void 0,!0,void 0,this),q0(c0,{children:Array.from(K).slice(0,Q).join("")},void 0,!1,void 0,this),q0(c0,{color:D.muted,inverse:!0,children:" "},void 0,!1,void 0,this),q0(c0,{children:Array.from(K).slice(Q).join("")},void 0,!1,void 0,this)]},void 0,!0,void 0,this),q0(M$,{flexShrink:0,children:q0(c0,{color:D.muted,dimColor:!0,wrap:"truncate-end",children:L},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var tG=C(()=>{P1();Y1();M5();e2()});function $4($){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 jF($,f){if($<=0||f<=0)return null;return Math.round($/f*100)}function aG($,f,Z=0){return{context:$.lastInputTokens>0?$.lastInputTokens:Z,input:$.totalInputTokens,output:$.totalOutputTokens,contextWindow:f}}function sG($){let f=jF($.context,$.contextWindow);if(f==null)return"";return`${$4($.context)}/${$4($.contextWindow)} ${f}%`}function eG($,f,Z=!1){let z=[`思考 ${$}`];if(Z)z.push("记忆 开");if(f&&f>0)z.push(`窗口 ${$4(f)}`);return z.join(" · ")}import{Box as $Q,Text as i5}from"ink";import{jsxDEV as b6}from"react/jsx-dev-runtime";function fQ({state:$,columns:f=80}){let Z=$.model||"unknown",z=b$(K1(void 0,$.model).thinking),J=eG(z,$.tokenInfo?.contextWindow,Q1()),K=$.tokenInfo?sG($.tokenInfo):"",G=Math.max(8,f-2),Q=$.copyNotice?`✓ ${$.copyNotice}`:$.selectionMode?"选择模式 ↑↓←→扩选 Enter复制 Esc退出":null,Y=Q?A0(Q):0;return b6($Q,{flexDirection:"column",flexShrink:0,width:"100%",children:[b6(i5,{dimColor:!0,wrap:"truncate-end",children:Q?`${"─".repeat(Math.max(0,G-Y-2))} ${Q}`:"─".repeat(G)},void 0,!1,void 0,this),b6($Q,{children:[b6(i5,{children:" \uD83E\uDD16 min-agent"},void 0,!1,void 0,this),b6(i5,{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 ZQ=C(()=>{G1();j1();P1()});import{useEffect as zQ,useState as t5}from"react";import{Box as W1,Text as q$,useInput as CF,useStdout as OF}from"ink";import{jsxDEV as b0}from"react/jsx-dev-runtime";function JQ($){let f=Math.max(4,$-11);return Math.min(6+f+3,Math.max(6,$-2))}function KQ({currentModel:$,onSelect:f,onCancel:Z}){let[z,J]=t5(null),[K,G]=t5(""),[Q,Y]=t5(0),{stdout:P}=OF();zQ(()=>{let v=!1,O=t(),b=s(O);if(b?.baseURL&&b?.apiKey)_4(b.baseURL,b.apiKey).then((T)=>{if(!v)J(T)}).catch(()=>{if(!v)J([])});else J([]);return()=>{v=!0}},[]);let X=P.rows||24,W=Math.max(4,X-11),H=h1(s(t())),U=K.trim().toLowerCase(),M=(z??[]).filter((v)=>v.toLowerCase().includes(U)),N=Math.min(Q,Math.max(0,M.length-1)),q=Math.min(N,Math.max(0,M.length-W)),L=M.slice(q,q+W),F=q,V=M.length-(q+L.length);zQ(()=>{Y(0)},[]),CF((v,O)=>{let b=v.replace(/[\r\n]+$/,""),T=O.return||/[\r\n]+$/.test(v);if(O.escape){Z();return}if(O.pageDown){if(M.length>0)Y((I)=>Math.min(M.length-1,I+W));return}if(O.pageUp){if(M.length>0)Y((I)=>Math.max(0,I-W));return}if(M.length>0){if(O.downArrow){Y((I)=>(I+1)%M.length);return}if(O.upArrow){Y((I)=>(I-1+M.length)%M.length);return}}if(T){if(M.length>0)f(M[N]);else if(U!==""&&!H)f(U);return}if(O.backspace||O.delete){G((I)=>Array.from(I).slice(0,-1).join(""));return}if(O.ctrl&&v==="u"){G("");return}if(O.ctrl||O.meta||O.tab)return;if(b)G((I)=>I+b)});let B=z===null,A=z!==null&&M.length===0&&U==="",j=U;return b0(W1,{flexDirection:"column",flexShrink:0,width:"100%",borderStyle:"round",borderColor:D.pickerBorder,paddingX:1,children:[b0(W1,{children:[b0(q$,{bold:!0,color:D.pickerBorder,children:"选择模型"},void 0,!1,void 0,this),b0(q$,{color:D.muted,children:$?` (当前: ${$})`:""},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b0(W1,{children:[b0(q$,{color:D.muted,children:"筛选: "},void 0,!1,void 0,this),b0(q$,{color:K?D.accent:D.muted,children:K||"输入字符过滤,↑↓/PgUpDn 导航"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),B&&b0(W1,{children:b0(q$,{color:D.muted,dimColor:!0,children:"正在获取模型列表..."},void 0,!1,void 0,this)},void 0,!1,void 0,this),A&&b0(W1,{children:b0(q$,{color:D.muted,dimColor:!0,children:"无法获取模型列表(可输入模型名后按 Enter)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),z!==null&&F>0&&b0(W1,{children:b0(q$,{color:D.muted,dimColor:!0,children:["… 上方还有 ",F," 个模型"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),z!==null&&L.map((v,O)=>b0(W1,{children:[b0(q$,{color:O===N-q?D.accent:D.muted,children:O===N-q?"❯ ":" "},void 0,!1,void 0,this),b0(q$,{bold:O===N-q,color:O===N-q?D.accent:void 0,children:v},void 0,!1,void 0,this),v===$&&b0(q$,{color:D.success,children:" ← 当前"},void 0,!1,void 0,this)]},v,!0,void 0,this)),V>0&&b0(W1,{children:b0(q$,{color:D.muted,dimColor:!0,children:["… 下方还有 ",V," 个模型(输入字符过滤)"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),z!==null&&M.length===0&&j!==""&&!H&&b0(W1,{children:[b0(q$,{color:D.accent,bold:!0,children:["❯"," "]},void 0,!0,void 0,this),b0(q$,{color:D.accent,bold:!0,children:["使用自定义模型: ",j]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),b0(W1,{children:b0(q$,{color:D.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 GQ=C(()=>{l();Y1()});import{useEffect as QQ,useRef as w8,useState as YQ}from"react";import{Box as j6,Text as I4,useInput as wF}from"ink";import{jsxDEV as u$}from"react/jsx-dev-runtime";function PQ(){return 11}function XQ({scope:$,modelId:f,onSelect:Z,onCancel:z}){let J=s(K0()),K=f??J?.defaultModel,G=K1(void 0,K),[Q,Y]=YQ(()=>l1(K)),[P,X]=YQ(()=>rf(G.thinking,l1(K))),W=w8(!1),H=w8(!1),U=w8(P),M=w8(Q);return U.current=P,M.current=Q,QQ(()=>{let N=setTimeout(()=>{W.current=!0},0);return()=>clearTimeout(N)},[]),QQ(()=>{if(!K)return;let N=!1;return Q2(K,{type:J?.type,baseURL:J?.baseURL}).then((q)=>{if(N||q.length===0)return;if(Y(q),H.current){X((L)=>Math.min(L,Math.max(0,q.length-1)));return}X(rf(K1(void 0,K).thinking,q))}),()=>{N=!0}},[K,J?.baseURL,J?.type]),wF((N,q)=>{if(q.escape){z();return}let L=M.current;if(L.length===0)return;if(q.downArrow){H.current=!0,X((F)=>(F+1)%L.length);return}if(q.upArrow){H.current=!0,X((F)=>(F-1+L.length)%L.length);return}if(i$(W.current,q,N)){let F=L[U.current];if(F)Z(F)}}),u$(j6,{flexDirection:"column",flexShrink:0,width:"100%",borderStyle:"round",borderColor:D.pickerBorder,paddingX:1,children:[u$(j6,{children:[u$(I4,{bold:!0,color:D.pickerBorder,children:"选择思考强度"},void 0,!1,void 0,this),$==="project"&&u$(I4,{color:D.muted,children:"(写入当前项目)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),u$(j6,{children:u$(I4,{color:D.muted,children:["当前: ",b$(G.thinking),"(",g9(G.source),")"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Q.map((N,q)=>{let L=q===P;return u$(j6,{children:[u$(I4,{color:L?D.accent:D.muted,children:L?"❯ ":" "},void 0,!1,void 0,this),u$(I4,{bold:L,color:L?D.accent:void 0,children:b$(N)},void 0,!1,void 0,this),N===G.thinking&&u$(I4,{color:D.success,children:" ← 当前"},void 0,!1,void 0,this)]},N,!0,void 0,this)}),u$(j6,{children:u$(I4,{color:D.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 WQ=C(()=>{l();G1();Y1()});var UQ={};M0(UQ,{tokensForCtxLevel:()=>T8,setOllamaContextChoice:()=>R4,parseCtxChoice:()=>C6,matchCtxLevel:()=>k4,isCtxLevel:()=>a5,isCtxChoice:()=>yF,ctxPayload:()=>I8,ctxChoiceLabel:()=>f4,configuredCtxChoice:()=>e5,activeProviderIsOllama:()=>s5,CTX_LEVELS:()=>y8,CTX_CHOICES:()=>F$,CTX_AUTO:()=>H1});function a5($){return y8.includes($)}function yF($){return $===H1||a5($)}function T8($){return HQ[$]}function k4($){return TF.get(Math.floor($))??null}function C6($){if($==null)return null;let f=$.trim().toLowerCase();if(!f)return null;if(f==="auto"||f==="default")return H1;if(a5(f))return f;if(!/^\d+$/.test(f))return null;return k4(Number(f))}function f4($){return $===H1?"自动":$}function s5(){return s(t())?.type==="ollama"}function e5(){let $=s(t())?.contextWindow;if(typeof $!=="number"||!Number.isFinite($)||$<=0)return{choice:H1};let f=k4($);if(f)return{choice:f,tokens:T8(f)};return{choice:H1,tokens:Math.floor($)}}function R4($){let f=t(),Z=s(f);if(!Z)return{ok:!1,reason:"no-provider"};if(Z.type!=="ollama")return{ok:!1,reason:"not-ollama"};if($===H1)delete Z.contextWindow;else Z.contextWindow=T8($);return I0(f),$===H1?{ok:!0,choice:$}:{ok:!0,choice:$,tokens:T8($)}}function I8(){let $=s(t());if($?.type!=="ollama")return{configurable:!1,level:null};let f=$.contextWindow;if(typeof f!=="number"||!Number.isFinite(f)||f<=0)return{configurable:!0,level:H1};return{configurable:!0,level:k4(f)}}var y8,H1="auto",F$,HQ,TF;var B2=C(()=>{l();y8=["2k","4k","8k","12k","16k","32k","64k","128k","256k"],F$=[...y8,H1],HQ={"2k":2048,"4k":4096,"8k":8192,"12k":12288,"16k":16384,"32k":32768,"64k":65536,"128k":131072,"256k":262144},TF=new Map(y8.map(($)=>[HQ[$],$]))});import{useEffect as IF,useRef as MQ,useState as kF}from"react";import{Box as O6,Text as V2,useInput as RF}from"ink";import{jsxDEV as t$}from"react/jsx-dev-runtime";function qQ(){return 4+F$.length+1}function FQ(){let $=s(t())?.contextWindow;if(typeof $==="number"&&Number.isFinite($)&&$>0)return Math.floor($);return}function SF(){let $=FQ();if($==null)return f4("auto");return k4($)??$4($)}function EF(){let $=FQ();if($==null)return"auto";return k4($)}function NQ({onSelect:$,onCancel:f}){let Z=EF(),[z,J]=kF(()=>{let Q=Z?F$.indexOf(Z):-1;return Q>=0?Q:F$.length-1}),K=MQ(!1),G=MQ(z);return G.current=z,IF(()=>{let Q=setTimeout(()=>{K.current=!0},0);return()=>clearTimeout(Q)},[]),RF((Q,Y)=>{if(Y.escape){f();return}if(Y.downArrow){J((P)=>(P+1)%F$.length);return}if(Y.upArrow){J((P)=>(P-1+F$.length)%F$.length);return}if(i$(K.current,Y,Q)){let P=F$[G.current];if(P)$(P)}}),t$(O6,{flexDirection:"column",flexShrink:0,width:"100%",borderStyle:"round",borderColor:D.pickerBorder,paddingX:1,children:[t$(O6,{children:t$(V2,{bold:!0,color:D.pickerBorder,children:"选择上下文窗口"},void 0,!1,void 0,this)},void 0,!1,void 0,this),t$(O6,{children:t$(V2,{color:D.muted,children:["当前: ",SF()]},void 0,!0,void 0,this)},void 0,!1,void 0,this),F$.map((Q,Y)=>{let P=Y===z;return t$(O6,{children:[t$(V2,{color:P?D.accent:D.muted,children:P?"❯ ":" "},void 0,!1,void 0,this),t$(V2,{bold:P,color:P?D.accent:void 0,children:f4(Q)},void 0,!1,void 0,this),Q===Z&&t$(V2,{color:D.success,children:" ← 当前"},void 0,!1,void 0,this)]},Q,!0,void 0,this)}),t$(O6,{children:t$(V2,{color:D.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 BQ=C(()=>{l();B2();Y1()});var VQ={};M0(VQ,{listProviderChoices:()=>L2,applyProviderSwitch:()=>$7});function vF($){return Boolean($.name?.trim())}function L2(){let $=K0(),f=s($)?.name;return($.providers??[]).filter(vF).map((Z)=>({name:Z.name,baseURL:Z.baseURL,defaultModel:Z.defaultModel,current:Z.name===f}))}function uF(){let $=w0();if($.activeProvider===void 0)return;let{activeProvider:f,...Z}=$;W$(Z)}function $7($){let f=U2(t(),$);if("error"in f)return{ok:!1,message:f.error};I0(f),uF();let Z=s(f);return{ok:!0,name:$,defaultModel:Z?.defaultModel??""}}var k8=C(()=>{l()});import{useEffect as xF,useRef as f7,useState as gF}from"react";import{Box as Z4,Text as y1,useInput as nF,useStdout as hF}from"ink";import{jsxDEV as r0}from"react/jsx-dev-runtime";function LQ($){let f=Math.max(1,L2().length),Z=Math.max(4,$-11),z=Math.min(f,Z),J=f>Z?2:0;return 4+z+J+1}function _Q({onSelect:$,onCancel:f}){let Z=L2(),z=Z.find((L)=>L.current)?.name,[J,K]=gF(()=>{let L=Z.findIndex((F)=>F.current);return L>=0?L:0}),G=f7(!1),Q=f7(J),Y=f7(Z);Q.current=J,Y.current=Z;let{stdout:P}=hF(),X=P.rows||24,W=Math.max(4,X-11),H=Z.length===0?0:Math.min(J,Z.length-1),U=Math.min(H,Math.max(0,Z.length-W)),M=Z.slice(U,U+W),N=U,q=Z.length-(U+M.length);return xF(()=>{let L=setTimeout(()=>{G.current=!0},0);return()=>clearTimeout(L)},[]),nF((L,F)=>{if(F.escape){f();return}let V=Y.current;if(V.length===0)return;if(F.pageDown){K((B)=>Math.min(V.length-1,B+W));return}if(F.pageUp){K((B)=>Math.max(0,B-W));return}if(F.downArrow){K((B)=>(B+1)%V.length);return}if(F.upArrow){K((B)=>(B-1+V.length)%V.length);return}if(i$(G.current,F,L)){let B=V[Q.current];if(B)$(B.name)}}),r0(Z4,{flexDirection:"column",flexShrink:0,width:"100%",borderStyle:"round",borderColor:D.pickerBorder,paddingX:1,children:[r0(Z4,{children:r0(y1,{bold:!0,color:D.pickerBorder,children:"选择服务商"},void 0,!1,void 0,this)},void 0,!1,void 0,this),r0(Z4,{children:r0(y1,{color:D.muted,children:["当前: ",z??"无"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Z.length===0&&r0(Z4,{children:r0(y1,{color:D.muted,dimColor:!0,children:"无已配置服务商"},void 0,!1,void 0,this)},void 0,!1,void 0,this),N>0&&r0(Z4,{children:r0(y1,{color:D.muted,dimColor:!0,children:["… 上方还有 ",N," 个服务商"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),M.map((L,F)=>{let V=F===H-U;return r0(Z4,{children:[r0(y1,{color:V?D.accent:D.muted,children:V?"❯ ":" "},void 0,!1,void 0,this),r0(y1,{bold:V,color:V?D.accent:void 0,wrap:"truncate-end",children:cF(L)},void 0,!1,void 0,this),L.current&&r0(y1,{color:D.success,children:" ← 当前"},void 0,!1,void 0,this)]},L.name,!0,void 0,this)}),q>0&&r0(Z4,{children:r0(y1,{color:D.muted,dimColor:!0,children:["… 下方还有 ",q," 个服务商"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),r0(Z4,{children:r0(y1,{color:D.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 cF($){return`${$.name} ${$.baseURL}`}var DQ=C(()=>{k8();Y1()});import{generateText as mF}from"ai";async function AQ($,f){let Z=f.find((Q)=>Q.role==="user");if(!Z)return null;let z=typeof Z.content==="string"?Z.content:Array.isArray(Z.content)?Z.content.filter((Q)=>("text"in Q)).map((Q)=>Q.text??"").join(" "):"";if(!z.trim())return null;let J=f.find((Q)=>Q.role==="assistant"),K=J?typeof J.content==="string"?J.content.slice(0,200):"":"",G=K?`User: ${z.slice(0,300)}
|
|
97
|
-
Assistant: ${
|
|
87
|
+
`}formatInline($,Z){return $.split(/(`[^`]*`)/g).map((z)=>{if(z.startsWith("`")&&z.endsWith("`")&&z.length>=2){let Q=z.slice(1,-1);return`${Z.cyan}${Q}${Z.reset}`}let G=z;return G=G.replace(/\*\*([^*]+)\*\*/g,`${Z.bold}$1${Z.reset}`),G=G.replace(/\*([^*]+)\*/g,`${Z.italic}$1${Z.reset}`),G=G.replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${Z.cyan}$1${Z.reset} ${Z.dim}($2)${Z.reset}`),G}).join("")}formatLine($,Z){if($.startsWith("```")){if(!this.inCodeBlock)return this.inCodeBlock=!0,this.codeLang=$.slice(3).trim(),`${Z.dim}┌─ ${this.codeLang||"code"} ${"─".repeat(Math.max(0,40-(this.codeLang?.length??0)))}${Z.reset}`;return this.inCodeBlock=!1,this.codeLang="",`${Z.dim}└${"─".repeat(44)}${Z.reset}`}if(this.inCodeBlock)return`${Z.dim}│${Z.reset} ${$}`;if($.startsWith("### "))return`${Z.bold}${this.formatInline($.slice(4),Z)}${Z.reset}`;if($.startsWith("## "))return`${Z.bold}${this.formatInline($.slice(3),Z)}${Z.reset}`;if($.startsWith("# "))return`${Z.bold}${Z.cyan}${this.formatInline($.slice(2),Z)}${Z.reset}`;if(/^---+$/.test($))return`${Z.dim}${"─".repeat(44)}${Z.reset}`;let J=$.match(/^(\s*)>\s?(.*)$/);if(J){let z=J[1],G=J[2];return`${z}${Z.dim}▎${Z.reset} ${this.formatInline(G,Z)}`}if(/^\s*\d+\.\s/.test($)){let z=$.match(/^(\s*)(\d+\.)(\s)(.*)$/);if(z)return`${z[1]}${Z.yellow}${z[2]}${Z.reset}${z[3]}${this.formatInline(z[4],Z)}`}if($.match(/^\s*[-*]\s/))return $.replace(/^(\s*)([-*])(\s)(.*)$/,(z,G,Q,Y,K)=>{return`${G}${Z.cyan}•${Z.reset}${Y}${this.formatInline(K,Z)}`});return this.formatInline($,Z)}}var FY,NY;var g7=C(()=>{H1();FY={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"},NY={reset:"",bold:"",dim:"",italic:"",cyan:"",green:"",yellow:"",magenta:"",gray:"",underline:""}});function V2($){return $.replace(/\x1b\[[0-9;]*m/g,"")}function j3($,Z,J){if(J<=Z)return $;let z="",G=0,Q=!1;for(let Y of $.split(/(\x1b\[[0-9;]*m)/g)){if(Y.startsWith("\x1B[")){if(Q&&Y===ZN){if(G<J)z+=Y+BY;else z+=u7+Y,Q=!1;continue}z+=Y;continue}for(let{text:K,width:X}of b$(Y)){let P=G,W=G+X,H=W>Z&&P<J;if(H&&!Q)z+=BY,Q=!0;else if(!H&&Q)z+=u7,Q=!1;z+=K,G=W}}if(Q)z+=u7;return z}function JN($,Z,J){if(J<=Z)return"";let z="",G=0;for(let{text:Q,width:Y}of b$(VY($))){let K=G+Y;if(K>Z&&G<J)z+=Q;if(G=K,G>=J)break}return z}function VY($){let Z=L3.get($);if(Z!==void 0)return Z;let J=V2($);if(L3.size>512)L3.clear();return L3.set($,J),J}function fY($,Z,J){let z=[];for(let G=0;G<J.length;G++){let Q=J[G],Y=$[G];if(!Q||!Y)continue;z.push(zN(JN(Y,Q.start,Q.end),Z[G]??"plain"))}while(z.length>0&&z[z.length-1]==="")z.pop();return z.join(`
|
|
88
|
+
`)}function zN($,Z){if(Z==="user-head"&&$.startsWith("> "))return $.slice(2);if(Z==="tool-head")return $.replace(/^⚡ .*?[▸▾] /,"");if(Z==="thinking-head")return $.replace(/^💭 .*?[▸▾] /,"");if((Z==="tool-body"||Z==="thinking-body")&&$.startsWith(" "))return $.slice(2);return $}function h7($,Z){if(Z==="user"&&$.startsWith("> "))return"> ";if(Z==="tool"){let J=$.match(/^⚡ .*?[▸▾] /);return J?J[0]:""}if(Z==="thinking"){let J=$.match(/^💭 .*?[▸▾] /);return J?J[0]:""}return""}function _Y($,Z){let J=$.start<Z&&$.end>0?{start:$.start,end:Math.min(Z,$.end)}:null,z=$.end>Z?{start:Math.max(0,$.start-Z),end:$.end-Z}:null;return{head:J&&J.end>J.start?J:null,tail:z&&z.end>z.start?z:null}}function LY($,Z){let J=[],z=0;for(let{text:K,width:X}of b$($))J.push({ch:K,start:z,end:z+X}),z+=X;let G=J.find((K)=>Z>=K.start&&Z<K.end);if(!G||/\s/.test(G.ch))return{start:Z,end:Z};let Q=J.indexOf(G),Y=Q;while(Q>0&&!/\s/.test(J[Q-1].ch))Q--;while(Y<J.length-1&&!/\s/.test(J[Y+1].ch))Y++;return{start:J[Q].start,end:J[Y].end}}function j6($,Z,J,z=1){let G=Math.max(0,$.length-1);return{row:Math.min(G,Math.max(0,Z-1)),col:Math.max(0,J-1-z)}}function jY($,Z){let J=new Map;for(let z=0;z<$.length;z++){let G=Z[z],Q=$[z];if(!G||!Q||Q.end<=Q.start)continue;let Y=J.get(G.part);if(!Y)Y=[],J.set(G.part,Y);Y[G.shown]=Q}return J}function m7($,Z,J){let z=$.map(()=>null),G=Math.min(Z.row,J.row),Q=Math.max(Z.row,J.row);for(let Y=G;Y<=Q;Y++){let K=$[Y];if(Y<0||Y>=$.length||K===null)continue;let X=A0(VY(K)),P,W;if(Z.row===J.row)P=Math.min(Z.col,J.col),W=Math.max(Z.col,J.col)+1;else if(Y===Z.row)if(Z.row<J.row)P=Z.col,W=X;else P=0,W=Z.col+1;else if(Y===J.row)if(Z.row<J.row)P=0,W=J.col+1;else P=J.col,W=X;else P=0,W=X;if(P=Math.max(0,P),W>P)z[Y]={start:P,end:W}}return z}var ZN="\x1B[0m",BY="\x1B[7m",u7="\x1B[27m",L3;var AY=C(()=>{H1();L3=new Map});function DY(){return{pending:null,selection:null}}function n7($){$.pending=null,$.selection=null}function OY($,Z,J){let{button:z,row:G,col:Q,press:Y}=Z,K=(z&oQ)===0,X=$.pending!=null;if(K&&X&&((z&B2)!==0||z===0&&Y)){let P=$.pending;if(G===P.row&&Q===P.col&&$.selection==null)return null;return $.selection={anchor:P,cur:{row:G,col:Q}},{type:"selection",selection:$.selection}}if(z===0&&Y)return $.selection=null,$.pending=G>=1&&G<=J?{row:G,col:Q}:null,{type:"selection",selection:null};if(z===0&&!Y){let{selection:P,pending:W}=$;if($.pending=null,$.selection=null,P&&(P.anchor.row!==P.cur.row||P.anchor.col!==P.cur.col))return{type:"copy",selection:P};if(W)return{type:"click",row:W.row,col:W.col}}return null}var CY=C(()=>{B6()});function bY(){return{row:-1,col:-1,at:Number.NEGATIVE_INFINITY,count:0}}function wY($,Z){let J=Z.row===$.row&&Math.abs(Z.col-$.col)<=2&&Z.at-$.at<=400;return $.count=J?$.count+1:1,$.row=Z.row,$.col=Z.col,$.at=Z.at,$.count}import GN,{useMemo as c7,useEffect as A3,useRef as $$,useState as D3,useCallback as QN}from"react";import{Box as G$,Text as v$,useInput as YN,useStdin as KN}from"ink";import{jsxDEV as N0}from"react/jsx-dev-runtime";function XN($,Z){let J=[],z="",G=0,Q="";for(let Y of $.split(/(\x1b\[[0-9;]*m)/g)){if(Y.startsWith("\x1B[")){if(Y===p7)Q="";else Q+=Y;z+=Y;continue}for(let{text:K,width:X}of b$(Y))if(G>0&&G+X>Z)J.push(z+p7),z=Q+K,G=X;else z+=K,G+=X}return J.push(z+p7),J}function IY($,Z){let J="",z=0;for(let{text:G,width:Q}of b$($)){if(z+Q>Z)break;J+=G,z+=Q}return J}function PN($){let Z=$.replace(/\s+$/,"").split(`
|
|
89
|
+
`);if(Z.length<=o7)return Z;let J=Z.length-o7;return[...Z.slice(0,o7),`… 结果还有 ${J} 行未显示`]}function TY($){return $.role==="tool"||$.role==="thinking"}function O3($,Z,J){return $.role==="thinking"?$.id===J:Z.has($.id)}function RY($,Z,J,z){let G=Math.max(1,z-A0($)),Q=A0(Z+J)<=G?`${$}${Z}${J}`:`${$}${IY(Z,Math.max(1,G-A0(J)-1))}…${J}`;return[IY(Q,z)]}function WN($,Z,J){let z=rQ(Z);switch($.role){case"user":return a0(`> ${$.content}`,z);case"assistant":try{let G=new L6,Y=(G.write(typeof $.content==="string"?$.content:String($.content??""))+G.flush()).replace(/\n$/,"");if(Y==="")return[];let K=Y.split(`
|
|
90
|
+
`),X=0,P=K.length;while(X<P&&K[X].trim()==="")X++;while(P>X&&K[P-1].trim()==="")P--;if(X===P)return[];let W=[];for(let H=X;H<P;H++)W.push(...XN(K[H],z));return W}catch{return a0(typeof $.content==="string"?$.content:String($.content??""),z)}case"thinking":{let G=$.content.trim();if(!G)return[];let Q=G.replace(/\s+/g," "),Y=`\uD83D\uDCAD 思考 ${J?"▾":"▸"} `;if(!J){let X=G.split(`
|
|
91
|
+
`).length,P=X>1?` → ${X} 行`:"";return RY(Y,Q,P,z)}let K=a0(Y,z);for(let X of G.replace(/\s+$/,"").split(`
|
|
92
|
+
`))K.push(...a0(` ${X}`,z));return K}case"tool":{let G=$.toolName??"",Q=$.content.replace(/\s+/g," ").trim(),Y=`⚡ ${G} ${J?"▾":"▸"} `;if(!J){let P=$.toolResultSummary?` → ${$.toolResultSummary}`:"";return RY(Y,Q,P,z)}let K=a0(`${Y}${Q}`,z);if($.toolChildren&&$.toolChildren.length>0)for(let P of $.toolChildren){let W=P.summary?` ${P.summary}`:"";K.push(...a0(` ↳ ${P.name}${W}`,z))}let X=$.toolResult;if(X&&X.trim()!=="")for(let P of PN(X))K.push(...a0(` ${P}`,z));return K}default:{if(!$.content)return[];let G=[];for(let Q of $.content.split(`
|
|
93
|
+
`))G.push(...a0(Q,z));return G}}}function kY($){let Z=0;for(let J=0;J<$.length;J++)Z=Z*31+$.charCodeAt(J)|0;return String(Z)}function qN($,Z,J){return[$.id,String($.content.length),kY($.content.slice(0,64)+$.content.slice(-32)),String($.toolResult?.length??0),$.toolResult?kY($.toolResult.slice(0,64)):"",String(Z),J?"1":"0",$.toolName??"",$.toolResultSummary??"",($.toolChildren??[]).map((z)=>`${z.name}:${z.summary}`).join("|")].join("\x00")}function C3($,Z,J){let z=qN($,Z,J),G=A6.get(z);if(G!==void 0)return G;let Q=WN($,Z,J);if(A6.size>=HN){let Y=A6.keys().next().value;if(Y!==void 0)A6.delete(Y)}return A6.set(z,Q),Q}function UN($,Z,J){return C3($,Z,J).length+($.role==="user"?SY:0)}function MN($,Z,J,z){let G=Z.reduce((q,U)=>q+U,0);if(J<=0)return{winTop:0,winBottom:G,above:0,below:0,parts:$.map((q,U)=>({msg:q,start:0,count:Z[U]??0}))};let Q=0,Y=0,K=0,X=J;for(let q=0;q<3;q++){let U=(Q>0?1:0)+(Y>0?1:0);X=Math.max(1,J-U);let M=Math.max(0,G-X);K=z===null?M:Math.min(z,M),Q=K,Y=Math.max(0,G-(K+X))}let P=Math.min(G,K+X),W=[],H=0;for(let q=0;q<$.length;q++){let U=Z[q]??0;if(H<P&&H+U>K){let M=Math.max(0,K-H),F=Math.min(U-M,P-H-M);W.push({msg:$[q],start:M,count:F})}H+=U}return{winTop:K,winBottom:P,above:Q,below:Y,parts:W}}function EY({messages:$,maxHeight:Z,columns:J=80,onCopyNotice:z,selectionMode:G,onExitSelectionMode:Q,interactive:Y=!0}){let[K,X]=D3(null),[P,W]=D3(new Set),[H,q]=D3(null),U=$[$.length-1],M=U?.role==="thinking"?U.id:null,F=$$(null);A3(()=>{if(M)F.current=M,q(M);else if(F.current!==null){let h=F.current;F.current=null,q((E)=>E===h?null:E)}},[M]);let[N,f]=D3(null),B=c7(()=>$.map((h)=>UN(h,J,O3(h,P,H))),[$,J,P,H]),_=c7(()=>MN($,B,Z??0,K),[$,B,Z,K]),V=$$(_);V.current=_;let A=c7(()=>NN(_,J,P,H),[_,J,P,H]),O=$$(A.rows);O.current=A.rows;let v=$$(A.kinds);v.current=A.kinds;let b=$$(A.partMeta);b.current=A.partMeta;let D=$$(z);D.current=z;let I=$$(Boolean(G));I.current=Boolean(G);let R=$$(null),J0=$$(bY()),m=(h)=>j6(A.rows,h.row,h.col),$0=N?m7(A.rows,m(N.anchor),m(N.cur)):null,x=$0?jY($0,A.partMeta):null,T=QN((h)=>{let E=O.current,t=fY(E,v.current,m7(E,j6(E,h.anchor.row,h.anchor.col),j6(E,h.cur.row,h.cur.col)));if(t==="")D.current?.("未选中文本");else if(k7(t))D.current?.(`已复制 ${Array.from(t).length} 字`);else D.current?.("复制失败")},[]),o=$$(T);o.current=T;let S=$$(N);S.current=N;let p=$$(Q);p.current=Q;let z0=()=>{let h=S.current;if(h)return h;if(R.current)return{anchor:R.current,cur:R.current};let t=O.current.findIndex((X0)=>X0!=null),d=t>=0?{row:t+1,col:2}:{row:1,col:2};return{anchor:d,cur:d}},u=(h)=>{let E=Math.max(1,O.current.length);return{anchor:h.anchor,cur:{row:Math.max(1,Math.min(E,h.cur.row)),col:Math.max(1,h.cur.col)}}},w=(h,E)=>{let t=z0(),d=Math.max(1,O.current.length),X0=Math.max(1,Math.min(d,t.cur.row+h));if(h!==0)while(X0>=1&&X0<=d&&O.current[X0-1]==null){let m2=X0+Math.sign(h);if(m2<1||m2>d)break;X0=m2}let I0=O.current[X0-1],O0=I0?A0(V2(I0)):0,X$=Math.max(1,Math.min(2+O0,t.cur.col+E));f({anchor:t.anchor,cur:{row:X0,col:X$}})};A3(()=>{if(!G)return;f((h)=>h??z0())},[G,z0]);let y0=(h)=>{if(h.role==="thinking"){F.current=null,q((E)=>E===h.id?null:h.id);return}W((E)=>{let t=new Set(E);if(t.has(h.id))t.delete(h.id);else t.add(h.id);return t})},Y0=$$(y0);Y0.current=y0;let q0=(h)=>{X((E)=>{let t=E??V.current.winTop;return Math.max(0,t-h)})},Z0=(h)=>{X((E)=>{if(E===null)return E;let t=V.current.winTop+V.current.below;return E+h>=t?null:E+h})},K0=$$(DY());YN((h,E)=>{if(I.current){let t=E;if(E.escape){f(null),p.current?.();return}if(E.return){let d=S.current??z0();o.current(d),p.current?.();return}if(E.leftArrow){w(0,-1);return}if(E.rightArrow){w(0,1);return}if(E.upArrow){w(-1,0);return}if(E.downArrow){w(1,0);return}if(t.home){let d=z0();f({anchor:d.anchor,cur:{row:d.cur.row,col:1}});return}if(t.end){let d=z0(),X0=O.current[d.cur.row-1],I0=X0?A0(V2(X0)):0;f({anchor:d.anchor,cur:{row:d.cur.row,col:2+I0}});return}if(E.pageUp)q0(_.winBottom-_.winTop),f((d)=>d?u(d):d);else if(E.pageDown)Z0(_.winBottom-_.winTop),f((d)=>d?u(d):d);return}if(!h.startsWith("[<")&&!/^[\d;,]+[Mm]$/.test(h))n7(K0.current),f(null);if(E.pageUp){let t=_.winBottom-_.winTop;q0(t)}else if(E.pageDown){let t=_.winBottom-_.winTop;Z0(t)}if((h===" "||h==="o")&&!E.ctrl&&!E.meta){let t=Math.floor((_.winTop+_.winBottom)/2),d=0;for(let X0=0;X0<$.length;X0++){let I0=B[X0]??0;if(t>=d&&t<d+I0&&TY($[X0])){Y0.current($[X0]);break}d+=I0}}},{isActive:Boolean(Y&&Z&&Z>0)});let U0=$$($.length);A3(()=>{if($.length<U0.current)X(null);U0.current=$.length},[$]);let c=(h)=>{let{above:E,parts:t}=V.current,d=h-1;if(d<0)return;if(E>0){if(d-=1,d<0)return}for(let X0 of t){if(d<X0.count){if(TY(X0.msg))Y0.current(X0.msg);return}d-=X0.count}},c0=(h,E)=>{let t=O.current,d=j6(t,h,E),X0=t[d.row];if(!X0)return;let I0=LY(V2(X0),d.col);if(I0.end<=I0.start)return;let O0={anchor:{row:d.row+1,col:I0.start+2},cur:{row:d.row+1,col:I0.end+1}};f(O0),o.current(O0)},f$=(h)=>{let E=h-1,t=b.current[E];if(!t)return;let d=E,X0=E;while(d>0&&b.current[d-1]?.part===t.part)d--;while(X0<b.current.length-1&&b.current[X0+1]?.part===t.part)X0++;let I0=O.current[X0],O0=I0?A0(V2(I0)):0,X$={anchor:{row:d+1,col:2},cur:{row:X0+1,col:Math.max(2,1+O0)}};f(X$),o.current(X$)},{stdin:g0}=KN(),_$=$$("");if(A3(()=>{if(!g0||!Z||Z<=0)return;let h=(E)=>{_$.current+=E.toString("utf-8");let t;while(t=q3(_$.current)){_$.current=t.rest;let{button:d,row:X0}=t.event,I0=O.current.length;if(d===N6||d===O7||d===N6+B2||d===O7+B2){if(X0>=1&&X0<=I0+2){if(n7(K0.current),!I.current)f(null);if(d===N6||d===N6+B2)q0(3);else Z0(3);if(I.current)f((X$)=>X$?u(X$):X$)}continue}let O0=OY(K0.current,t.event,Z);if(O0?.type==="selection")f(O0.selection);else if(O0?.type==="copy")o.current(O0.selection);else if(O0?.type==="click"){R.current={row:O0.row,col:O0.col};let X$=wY(J0.current,{row:O0.row,col:O0.col,at:Date.now()});if(X$>=3)f$(O0.row);else if(X$===2)c0(O0.row,O0.col);else c(O0.row)}}if(_$.current.length>64){let d=_$.current.lastIndexOf("\x1B");_$.current=d===-1?"":_$.current.slice(d)}};return g0.on("data",h),()=>{g0.off("data",h)}},[g0,Z,u,c,Z0,q0,f$,c0]),!Z||Z<=0)return N0(G$,{flexDirection:"column",children:[$.length===0&&N0(G$,{paddingLeft:1,paddingTop:1,children:N0(v$,{color:"gray",children:"输入消息开始对话,输入 /help 查看命令,Esc 取消运行"},void 0,!1,void 0,this)},void 0,!1,void 0,this),$.map((h)=>N0(yY,{message:h,lines:C3(h,J,O3(h,P,H))},h.id,!1,void 0,this))]},void 0,!0,void 0,this);return N0(G$,{flexDirection:"column",height:Z,overflow:"hidden",width:"100%",children:[$.length===0&&N0(G$,{paddingLeft:1,paddingTop:1,children:N0(v$,{color:"gray",children:"输入消息开始对话,输入 /help 查看命令,Esc 取消运行"},void 0,!1,void 0,this)},void 0,!1,void 0,this),_.above>0&&N0(G$,{paddingLeft:1,flexShrink:0,children:N0(v$,{color:"gray",dimColor:!0,children:["… 以上 ",_.above," 行"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),_.parts.map(({msg:h,start:E,count:t},d)=>N0(yY,{message:h,lines:C3(h,J,O3(h,P,H)),start:E,count:t,selection:x?.get(d)},h.id,!1,void 0,this)),_.below>0&&N0(G$,{paddingLeft:1,flexShrink:0,children:N0(v$,{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 vY($,Z,J,z=Z.length){if($.role!=="user")return{lines:Z.slice(J,J+z),marginTop:!1,lineOffset:J};let G=SY;if(J===0)return{lines:Z.slice(0,Math.max(0,z-G)),marginTop:!0,lineOffset:0};let Q=J-G;return{lines:Z.slice(Q,Q+z),marginTop:!1,lineOffset:Q}}function FN($,Z){if($.role==="user")return Z===0?"user-head":"plain";if($.role==="tool")return Z===0?"tool-head":"tool-body";if($.role==="thinking")return Z===0?"thinking-head":"thinking-body";return"plain"}function NN($,Z,J,z){let G=[],Q=[],Y=[];if($.above>0)G.push(null),Q.push("plain"),Y.push(null);for(let K=0;K<$.parts.length;K++){let X=$.parts[K],P=C3(X.msg,Z,O3(X.msg,J,z)),{lines:W,marginTop:H,lineOffset:q}=vY(X.msg,P,X.start,X.count);if(H)G.push(null),Q.push("plain"),Y.push(null);for(let U=0;U<W.length;U++)G.push(W[U]),Q.push(FN(X.msg,q+U)),Y.push({part:K,shown:U})}if($.below>0)G.push(null),Q.push("plain"),Y.push(null);return{rows:G,kinds:Q,partMeta:Y}}var p7="\x1B[0m",o7=120,HN=256,A6,SY=1,yY;var xY=C(()=>{g7();H1();B6();AY();CY();B3();A6=new Map;yY=GN.memo(function({message:Z,lines:J,start:z=0,count:G,selection:Q}){let{lines:Y,marginTop:K}=vY(Z,J,z,G);if(Y.length===0){if(!K)return null;return N0(G$,{height:1,flexShrink:0},void 0,!1,void 0,this)}let X=Q,P=(U,M)=>{let F=X?.[U];return F&&F.end>F.start?j3(M,F.start,F.end):M},W=(U)=>{let M=X?.[0];if(!M)return{head:null,tail:null};return _Y(M,A0(U))},H=(U,M)=>M?j3(U,M.start,M.end):U,q=(U,M)=>M?j3(U,M.start,M.end):U;switch(Z.role){case"user":{let U=Y[0]??"",M=Y.slice(1),F=h7(U,"user"),N=F?W(F):null,f=F?q(U.slice(F.length),N.tail):P(0,U);return N0(G$,{flexDirection:"column",paddingLeft:1,marginTop:K?1:0,flexShrink:0,children:[N0(G$,{flexWrap:"nowrap",children:[F!==""&&N0(G$,{flexShrink:0,children:N0(v$,{color:"cyan",bold:!0,children:H(F,N.head)},void 0,!1,void 0,this)},void 0,!1,void 0,this),N0(v$,{wrap:"truncate-end",children:f},void 0,!1,void 0,this)]},void 0,!0,void 0,this),M.map((B,_)=>N0(v$,{wrap:"truncate-end",children:P(_+1,B)},_,!1,void 0,this))]},void 0,!0,void 0,this)}case"assistant":return N0(G$,{flexDirection:"column",paddingLeft:1,flexShrink:0,children:Y.map((U,M)=>N0(v$,{wrap:"truncate-end",children:P(M,U)},M,!1,void 0,this))},void 0,!1,void 0,this);case"thinking":case"tool":{let U=Y[0]??"",M=Y.slice(1),F=Z.role==="thinking",N=h7(U,F?"thinking":"tool"),f=N?W(N):null,B=N?q(U.slice(N.length),f.tail):P(0,U),_=F?void 0:Z.toolIsError?"red":N?"gray":void 0;return N0(G$,{flexDirection:"column",paddingLeft:1,flexShrink:0,children:[N0(G$,{flexWrap:"nowrap",children:[N!==""&&N0(G$,{flexShrink:0,children:N0(v$,{color:F?"gray":"yellow",dimColor:F,children:H(N,f.head)},void 0,!1,void 0,this)},void 0,!1,void 0,this),N0(v$,{color:_,dimColor:F,wrap:"truncate-end",children:B},void 0,!1,void 0,this)]},void 0,!0,void 0,this),M.map((V,A)=>N0(v$,{color:_,dimColor:F,wrap:"truncate-end",children:P(A+1,V)},A,!1,void 0,this))]},void 0,!0,void 0,this)}case"system":return N0(G$,{flexDirection:"column",paddingLeft:1,flexShrink:0,children:Y.map((U,M)=>N0(v$,{wrap:"truncate-end",children:P(M,U)},M,!1,void 0,this))},void 0,!1,void 0,this);default:return null}},($,Z)=>$.message.id===Z.message.id&&$.start===Z.start&&$.count===Z.count&&$.lines===Z.lines&&$.selection===Z.selection)});function i$($,Z,J){if(!$)return!1;if(J===`
|
|
94
|
+
`&&!Z.return)return!1;return Boolean(Z.return)}import{useEffect as BN,useMemo as gY,useRef as VN,useState as uY}from"react";import{Box as $4,Text as q1,useInput as fN}from"ink";import{jsxDEV as m0}from"react/jsx-dev-runtime";function hY($,Z){let J=F3(Z);return String($??"").split(`
|
|
95
|
+
`).flatMap((z)=>a0(z,J))}function mY($,Z,J=0){let z=hY($,Z).length+U3;return Math.min(z,f6(J,U3))}function nY({message:$,onConfirm:Z,columns:J,maxRows:z}){let G=gY(()=>hY($,J),[$,J]),Q=Math.max(0,z-U3),[Y,K]=uY(0),[X,P]=uY(1),W=gY(()=>s0(G,Q,Y),[G,Q,Y]),H=W.above>0||W.below>0,q=VN(!1);BN(()=>{let F=setTimeout(()=>{q.current=!0},0);return()=>clearTimeout(F)},[]),fN((F,N)=>{if(N.escape){Z(!1);return}let f=F.replace(/[\r\n]+/g,"").trim().toLowerCase();if(f==="y"){Z(!0);return}if(f==="n"){Z(!1);return}if(i$(q.current,N,F)){Z(X===0);return}if(N.leftArrow){P((B)=>B===0?B:B-1);return}if(N.rightArrow){P((B)=>B===1?B:B+1);return}if(N.upArrow){if(H)K((B)=>s0(G,Q,B-1).start);else P((B)=>B===0?B:B-1);return}if(N.downArrow){if(H)K((B)=>s0(G,Q,B+1).start);else P((B)=>B===1?B:B+1);return}if(N.pageUp){if(!H)return;let B=Math.max(1,W.lines.length);K((_)=>s0(G,Q,_-B).start);return}if(N.pageDown){if(!H)return;let B=Math.max(1,W.lines.length);K((_)=>s0(G,Q,_+B).start);return}});let U=X===0,M=X===1;return m0($4,{flexDirection:"column",flexShrink:0,width:"100%",borderStyle:"round",borderColor:j.confirmBorder,paddingX:1,children:[m0($4,{flexShrink:0,children:m0(q1,{bold:!0,color:j.confirmBorder,wrap:"truncate-end",children:"⚠ 请求执行权限"},void 0,!1,void 0,this)},void 0,!1,void 0,this),Q>0&&m0($4,{flexDirection:"column",height:Q,overflow:"hidden",flexShrink:0,width:"100%",children:[W.above>0&&m0($4,{paddingLeft:1,flexShrink:0,children:m0(q1,{color:j.muted,dimColor:!0,children:["… 以上 ",W.above," 行"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),W.lines.map((F,N)=>m0($4,{paddingLeft:1,flexShrink:0,children:m0(q1,{wrap:"truncate-end",children:F},void 0,!1,void 0,this)},N,!1,void 0,this)),W.below>0&&m0($4,{paddingLeft:1,flexShrink:0,children:m0(q1,{color:j.muted,dimColor:!0,children:["↓ 还有 ",W.below," 行"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),m0($4,{marginTop:1,flexShrink:0,height:1,overflow:"hidden",width:"100%",children:[m0(q1,{bold:!0,color:U?j.success:j.muted,children:U?"▸ ":" "},void 0,!1,void 0,this),m0(q1,{bold:!0,color:U?j.success:void 0,children:"[y] 允许"},void 0,!1,void 0,this),m0(q1,{color:j.muted,children:" "},void 0,!1,void 0,this),m0(q1,{bold:!0,color:M?j.error:j.muted,children:M?"▸ ":" "},void 0,!1,void 0,this),m0(q1,{bold:!0,color:M?j.error:void 0,children:"[N] 拒绝"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),m0($4,{flexShrink:0,height:1,overflow:"hidden",width:"100%",children:m0(q1,{color:j.muted,wrap:"truncate-end",children:H?"←→ 选择 · ↑↓ 滚动 · 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 cY=C(()=>{H1();P1()});import{useEffect as d7,useMemo as r7,useRef as T1,useState as R1}from"react";import{Box as M$,Text as n0,useInput as pY}from"ink";import{jsxDEV as F0,Fragment as ON}from"react/jsx-dev-runtime";function oY($){return $?6:2}function dY($,Z,J,z=!1){let G=F3(J),Q=`❓ ${p1($)}`.split(`
|
|
96
|
+
`).flatMap((W)=>a0(W,G)),Y=d1(o1(Z)),K=Math.max(1,G-oY(z)),X=Y.map((W,H)=>({label:W,lines:`${H+1}. ${W}`.split(`
|
|
97
|
+
`).flatMap((q)=>a0(q,K))})),P=[...Q.map((W)=>({text:W,kind:"prompt"})),...X.flatMap((W,H)=>W.lines.map((q,U)=>({text:q,kind:"option",optionIndex:H,optionLead:U===0})))];return{promptLines:Q,optionBlocks:X,body:P,lines:P.map((W)=>W.text),hasOptions:Y.length>0}}function rY($,Z,J,z=0,G=!1){let Q=dY($,Z,J,G),Y=M3(Q.hasOptions),K=Q.lines.length+Y;return Math.min(K,f6(z,Y))}function _N($,Z,J){if(J<=0||!/^[0-9]$/.test(Z))return null;let z=$+Z,G=Number.parseInt(z,10);if(Number.isFinite(G)&&G>=1&&G<=J)return{buf:z,index:G-1};let Q=Number.parseInt(Z,10);if(Number.isFinite(Q)&&Q>=1&&Q<=J)return{buf:Z,index:Q-1};return null}function LN($,Z,J,z,G){if(Z<=0||$<=0)return 0;let Q=Array.from({length:$},()=>"x"),Y=s0(Q,Z,J),K=Y.start,X=Y.start+Y.lines.length;if(z>=K&&G<=X)return Y.start;if(z<K)return s0(Q,Z,z).start;let P=Math.max(0,G-Math.max(1,Y.lines.length));return s0(Q,Z,P).start}function jN($,Z){let J=$.findIndex((Q)=>Q.kind==="option"&&Q.optionIndex===Z);if(J<0)return{start:0,end:0};let G=$.slice(J).findIndex((Q)=>Q.kind!=="option"||Q.optionIndex!==Z);return{start:J,end:G<0?$.length:J+G}}function lY($){return Array.from($.replace(/[\r\n]+$/,"")).filter((Z)=>{let J=Z.codePointAt(0)??0;return J>=32&&J!==127}).join("")}function iY({prompt:$,options:Z,multiple:J=!1,onAnswer:z,columns:G,maxRows:Q}){let Y=r7(()=>dY($,Z,G,J),[$,Z,G,J]);if(Y.hasOptions)return F0(AN,{layout:Y,multiple:J,onAnswer:z,maxRows:Q},void 0,!1,void 0,this);return F0(DN,{layout:Y,onAnswer:z,maxRows:Q},void 0,!1,void 0,this)}function AN({layout:$,multiple:Z,onAnswer:J,maxRows:z}){let G=M3(!0),Q=Math.max(0,z-G),[Y,K]=R1(0),[X,P]=R1(0),[W,H]=R1(""),[q,U]=R1(()=>new Set),[M,F]=R1(""),[N,f]=R1(0),B=T1(0),_=T1(""),V=T1(q),A=T1(""),O=T1(0),v=T1(!1);B.current=Y,_.current=W,V.current=q,A.current=M,O.current=N;let b=$.optionBlocks.length,D=$.optionBlocks.findIndex((u)=>s2(u.label)),I=Y===D,R=jN($.body,Math.min(Y,Math.max(0,b-1)));d7(()=>{let u=setTimeout(()=>{v.current=!0},0);return()=>clearTimeout(u)},[]),d7(()=>{P((u)=>LN($.body.length,Q,u,R.start,R.end))},[$.body.length,Q,R.start,R.end]);let J0=r7(()=>s0($.lines,Q,X),[$.lines,Q,X]),m=J0.above>0||J0.below>0,$0=()=>{_.current="",H("")},x=(u)=>{let w=u(A.current,O.current);A.current=w.value,O.current=w.caretIndex,F(w.value),f(w.caretIndex)},T=(u)=>{let w=new Set(V.current);if(w.has(u))w.delete(u);else w.add(u);V.current=w,U(w)},o=()=>{let u=gz({multiple:Z,choices:$.optionBlocks.map((w)=>w.label),index:B.current,checked:V.current,otherText:A.current});if(!u)return;J(JSON.stringify(u))};pY((u,w)=>{if(w.escape){J(null);return}if(b===0)return;if(w.downArrow){$0(),K((Z0)=>(Z0+1)%b);return}if(w.upArrow){$0(),K((Z0)=>(Z0-1+b)%b);return}let y0=new Set(J0.lines.map((Z0,K0)=>$.body[J0.start+K0]?.optionIndex).filter((Z0)=>Z0!=null)).size,Y0=Math.max(1,y0);if(w.pageDown){$0(),K((Z0)=>Math.min(b-1,Z0+Y0));return}if(w.pageUp){$0(),K((Z0)=>Math.max(0,Z0-Y0));return}if(i$(v.current,w,u)){o();return}if(Z&&u===" "){if(I&&V.current.has(D)&&A.current.length>0){x((Z0,K0)=>z$(Z0,K0," "));return}T(B.current);return}if(!Z&&u===" "){if(I)x((Z0,K0)=>z$(Z0,K0," "));return}if(I&&(w.leftArrow||w.rightArrow)){x((Z0,K0)=>({value:Z0,caretIndex:I4(Z0,K0,w.leftArrow?-1:1)}));return}if(I&&(w.backspace||w.delete)){if(x((Z0,K0)=>N2(Z0,K0)),Z&&A.current.length===0&&V.current.has(D))T(D);return}if(I&&w.ctrl&&u==="a"){x((Z0)=>({value:Z0,caretIndex:0}));return}if(I&&w.ctrl&&u==="e"){x((Z0)=>({value:Z0,caretIndex:Array.from(Z0).length}));return}if(I&&w.ctrl&&u==="u"){x(()=>({value:"",caretIndex:0}));return}if(w.backspace||w.delete){H((Z0)=>{let K0=Array.from(Z0).slice(0,-1).join("");return _.current=K0,K0});return}if(w.ctrl||w.meta||w.tab)return;let q0=lY(u);if(!q0)return;if(I){if(x((Z0,K0)=>z$(Z0,K0,q0)),Z&&!V.current.has(D))T(D);return}if(q0.length===1&&/^[0-9]$/.test(q0)){let Z0=_N(_.current,q0,b);if(Z0)_.current=Z0.buf,H(Z0.buf),K(Z0.index);return}if(D>=0){if($0(),K(D),x((Z0,K0)=>z$(Z0,K0,q0)),Z&&!V.current.has(D))T(D)}});let S=[m?"↑↓/PgUpDn 移动":"↑↓ 移动",Z?"空格 勾选":"","数字键跳转","Enter 确认","Esc 取消",W?`数字 ${W}`:""].filter(Boolean).join(" · "),p=I||Z&&q.has(D)&&M.length>0,z0=I;return F0(M$,{flexDirection:"column",flexShrink:0,width:"100%",borderStyle:"round",borderColor:j.questionBorder,paddingX:1,children:[Q>0&&F0(M$,{flexDirection:"column",height:Q,overflow:"hidden",flexShrink:0,width:"100%",children:[J0.above>0&&F0(M$,{flexShrink:0,children:F0(n0,{color:j.muted,dimColor:!0,children:["… 以上 ",J0.above," 行"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),J0.lines.map((u,w)=>{let y0=J0.start+w,Y0=$.body[y0];if(!Y0)return null;let q0=Y0.kind==="prompt",Z0=Y0.optionIndex??-1,K0=Y0.kind==="option"&&Z0===Y,U0=Z&&q.has(Z0),c=q0?"":Y0.optionLead?`${K0?"❯ ":" "}${Z?U0?"[x] ":"[ ] ":""}`:" ".repeat(oY(Z));return F0(M$,{flexShrink:0,children:[!q0&&F0(n0,{color:K0?j.accent:j.muted,children:c},void 0,!1,void 0,this),F0(n0,{bold:q0||K0,color:q0?j.questionBorder:K0?j.accent:j.muted,wrap:"truncate-end",children:u},void 0,!1,void 0,this)]},`${Y0.kind}-${Z0}-${y0}`,!0,void 0,this)}),J0.below>0&&F0(M$,{flexShrink:0,children:F0(n0,{color:j.muted,dimColor:!0,children:["↓ 还有 ",J0.below," 行"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),F0(M$,{marginTop:1,flexShrink:0,height:1,overflow:"hidden",width:"100%",children:p||z0?F0(ON,{children:[F0(n0,{bold:!0,color:j.questionBorder,children:["→"," "]},void 0,!0,void 0,this),F0(n0,{children:Array.from(M).slice(0,z0?N:M.length).join("")},void 0,!1,void 0,this),z0&&F0(n0,{color:j.muted,inverse:!0,children:" "},void 0,!1,void 0,this),z0&&F0(n0,{children:Array.from(M).slice(N).join("")},void 0,!1,void 0,this)]},void 0,!0,void 0,this):F0(n0,{color:j.muted,dimColor:!0,children:"→ 选「其他」后可输入"},void 0,!1,void 0,this)},void 0,!1,void 0,this),F0(M$,{flexShrink:0,children:F0(n0,{color:j.muted,dimColor:!0,wrap:"truncate-end",children:S},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}function DN({layout:$,onAnswer:Z,maxRows:J}){let z=M3(!1),G=Math.max(0,J-z),[Q,Y]=R1(""),[K,X]=R1(0),[P,W]=R1(0),H=T1(""),q=T1(0),U=T1(!1);H.current=Q,q.current=K,d7(()=>{let B=setTimeout(()=>{U.current=!0},0);return()=>clearTimeout(B)},[]);let M=r7(()=>s0($.lines,G,P),[$.lines,G,P]),F=M.above>0||M.below>0,N=(B)=>{let _=B(H.current,q.current);H.current=_.value,q.current=_.caretIndex,Y(_.value),X(_.caretIndex)};pY((B,_)=>{if(_.escape){Z(null);return}if(_.return){if(!i$(U.current,_,B))return;Z(H.current.trim());return}if(F){let A=Math.max(1,M.lines.length);if(_.upArrow){W((O)=>s0($.lines,G,O-1).start);return}if(_.downArrow){W((O)=>s0($.lines,G,O+1).start);return}if(_.pageUp){W((O)=>s0($.lines,G,O-A).start);return}if(_.pageDown){W((O)=>s0($.lines,G,O+A).start);return}}if(_.leftArrow){N((A,O)=>({value:A,caretIndex:I4(A,O,-1)}));return}if(_.rightArrow){N((A,O)=>({value:A,caretIndex:I4(A,O,1)}));return}if(_.backspace||_.delete){N((A,O)=>N2(A,O));return}if(_.ctrl&&B==="a"){N((A)=>({value:A,caretIndex:0}));return}if(_.ctrl&&B==="e"){N((A)=>({value:A,caretIndex:Array.from(A).length}));return}if(_.ctrl&&B==="u"){N(()=>({value:"",caretIndex:0}));return}if(_.ctrl&&B==="k"){N((A,O)=>{let v=Array.from(A);return v.splice(O),{value:v.join(""),caretIndex:O}});return}if(_.ctrl||_.meta)return;if(_.upArrow||_.downArrow||_.tab)return;let V=lY(B);if(!V)return;N((A,O)=>z$(A,O,V))});let f=F?"Enter 提交 · Esc 取消 · ↑↓ 滚动 · ←→ 光标":"Enter 提交 · Esc 取消 · ←→ 光标";return F0(M$,{flexDirection:"column",flexShrink:0,width:"100%",borderStyle:"round",borderColor:j.questionBorder,paddingX:1,children:[G>0&&F0(M$,{flexDirection:"column",height:G,overflow:"hidden",flexShrink:0,width:"100%",children:[M.above>0&&F0(M$,{flexShrink:0,children:F0(n0,{color:j.muted,dimColor:!0,children:["… 以上 ",M.above," 行"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),M.lines.map((B,_)=>F0(M$,{flexShrink:0,children:F0(n0,{bold:!0,color:j.questionBorder,wrap:"truncate-end",children:B},void 0,!1,void 0,this)},`${M.start+_}:${B}`,!1,void 0,this)),M.below>0&&F0(M$,{flexShrink:0,children:F0(n0,{color:j.muted,dimColor:!0,children:["↓ 还有 ",M.below," 行"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),F0(M$,{marginTop:1,flexShrink:0,height:1,overflow:"hidden",width:"100%",children:[F0(n0,{bold:!0,color:j.questionBorder,children:["→"," "]},void 0,!0,void 0,this),F0(n0,{children:Array.from(Q).slice(0,K).join("")},void 0,!1,void 0,this),F0(n0,{color:j.muted,inverse:!0,children:" "},void 0,!1,void 0,this),F0(n0,{children:Array.from(Q).slice(K).join("")},void 0,!1,void 0,this)]},void 0,!0,void 0,this),F0(M$,{flexShrink:0,children:F0(n0,{color:j.muted,dimColor:!0,wrap:"truncate-end",children:f},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var tY=C(()=>{H1();P1();U7();e2()});function Z4($){let Z=Math.max(0,Math.round($));if(Z<1000)return String(Z);if(Z<1e5)return`${(Z/1000).toFixed(1).replace(/\.0$/,"")}k`;if(Z<1e6)return`${Math.round(Z/1000)}k`;if(Z<1e7)return`${(Z/1e6).toFixed(1).replace(/\.0$/,"")}M`;return`${Math.round(Z/1e6)}M`}function CN($,Z){if($<=0||Z<=0)return null;return Math.round($/Z*100)}function aY($,Z,J=0){return{context:$.lastInputTokens>0?$.lastInputTokens:J,input:$.totalInputTokens,output:$.totalOutputTokens,contextWindow:Z}}function sY($){let Z=CN($.context,$.contextWindow);if(Z==null)return"";return`${Z4($.context)}/${Z4($.contextWindow)} ${Z}%`}function eY($,Z,J=!1){let z=[`思考 ${$}`];if(J)z.push("记忆 开");if(Z&&Z>0)z.push(`窗口 ${Z4(Z)}`);return z.join(" · ")}import{Box as $K,Text as l7}from"ink";import{jsxDEV as D6}from"react/jsx-dev-runtime";function ZK({state:$,columns:Z=80}){let J=$.model||"unknown",z=D$(Y1(void 0,$.model).thinking),G=eY(z,$.tokenInfo?.contextWindow,X1()),Q=$.tokenInfo?sY($.tokenInfo):"",Y=Math.max(8,Z-2),K=$.copyNotice?`✓ ${$.copyNotice}`:$.selectionMode?"选择模式 ↑↓←→扩选 Enter复制 Esc退出":null,X=K?A0(K):0;return D6($K,{flexDirection:"column",flexShrink:0,width:"100%",children:[D6(l7,{dimColor:!0,wrap:"truncate-end",children:K?`${"─".repeat(Math.max(0,Y-X-2))} ${K}`:"─".repeat(Y)},void 0,!1,void 0,this),D6($K,{children:[D6(l7,{children:" \uD83E\uDD16 min-agent"},void 0,!1,void 0,this),D6(l7,{color:"gray",wrap:"truncate-end",children:[" ","(",J," · ",G,")",Q?` ${Q}`:""]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)}var JK=C(()=>{K1();b1();H1()});import{useEffect as zK,useState as i7}from"react";import{Box as U1,Text as F$,useInput as bN,useStdout as wN}from"ink";import{jsxDEV as D0}from"react/jsx-dev-runtime";function GK($){let Z=Math.max(4,$-11);return Math.min(6+Z+3,Math.max(6,$-2))}function QK({currentModel:$,onSelect:Z,onCancel:J}){let[z,G]=i7(null),[Q,Y]=i7(""),[K,X]=i7(0),{stdout:P}=wN();zK(()=>{let v=!1,b=a(),D=s(b);if(D?.baseURL&&D?.apiKey)j4(D.baseURL,D.apiKey).then((I)=>{if(!v)G(I)}).catch(()=>{if(!v)G([])});else G([]);return()=>{v=!0}},[]);let W=P.rows||24,H=Math.max(4,W-11),q=z1(s(a())),U=Q.trim().toLowerCase(),M=(z??[]).filter((v)=>v.toLowerCase().includes(U)),F=Math.min(K,Math.max(0,M.length-1)),N=Math.min(F,Math.max(0,M.length-H)),f=M.slice(N,N+H),B=N,_=M.length-(N+f.length);zK(()=>{X(0)},[]),bN((v,b)=>{let D=v.replace(/[\r\n]+$/,""),I=b.return||/[\r\n]+$/.test(v);if(b.escape){J();return}if(b.pageDown){if(M.length>0)X((R)=>Math.min(M.length-1,R+H));return}if(b.pageUp){if(M.length>0)X((R)=>Math.max(0,R-H));return}if(M.length>0){if(b.downArrow){X((R)=>(R+1)%M.length);return}if(b.upArrow){X((R)=>(R-1+M.length)%M.length);return}}if(I){if(M.length>0)Z(M[F]);else if(U!==""&&!q)Z(U);return}if(b.backspace||b.delete){Y((R)=>Array.from(R).slice(0,-1).join(""));return}if(b.ctrl&&v==="u"){Y("");return}if(b.ctrl||b.meta||b.tab)return;if(D)Y((R)=>R+D)});let V=z===null,A=z!==null&&M.length===0&&U==="",O=U;return D0(U1,{flexDirection:"column",flexShrink:0,width:"100%",borderStyle:"round",borderColor:j.pickerBorder,paddingX:1,children:[D0(U1,{children:[D0(F$,{bold:!0,color:j.pickerBorder,children:"选择模型"},void 0,!1,void 0,this),D0(F$,{color:j.muted,children:$?` (当前: ${$})`:""},void 0,!1,void 0,this)]},void 0,!0,void 0,this),D0(U1,{children:[D0(F$,{color:j.muted,children:"筛选: "},void 0,!1,void 0,this),D0(F$,{color:Q?j.accent:j.muted,children:Q||"输入字符过滤,↑↓/PgUpDn 导航"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),V&&D0(U1,{children:D0(F$,{color:j.muted,dimColor:!0,children:"正在获取模型列表..."},void 0,!1,void 0,this)},void 0,!1,void 0,this),A&&D0(U1,{children:D0(F$,{color:j.muted,dimColor:!0,children:"无法获取模型列表(可输入模型名后按 Enter)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),z!==null&&B>0&&D0(U1,{children:D0(F$,{color:j.muted,dimColor:!0,children:["… 上方还有 ",B," 个模型"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),z!==null&&f.map((v,b)=>D0(U1,{children:[D0(F$,{color:b===F-N?j.accent:j.muted,children:b===F-N?"❯ ":" "},void 0,!1,void 0,this),D0(F$,{bold:b===F-N,color:b===F-N?j.accent:void 0,children:v},void 0,!1,void 0,this),v===$&&D0(F$,{color:j.success,children:" ← 当前"},void 0,!1,void 0,this)]},v,!0,void 0,this)),_>0&&D0(U1,{children:D0(F$,{color:j.muted,dimColor:!0,children:["… 下方还有 ",_," 个模型(输入字符过滤)"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),z!==null&&M.length===0&&O!==""&&!q&&D0(U1,{children:[D0(F$,{color:j.accent,bold:!0,children:["❯"," "]},void 0,!0,void 0,this),D0(F$,{color:j.accent,bold:!0,children:["使用自定义模型: ",O]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),D0(U1,{children:D0(F$,{color:j.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 YK=C(()=>{l();P1()});import{useEffect as KK,useRef as b3,useState as XK}from"react";import{Box as O6,Text as R4,useInput as IN}from"ink";import{jsxDEV as x$}from"react/jsx-dev-runtime";function PK(){return 11}function WK({scope:$,modelId:Z,onSelect:J,onCancel:z}){let G=s(G0()),Q=Z??G?.defaultModel,Y=Y1(void 0,Q),[K,X]=XK(()=>t1(Q)),[P,W]=XK(()=>o8(Y.thinking,t1(Q))),H=b3(!1),q=b3(!1),U=b3(P),M=b3(K);return U.current=P,M.current=K,KK(()=>{let F=setTimeout(()=>{H.current=!0},0);return()=>clearTimeout(F)},[]),KK(()=>{if(!Q)return;let F=!1;return X2(Q,{type:G?.type,baseURL:G?.baseURL}).then((N)=>{if(F||N.length===0)return;if(X(N),q.current){W((f)=>Math.min(f,Math.max(0,N.length-1)));return}W(o8(Y1(void 0,Q).thinking,N))}),()=>{F=!0}},[Q,G?.baseURL,G?.type]),IN((F,N)=>{if(N.escape){z();return}let f=M.current;if(f.length===0)return;if(N.downArrow){q.current=!0,W((B)=>(B+1)%f.length);return}if(N.upArrow){q.current=!0,W((B)=>(B-1+f.length)%f.length);return}if(i$(H.current,N,F)){let B=f[U.current];if(B)J(B)}}),x$(O6,{flexDirection:"column",flexShrink:0,width:"100%",borderStyle:"round",borderColor:j.pickerBorder,paddingX:1,children:[x$(O6,{children:[x$(R4,{bold:!0,color:j.pickerBorder,children:"选择思考强度"},void 0,!1,void 0,this),$==="project"&&x$(R4,{color:j.muted,children:"(写入当前项目)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),x$(O6,{children:x$(R4,{color:j.muted,children:["当前: ",D$(Y.thinking),"(",g5(Y.source),")"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),K.map((F,N)=>{let f=N===P;return x$(O6,{children:[x$(R4,{color:f?j.accent:j.muted,children:f?"❯ ":" "},void 0,!1,void 0,this),x$(R4,{bold:f,color:f?j.accent:void 0,children:D$(F)},void 0,!1,void 0,this),F===Y.thinking&&x$(R4,{color:j.success,children:" ← 当前"},void 0,!1,void 0,this)]},F,!0,void 0,this)}),x$(O6,{children:x$(R4,{color:j.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 HK=C(()=>{l();K1();P1()});var UK={};M0(UK,{tokensForCtxLevel:()=>w3,setOllamaContextChoice:()=>y4,parseCtxChoice:()=>C6,matchCtxLevel:()=>k4,isCtxLevel:()=>t7,isCtxChoice:()=>RN,ctxPayload:()=>T3,ctxChoiceLabel:()=>J4,configuredCtxChoice:()=>s7,activeProviderIsOllama:()=>a7,CTX_LEVELS:()=>I3,CTX_CHOICES:()=>N$,CTX_AUTO:()=>M1});function t7($){return I3.includes($)}function RN($){return $===M1||t7($)}function w3($){return qK[$]}function k4($){return TN.get(Math.floor($))??null}function C6($){if($==null)return null;let Z=$.trim().toLowerCase();if(!Z)return null;if(Z==="auto"||Z==="default")return M1;if(t7(Z))return Z;if(!/^\d+$/.test(Z))return null;return k4(Number(Z))}function J4($){return $===M1?"自动":$}function a7(){return s(a())?.type==="ollama"}function s7(){let $=s(a())?.contextWindow;if(typeof $!=="number"||!Number.isFinite($)||$<=0)return{choice:M1};let Z=k4($);if(Z)return{choice:Z,tokens:w3(Z)};return{choice:M1,tokens:Math.floor($)}}function y4($){let Z=a(),J=s(Z);if(!J)return{ok:!1,reason:"no-provider"};if(J.type!=="ollama")return{ok:!1,reason:"not-ollama"};if($===M1)delete J.contextWindow;else J.contextWindow=w3($);return R0(Z),$===M1?{ok:!0,choice:$}:{ok:!0,choice:$,tokens:w3($)}}function T3(){let $=s(a());if($?.type!=="ollama")return{configurable:!1,level:null};let Z=$.contextWindow;if(typeof Z!=="number"||!Number.isFinite(Z)||Z<=0)return{configurable:!0,level:M1};return{configurable:!0,level:k4(Z)}}var I3,M1="auto",N$,qK,TN;var f2=C(()=>{l();I3=["2k","4k","8k","12k","16k","32k","64k","128k","256k"],N$=[...I3,M1],qK={"2k":2048,"4k":4096,"8k":8192,"12k":12288,"16k":16384,"32k":32768,"64k":65536,"128k":131072,"256k":262144},TN=new Map(I3.map(($)=>[qK[$],$]))});import{useEffect as kN,useRef as MK,useState as yN}from"react";import{Box as b6,Text as _2,useInput as SN}from"ink";import{jsxDEV as t$}from"react/jsx-dev-runtime";function FK(){return 4+N$.length+1}function NK(){let $=s(a())?.contextWindow;if(typeof $==="number"&&Number.isFinite($)&&$>0)return Math.floor($);return}function EN(){let $=NK();if($==null)return J4("auto");return k4($)??Z4($)}function vN(){let $=NK();if($==null)return"auto";return k4($)}function BK({onSelect:$,onCancel:Z}){let J=vN(),[z,G]=yN(()=>{let K=J?N$.indexOf(J):-1;return K>=0?K:N$.length-1}),Q=MK(!1),Y=MK(z);return Y.current=z,kN(()=>{let K=setTimeout(()=>{Q.current=!0},0);return()=>clearTimeout(K)},[]),SN((K,X)=>{if(X.escape){Z();return}if(X.downArrow){G((P)=>(P+1)%N$.length);return}if(X.upArrow){G((P)=>(P-1+N$.length)%N$.length);return}if(i$(Q.current,X,K)){let P=N$[Y.current];if(P)$(P)}}),t$(b6,{flexDirection:"column",flexShrink:0,width:"100%",borderStyle:"round",borderColor:j.pickerBorder,paddingX:1,children:[t$(b6,{children:t$(_2,{bold:!0,color:j.pickerBorder,children:"选择上下文窗口"},void 0,!1,void 0,this)},void 0,!1,void 0,this),t$(b6,{children:t$(_2,{color:j.muted,children:["当前: ",EN()]},void 0,!0,void 0,this)},void 0,!1,void 0,this),N$.map((K,X)=>{let P=X===z;return t$(b6,{children:[t$(_2,{color:P?j.accent:j.muted,children:P?"❯ ":" "},void 0,!1,void 0,this),t$(_2,{bold:P,color:P?j.accent:void 0,children:J4(K)},void 0,!1,void 0,this),K===J&&t$(_2,{color:j.success,children:" ← 当前"},void 0,!1,void 0,this)]},K,!0,void 0,this)}),t$(b6,{children:t$(_2,{color:j.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 VK=C(()=>{l();f2();P1()});var fK={};M0(fK,{listProviderChoices:()=>L2,applyProviderSwitch:()=>e7});function xN($){return Boolean($.name?.trim())}function L2(){let $=G0(),Z=s($)?.name;return($.providers??[]).filter(xN).map((J)=>({name:J.name,baseURL:J.baseURL,defaultModel:J.defaultModel,current:J.name===Z}))}function gN(){let $=w0();if($.activeProvider===void 0)return;let{activeProvider:Z,...J}=$;H$(J)}function e7($){let Z=M2(a(),$);if("error"in Z)return{ok:!1,message:Z.error};R0(Z),gN();let J=s(Z);return{ok:!0,name:$,defaultModel:J?.defaultModel??""}}var R3=C(()=>{l()});import{useEffect as uN,useRef as $Z,useState as hN}from"react";import{Box as z4,Text as k1,useInput as mN,useStdout as nN}from"ink";import{jsxDEV as o0}from"react/jsx-dev-runtime";function _K($){let Z=Math.max(1,L2().length),J=Math.max(4,$-11),z=Math.min(Z,J),G=Z>J?2:0;return 4+z+G+1}function LK({onSelect:$,onCancel:Z}){let J=L2(),z=J.find((f)=>f.current)?.name,[G,Q]=hN(()=>{let f=J.findIndex((B)=>B.current);return f>=0?f:0}),Y=$Z(!1),K=$Z(G),X=$Z(J);K.current=G,X.current=J;let{stdout:P}=nN(),W=P.rows||24,H=Math.max(4,W-11),q=J.length===0?0:Math.min(G,J.length-1),U=Math.min(q,Math.max(0,J.length-H)),M=J.slice(U,U+H),F=U,N=J.length-(U+M.length);return uN(()=>{let f=setTimeout(()=>{Y.current=!0},0);return()=>clearTimeout(f)},[]),mN((f,B)=>{if(B.escape){Z();return}let _=X.current;if(_.length===0)return;if(B.pageDown){Q((V)=>Math.min(_.length-1,V+H));return}if(B.pageUp){Q((V)=>Math.max(0,V-H));return}if(B.downArrow){Q((V)=>(V+1)%_.length);return}if(B.upArrow){Q((V)=>(V-1+_.length)%_.length);return}if(i$(Y.current,B,f)){let V=_[K.current];if(V)$(V.name)}}),o0(z4,{flexDirection:"column",flexShrink:0,width:"100%",borderStyle:"round",borderColor:j.pickerBorder,paddingX:1,children:[o0(z4,{children:o0(k1,{bold:!0,color:j.pickerBorder,children:"选择服务商"},void 0,!1,void 0,this)},void 0,!1,void 0,this),o0(z4,{children:o0(k1,{color:j.muted,children:["当前: ",z??"无"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),J.length===0&&o0(z4,{children:o0(k1,{color:j.muted,dimColor:!0,children:"无已配置服务商"},void 0,!1,void 0,this)},void 0,!1,void 0,this),F>0&&o0(z4,{children:o0(k1,{color:j.muted,dimColor:!0,children:["… 上方还有 ",F," 个服务商"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),M.map((f,B)=>{let _=B===q-U;return o0(z4,{children:[o0(k1,{color:_?j.accent:j.muted,children:_?"❯ ":" "},void 0,!1,void 0,this),o0(k1,{bold:_,color:_?j.accent:void 0,wrap:"truncate-end",children:cN(f)},void 0,!1,void 0,this),f.current&&o0(k1,{color:j.success,children:" ← 当前"},void 0,!1,void 0,this)]},f.name,!0,void 0,this)}),N>0&&o0(z4,{children:o0(k1,{color:j.muted,dimColor:!0,children:["… 下方还有 ",N," 个服务商"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),o0(z4,{children:o0(k1,{color:j.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 cN($){return`${$.name} ${$.baseURL}`}var jK=C(()=>{R3();P1()});import{generateText as pN}from"ai";async function AK($,Z){let J=Z.find((K)=>K.role==="user");if(!J)return null;let z=typeof J.content==="string"?J.content:Array.isArray(J.content)?J.content.filter((K)=>("text"in K)).map((K)=>K.text??"").join(" "):"";if(!z.trim())return null;let G=Z.find((K)=>K.role==="assistant"),Q=G?typeof G.content==="string"?G.content.slice(0,200):"":"",Y=Q?`User: ${z.slice(0,300)}
|
|
98
|
+
Assistant: ${Q}`:`User: ${z.slice(0,300)}`;try{return(await pN({model:$,system:oN,messages:[{role:"user",content:Y}],temperature:0.5,maxOutputTokens:30})).text.trim().replace(/^["']|["']$/g,"").slice(0,60)||null}catch{return null}}var oN=`Generate a very short title (max 50 chars) for this conversation.
|
|
98
99
|
Output ONLY the title text, nothing else. No quotes, no prefix.
|
|
99
|
-
The title should capture the main topic or intent.`;var
|
|
100
|
-
`)}function
|
|
101
|
-
`)}function
|
|
102
|
-
`)},
|
|
100
|
+
The title should capture the main topic or intent.`;var DK=()=>{};function CK($){OK.add($)}function j2($){return OK.has($)}var OK;var k3=C(()=>{OK=new WeakSet});import{tool as dN,jsonSchema as rN}from"ai";function g$(){return{goal:"",todos:[],nextId:1}}function JZ($){$.goal="",$.todos.length=0,$.nextId=1}function w6($,Z){if(!$){JZ(Z);return}Z.goal=$.goal,Z.todos=$.todos.map((J)=>({...J})),Z.nextId=$.nextId}function iN($){return typeof $==="string"&&ZZ.includes($)}function bK($){if(!$||typeof $!=="object")return;let Z=$,J=[];if(Array.isArray(Z.todos))for(let Q of Z.todos){if(!Q||typeof Q!=="object")continue;let Y=Q;if(typeof Y.id!=="number"||typeof Y.text!=="string")continue;J.push({id:Y.id,text:Y.text,status:iN(Y.status)?Y.status:"pending"})}let z=J.reduce((Q,Y)=>Math.max(Q,Y.id),0),G=typeof Z.nextId==="number"&&Number.isFinite(Z.nextId)&&Z.nextId>z?Math.floor(Z.nextId):z+1;return{goal:typeof Z.goal==="string"?Z.goal:"",todos:J,nextId:G}}function tN($){if(typeof $.content==="string")return $.content;if(!Array.isArray($.content))return"";return $.content.filter((Z)=>Z.type==="text"&&typeof Z.text==="string").map((Z)=>Z.text).join(`
|
|
101
|
+
`)}function zZ($){let Z=$.trim().replace(/[\s\p{P}\p{S}\p{Emoji_Presentation}\p{Extended_Pictographic}]/gu,"");return Z.length===0||aN.test(Z)}function sN($){let Z=$.trim();if(!Z||zZ(Z))return;return Z.slice(0,lN)}function wK($,Z){if($.goal.trim()&&!zZ($.goal))return;for(let J of Z){if(J.role!=="user")continue;if(j2(J))continue;let z=sN(tN(J));if(!z)continue;$.goal=z;return}}function IK($){let Z=$.goal.trim()&&!zZ($.goal)?$.goal:"";if(!Z&&$.todos.length===0)return"";let J={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(Z)z.push("","### Original goal",Z);if($.todos.length>0){z.push("","### Task list");for(let G of $.todos)z.push(`- [${J[G.status]}] #${G.id} ${G.text}`)}return z.join(`
|
|
102
|
+
`)}function y3($){let Z=$?.silent??!1,J=$?.store??g$(),z=()=>{if(J.todos.length===0)return"No tasks.";let Q={pending:"○",in_progress:"◐",done:"●",cancelled:"✕"};return J.todos.map((Y)=>` ${Q[Y.status]} #${Y.id} ${Y.text}`).join(`
|
|
103
|
+
`)},G=()=>{if(Z||J.todos.length===0)return;console.log(`\x1B[90m ┌─ Tasks${"─".repeat(36)}\x1B[0m`);for(let Q of J.todos){let Y=Q.status==="done"?"\x1B[32m●\x1B[0m":Q.status==="in_progress"?"\x1B[33m◐\x1B[0m":Q.status==="cancelled"?"\x1B[90m✕\x1B[0m":"\x1B[90m○\x1B[0m",K=Q.status==="done"||Q.status==="cancelled"?"\x1B[90m":"",X=K?"\x1B[0m":"";console.log(`\x1B[90m │\x1B[0m ${Y} ${K}#${Q.id} ${Q.text}${X}`)}console.log(`\x1B[90m └${"─".repeat(44)}\x1B[0m`)};return dN({description:`Create or update tasks to track progress. The list persists across context compaction and auto-continue. Use this FREQUENTLY to:
|
|
103
104
|
- Plan multi-step work by creating tasks upfront (research, then the deliverable)
|
|
104
105
|
- Mark research tasks done before more searching — then write the output
|
|
105
106
|
- Mark tasks as in_progress when starting them
|
|
@@ -108,74 +109,74 @@ The title should capture the main topic or intent.`;var bQ=()=>{};function CQ($)
|
|
|
108
109
|
|
|
109
110
|
To create new tasks: provide items with "text" and optionally "status" (defaults to "pending").
|
|
110
111
|
To update existing tasks: provide items with "id" and "status".
|
|
111
|
-
You can mix creates and updates in one call.`,inputSchema:
|
|
112
|
-
|
|
113
|
-
Warnings: ${G.join("; ")}`:z()}})}var Z7,dF=4000,tF;var S4=C(()=>{R8();Z7=["pending","in_progress","done","cancelled"];tF=/^(你好|您好|嗨|哈喽|哈罗|哈囉|在吗|在嗎|早上好|晚上好|早安|午安|hello|hi|hey|yo|sup|thanks|thankyou|thx|ty|谢谢|谢谢你|多谢|感谢|ok|okay|好的|收到)$/i});var E4={};M0(E4,{withSessionLock:()=>y6,saveSessionWithTitle:()=>WN,saveSession:()=>w$,sanitizeForStorage:()=>R6,renameSession:()=>Y7,loadSession:()=>K$,loadExecHistory:()=>HN,listSessions:()=>z4,deleteSession:()=>Q7});import{readFileSync as yQ,mkdirSync as sF,existsSync as T6,readdirSync as eF,unlinkSync as $N,openSync as fN,readSync as ZN,closeSync as zN,statSync as JN}from"fs";import K7 from"path";import{randomUUID as KN}from"crypto";function G7(){return K7.join(P0(),"sessions")}async function y6($,f){if(!$)return f();let Z=E8.get($)??Promise.resolve(),z,J=new Promise((G)=>{z=G}),K=Z.then(()=>J);E8.set($,K),await Z;try{return await f()}finally{if(z(),E8.get($)===K)E8.delete($)}}function k6($){if(!I6.test($))throw Error(`invalid session id: ${$}`);return K7.join(G7(),`${$}.json`)}function kQ($,f){let Z=fN($,"r");try{let z=Buffer.alloc(Math.min(JN($).size,f));if(z.length===0)return"";return ZN(Z,z,0,z.length,0),z.toString("utf-8")}finally{zN(Z)}}function GN($,f){let Z=0,z=!1,J=!1;for(let K=f;K<$.length;K++){let G=$[K];if(z){if(J)J=!1;else if(G==="\\")J=!0;else if(G==='"')z=!1;continue}if(G==='"')z=!0;else if(G==="{")Z++;else if(G==="}"){if(Z--,Z===0)return K}}return-1}function RQ($){let f=$.indexOf('"meta"');if(f<0)return null;let Z=$.indexOf("{",f);if(Z<0)return null;let z=GN($,Z);if(z<0)return null;try{return JSON.parse($.slice(Z,z+1))}catch{return null}}function QN(){return KN()}function YN($){if(typeof $==="string")return $;return $.map((f)=>f.type==="text"?f.text:"").join(" ").trim()}function PN($){let f=$.find((z)=>z.role==="user");if(!f)return"Untitled";return YN(f.content).slice(0,60)||"Untitled"}function R6($){return $.filter((f)=>!_2(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 G=z.image.data;if(Buffer.isBuffer(G)||G instanceof Uint8Array)J=Buffer.isBuffer(G)?G:Buffer.from(G)}if(!J)return z;let K=z.mimeType??"image/png";return{...z,image:`data:${K};base64,${J.toString("base64")}`}});return{...f,content:Z}})}function w$($,f,Z,z,J){let K=G7();sF(K,{recursive:!0});let G=f&&I6.test(f)?f:QN(),Q=new Date().toISOString(),Y=f?XN(G):null,P=J===void 0&&f?K$(G)?.taskState:void 0,X=J??P,W={meta:{id:G,title:Z??Y?.title??PN($),created:z??Y?.created??Q,updated:Q,messageCount:$.length},...X?{taskState:X}:{},messages:R6($)};return y0(k6(G),JSON.stringify(W,null,2)),G}function XN($){let f=k6($);if(!T6(f))return null;try{return RQ(kQ(f,IQ))}catch{return null}}async function WN($,f,Z){let z=null;try{z=await AQ(f,$)}catch{}return w$($,Z,z??void 0)}function K$($){if(!I6.test($))return null;let f=k6($);if(!T6(f))return null;try{let Z=JSON.parse(yQ(f,"utf-8")),z=OQ(Z.taskState);return z?{...Z,taskState:z}:Z}catch{return null}}function HN($){if(!$)return{ok:!0,messages:[],sessionId:void 0};let f=K$($);if(!f)return{ok:!1,error:`会话不存在: ${$}`};return{ok:!0,messages:[...f.messages],sessionId:$,taskState:f.taskState}}function z4(){let $=G7();if(!T6($))return[];return eF($).filter((f)=>f.endsWith(".json")).map((f)=>{try{return RQ(kQ(K7.join($,f),IQ))}catch{return null}}).filter((f)=>f!==null).sort((f,Z)=>Z.updated.localeCompare(f.updated))}function Q7($){if(!I6.test($))return!1;let f=k6($);if(!T6(f))return!1;try{return $N(f),!0}catch{return!1}}function Y7($,f){if(!I6.test($))return!1;let Z=k6($);if(!T6(Z))return!1;try{let z=JSON.parse(yQ(Z,"utf-8"));return z.meta.title=f,z.meta.updated=new Date().toISOString(),y0(Z,JSON.stringify(z,null,2)),!0}catch{return!1}}var E8,I6,IQ=65536;var g$=C(()=>{_$();l();bQ();R8();S4();E8=new Map;I6=/^[a-zA-Z0-9_-]+$/});import{useEffect as UN,useState as SQ}from"react";import{Box as I1,Text as n$,useInput as MN,useStdout as qN}from"ink";import{jsxDEV as k0}from"react/jsx-dev-runtime";function EQ($){let f=Math.max(4,$-11);return Math.min(6+f+3,Math.max(6,$-2))}function FN($){let f=$.updated.split("T")[0]??"";return`${$.id} ${f} ${$.title} (${$.messageCount})`}function vQ({currentId:$,onSelect:f,onCancel:Z}){let z=z4(),[J,K]=SQ(""),[G,Q]=SQ(0),{stdout:Y}=qN(),P=Y.rows||24,X=Math.max(4,P-11),W=J.trim().toLowerCase(),H=z.filter((B)=>B.id.toLowerCase().includes(W)||B.title.toLowerCase().includes(W)),U=Math.min(G,Math.max(0,H.length-1)),M=Math.min(U,Math.max(0,H.length-X)),N=H.slice(M,M+X),q=M,L=H.length-(M+N.length);UN(()=>{Q(0)},[]),MN((B,A)=>{let j=B.replace(/[\r\n]+$/,""),v=A.return||/[\r\n]+$/.test(B);if(A.escape){Z();return}if(A.pageDown){if(H.length>0)Q((O)=>Math.min(H.length-1,O+X));return}if(A.pageUp){if(H.length>0)Q((O)=>Math.max(0,O-X));return}if(H.length>0){if(A.downArrow){Q((O)=>(O+1)%H.length);return}if(A.upArrow){Q((O)=>(O-1+H.length)%H.length);return}}if(v){if(H.length>0)f(H[U].id);return}if(A.backspace||A.delete){K((O)=>Array.from(O).slice(0,-1).join(""));return}if(A.ctrl&&B==="u"){K("");return}if(A.ctrl||A.meta||A.tab)return;if(j)K((O)=>O+j)});let F=H.length===0&&W==="",V=H.length===0&&W!=="";return k0(I1,{flexDirection:"column",flexShrink:0,width:"100%",borderStyle:"round",borderColor:D.pickerBorder,paddingX:1,children:[k0(I1,{children:[k0(n$,{bold:!0,color:D.pickerBorder,children:"选择会话"},void 0,!1,void 0,this),k0(n$,{color:D.muted,children:$?` (当前: ${$})`:""},void 0,!1,void 0,this)]},void 0,!0,void 0,this),k0(I1,{children:[k0(n$,{color:D.muted,children:"筛选: "},void 0,!1,void 0,this),k0(n$,{color:J?D.accent:D.muted,children:J||"输入字符过滤标题或 id"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),F&&k0(I1,{children:k0(n$,{color:D.muted,dimColor:!0,children:"无已保存的会话"},void 0,!1,void 0,this)},void 0,!1,void 0,this),V&&k0(I1,{children:k0(n$,{color:D.muted,dimColor:!0,children:"没有匹配的会话"},void 0,!1,void 0,this)},void 0,!1,void 0,this),q>0&&k0(I1,{children:k0(n$,{color:D.muted,dimColor:!0,children:["… 上方还有 ",q," 个会话"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),N.map((B,A)=>k0(I1,{children:[k0(n$,{color:A===U-M?D.accent:D.muted,children:A===U-M?"❯ ":" "},void 0,!1,void 0,this),k0(n$,{bold:A===U-M,color:A===U-M?D.accent:void 0,wrap:"truncate-end",children:FN(B)},void 0,!1,void 0,this),B.id===$&&k0(n$,{color:D.success,children:" ←"},void 0,!1,void 0,this)]},B.id,!0,void 0,this)),L>0&&k0(I1,{children:k0(n$,{color:D.muted,dimColor:!0,children:["… 下方还有 ",L," 个会话"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),k0(I1,{children:k0(n$,{color:D.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 uQ=C(()=>{g$();Y1()});import{useCallback as NN,useEffect as xQ,useState as gQ}from"react";import{Box as P7,useInput as BN,useStdout as VN}from"ink";import{jsxDEV as N$}from"react/jsx-dev-runtime";function nQ({initialState:$,onSubmit:f,onConfirm:Z,onQuestionAnswer:z,onModelPick:J,onModelCancel:K,onThinkPick:G,onThinkCancel:Q,onCtxPick:Y,onCtxCancel:P,onProviderPick:X,onProviderCancel:W,onSessionPick:H,onSessionCancel:U,onToggleSelectionMode:M,onExitSelectionMode:N,onExit:q,onCopyNotice:L,onNotice:F}){let{stdout:V}=VN(),[B,A]=gQ({columns:V.columns||80,rows:V.rows||0});if(xQ(()=>{let G0=()=>A({columns:V.columns||80,rows:V.rows||0});return V.on("resize",G0),()=>{V.off("resize",G0)}},[V]),BN((G0,H0)=>{if(P8(G0,H0)){if($.confirmMessage){Z(!1);return}if($.question){z(null);return}if($.modelPicker){K();return}if($.thinkPicker){Q();return}if($.ctxPicker){P();return}if($.providerPicker){W();return}if($.sessionPicker){U();return}if($.selectionMode){N();return}if($.isRunning)q();return}if(H0.ctrl&&G0==="b"){if($.confirmMessage||$.question||$.modelPicker||$.thinkPicker||$.ctxPicker||$.providerPicker||$.sessionPicker)return;if($.isRunning)return;if(!$.selectionMode)return;M();return}if(H0.escape&&$.isRunning&&!$.confirmMessage&&!$.question&&!$.modelPicker&&!$.thinkPicker&&!$.ctxPicker&&!$.providerPicker&&!$.sessionPicker)q()}),$.confirmMessage||$.question||$.modelPicker||$.thinkPicker||$.ctxPicker||$.providerPicker||$.sessionPicker)w4(null);let{columns:j,rows:v}=B,O=oK(v),[b,T]=gQ(B6),I=NN((G0)=>{T((H0)=>H0===G0?H0:G0)},[]),Z0=Boolean($.confirmMessage),h=Boolean($.question),$0=Boolean($.modelPicker),u=Boolean($.thinkPicker),y=Boolean($.ctxPicker),r=Boolean($.providerPicker),S=Boolean($.sessionPicker),p=Z0||h||$0||u||y||r||S;xQ(()=>{if(p)T(B6)},[p]);let z0=Z0?hG($.confirmMessage??"",j,O):h?dG($.question.prompt,$.question.options,j,O,Boolean($.question.multiple)):$0?JQ(O):u?PQ():y?qQ():r?LQ(O):S?EQ(O):b,g=$.isRunning&&!Z0&&!h&&!$0&&!u&&!y&&!r&&!S,R0=lK(O,z0,g?1:0);return N$(P7,{flexDirection:"column",width:"100%",height:O||void 0,overflow:"hidden",children:[!$0&&N$(P7,{flexDirection:"column",flexGrow:1,flexShrink:1,minHeight:0,overflow:"hidden",width:"100%",children:N$(EG,{messages:$.messages,maxHeight:R0,columns:j,onCopyNotice:L,selectionMode:Boolean($.selectionMode),onExitSelectionMode:N,interactive:!p},void 0,!1,void 0,this)},void 0,!1,void 0,this),g&&N$(P7,{paddingLeft:1,flexShrink:0,width:"100%",children:N$(_K,{label:$.spinnerText||"思考中..."},void 0,!1,void 0,this)},void 0,!1,void 0,this),N$(fQ,{state:$,columns:j},void 0,!1,void 0,this),$.confirmMessage?N$(cG,{message:$.confirmMessage,onConfirm:Z,columns:j,maxRows:z0},void 0,!1,void 0,this):$.question?N$(iG,{prompt:$.question.prompt,options:$.question.options,multiple:Boolean($.question.multiple),onAnswer:z,columns:j,maxRows:z0},void 0,!1,void 0,this):$.modelPicker?N$(KQ,{currentModel:$.model,onSelect:J,onCancel:K},void 0,!1,void 0,this):$.thinkPicker?N$(XQ,{scope:$.thinkPicker.scope,modelId:$.model,onSelect:(G0)=>G(G0,$.thinkPicker.scope),onCancel:Q},void 0,!1,void 0,this):$.ctxPicker?N$(NQ,{onSelect:Y,onCancel:P},void 0,!1,void 0,this):$.providerPicker?N$(_Q,{onSelect:X,onCancel:W},void 0,!1,void 0,this):$.sessionPicker?N$(vQ,{currentId:$.sessionId,onSelect:H,onCancel:U},void 0,!1,void 0,this):N$(HG,{onSubmit:f,disabled:$.isRunning||Boolean($.selectionMode),placeholder:$.isRunning?"按 Esc 取消运行...":"输入消息... (Ctrl+J 换行)",columns:j,terminalRows:O,onSelectionMode:M,onExit:q,onRowsChange:I,onNotice:F},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var hQ=C(()=>{DK();UG();uG();mG();tG();ZQ();GQ();WQ();BQ();DQ();uQ();V5()});function cQ($,f,Z){let z=-1;if(f)z=$.findIndex((G)=>G.role==="tool"&&G.toolCallId===f);if(z===-1){for(let G=$.length-1;G>=0;G--)if($[G].role==="tool"&&$[G].toolName==="task"){z=G;break}}if(z===-1)return $;let J=$[z],K=$.slice();return K[z]={...J,toolChildren:[...J.toolChildren??[],Z]},K}import{render as LN}from"ink";import{jsxDEV as _N}from"react/jsx-dev-runtime";class X7{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 _N(nQ,{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=LN(this.appElement(),{exitOnCtrlC:!1,stdout:bK(process.stdout)})}update($){if(this.state={...this.state,...$},this.inkInstance)this.inkInstance.rerender(this.appElement())}addMessage($){this.flushPendingThinking(),this.flushPendingDeltas(),this.state.messages=[...this.state.messages,$],this.update({})}messageCount(){return this.state.messages.length}setToolResult($,f,Z,z,J){let K=[...this.state.messages],G=K.findIndex((Q)=>Q.role==="tool"&&Q.toolCallId===$);if(G===-1)for(let Q=K.length-1;Q>=0;Q--){let Y=K[Q];if(Y.role==="tool"&&Y.toolName===f&&Y.toolResult===void 0){G=Q;break}}if(G===-1)return;K[G]={...K[G],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.flushPendingThinking(),this.flushPendingDeltas();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=r1(p1(f));this.update({question:{prompt:m1($),...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=cQ(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;w4(null);try{process.stdout.write("\x1B[?1000l\x1B[?1002l\x1B[?1006l")}catch{}this.inkInstance?.unmount(),this.inkInstance=null}}var mQ=C(()=>{hQ();e2()});import{existsSync as DN,mkdirSync as AN,readdirSync as bN,statSync as jN,unlinkSync as CN,writeFileSync as ON}from"fs";import W7 from"path";import{randomBytes as wN}from"crypto";function kN(){return W7.join(P0(),"tool-output")}function RN($){let f=Date.now();if(f-pQ<IN)return;if(pQ=f,!DN($))return;try{for(let Z of bN($)){if(!Z.startsWith("tool-")||!Z.endsWith(".txt"))continue;let z=W7.join($,Z);try{if(f-jN(z).mtimeMs>yN)CN(z)}catch{}}}catch{}}function U7($){let f=kN();AN(f,{recursive:!0}),RN(f);let Z=`tool-${Date.now()}-${wN(4).toString("hex")}.txt`,z=W7.join(f,Z);return ON(z,$,"utf-8"),z}function SN($,f,Z,z,J,K){if(J.length<=f&&K<=Z)return{text:$,cut:!1};let G=[],Q=0,Y=(P,X)=>{let W=Buffer.byteLength(J[P],"utf-8")+(X?0:1);if(Q+W>Z)return!1;if(z==="head")G.push(J[P]);else G.unshift(J[P]);return Q+=W,!0};if(z==="head"){for(let P=0;P<J.length&&G.length<f;P++)if(!Y(P,G.length===0)){if(G.length===0){let X=Buffer.from(J[P],"utf-8"),W=Math.min(Z,X.length);while(W>0&&(X[W]&192)===128)W--;G.push(X.subarray(0,W).toString("utf-8"))}break}}else for(let P=J.length-1;P>=0&&G.length<f;P--)if(!Y(P,G.length===0)){if(G.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++;G.unshift(X.subarray(W).toString("utf-8"))}break}return{text:G.join(`
|
|
114
|
-
`),cut:!0}}function
|
|
115
|
-
`),
|
|
116
|
-
|
|
117
|
-
`;return{content:
|
|
118
|
-
|
|
119
|
-
${
|
|
120
|
-
|
|
121
|
-
${P}${
|
|
122
|
-
Use the read tool with startLine/endLine, or grep, to inspect further.`;var
|
|
123
|
-
`,{flag:"a"})}catch{}}function
|
|
124
|
-
`))!==-1){let
|
|
125
|
-
Server stderr (last ${
|
|
126
|
-
${
|
|
127
|
-
`)}`:"";throw Error(`${
|
|
128
|
-
min-agent mcp add ${$} --url ${z} --token YOUR_TOKEN`)}throw Error(`MCP "${$}" remote connection failed: ${
|
|
129
|
-
`)||JSON.stringify(
|
|
130
|
-
|
|
131
|
-
`)}function
|
|
132
|
-
|
|
133
|
-
`:"",
|
|
134
|
-
`);return
|
|
135
|
-
`),{direction:"head"}).content}}),
|
|
136
|
-
`),{direction:"head"}).content}}),z=E6({description:"Fill an MCP prompt template. Use mcp_list_prompts first. Pass server when more than one MCP server is connected.",inputSchema:
|
|
137
|
-
`),z=
|
|
138
|
-
`)).trim();return
|
|
139
|
-
`),z=
|
|
140
|
-
`),Z
|
|
141
|
-
`);return
|
|
142
|
-
`)}catch(
|
|
112
|
+
You can mix creates and updates in one call.`,inputSchema:rN({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:Q})=>{let Y=[];for(let K of Q)if(K.id!=null){let X=J.todos.find((P)=>P.id===K.id);if(!X){Y.push(`task #${K.id} not found`);continue}if(K.status){if(!ZZ.includes(K.status)){Y.push(`invalid status "${K.status}" for task #${K.id}`);continue}X.status=K.status}if(K.text)X.text=K.text}else if(K.text)J.todos.push({id:J.nextId++,text:K.text,status:ZZ.includes(K.status)?K.status:"pending"});else Y.push("item needs either an id (update) or text (create)");return G(),Y.length>0?`${z()}
|
|
113
|
+
|
|
114
|
+
Warnings: ${Y.join("; ")}`:z()}})}var ZZ,lN=4000,aN;var S4=C(()=>{k3();ZZ=["pending","in_progress","done","cancelled"];aN=/^(你好|您好|嗨|哈喽|哈罗|哈囉|在吗|在嗎|早上好|晚上好|早安|午安|hello|hi|hey|yo|sup|thanks|thankyou|thx|ty|谢谢|谢谢你|多谢|感谢|ok|okay|好的|收到)$/i});var E4={};M0(E4,{withSessionLock:()=>T6,saveSessionWithTitle:()=>qB,saveSession:()=>w$,sanitizeForStorage:()=>y6,renameSession:()=>KZ,loadSession:()=>Q$,loadExecHistory:()=>UB,listSessions:()=>G4,deleteSession:()=>YZ});import{readFileSync as TK,mkdirSync as eN,existsSync as I6,readdirSync as $B,unlinkSync as ZB,openSync as JB,readSync as zB,closeSync as GB,statSync as QB}from"fs";import GZ from"path";import{randomUUID as YB}from"crypto";function QZ(){return GZ.join(P0(),"sessions")}async function T6($,Z){if(!$)return Z();let J=S3.get($)??Promise.resolve(),z,G=new Promise((Y)=>{z=Y}),Q=J.then(()=>G);S3.set($,Q),await J;try{return await Z()}finally{if(z(),S3.get($)===Q)S3.delete($)}}function k6($){if(!R6.test($))throw Error(`invalid session id: ${$}`);return GZ.join(QZ(),`${$}.json`)}function kK($,Z){let J=JB($,"r");try{let z=Buffer.alloc(Math.min(QB($).size,Z));if(z.length===0)return"";return zB(J,z,0,z.length,0),z.toString("utf-8")}finally{GB(J)}}function KB($,Z){let J=0,z=!1,G=!1;for(let Q=Z;Q<$.length;Q++){let Y=$[Q];if(z){if(G)G=!1;else if(Y==="\\")G=!0;else if(Y==='"')z=!1;continue}if(Y==='"')z=!0;else if(Y==="{")J++;else if(Y==="}"){if(J--,J===0)return Q}}return-1}function yK($){let Z=$.indexOf('"meta"');if(Z<0)return null;let J=$.indexOf("{",Z);if(J<0)return null;let z=KB($,J);if(z<0)return null;try{return JSON.parse($.slice(J,z+1))}catch{return null}}function XB(){return YB()}function PB($){if(typeof $==="string")return $;return $.map((Z)=>Z.type==="text"?Z.text:"").join(" ").trim()}function WB($){let Z=$.find((z)=>z.role==="user");if(!Z)return"Untitled";return PB(Z.content).slice(0,60)||"Untitled"}function y6($){return $.filter((Z)=>!j2(Z)).map((Z)=>{if(!Array.isArray(Z.content))return Z;let J=Z.content.map((z)=>{if(z.type!=="image"||z.image==null||typeof z.image==="string")return z;let G=null;if(Buffer.isBuffer(z.image)||z.image instanceof Uint8Array)G=Buffer.isBuffer(z.image)?z.image:Buffer.from(z.image);else if(typeof z.image==="object"&&!(z.image instanceof URL)){let Y=z.image.data;if(Buffer.isBuffer(Y)||Y instanceof Uint8Array)G=Buffer.isBuffer(Y)?Y:Buffer.from(Y)}if(!G)return z;let Q=z.mimeType??"image/png";return{...z,image:`data:${Q};base64,${G.toString("base64")}`}});return{...Z,content:J}})}function w$($,Z,J,z,G){let Q=QZ();eN(Q,{recursive:!0});let Y=Z&&R6.test(Z)?Z:XB(),K=new Date().toISOString(),X=Z?HB(Y):null,P=G===void 0&&Z?Q$(Y)?.taskState:void 0,W=G??P,H={meta:{id:Y,title:J??X?.title??WB($),created:z??X?.created??K,updated:K,messageCount:$.length},...W?{taskState:W}:{},messages:y6($)};return T0(k6(Y),JSON.stringify(H,null,2)),Y}function HB($){let Z=k6($);if(!I6(Z))return null;try{return yK(kK(Z,RK))}catch{return null}}async function qB($,Z,J){let z=null;try{z=await AK(Z,$)}catch{}return w$($,J,z??void 0)}function Q$($){if(!R6.test($))return null;let Z=k6($);if(!I6(Z))return null;try{let J=JSON.parse(TK(Z,"utf-8")),z=bK(J.taskState);return z?{...J,taskState:z}:J}catch{return null}}function UB($){if(!$)return{ok:!0,messages:[],sessionId:void 0};let Z=Q$($);if(!Z)return{ok:!1,error:`会话不存在: ${$}`};return{ok:!0,messages:[...Z.messages],sessionId:$,taskState:Z.taskState}}function G4(){let $=QZ();if(!I6($))return[];return $B($).filter((Z)=>Z.endsWith(".json")).map((Z)=>{try{return yK(kK(GZ.join($,Z),RK))}catch{return null}}).filter((Z)=>Z!==null).sort((Z,J)=>J.updated.localeCompare(Z.updated))}function YZ($){if(!R6.test($))return!1;let Z=k6($);if(!I6(Z))return!1;try{return ZB(Z),!0}catch{return!1}}function KZ($,Z){if(!R6.test($))return!1;let J=k6($);if(!I6(J))return!1;try{let z=JSON.parse(TK(J,"utf-8"));return z.meta.title=Z,z.meta.updated=new Date().toISOString(),T0(J,JSON.stringify(z,null,2)),!0}catch{return!1}}var S3,R6,RK=65536;var u$=C(()=>{L$();l();DK();k3();S4();S3=new Map;R6=/^[a-zA-Z0-9_-]+$/});import{useEffect as MB,useState as SK}from"react";import{Box as y1,Text as h$,useInput as FB,useStdout as NB}from"ink";import{jsxDEV as k0}from"react/jsx-dev-runtime";function EK($){let Z=Math.max(4,$-11);return Math.min(6+Z+3,Math.max(6,$-2))}function BB($){let Z=$.updated.split("T")[0]??"";return`${$.id} ${Z} ${$.title} (${$.messageCount})`}function vK({currentId:$,onSelect:Z,onCancel:J}){let z=G4(),[G,Q]=SK(""),[Y,K]=SK(0),{stdout:X}=NB(),P=X.rows||24,W=Math.max(4,P-11),H=G.trim().toLowerCase(),q=z.filter((V)=>V.id.toLowerCase().includes(H)||V.title.toLowerCase().includes(H)),U=Math.min(Y,Math.max(0,q.length-1)),M=Math.min(U,Math.max(0,q.length-W)),F=q.slice(M,M+W),N=M,f=q.length-(M+F.length);MB(()=>{K(0)},[]),FB((V,A)=>{let O=V.replace(/[\r\n]+$/,""),v=A.return||/[\r\n]+$/.test(V);if(A.escape){J();return}if(A.pageDown){if(q.length>0)K((b)=>Math.min(q.length-1,b+W));return}if(A.pageUp){if(q.length>0)K((b)=>Math.max(0,b-W));return}if(q.length>0){if(A.downArrow){K((b)=>(b+1)%q.length);return}if(A.upArrow){K((b)=>(b-1+q.length)%q.length);return}}if(v){if(q.length>0)Z(q[U].id);return}if(A.backspace||A.delete){Q((b)=>Array.from(b).slice(0,-1).join(""));return}if(A.ctrl&&V==="u"){Q("");return}if(A.ctrl||A.meta||A.tab)return;if(O)Q((b)=>b+O)});let B=q.length===0&&H==="",_=q.length===0&&H!=="";return k0(y1,{flexDirection:"column",flexShrink:0,width:"100%",borderStyle:"round",borderColor:j.pickerBorder,paddingX:1,children:[k0(y1,{children:[k0(h$,{bold:!0,color:j.pickerBorder,children:"选择会话"},void 0,!1,void 0,this),k0(h$,{color:j.muted,children:$?` (当前: ${$})`:""},void 0,!1,void 0,this)]},void 0,!0,void 0,this),k0(y1,{children:[k0(h$,{color:j.muted,children:"筛选: "},void 0,!1,void 0,this),k0(h$,{color:G?j.accent:j.muted,children:G||"输入字符过滤标题或 id"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),B&&k0(y1,{children:k0(h$,{color:j.muted,dimColor:!0,children:"无已保存的会话"},void 0,!1,void 0,this)},void 0,!1,void 0,this),_&&k0(y1,{children:k0(h$,{color:j.muted,dimColor:!0,children:"没有匹配的会话"},void 0,!1,void 0,this)},void 0,!1,void 0,this),N>0&&k0(y1,{children:k0(h$,{color:j.muted,dimColor:!0,children:["… 上方还有 ",N," 个会话"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),F.map((V,A)=>k0(y1,{children:[k0(h$,{color:A===U-M?j.accent:j.muted,children:A===U-M?"❯ ":" "},void 0,!1,void 0,this),k0(h$,{bold:A===U-M,color:A===U-M?j.accent:void 0,wrap:"truncate-end",children:BB(V)},void 0,!1,void 0,this),V.id===$&&k0(h$,{color:j.success,children:" ←"},void 0,!1,void 0,this)]},V.id,!0,void 0,this)),f>0&&k0(y1,{children:k0(h$,{color:j.muted,dimColor:!0,children:["… 下方还有 ",f," 个会话"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),k0(y1,{children:k0(h$,{color:j.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 xK=C(()=>{u$();P1()});import{useCallback as VB,useEffect as gK,useState as uK}from"react";import{Box as XZ,useInput as fB,useStdout as _B}from"ink";import{jsxDEV as B$}from"react/jsx-dev-runtime";function hK({initialState:$,onSubmit:Z,onConfirm:J,onQuestionAnswer:z,onModelPick:G,onModelCancel:Q,onThinkPick:Y,onThinkCancel:K,onCtxPick:X,onCtxCancel:P,onProviderPick:W,onProviderCancel:H,onSessionPick:q,onSessionCancel:U,onToggleSelectionMode:M,onExitSelectionMode:F,onExit:N,onCopyNotice:f,onNotice:B}){let{stdout:_}=_B(),[V,A]=uK({columns:_.columns||80,rows:_.rows||0});if(gK(()=>{let Y0=()=>A({columns:_.columns||80,rows:_.rows||0});return _.on("resize",Y0),()=>{_.off("resize",Y0)}},[_]),fB((Y0,q0)=>{if(X3(Y0,q0)){if($.confirmMessage){J(!1);return}if($.question){z(null);return}if($.modelPicker){Q();return}if($.thinkPicker){K();return}if($.ctxPicker){P();return}if($.providerPicker){H();return}if($.sessionPicker){U();return}if($.selectionMode){F();return}if($.isRunning)N();return}if(q0.ctrl&&Y0==="b"){if($.confirmMessage||$.question||$.modelPicker||$.thinkPicker||$.ctxPicker||$.providerPicker||$.sessionPicker)return;if($.isRunning)return;if(!$.selectionMode)return;M();return}if(q0.escape&&$.isRunning&&!$.confirmMessage&&!$.question&&!$.modelPicker&&!$.thinkPicker&&!$.ctxPicker&&!$.providerPicker&&!$.sessionPicker)N()}),$.confirmMessage||$.question||$.modelPicker||$.thinkPicker||$.ctxPicker||$.providerPicker||$.sessionPicker)w4(null);let{columns:O,rows:v}=V,b=dQ(v),[D,I]=uK(V6),R=VB((Y0)=>{I((q0)=>q0===Y0?q0:Y0)},[]),J0=Boolean($.confirmMessage),m=Boolean($.question),$0=Boolean($.modelPicker),x=Boolean($.thinkPicker),T=Boolean($.ctxPicker),o=Boolean($.providerPicker),S=Boolean($.sessionPicker),p=J0||m||$0||x||T||o||S;gK(()=>{if(p)I(V6)},[p]);let z0=J0?mY($.confirmMessage??"",O,b):m?rY($.question.prompt,$.question.options,O,b,Boolean($.question.multiple)):$0?GK(b):x?PK():T?FK():o?_K(b):S?EK(b):D,u=$.isRunning&&!J0&&!m&&!$0&&!x&&!T&&!o&&!S,y0=lQ(b,z0,u?1:0);return B$(XZ,{flexDirection:"column",width:"100%",height:b||void 0,overflow:"hidden",children:[!$0&&B$(XZ,{flexDirection:"column",flexGrow:1,flexShrink:1,minHeight:0,overflow:"hidden",width:"100%",children:B$(EY,{messages:$.messages,maxHeight:y0,columns:O,onCopyNotice:f,selectionMode:Boolean($.selectionMode),onExitSelectionMode:F,interactive:!p},void 0,!1,void 0,this)},void 0,!1,void 0,this),u&&B$(XZ,{paddingLeft:1,flexShrink:0,width:"100%",children:B$(LQ,{label:$.spinnerText||"思考中..."},void 0,!1,void 0,this)},void 0,!1,void 0,this),B$(ZK,{state:$,columns:O},void 0,!1,void 0,this),$.confirmMessage?B$(nY,{message:$.confirmMessage,onConfirm:J,columns:O,maxRows:z0},void 0,!1,void 0,this):$.question?B$(iY,{prompt:$.question.prompt,options:$.question.options,multiple:Boolean($.question.multiple),onAnswer:z,columns:O,maxRows:z0},void 0,!1,void 0,this):$.modelPicker?B$(QK,{currentModel:$.model,onSelect:G,onCancel:Q},void 0,!1,void 0,this):$.thinkPicker?B$(WK,{scope:$.thinkPicker.scope,modelId:$.model,onSelect:(Y0)=>Y(Y0,$.thinkPicker.scope),onCancel:K},void 0,!1,void 0,this):$.ctxPicker?B$(BK,{onSelect:X,onCancel:P},void 0,!1,void 0,this):$.providerPicker?B$(LK,{onSelect:W,onCancel:H},void 0,!1,void 0,this):$.sessionPicker?B$(vK,{currentId:$.sessionId,onSelect:q,onCancel:U},void 0,!1,void 0,this):B$(qY,{onSubmit:Z,disabled:$.isRunning||Boolean($.selectionMode),placeholder:$.isRunning?"按 Esc 取消运行...":"输入消息... (Ctrl+J 换行)",columns:O,terminalRows:b,onSelectionMode:M,onExit:N,onRowsChange:R,onNotice:B},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}var mK=C(()=>{jQ();UY();xY();cY();tY();JK();YK();HK();VK();jK();xK();V7()});function nK($,Z,J){let z=-1;if(Z)z=$.findIndex((Y)=>Y.role==="tool"&&Y.toolCallId===Z);if(z===-1){for(let Y=$.length-1;Y>=0;Y--)if($[Y].role==="tool"&&$[Y].toolName==="task"){z=Y;break}}if(z===-1)return $;let G=$[z],Q=$.slice();return Q[z]={...G,toolChildren:[...G.toolChildren??[],J]},Q}import{render as LB}from"ink";import{jsxDEV as jB}from"react/jsx-dev-runtime";class PZ{state;rerender=null;inkInstance=null;callbacks;pendingDelta="";deltaTimer=null;pendingThinking="";thinkingTimer=null;copyNoticeTimer=null;constructor($,Z,J){this.state={messages:[],isRunning:!1,model:Z,sessionId:J},this.callbacks=$}appElement(){return jB(hK,{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=LB(this.appElement(),{exitOnCtrlC:!1,stdout:DQ(process.stdout)})}update($){if(this.state={...this.state,...$},this.inkInstance)this.inkInstance.rerender(this.appElement())}addMessage($){this.flushPendingThinking(),this.flushPendingDeltas(),this.state.messages=[...this.state.messages,$],this.update({})}messageCount(){return this.state.messages.length}setToolResult($,Z,J,z,G){let Q=[...this.state.messages],Y=Q.findIndex((K)=>K.role==="tool"&&K.toolCallId===$);if(Y===-1)for(let K=Q.length-1;K>=0;K--){let X=Q[K];if(X.role==="tool"&&X.toolName===Z&&X.toolResult===void 0){Y=K;break}}if(Y===-1)return;Q[Y]={...Q[Y],toolResultSummary:J,toolResult:z,toolIsError:G},this.state.messages=Q,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 Z=[...this.state.messages],J=Z[Z.length-1];if(J&&J.role==="thinking")Z[Z.length-1]={...J,content:J.content+$},this.state.messages=Z,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 Z=[...this.state.messages],J=Z[Z.length-1];if(J&&J.role==="assistant")Z[Z.length-1]={...J,content:J.content+$},this.state.messages=Z,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($,Z){if(!$)this.flushPendingThinking(),this.flushPendingDeltas();if(this.state.isRunning===$&&this.state.spinnerText===Z)return;this.update({isRunning:$,spinnerText:Z})}showConfirm($){this.update({confirmMessage:$,selectionMode:!1})}hideConfirm(){this.update({confirmMessage:void 0})}showQuestion($,Z,J=!1){let z=d1(o1(Z));this.update({question:{prompt:p1($),...z.length>0?{options:z}:{},...J?{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($,Z){this.state.messages=nK(this.state.messages,$,Z),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;w4(null);try{process.stdout.write("\x1B[?1000l\x1B[?1002l\x1B[?1006l")}catch{}this.inkInstance?.unmount(),this.inkInstance=null}}var cK=C(()=>{mK();e2()});import{existsSync as AB,mkdirSync as DB,readdirSync as OB,statSync as CB,unlinkSync as bB,writeFileSync as wB}from"fs";import WZ from"path";import{randomBytes as IB}from"crypto";function yB(){return WZ.join(P0(),"tool-output")}function SB($){let Z=Date.now();if(Z-pK<kB)return;if(pK=Z,!AB($))return;try{for(let J of OB($)){if(!J.startsWith("tool-")||!J.endsWith(".txt"))continue;let z=WZ.join($,J);try{if(Z-CB(z).mtimeMs>RB)bB(z)}catch{}}}catch{}}function qZ($){let Z=yB();DB(Z,{recursive:!0}),SB(Z);let J=`tool-${Date.now()}-${IB(4).toString("hex")}.txt`,z=WZ.join(Z,J);return wB(z,$,"utf-8"),z}function EB($,Z,J,z,G,Q){if(G.length<=Z&&Q<=J)return{text:$,cut:!1};let Y=[],K=0,X=(P,W)=>{let H=Buffer.byteLength(G[P],"utf-8")+(W?0:1);if(K+H>J)return!1;if(z==="head")Y.push(G[P]);else Y.unshift(G[P]);return K+=H,!0};if(z==="head"){for(let P=0;P<G.length&&Y.length<Z;P++)if(!X(P,Y.length===0)){if(Y.length===0){let W=Buffer.from(G[P],"utf-8"),H=Math.min(J,W.length);while(H>0&&(W[H]&192)===128)H--;Y.push(W.subarray(0,H).toString("utf-8"))}break}}else for(let P=G.length-1;P>=0&&Y.length<Z;P--)if(!X(P,Y.length===0)){if(Y.length===0){let W=Buffer.from(G[P],"utf-8"),H=W.length-J;if(H<0)H=0;while(H<W.length&&(W[H]&192)===128)H++;Y.unshift(W.subarray(H).toString("utf-8"))}break}return{text:Y.join(`
|
|
115
|
+
`),cut:!0}}function f0($,Z={}){let J=Z.maxLines??TB,z=Z.maxBytes??HZ,G=Z.direction??"head",Q=$.split(`
|
|
116
|
+
`),Y=Buffer.byteLength($,"utf-8");if(Q.length<=J&&Y<=z)return{content:$,truncated:!1};let K=qZ($),X=EB($,J,z,G,Q,Y),P=`...output truncated...
|
|
117
|
+
|
|
118
|
+
`;return{content:G==="tail"?`${P}${oK(K)}
|
|
119
|
+
|
|
120
|
+
${X.text}`:`${X.text}
|
|
121
|
+
|
|
122
|
+
${P}${oK(K)}`,truncated:!0,outputPath:K}}var TB=2000,HZ=51200,RB=604800000,kB=600000,pK=0,oK=($)=>`The tool output was truncated. Full output saved to: ${$}
|
|
123
|
+
Use the read tool with startLine/endLine, or grep, to inspect further.`;var I$=C(()=>{l()});import{mkdirSync as vB,readdirSync as xB,unlinkSync as gB,writeFileSync as uB}from"fs";import UZ from"path";function E3(){return UZ.join(P0(),"logs")}function mB($){let Z=$.getFullYear(),J=String($.getMonth()+1).padStart(2,"0"),z=String($.getDate()).padStart(2,"0");return UZ.join(E3(),`min-agent.${Z}-${J}-${z}.log`)}function dK(){try{vB(E3(),{recursive:!0});let $=Date.now()-hB*24*60*60*1000;for(let Z of xB(E3())){let J=Z.match(/^min-agent\.(\d{4})-(\d{2})-(\d{2})\.log$/);if(!J)continue;if(new Date(`${J[1]}-${J[2]}-${J[3]}T00:00:00`).getTime()<$)try{gB(UZ.join(E3(),Z))}catch{}}}catch{}}function MZ($,Z){try{let J=new Date,z=`${String(J.getHours()).padStart(2,"0")}:${String(J.getMinutes()).padStart(2,"0")}:${String(J.getSeconds()).padStart(2,"0")}`;uB(mB(J),`[${z}] [${$}]${nB()} ${pB(Z)}
|
|
124
|
+
`,{flag:"a"})}catch{}}function nB(){if(!Q4)return"";return` [run=${Q4.runId} pass=${Q4.pass}]`}function FZ(){let $=Math.random().toString(36).slice(2,8);return Q4={runId:$,pass:0},$}function rK(){if(!Q4)FZ();return Q4.pass++,Q4.pass}function lK(){Q4=null}function pB($){let Z=$;for(let J of cB)Z=Z.replace(J,"$1***");return Z}function Q0($,Z){MZ($,Z)}function iK($,Z=200){let J=typeof $==="string"?$:JSON.stringify($)??String($);return J.length>Z?J.slice(0,Z)+"…":J}function NZ($,Z){MZ("info",`tool_call ${$} ${iK(Z)}`)}function S6($,Z){MZ("info",`tool_result ${$} ${iK(Z)}`)}var hB=7,Q4=null,cB;var v4=C(()=>{l();cB=[/\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 b2={};M0(b2,{syncMcpConnections:()=>O2,shutdownMcp:()=>X4,saveMcpConfig:()=>v6,resolveMcpTimeouts:()=>bZ,readMcpResource:()=>g3,mcpConfigPathFor:()=>OZ,loadMcpConfigFile:()=>S1,loadMcpConfigEntries:()=>F1,loadMcpConfig:()=>WV,listMcpCatalog:()=>K4,isRemoteMcpConfig:()=>CZ,initMcp:()=>u4,getMcpTools:()=>C2,getMcpStatus:()=>a$,getMcpReadOnlyToolIds:()=>TZ,getMcpPrompt:()=>u3,getMcpCatalogTools:()=>x6,formatResourceContents:()=>qX,formatPromptResult:()=>UX,formatMcpServerBinding:()=>v3,discoverMcpExtras:()=>QX,connectMcpServer:()=>KX,checkMcpServer:()=>x3,checkAllMcpServers:()=>IZ,buildMcpToolsMap:()=>WX});import{Client as fZ}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as oB}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as dB}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{SSEClientTransport as rB}from"@modelcontextprotocol/sdk/client/sse.js";import{UnauthorizedError as lB,auth as tK}from"@modelcontextprotocol/sdk/client/auth.js";import{tool as E6,jsonSchema as A2}from"ai";import{readFileSync as JX,writeFileSync as zX,mkdirSync as GX,statSync as iB,existsSync as tB}from"fs";import g4 from"path";import{createServer as aB}from"http";import{spawn as BZ}from"child_process";import{Writable as sB}from"stream";import{randomUUID as eB}from"crypto";function _Z($){if(typeof $==="string")return $.length>aK?$.slice(0,aK)+"… [truncated]":$;if(Array.isArray($))return $.slice(0,$V).map(_Z);if($!==null&&typeof $==="object"){let Z={};for(let[J,z]of Object.entries($))Z[J]=_Z(z);return Z}return $}function KV(){return g4.join(P0(),"mcp.json")}function XV(){return g4.join(process.cwd(),".min-agent","mcp.json")}function OZ($){return $==="project"?XV():KV()}function PV($){let Z=jZ.get($);try{let J=iB($);if(Z&&Z.mtimeMs===J.mtimeMs&&Z.size===J.size)return Z;let z=JSON.parse(JX($,"utf-8")),G={mtimeMs:J.mtimeMs,size:J.size,config:z};return jZ.set($,G),G}catch{return null}}function S1($){return PV(OZ($))?.config??{mcpServers:{}}}function WV(){return{mcpServers:{...S1("global").mcpServers,...S1("project").mcpServers}}}function F1(){let $=S1("global"),Z=S1("project");return Object.entries({...$.mcpServers,...Z.mcpServers}).map(([J,z])=>({name:J,config:z,scope:Z.mcpServers[J]!==void 0?"project":"global"}))}function v6($,Z="global"){let J=OZ(Z);if(Z==="project"&&!tB(g4.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=g4.dirname(J);GX(z,{recursive:!0}),zX(J,JSON.stringify($,null,2),"utf-8"),jZ.delete(J)}function CZ($){return typeof $.url==="string"&&$.url.trim().length>0}function bZ($){return{connectTimeout:$.connectTimeout??$.timeout??sK,callTimeout:$.callTimeout??$.timeout??sK}}function AZ($){return JSON.stringify($)}function HV($){let Z=new Headers($.headers??{}),J=$.token?.trim();if(J&&!Z.has("Authorization"))Z.set("Authorization",`Bearer ${J}`);if([...Z.keys()].length===0)return;return{headers:Z}}function qV($){let Z=[],J="";return{stream:new sB({write(G,Q,Y){J+=String(G);let K=-1;while((K=J.indexOf(`
|
|
125
|
+
`))!==-1){let X=J.slice(0,K).trim();if(J=J.slice(K+1),!X)continue;if(Z.push(X),Z.length>QV)Z.shift();Q0("warn",`mcp "${$}" stderr: ${X}`)}Y()}}),lines:Z}}async function UV($){let Z=[],J;do{let z=await $.listTools(J?{cursor:J}:void 0);Z.push(...z.tools),J=z.nextCursor}while(J);return Z}async function VZ($,Z){let J=[],z;do{let G=await $(z);if(J.push(...G.items),z=G.nextCursor,J.length>=Z)return J.slice(0,Z)}while(z);return J}async function QX($){let Z=$.getServerCapabilities(),J=[],z=[],G=[];if(Z?.resources){try{J=await VZ(async(Q)=>{let Y=await $.listResources(Q?{cursor:Q}:void 0);return{items:Y.resources.map((K)=>({uri:K.uri,name:K.name,...K.description?{description:K.description}:{},...K.mimeType?{mimeType:K.mimeType}:{}})),nextCursor:Y.nextCursor}},ZV)}catch{J=[]}try{z=await VZ(async(Q)=>{let Y=await $.listResourceTemplates(Q?{cursor:Q}:void 0);return{items:Y.resourceTemplates.map((K)=>({uriTemplate:K.uriTemplate,name:K.name,...K.description?{description:K.description}:{},...K.mimeType?{mimeType:K.mimeType}:{}})),nextCursor:Y.nextCursor}},JV)}catch{z=[]}}if(Z?.prompts)try{G=await VZ(async(Q)=>{let Y=await $.listPrompts(Q?{cursor:Q}:void 0);return{items:Y.prompts.map((K)=>({name:K.name,...K.description?{description:K.description}:{},...K.arguments&&K.arguments.length>0?{arguments:K.arguments}:{}})),nextCursor:Y.nextCursor}},zV)}catch{G=[]}return{resources:J,resourceTemplates:z,prompts:G}}async function DZ($,Z,J,z={}){let G=await UV($),Q=await QX($);return{client:$,transport:Z,tools:G,...Q,callTimeout:bZ(J).callTimeout,signature:AZ(J),...z}}async function MV($,Z,J){let z,G;if(Array.isArray(Z.command))[z,...G]=Z.command;else if(typeof Z.command==="string")z=Z.command,G=Z.args??[];else throw Error(`MCP "${$}" has empty command`);if(!z)throw Error(`MCP "${$}" has empty command`);let Q=qV($),Y=new oB({command:z,args:G,env:{...process.env,...Z.environment??{}},stderr:"pipe"});Y.stderr?.pipe(Q.stream),J?.onTransport?.(Y);let K=new fZ({name:"min-agent",version:"0.1.0"});try{return await K.connect(Y),await DZ(K,Y,Z,{stderrSink:Q})}catch(X){await Y.close().catch(()=>{});let P=Q.lines.length?`
|
|
126
|
+
Server stderr (last ${Q.lines.length} lines):
|
|
127
|
+
${Q.lines.map((W)=>` ${W}`).join(`
|
|
128
|
+
`)}`:"";throw Error(`${X?.message??String(X)}${P}`)}}class wZ{name;serverConfig;tokensStore;clientInfo;discoveryStore;verifier;pendingState;pendingCode;pendingError;resolveCode;rejectCode;callbackServer;callbackBase="http://127.0.0.1";redirectUrl="";constructor($,Z,J){this.name=$;this.serverConfig=Z;this.loadStore(J)}static async create($,Z){let J=g4.join(P0(),"mcp-oauth",`${D2($)}-${ZX($).toString(16)}.json`),z=new wZ($,Z,J);return await z.bindCallbackServer(),z}storeFile(){return g4.join(P0(),"mcp-oauth",`${D2(this.name)}-${ZX(this.name).toString(16)}.json`)}loadStore($){try{let Z=JSON.parse(JX($,"utf-8"));this.clientInfo=Z.clientInfo,this.tokensStore=Z.tokens,this.discoveryStore=Z.discovery}catch{}}saveStore(){let $=this.storeFile();GX(g4.dirname($),{recursive:!0}),zX($,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(($,Z)=>{let J=aB((z,G)=>{let Q=new URL(z.url??"/",this.callbackBase),Y=Q.searchParams.get("code"),K=Q.searchParams.get("state"),X=Q.searchParams.get("error"),P=Y?"<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(G.writeHead(Y?200:400,{"Content-Type":"text/html; charset=utf-8"}),G.end(P),this.pendingState&&K&&K!==this.pendingState){this.failCode(Error("OAuth state mismatch — authorization attempt rejected"));return}if(Y)this.settleCode(Y);else this.failCode(Error(X?`OAuth authorization failed: ${X}`:"OAuth authorization failed: no code returned"))});J.on("error",(z)=>{this.failCode(Error(`OAuth callback server failed: ${z.message}`))}),J.listen(0,"127.0.0.1",()=>{let z=J.address();if(!z||typeof z==="string"){Z(Error("OAuth callback server could not bind a port"));return}this.callbackServer=J,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(($,Z)=>{this.resolveCode=$,this.rejectCode=Z})}get clientMetadata(){let $=this.serverConfig.oauth,Z={redirect_uris:[this.redirectUrl],client_name:"min-agent"};if(typeof $==="object"&&$){if($.clientId)Z.client_id=$.clientId;if($.clientSecret)Z.client_secret=$.clientSecret;if($.scope)Z.scope=$.scope}return Z}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=eB(),this.pendingState}redirectToAuthorization($){FV($.href)}}function FV($){let Z=process.platform;try{if(Z==="darwin")BZ("open",[$],{detached:!0,stdio:"ignore"}).unref();else if(Z==="win32")BZ("cmd",["/c","start","",$],{detached:!0,stdio:"ignore"}).unref();else BZ("xdg-open",[$],{detached:!0,stdio:"ignore"}).unref()}catch(J){Q0("warn",`mcp oauth: failed to open browser: ${J.message}`)}}async function NV($,Z,J){if(!Z.oauth||Z.token?.trim())return;let z=await wZ.create($,Z);try{if(await tK(z,{serverUrl:J.href})==="REDIRECT"){console.log(`\x1B[90m MCP "${$}" needs authorization — a browser tab was opened. Waiting for login…\x1B[0m`);let Q=await Promise.race([z.waitForCode(),new Promise((Y,K)=>{setTimeout(()=>K(Error("OAuth authorization timed out after 5 minutes")),YV)})]);await tK(z,{serverUrl:J.href,authorizationCode:Q})}return z}catch(G){throw z.close(),Error(`MCP "${$}" OAuth failed: ${G?.message??String(G)}`)}}async function BV($,Z,J){let z=Z.url?.trim();if(!z)throw Error(`MCP "${$}" has empty url`);let G;try{G=new URL(z)}catch{throw Error(`MCP "${$}" has invalid url: ${z}`)}if(G.protocol!=="http:"&&G.protocol!=="https:")throw Error(`MCP "${$}" url must be http or https`);let Q=HV(Z),Y=Z.remoteTransport??"auto",K=await NV($,Z,G);if(K)J?.onOAuthProvider?.(K);let X=async()=>{let W=new fZ({name:"min-agent",version:"0.1.0"}),H=new dB(G,Q||K?{requestInit:Q,authProvider:K}:void 0);J?.onTransport?.(H);try{return await W.connect(H),await DZ(W,H,Z,{oauthProvider:K})}catch(q){throw await H.close().catch(()=>{}),q}},P=async()=>{let W=new fZ({name:"min-agent",version:"0.1.0"}),H=new rB(G,Q||K?{requestInit:Q,authProvider:K}:void 0);J?.onTransport?.(H);try{return await W.connect(H),await DZ(W,H,Z,{oauthProvider:K})}catch(q){throw await H.close().catch(()=>{}),q}};try{if(Y==="streamable-http")return await X();if(Y==="sse")return await P();try{return await X()}catch(W){try{return await P()}catch{throw W}}}catch(W){K?.close();let H=W instanceof Error?W.message:String(W);if(W instanceof lB||H.includes("Unauthorized")||H.includes("401")){if(Z.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:
|
|
129
|
+
min-agent mcp add ${$} --url ${z} --token YOUR_TOKEN`)}throw Error(`MCP "${$}" remote connection failed: ${H}`)}}async function VV($,Z,J){if(CZ(Z))return await BV($,Z,J);return await MV($,Z,J)}function v3($){if(CZ($)){let J=$.remoteTransport??"auto";return`${$.url} [remote:${J}]`}return(Array.isArray($.command)?$.command.join(" "):`${$.command??""} ${($.args??[]).join(" ")}`.trim())||"(no command)"}async function YX($,Z){let J=bZ(Z).connectTimeout,z,G={transport:null},Q={provider:null},Y=new Promise((X,P)=>{z=setTimeout(()=>P(Error(`connection timed out after ${J}ms`)),J)}),K=VV($,Z,{onTransport:(X)=>{G.transport=X},onOAuthProvider:(X)=>{Q.provider=X}});K.catch(()=>{});try{return{server:await Promise.race([K,Y])}}catch(X){return await G.transport?.close().catch(()=>{}),Q.provider?.close(),K.then((P)=>XX(P)).catch(()=>{}),{error:X}}finally{if(z)clearTimeout(z)}}async function KX($,Z){if(Z.enabled===!1)return null;let{server:J,error:z}=await YX($,Z);if(J)return delete Y4[$],console.log(`\x1B[90m MCP "${$}" connected (${J.tools.length} tools, ${J.resources.length} resources, ${J.prompts.length} prompts)\x1B[0m`),Q0("info",`mcp "${$}" connected (${J.tools.length} tools, ${J.resources.length} resources, ${J.prompts.length} prompts)`),J;let G=z?.message??String(z);return Y4[$]=G,console.error(`\x1B[31m MCP "${$}" failed: ${G}\x1B[0m`),Q0("error",`mcp "${$}" failed: ${G}`),null}async function x3($,Z){if(Z.enabled===!1)return{name:$,enabled:!1,ok:!0,toolCount:0};let{server:J,error:z}=await YX($,Z);if(!J)return{name:$,enabled:!0,ok:!1,toolCount:0,error:z instanceof Error?z.message:String(z)};let G=J.tools.length;try{await J.client.close()}catch{}return J.oauthProvider?.close(),{name:$,enabled:!0,ok:!0,toolCount:G}}async function IZ(){let $=F1();return(await Promise.allSettled($.map(({name:J,config:z})=>x3(J,z)))).map((J,z)=>J.status==="fulfilled"?J.value:{name:$[z]?.name??"unknown",enabled:!0,ok:!1,toolCount:0,error:String(J.reason)})}async function XX($){try{await $.client.close()}catch{}$.oauthProvider?.close()}async function PX($,Z){await XX(Z),delete Y$[$],delete Y4[$]}async function X4(){x4=null,await Promise.all(Object.entries(Y$).map(([$,Z])=>PX($,Z))),Y$={}}function O2(){let $=eK.then(()=>fV());return eK=$.catch(()=>{}),$}async function fV(){x4=null;let $=F1();for(let[G,Q]of Object.entries(Y$)){let Y=$.find((K)=>K.name===G);if(!Y||Y.config.enabled===!1||AZ(Y.config)!==Q.signature)await PX(G,Q)}let Z=$.filter(({name:G,config:Q})=>{if(Q.enabled===!1)return!1;let Y=Y$[G];if(!Y)return!0;return AZ(Q)!==Y.signature}),J=await Promise.allSettled(Z.map(async({name:G,config:Q})=>{let Y=await KX(G,Q);if(Y)Y$[G]=Y})),z=new Set;return J.forEach((G,Q)=>{if(G.status==="rejected"){let Y=Z[Q].name;z.add(Y),Y4[Y]=String(G.reason),console.error(`\x1B[31m MCP "${Y}" failed: ${String(G.reason)}\x1B[0m`),Q0("error",`mcp "${Y}" failed: ${String(G.reason)}`)}}),$.map(({name:G,config:Q})=>{let Y=Y$[G];if(Q.enabled===!1)return{name:G,state:"disabled"};if(Y){let K=Z.some((X)=>X.name===G);return{name:G,state:K?"connected":"unchanged",tools:Y.tools.length}}return{name:G,state:"failed",...Y4[G]?{error:Y4[G]}:{}}})}async function u4(){x4=null,await X4(),await O2()}function C2(){if(x4)return x4;return LZ=new Set,x4=WX(Y$,LZ),x4}function TZ(){return C2(),LZ}function WX($,Z){let J={},z=new Set;for(let[G,Q]of Object.entries($))for(let Y of Q.tools){let K=`${D2(G)}_${D2(Y.name)}`,X=2;while(z.has(K))K=`${D2(G)}_${D2(Y.name)}_${X++}`;z.add(K);let P=Y.inputSchema??{},W={...P,...P.type?{}:{type:"object"},...P.properties?{}:{properties:{}}},H=Y.annotations?.readOnlyHint===!0;if(H)Z?.add(K);let q=`[${G}] ${Y.description??`MCP tool: ${Y.name}`}`+(H?" (read-only)":""),U=Y.outputSchema;J[K]=E6({description:q,inputSchema:A2(W),...U&&U.type==="object"?{outputSchema:A2(U)}:{},execute:async(M,F)=>{try{let N=[AbortSignal.timeout(Q.callTimeout)];if(F?.abortSignal)N.push(F.abortSignal);let f=N.length===1?N[0]:AbortSignal.any(N),B=await Q.client.callTool({name:Y.name,arguments:M??{}},void 0,{signal:f});if(B.isError)return f0(`Error: ${JSON.stringify(B.content)}`,{direction:"head"}).content;if(B.structuredContent!==void 0)return _Z(B.structuredContent);let V=B.content.filter((A)=>A.type==="text").map((A)=>A.text??"").join(`
|
|
130
|
+
`)||JSON.stringify(B.content);return f0(V,{direction:"head"}).content}catch(N){return f0(`MCP tool error: ${N.message}`,{direction:"head"}).content}}})}return J}function a$(){let $={};for(let{name:Z,config:J}of F1()){let z=Y$[Z];$[Z]={connected:!!z,enabled:J.enabled!==!1,tools:z?.tools.map((G)=>G.name)??[],resource_count:z?.resources.length??0,prompt_count:z?.prompts.length??0,...Y4[Z]?{error:Y4[Z]}:{}}}return $}function K4($){return{servers:($?[$]:Object.keys(Y$)).flatMap((J)=>{let z=Y$[J];if(!z)return[];return[{name:J,resources:z.resources,templates:z.resourceTemplates,prompts:z.prompts}]})}}function $X(){return Object.keys(Y$)}function HX($,Z){if($){let z=Y$[$];if(!z)return`MCP server "${$}" is not connected. Connected: ${$X().join(", ")||"none"}`;return z}let J=$X();if(J.length===0)return"No MCP servers connected.";if(J.length===1)return Y$[J[0]];return`Multiple MCP servers are connected (${J.join(", ")}). Pass server to choose which ${Z} to use.`}async function g3($,Z){let J=HX(Z,"resource");if(typeof J==="string")return J;try{let z=await J.client.readResource({uri:$},{timeout:J.callTimeout});return qX(z.contents)}catch(z){return`Failed to read resource: ${z instanceof Error?z.message:String(z)}`}}async function u3($,Z,J){let z=HX(J,"prompt");if(typeof z==="string")return z;try{let G=await z.client.getPrompt({name:$,...Z&&Object.keys(Z).length>0?{arguments:Z}:{}},{timeout:z.callTimeout});return UX(G)}catch(G){return`Failed to get prompt: ${G instanceof Error?G.message:String(G)}`}}function qX($){if($.length===0)return"(empty resource)";return $.map((Z)=>{if(typeof Z.text==="string")return Z.text;if(typeof Z.blob==="string"){if(Z.blob.length<=GV)return Z.blob;return`[binary ${Z.mimeType??"application/octet-stream"} ${Z.blob.length} chars, omitted]`}return JSON.stringify(Z)}).join(`
|
|
131
|
+
|
|
132
|
+
`)}function UX($){let Z=$.description?`${$.description}
|
|
133
|
+
|
|
134
|
+
`:"",J=$.messages.map((z)=>{let G=z.content;if(G&&typeof G==="object"&&"type"in G&&G.type==="text"&&"text"in G)return`${z.role}: ${String(G.text)}`;return`${z.role}: ${JSON.stringify(G)}`}).join(`
|
|
135
|
+
`);return Z+J}function x6(){if(Object.keys(Y$).length===0)return{};let $=E6({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:A2({type:"object",properties:{server:{type:"string",description:"MCP server name. Omit to list every connected server."}}}),execute:async({server:G})=>{let Q=K4(G);if(Q.servers.length===0)return G?`MCP server "${G}" is not connected.`:"No MCP servers connected.";let Y=Q.servers.flatMap((K)=>{let X=K.resources.map((W)=>` resource ${W.uri} ${W.name}${W.description?` — ${W.description}`:""}`),P=K.templates.map((W)=>` template ${W.uriTemplate} ${W.name}${W.description?` — ${W.description}`:""}`);if(X.length===0&&P.length===0)return[`[${K.name}] (no resources)`];return[`[${K.name}]`,...X,...P]});return f0(Y.join(`
|
|
136
|
+
`),{direction:"head"}).content}}),Z=E6({description:"Read an MCP resource by URI. Use mcp_list_resources first. Pass server when more than one MCP server is connected.",inputSchema:A2({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:G,server:Q})=>f0(await g3(G,Q),{direction:"head"}).content}),J=E6({description:"List MCP prompt templates from connected servers. Use this before mcp_get_prompt. Optional server name limits the listing to one server.",inputSchema:A2({type:"object",properties:{server:{type:"string",description:"MCP server name. Omit to list every connected server."}}}),execute:async({server:G})=>{let Q=K4(G);if(Q.servers.length===0)return G?`MCP server "${G}" is not connected.`:"No MCP servers connected.";let Y=Q.servers.flatMap((K)=>{if(K.prompts.length===0)return[`[${K.name}] (no prompts)`];return[`[${K.name}]`,...K.prompts.map((X)=>{let P=X.arguments?.map((W)=>`${W.name}${W.required?"*":""}`).join(", ");return` ${X.name}${P?`(${P})`:""}${X.description?` — ${X.description}`:""}`})]});return f0(Y.join(`
|
|
137
|
+
`),{direction:"head"}).content}}),z=E6({description:"Fill an MCP prompt template. Use mcp_list_prompts first. Pass server when more than one MCP server is connected.",inputSchema:A2({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:G,server:Q,arguments:Y})=>f0(await u3(G,Y,Q),{direction:"head"}).content});return{mcp_list_resources:$,mcp_read_resource:Z,mcp_list_prompts:J,mcp_get_prompt:z}}function D2($){return $.replace(/[^a-zA-Z0-9_-]/g,"_")}function ZX($){let Z=5381;for(let J=0;J<$.length;J++)Z=(Z<<5)+Z+$.charCodeAt(J)>>>0;return Z}var aK=8000,$V=500,ZV=200,JV=100,zV=100,GV=2048,sK=30000,QV=20,YV=300000,Y$,Y4,x4=null,LZ,jZ,eK;var m$=C(()=>{I$();l();v4();Y$={},Y4={},LZ=new Set,jZ=new Map;eK=Promise.resolve()});var m6={};M0(m6,{setSkillEnabled:()=>yZ,scanSkillDir:()=>RZ,readFrontmatterValue:()=>g6,getStaleDisabledSkills:()=>I2,getSkillsTool:()=>LX,getSkills:()=>_X,getSkill:()=>m3,getBuiltinSkillsDir:()=>BX,getAllSkills:()=>B1,discoverSkills:()=>T$,collectLoadedSkillNames:()=>T2,buildSkillsPrompt:()=>jX,buildSkillReloadNote:()=>EZ,buildSkillContent:()=>SZ,attachSkills:()=>h6,SELF_CONFIG_SKILL:()=>CV});import{tool as _V,jsonSchema as LV}from"ai";import{readFileSync as jV,existsSync as NX,readdirSync as AV,realpathSync as MX}from"fs";import DV from"os";import E0 from"path";import{globSync as OV}from"glob";function BX(){return E0.join(g8(),"skills")}function bV(){let $=process.env.MIN_AGENT_NO_BUILTIN_SKILLS?.trim().toLowerCase();return $!=="1"&&$!=="true"}function wV($,Z){let J=E0.relative($,Z);return J===""||!J.startsWith("..")&&!E0.isAbsolute(J)}function N1($){return Array.isArray($)?$.filter((Z)=>typeof Z==="string"):[]}function u6(){let $=w0(),Z=new Set(N1($.enabledSkills)),J=new Set,z=new Map;for(let G of N1(a().disabledSkills)){if(Z.has(G))continue;J.add(G),z.set(G,"global")}for(let G of N1($.disabledSkills))J.add(G),z.set(G,"project");return{disabled:J,scopeOf:z}}function kZ($,Z){let J=Z.disabled.has($.name);return{...$,enabled:!J,...J?{disabledScope:Z.scopeOf.get($.name)}:{}}}function kV(){let $=process.env.MIN_AGENT_SKILLS_DIRS?.trim();if($)return $.split(E0.delimiter).map((Z)=>Z.trim()).filter(Boolean).map((Z)=>E0.resolve(Z));return[E0.join(DV.homedir(),".agents","skills"),E0.join(process.cwd(),".min-agent","skills"),E0.join(process.cwd(),".agents","skills"),E0.join(process.cwd(),".opencode","skills"),E0.join(process.cwd(),".claude","skills")]}function yV($,Z){if($===Z)return!0;try{return MX($)===MX(Z)}catch{return!1}}function RZ($,Z=VX){if(!NX($))return[];let J=OV("**/SKILL.md",{cwd:$,absolute:!0,follow:!0,maxDepth:IV,ignore:["**/node_modules/**","**/.git/**","**/dist/**"]}).sort((G,Q)=>G.split(E0.sep).length-Q.split(E0.sep).length||G.localeCompare(Q)),z=new Map;for(let G of J){let Q=EV(G,Z);if(!Q||z.has(Q.name))continue;z.set(Q.name,Q)}return[...z.values()]}function FX($,Z,J){let z=$[Z.name];if(z&&yV(z.location,Z.location)){if(Z.builtin&&!z.builtin)$[Z.name]={...z,builtin:!0};return}if(z){let G=z.version&&Z.version&&z.version!==Z.version?` (version ${z.version} → ${Z.version})`:"";J?.(`\x1B[33m ⚠ Duplicate skill "${Z.name}": ${Z.location} overrides ${z.location}${G}\x1B[0m`)}$[Z.name]=Z}function T$($){let Z=$?.silent?null:VX,J={};for(let Q of kV())for(let Y of RZ(Q,Z))FX(J,Y,Z);if(bV()){let Q=BX();for(let Y of RZ(Q,Z))FX(J,{...Y,builtin:wV(Q,Y.location)},Z)}let z=u6();E1=Object.fromEntries(Object.entries(J).map(([Q,Y])=>[Q,kZ(Y,z)]));let G=Object.keys(E1).length;if(G>0&&!$?.silent){let Q=Object.values(E1).filter((Y)=>Y.enabled).length;Z?.(`\x1B[90m Skills: ${Q} enabled${G>Q?`, ${G-Q} disabled`:""}\x1B[0m`)}}function h3($){let Z=$.trim(),J=Z.match(/^"([\s\S]*)"$/)??Z.match(/^'([\s\S]*)'$/);return J?J[1]:Z}function g6($,Z){let J=$.split(`
|
|
138
|
+
`),z=J.findIndex((P)=>new RegExp(`^${Z}:(\\s|$)`).test(P));if(z===-1)return null;let G=J[z].slice(Z.length+1).trim(),Q=/^[|>][+-]?\d*$/.test(G),Y=[];for(let P of J.slice(z+1)){if(P.trim()!==""&&!/^\s/.test(P))break;Y.push(P.replace(/^\s+/,""))}if(G&&!Q){let P=Y.filter((W)=>W!=="").join(" ");return h3(P?`${G} ${P}`:G)}let X=(Q&&G.startsWith(">")?Y.join(" "):Y.join(`
|
|
139
|
+
`)).trim();return X===""?null:X}function fX($,Z){let J=$.split(`
|
|
140
|
+
`),z=J.findIndex((P)=>new RegExp(`^\\s*${Z}:(\\s|$)`).test(P));if(z===-1)return[];let G=J[z],Q=G.match(/^\s*/)[0].length,Y=G.slice(G.indexOf(":")+1).trim(),K=Y.match(/^\[([\s\S]*)\]$/);if(K)return K[1].split(",").map((P)=>h3(P)).filter(Boolean);if(Y)return[h3(Y)].filter(Boolean);let X=[];for(let P of J.slice(z+1)){if(P.trim()==="")continue;if(P.match(/^\s*/)[0].length<=Q)break;let H=P.trim();if(!H.startsWith("- "))break;X.push(h3(H.slice(2)))}return X}function SV($){let Z=$.split(`
|
|
141
|
+
`),J=Z.findIndex((P)=>/^metadata:(\s|$)/.test(P));if(J===-1)return[];let z=Z[J].match(/^\s*/)[0].length,G=Z.slice(J+1).findIndex((P)=>{if(P.trim()===""||/^\s*$/.test(P))return!1;return P.match(/^\s*/)[0].length>z&&/^requires:(\s|$)/.test(P.trim())});if(G===-1)return[];let Y=Z[J+1+G].match(/^\s*/)[0].length,K=Z.slice(J+1+G+1).findIndex((P)=>{if(P.trim()===""||/^\s*$/.test(P))return!1;return P.match(/^\s*/)[0].length>Y&&/^bins:(\s|$)/.test(P.trim())});if(K===-1)return[];let X=Z.slice(J+1+G+1+K).join(`
|
|
142
|
+
`);return fX(X,"bins")}function EV($,Z){let J;try{J=jV($,"utf-8").replace(/^\uFEFF/,"").replace(/\r\n/g,`
|
|
143
|
+
`)}catch(X){return Z?.(`\x1B[33m ⚠ Skill skipped (unreadable): ${$} — ${X.message}\x1B[0m`),null}let z=J.match(/^---[ \t]*\n([\s\S]*?)\n---[ \t]*(?:\n([\s\S]*))?$/);if(!z)return Z?.(`\x1B[33m ⚠ Skill skipped (missing --- frontmatter block): ${$}\x1B[0m`),null;let G=z[1],Q=g6(G,"name"),Y=g6(G,"description"),K=[!Q&&"name",!Y&&"description"].filter(Boolean);if(!Q||!Y)return Z?.(`\x1B[33m ⚠ Skill skipped (frontmatter missing ${K.join(", ")}): ${$}\x1B[0m`),null;return{name:Q,description:Y,location:$,content:(z[2]??"").trim(),enabled:!0,allowedTools:fX(G,"allowed-tools"),requiredBins:SV(G),version:g6(G,"version")??void 0,builtin:!1,alwaysLoad:vV(G,"always-load")}}function vV($,Z){let J=g6($,Z);if(J==null)return!1;let z=J.trim().toLowerCase();return z==="true"||z==="yes"||z==="1"}function B1(){let $=u6();return Object.values(E1).map((Z)=>kZ(Z,$))}function _X(){return B1().filter(($)=>$.enabled)}function m3($){let Z=E1[$];return Z?kZ(Z,u6()):void 0}function I2(){let $=w0();return[...new Set([...N1(a().disabledSkills),...N1($.disabledSkills),...N1($.enabledSkills)])].filter((J)=>!E1[J])}function yZ($,Z,J){if(J==="global"){let G=a(),Q=new Set(N1(G.disabledSkills));for(let Y of $)if(Z)Q.delete(Y);else Q.add(Y);G.disabledSkills=[...Q],R0(G)}else{let G=w0(),Q=new Set(N1(G.disabledSkills)),Y=new Set(N1(G.enabledSkills)),K=new Set(N1(a().disabledSkills));for(let X of $)if(Z)if(Q.delete(X),K.has(X))Y.add(X);else Y.delete(X);else Q.add(X),Y.delete(X);H$({...G,disabledSkills:[...Q],enabledSkills:[...Y]})}let z=u6();return $.map((G)=>{let Q=!z.disabled.has(G);return{name:G,enabled:Q,...Q===Z?{}:{blockedBy:z.scopeOf.get(G)}}})}function xV($){let Z=[],J=0,z=(G,Q)=>{let Y;try{Y=AV(G,{withFileTypes:!0})}catch{return}for(let K of Y){if(K.name==="SKILL.md"||K.name.startsWith("."))continue;if(J++,Z.length<TV)Z.push(K.isDirectory()?`${E0.join(G,K.name)}/`:E0.join(G,K.name));if(K.isDirectory()&&Q>0)z(E0.join(G,K.name),Q-1)}};return z($,2),{entries:Z.sort(),total:J}}function gV($){if($.length===0)return[];let Z=(process.env.PATH??"").split(E0.delimiter).filter(Boolean),J=process.platform==="win32"?["",".exe",".cmd",".bat",".ps1"]:[""],z=(G)=>Z.some((Q)=>J.some((Y)=>NX(E0.join(Q,`${G}${Y}`))));return $.filter((G)=>!z(G))}function SZ($){let Z=E0.dirname($.location),{entries:J,total:z}=xV(Z),G=gV($.requiredBins),Q=[`<skill_content name="${uV($.name)}">`,`# Skill: ${$.name}`,"",`Base directory for this skill: ${Z}`,"Relative paths in this skill (e.g., scripts/, reference/) are relative to this base directory.","",$.allowedTools.length?`This skill declares allowed-tools: ${w2($.allowedTools.join(", "))}. Prefer these tools while the skill is active.`:"",G.length?`⚠ Required binaries not found on PATH: ${G.join(", ")}. Tell the user to install them before running this skill's commands.`:"",J.length?["<skill_files>",...J.map((Y)=>` <file>${w2(Y)}</file>`),z>J.length?` <note>${z-J.length} more entries not listed; use glob on the base directory</note>`:"","</skill_files>"].filter(Boolean).join(`
|
|
143
144
|
`):"","",$.content,"</skill_content>"].filter(Boolean).join(`
|
|
144
|
-
`);return
|
|
145
|
-
`)}function
|
|
146
|
-
`)}function
|
|
147
|
-
`)}var
|
|
148
|
-
`),
|
|
149
|
-
${
|
|
150
|
-
${
|
|
151
|
-
${z}`)}catch{}for(let
|
|
152
|
-
${z}`)}catch{}for(let
|
|
153
|
-
${z}`)}catch{}let
|
|
154
|
-
`);return(
|
|
155
|
-
`).map((
|
|
156
|
-
`)+(
|
|
157
|
-
`:"")}function
|
|
158
|
-
`);if(P<0)continue;let
|
|
159
|
-
|
|
160
|
-
[... ${$.length-
|
|
161
|
-
`).filter((z)=>z.startsWith("- ")).map((z)=>z.slice(2).replace(/\s*\(base dir:.*$/,"").trim()).filter(Boolean)}function
|
|
145
|
+
`);return f0(Q,{direction:"head",maxBytes:RV}).content}function LX($=new Set){return _V({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:LV({type:"object",properties:{name:{type:"string",description:"The name of the skill from available_skills"}},required:["name"]}),execute:async({name:Z})=>{let J=u6(),z=Object.keys(E1).filter((Q)=>!J.disabled.has(Q)).sort();if(J.disabled.has(Z))return`Skill "${Z}" is disabled (${J.scopeOf.get(Z)} scope). Available skills: ${z.join(", ")||"none"}`;let G=E1[Z];if(!G)return`Skill "${Z}" not found. Available skills: ${z.length?z.join(", "):"none"}`;if($.has(Z))return`Skill "${Z}" is already loaded in this conversation — its instructions are still in effect above. Base directory: ${E0.dirname(G.location)}`;return $.add(Z),SZ(G)}})}function w2($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function uV($){return w2($).replace(/"/g,""")}function hV($){return $.replace(/"/g,'"').replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}function jX($){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((J)=>J.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((J)=>[" <skill>",` <name>${w2(J.name)}</name>`,` <description>${w2(J.description)}</description>`,` <location>${w2(J.location)}</location>`,J.alwaysLoad?" <always_load>true</always_load>":"",J.builtin?" <builtin>true</builtin>":""," </skill>"]),"</available_skills>"].filter((J)=>J!=="").join(`
|
|
146
|
+
`)}function nV($){if(typeof $==="string")return $;if(!$||typeof $!=="object")return"";let Z=$;if(typeof Z.text==="string")return Z.text;let J=Z.output;if(typeof J==="string")return J;if(J&&typeof J==="object"&&typeof J.value==="string")return J.value;return""}function T2($){let Z=new Set,J=(z)=>{for(let G of z.matchAll(mV))Z.add(hV(G[1]))};for(let z of $)if(typeof z.content==="string")J(z.content);else if(Array.isArray(z.content))for(let G of z.content)J(nV(G));return Z}function EZ($){if($.length===0)return"";return["## Skills Previously Loaded",...$.map((J)=>{let z=E1[J];return z?`${J} (base dir: ${E0.dirname(z.location)})`:J}).map((J)=>`- ${J}`),"Their full instructions were dropped during compaction. Re-call the skill tool if you still need them."].join(`
|
|
147
|
+
`)}function h6($,Z){let J=_X();if(J.length===0)return"";let z=Z??new Set,G=J.filter((Y)=>Y.alwaysLoad);for(let Y of G)z.add(Y.name);$.skill=LX(z);let Q=jX(J);if(G.length===0)return Q;return[Q,"","The following skills are already loaded for this conversation. Follow them without calling the skill tool again.",...G.map(SZ)].join(`
|
|
148
|
+
`)}var CV="self-config",IV=3,TV=20,RV=32768,E1,VX=($)=>process.stderr.write(`${$}
|
|
149
|
+
`),mV;var n$=C(()=>{l();O5();I$();E1={};mV=/<skill_content name="([^"]*)"/g});var IX={};M0(IX,{runWithInstructionTracker:()=>xZ,resetActiveInstructionTracker:()=>uZ,loadInstructions:()=>V1,getActiveInstructionTracker:()=>gZ,findProjectInstructions:()=>bX,fetchRemoteInstructions:()=>wX,InstructionTracker:()=>c3});import{AsyncLocalStorage as cV}from"async_hooks";import{readFileSync as n3,existsSync as n6}from"fs";import d0 from"path";import pV from"os";function oV($,Z){let J=d0.relative($,Z);return J===""||!J.startsWith("..")&&!d0.isAbsolute(J)}function OX($,Z){let J=[],z=d0.resolve($);while(z!==d0.dirname(Z)&&oV(Z,z)){if(J.push(z),z===Z)break;z=d0.dirname(z)}return J}class c3{loaded=new Set;isLoaded($){return this.loaded.has(d0.resolve($))}markLoaded($){this.loaded.add(d0.resolve($))}reset(){this.loaded.clear()}resolveForFile($){let Z=[],J=process.cwd();for(let z of OX(d0.dirname(d0.resolve($)),J)){for(let G of DX){let Q=d0.join(z,G);if(n6(Q)&&!this.isLoaded(Q))try{let Y=n3(Q,"utf-8").trim();if(Y)this.markLoaded(Q),Z.push(`Instructions from: ${Q}
|
|
150
|
+
${Y}`)}catch{}}if(Z.length>0)break}return Z}}async function xZ($){return vZ.run(new c3,$)}function gZ(){return vZ.getStore()??CX}function uZ(){let $=vZ.getStore();if($)$.reset();else CX.reset()}function bX(){let $=[],Z=d0.parse(process.cwd()).root;for(let J of OX(process.cwd(),Z)){let z=d0.join(J,".min-agent","AGENTS.md");if(n6(z)){$.push(z);break}let G=DX.find((Q)=>n6(d0.join(J,Q)));if(G){$.push(d0.join(J,G));break}}return $}function dV(){let $=[],Z=$2();if(n6(Z))$.push(Z);return $}function rV(){let Z=a().instructions??[],J=[];for(let z of Z){if(z.startsWith("http://")||z.startsWith("https://"))continue;let G=z.startsWith("~/")?d0.join(pV.homedir(),z.slice(2)):d0.isAbsolute(z)?z:d0.resolve(process.cwd(),z);if(n6(G))J.push(G)}return J}async function iV($){let Z=AX.get($);if(Z&&Date.now()-Z.fetchedAt<lV)return Z.text;try{let J=await fetch($,{signal:AbortSignal.timeout(5000)});if(J.ok){let z=await J.text();if(z.trim())return AX.set($,{fetchedAt:Date.now(),text:z}),z}}catch{}return null}async function wX($){let Z=a(),J=$??Z.instructions??[];return(await Promise.all(J.filter((G)=>G.startsWith("http://")||G.startsWith("https://")).map(async(G)=>{let Q=await iV(G);return Q?`Instructions from: ${G}
|
|
151
|
+
${Q}`:""}))).filter(Boolean)}async function V1(){let $=[];for(let J of dV())try{let z=n3(J,"utf-8").trim();if(z)$.push(`Instructions from: ${J}
|
|
152
|
+
${z}`)}catch{}for(let J of bX())try{let z=n3(J,"utf-8").trim();if(z)$.push(`Instructions from: ${J}
|
|
153
|
+
${z}`)}catch{}for(let J of rV())try{let z=n3(J,"utf-8").trim();if(z)$.push(`Instructions from: ${J}
|
|
154
|
+
${z}`)}catch{}let Z=await wX();return $.push(...Z),$}var DX,vZ,CX,lV=60000,AX;var P4=C(()=>{l();DX=["AGENTS.md","RULES.md","CLAUDE.md"];vZ=new cV,CX=new c3;AX=new Map});function RX($,Z){let J=Error(`${TX}: no ${$} for ${Z}ms`);return J.name="ProviderStallError",J}function p3($,Z=4){let J=[],z=$;for(let G=0;G<Z&&z!=null;G++){if(z instanceof Error){J.push(z.message),z=z.cause;continue}J.push(String(z));break}return J.join(" | ")}function nZ($){return p3($).includes(TX)}function tV($,Z){let J=typeof Z?.body==="string"?Z.body:"",z=`bytes=${J.length}`;try{let G=JSON.parse(J||"{}"),Q=G.tools?.map((Y)=>Y.function?.name??"?")??[];z+=` model=${G.model??"?"} messages=${G.messages?.length??0} tools=${Q.length} stream=${G.stream??!1}`}catch{}return`trace request ${$} ${z}`}function aV($,Z,J){if(!$.body||Z<=0)return $;let G=$.body.getReader(),Q,Y=()=>{if(Q)clearTimeout(Q);Q=void 0},K=new ReadableStream({async pull(X){(()=>{Y(),Q=setTimeout(()=>J(RX("stream",Z)),Z)})();try{let{done:W,value:H}=await G.read();if(Y(),W){X.close();return}X.enqueue(H)}catch(W){Y(),X.error(W)}},cancel(X){return Y(),G.cancel(X)}});return new Response(K,{status:$.status,statusText:$.statusText,headers:$.headers})}function kX($={}){let Z=$.firstByteTimeoutMs??hZ,J=$.idleTimeoutMs??mZ,z=$.fetchImpl??fetch,G=$.now??Date.now,Q=$.trace??!1;return async(Y,K)=>{let X=typeof Y==="string"?Y:Y instanceof URL?Y.toString():Y.url,P=new AbortController,W,H=(N)=>{W=N,Q0("warn",`${N.message} (${X})`),P.abort(N)},q=K?.signal,U=()=>P.abort(q?.reason);if(q)if(q.aborted)U();else q.addEventListener("abort",U,{once:!0});let M;if(Z>0)M=setTimeout(()=>H(RX("first byte",Z)),Z);if(Q)Q0("info",tV(X,K));let F=G();try{let N=await z(Y,{...K,signal:P.signal});if(M)clearTimeout(M);if(Q)Q0("info",`trace response ${X} status=${N.status} ttfb=${G()-F}ms`);return aV(N,J,H)}catch(N){if(M)clearTimeout(M);if(W)throw W;throw N}finally{q?.removeEventListener("abort",U)}}}var TX="min-agent: provider stalled",hZ=180000,mZ=90000;var cZ=C(()=>{v4()});function R2($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function sV($){return $.replace(/<\/?(?:think|thinking)>/gi,"")}function o3($,Z){if(!R2($))return"";return typeof $[Z]==="string"?$[Z]:""}function eV($){if(!Array.isArray($))return"";return $.map((Z)=>{let J=o3(Z,"text");if(J)return J;return o3(Z,"content")}).join("")}function pZ($){if(typeof $==="string")return $;if(!R2($))return"";return o3($,"content")||o3($,"text")}function $f($,Z){if(!$)return Z;if(!Z)return $;if($===Z||Z.includes($))return Z;if($.includes(Z))return $;return $+Z}function Zf($){let Z=eV($.reasoning_details),J=pZ($.reasoning_content)||pZ($.reasoning)||pZ($.thinking);return sV($f(Z,J))}function Jf(){let $="";return(Z)=>{if(!Z)return"";if($&&Z.startsWith($)){let J=Z.slice($.length);return $=Z,J}return $+=Z,Z}}function yX($,Z){let J=Z(Zf($));if(!J)return!1;let z=typeof $.content==="string"?$.content:"";return $.content=`<think>${J}</think>${z}`,!0}function zf($,Z=(J)=>J){if(!R2($)||!Array.isArray($.choices))return!1;let J=!1;for(let z of $.choices){if(!R2(z))continue;if(R2(z.delta)&&yX(z.delta,Z))J=!0;if(R2(z.message)&&yX(z.message,Z))J=!0}return J}function Gf($,Z){let J=$.replace(/\r$/,"");if(!J.startsWith("data:"))return $;let z=J.slice(5).trim();if(!z||z==="[DONE]")return $;try{let G=JSON.parse(z);if(!zf(G,Z))return $;let Q=$.startsWith("data: ")?"data: ":"data:",Y=$.endsWith("\r")?"\r":"";return`${Q}${JSON.stringify(G)}${Y}`}catch{return $}}function SX($,Z){let J=$.endsWith(`
|
|
155
|
+
`);return(J?$.slice(0,-1):$).split(`
|
|
156
|
+
`).map((G)=>Gf(G,Z)).join(`
|
|
157
|
+
`)+(J?`
|
|
158
|
+
`:"")}function Qf($){let Z=new TextDecoder,J=new TextEncoder,z=$.getReader(),G=Jf(),Q="";return new ReadableStream({async pull(Y){for(;;){let{done:K,value:X}=await z.read();if(K){if(Q+=Z.decode(),Q)Y.enqueue(J.encode(SX(Q,G)));Y.close();return}Q+=Z.decode(X,{stream:!0});let P=Q.lastIndexOf(`
|
|
159
|
+
`);if(P<0)continue;let W=Q.slice(0,P+1);Q=Q.slice(P+1),Y.enqueue(J.encode(SX(W,G)));return}},cancel(Y){return z.cancel(Y)}})}function Yf($){let Z=($.headers.get("content-type")??"").toLowerCase();if(Z.includes("event-stream"))return!0;if(!Z||Z.startsWith("text/plain"))return!0;return!1}function EX($){if(!$.body||$.status>=400)return $;if(!Yf($))return $;return new Response(Qf($.body),{status:$.status,statusText:$.statusText,headers:$.headers})}var uX={};M0(uX,{resolveModelForProvider:()=>gX,resolveModel:()=>s$,modelFetch:()=>xX});import{createOpenAI as oZ}from"@ai-sdk/openai";function vX($,Z){let J=typeof $==="string"?Number($):$;if(typeof J!=="number"||!Number.isFinite(J)||J<0)return Z;return J}function xX(){let $=G0(),Z=kX({firstByteTimeoutMs:vX(process.env.MIN_AGENT_REQUEST_TIMEOUT_MS??$.agent?.requestTimeoutMs,hZ),idleTimeoutMs:vX(process.env.MIN_AGENT_STREAM_IDLE_TIMEOUT_MS??$.agent?.streamIdleTimeoutMs,mZ),trace:process.env.MIN_AGENT_TRACE==="1"||process.env.MIN_AGENT_TRACE==="true"});return(J,z)=>hG(Z,J,z).then(EX)}function gX($,Z){if(!$.baseURL||!$.apiKey)throw Error("Not configured. Run: min-agent setup");let J=Z??$.defaultModel;if(!J)throw Error("No model specified. Run: min-agent setup");if(z1($)&&J!==e4)throw Error(`The preset OpenRouter provider only supports the model: ${e4}`);let z=xX();switch($.type??"openai-compatible"){case"openai":return oZ({apiKey:$.apiKey,fetch:z}).chat(J);case"ollama":return oZ({baseURL:O1($.baseURL),apiKey:$.apiKey||"ollama",fetch:z}).chat(J);case"openai-compatible":return oZ({baseURL:$.baseURL,apiKey:$.apiKey,fetch:z}).chat(J);default:throw Error(`Unknown provider type: ${$.type}`)}}function s$($,Z){let J=G0(),z=Z?J.providers?.find((G)=>G.name===Z):s(J);if(!z)throw Error(Z?`Provider "${Z}" not found`:"Not configured. Run: min-agent setup");return gX(z,$)}var h4=C(()=>{l();cZ();E5()});var iZ={};M0(iZ,{getContextWindowInfo:()=>e$,getContextWindow:()=>ff,extractModelContextLength:()=>d3,DEFAULT_CONTEXT_WINDOW:()=>k2});import{readFileSync as Kf,mkdirSync as Xf,existsSync as Pf}from"fs";import hX from"path";function nX(){return hX.join(P0(),"context-window-cache.json")}function cX(){let $=nX();if(!Pf($))return{};try{return JSON.parse(Kf($,"utf-8"))}catch{return{}}}function Hf($){let Z=nX();Xf(hX.dirname(Z),{recursive:!0}),T0(Z,JSON.stringify($))}function qf($){return $==="fallback"?Wf:mX}function Uf($){let Z=z2($);if(Z?.contextWindow)return{tokens:Z.contextWindow,source:"detected"};let J=rZ.get($);if(J&&Date.now()-J.timestamp<=qf(J.source))return{tokens:J.contextWindow,source:J.source};let z=cX()[$];if(!z||z.source!=="detected")return null;if(Date.now()-z.timestamp>mX)return null;return rZ.set($,{...z,source:"detected"}),{tokens:z.contextWindow,source:"detected"}}function c6($,Z,J){let z={contextWindow:Z,timestamp:Date.now(),source:J};if(rZ.set($,z),J!=="detected")return;let G=cX();G[$]=z,Hf(G)}function d3($){if(!$||typeof $!=="object")return null;let Z=$,J=[Z,Z.meta,Z.limits,Z.limit,Z.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 G of J){if(!G||typeof G!=="object")continue;let Q=G;for(let Y of z){let K=Q[Y];if(typeof K==="number"&&Number.isFinite(K)&&K>=4096)return Math.floor(K)}}return null}function lZ($,Z){let J=$.find((z)=>z&&typeof z==="object"&&z.id===Z);if(J)return J;return $.find((z)=>{if(!z||typeof z!=="object")return!1;let G=z.id;return typeof G==="string"&&(G.endsWith(`/${Z}`)||Z.endsWith(`/${G}`))})}async function Mf($,Z,J){if(!$.includes("openrouter"))return null;try{let z=await fetch("https://openrouter.ai/api/v1/models",{headers:{Authorization:`Bearer ${Z}`},signal:AbortSignal.timeout(8000)});if(!z.ok)return null;let G=await z.json();return d3(lZ(G.data??[],J))}catch{return null}}async function Ff($,Z,J){if(!$.includes("vllm"))return null;try{let z=`${$.replace(/\/$/,"")}/models`,G=await fetch(z,{headers:{Authorization:`Bearer ${Z}`},signal:AbortSignal.timeout(5000)});if(!G.ok)return null;let Q=await G.json();return d3(lZ(Q.data??[],J))}catch{return null}}async function pX($,Z,J){if(!$)return null;try{let z=`${$.replace(/\/$/,"")}/models`,G=await fetch(z,{headers:{Authorization:`Bearer ${Z}`},signal:AbortSignal.timeout(8000)});if(!G.ok)return null;let Q=await G.json(),Y=Array.isArray(Q)?Q:Q.data??[];return d3(lZ(Y,J))}catch{return null}}async function Nf($,Z){if(!$.includes("localhost")&&!$.includes("127.0.0.1")&&!$.includes("ollama"))return null;return(await X6(Z,$))?.contextWindow??null}async function Bf($,Z){let J=await X6(Z,$);if(J?.contextWindow)return c6(Z,J.contextWindow,"detected"),{tokens:J.contextWindow,source:"detected"};let z=await pX($,"ollama",Z);if(z){let G=Math.min(z,y5);return c6(Z,G,"detected"),{tokens:G,source:"detected"}}return c6(Z,h8,"fallback"),{tokens:h8,source:"fallback"}}async function Vf($,Z){let J=s($),z=J?.baseURL??"",G=J?.apiKey??"";if(J?.type==="ollama")return Bf(z,Z);let Q=await u8(Z,z);if(Q?.contextWindow)return{tokens:Q.contextWindow,source:"detected"};let K=(await Promise.all([Mf(z,G,Z),Nf(z,Z),Ff(z,G,Z),pX(z,G,Z)])).find((X)=>X!==null);if(K)return c6(Z,K,"detected"),{tokens:K,source:"detected"};return c6(Z,k2,"fallback"),{tokens:k2,source:"fallback"}}async function e$($){let Z=G0(),J=s(Z);if(J?.contextWindow)return{tokens:J.contextWindow,source:"config"};let z=$??J?.defaultModel;if(!z)return{tokens:k2,source:"fallback"};if(J?.type==="ollama"){let Y=i1(z,J.baseURL);if(Y?.contextWindow)return{tokens:Y.contextWindow,source:"detected"}}else{let Y=Uf(z);if(Y)return Y}let G=dZ.get(z);if(G)return G;let Q=Vf(Z,z);dZ.set(z,Q);try{return await Q}finally{dZ.delete(z)}}async function ff($){return(await e$($)).tokens}var k2=512000,mX=604800000,Wf=600000,rZ,dZ;var m4=C(()=>{L$();l();T5();n8();rZ=new Map,dZ=new Map});var t3={};M0(t3,{pruneToolOutputs:()=>p6,needsCompaction:()=>JJ,estimateTokens:()=>x1,estimateStringTokens:()=>l3,estimateOverheadTokens:()=>i3,compactMessages:()=>d6,applyToolPrune:()=>o6,TokenTracker:()=>W4,PRUNE_TARGET_RATIO:()=>ZJ,PRUNE_PRESSURE_RATIO:()=>$J,COMPACTION_RATIO:()=>r3});import{generateText as _f}from"ai";class W4{_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 Rf($){return $>=11904&&$<=40959||$>=63744&&$<=64255||$>=65280&&$<=65519||$>=131072&&$<=262141||$>=12352&&$<=12543||$>=44032&&$<=55215}function v1($){let Z=0,J=0;for(let z of $)if(Rf(z.codePointAt(0)??0))J++;else Z++;return Z/4+J*0.7}function yf($){if(typeof $.text==="string")return v1($.text);if($.type==="image"||$.type==="file")return kf;if($.type==="tool-call"&&$.input!==void 0)try{return v1(JSON.stringify($.input))}catch{return 0}return 0}function iX($){let Z=$.content;if(typeof Z==="string")return v1(Z);if(Array.isArray(Z)){let J=0;for(let z of Z){if($P(z)){let G=aX(z);J+=G?v1(G):0;continue}J+=yf(z)}return J}return 0}function x1($){return Math.ceil($.reduce((Z,J)=>Z+iX(J),0))}function l3($){return Math.ceil(v1($))}function aZ($){return Math.ceil(iX($))}function i3($,Z){let J=v1($);for(let[z,G]of Object.entries(Z??{})){J+=v1(z);let Q=G;if(typeof Q?.description==="string")J+=v1(Q.description);let Y=Q?.inputSchema??Q?.parameters;if(Y!=null)try{J+=v1(JSON.stringify(Y))}catch{}}return Math.ceil(J)}async function tX($){if($?.maxTokens)return{tokens:$.maxTokens,source:"config"};try{return await e$($?.modelId)}catch{return{tokens:k2,source:"fallback"}}}async function JJ($,Z,J){if(J?.force)return!0;let G=(await tX(J)).tokens*r3,Q=J?.overheadTokens??0;if(Z&&Z.lastInputTokens>0)return Z.lastInputTokens>G;return x1($)+Q>G}function aX($){let Z=$.output;if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&"value"in Z){let J=Z.value;if(typeof J==="string")return J}return null}function Sf($){return $.includes(lX)}function Ef($){let Z=/Full output saved to:\s*(\S+)/.exec($);return Z?`, full output: ${Z[1]}`:""}function vf($,Z){return`[${lX}: ${$}, ${Z.length} chars${Ef(Z)}]`}function sZ($){if(typeof $==="string"){if($.length<=tZ)return $;return`${$.slice(0,tZ)}
|
|
160
|
+
|
|
161
|
+
[... ${$.length-tZ} chars omitted from old tool call ...]`}if(Array.isArray($))return $.map(sZ);if($&&typeof $==="object")return Object.fromEntries(Object.entries($).map(([Z,J])=>[Z,sZ(J)]));return $}function sX($){if(typeof $.content==="string")return $.content.includes("<skill_content");if(Array.isArray($.content))return $.content.some((Z)=>(Z.type==="tool-result"||Z.type==="tool-call")&&("toolName"in Z)&&Tf.has(Z.toolName));return!1}function xf($){let Z=[];for(let J=0;J<$.length;J++){let z=$[J].role;if(z==="user"||z==="assistant")Z.push(J)}return Z}function gf($){let Z=[];for(let J=0;J<$.length;J++)if($[J].role==="assistant")Z.push(J);return Z}function uf($){let Z=gf($);if(Z.length<=oX)return 0;return Z[Z.length-oX]}function hf($){if($.role!=="tool"||!Array.isArray($.content)||sX($))return null;let Z=[...$.content],J=!1;for(let z=0;z<Z.length;z++){let G=Z[z];if(G.type!=="tool-result")continue;let Q=aX(G);if(!Q||Sf(Q)||Q.length<=Cf)continue;Z[z]={...G,output:{type:"text",value:vf(G.toolName,Q)}},J=!0}return J?{...$,content:Z}:null}function mf($){if($.role!=="assistant"||!Array.isArray($.content)||sX($))return null;let Z=[...$.content],J=!1;for(let z=0;z<Z.length;z++){let G=Z[z];if(G.type!=="tool-call"||G.input===void 0)continue;let Q=sZ(G.input),Y=Q===G.input;if(!Y)try{Y=JSON.stringify(Q)===JSON.stringify(G.input)}catch{Y=!1}if(Y)continue;Z[z]={...G,input:Q},J=!0}return J?{...$,content:Z}:null}function p6($,Z={}){let J=uf($),z=[];for(let Y=0;Y<J;Y++){let K=$[Y],X=K.role==="tool"?hf(K):K.role==="assistant"?mf(K):null;if(!X)continue;z.push({index:Y,pruned:X,tokensSaved:Math.max(0,aZ(K)-aZ(X))})}if(z.length===0)return $;let G=Z.pressureTokens??Z.targetTokens,Q=new Map;if(Z.force||G==null)for(let Y of z)Q.set(Y.index,Y.pruned);else{let Y=x1($)+(Z.overheadTokens??0);if(Y<=G)return $;let K=Z.targetTokens??G;for(let X of[...z].sort((P,W)=>W.tokensSaved-P.tokensSaved)){if(Y<=K)break;if(X.tokensSaved<=0)continue;Q.set(X.index,X.pruned),Y-=X.tokensSaved}}if(Q.size===0)return $;return $.map((Y,K)=>Q.get(K)??Y)}function o6($,Z={}){let J=p6($,Z);if(J===$)return!1;return $.length=0,$.push(...J),!0}async function nf($,Z){let J=await tX(Z),z=Math.min(Of,Math.max(Df,Math.floor(J.tokens*Af))),G=xf($);if(G.length===0)return{headEnd:0,tailStart:0};let Q=0,Y=$.length;for(let P=G.length-1;P>=0;P--){let W=G[P],H=P<G.length-1?G[P+1]:$.length,q=0;for(let U=W;U<H;U++)q+=aZ($[U]);if(Q+q>z&&Q>0)break;Q+=q,Y=W}if(Y>=$.length)Y=G[G.length-1];let K=Z?.keepRecentTurns??jf,X=[];for(let P=0;P<$.length;P++)if($[P].role==="user")X.push(P);if(Y===0&&X.length>K)Y=X[X.length-K];return{headEnd:Y,tailStart:Y}}function pf($){let J=G0().compaction?.model;if(J)return s$(J);return $}function of($){let Z=$[0];if(Z?.role==="system"&&typeof Z.content==="string"&&Z.content.includes("[Context Summary"))return Z.content.match(/\[Context Summary[^\]]*\]\n\n([\s\S]*)/)?.[1]?.split(eX)[0]?.trimEnd();return}function df($){let Z=$[0];if(Z?.role!=="system"||typeof Z.content!=="string")return[];let J=Z.content.split(eX)[1];if(!J)return[];return J.split(`
|
|
162
|
+
`).filter((z)=>z.startsWith("- ")).map((z)=>z.slice(2).replace(/\s*\(base dir:.*$/,"").trim()).filter(Boolean)}function rf($,Z){let J=Z?.trim()?["The original user goal that must be preserved in ## Goal:",Z.trim(),""].join(`
|
|
162
163
|
`):"",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(`
|
|
163
|
-
`):"Create a new anchored summary from the conversation history above.";return[
|
|
164
|
-
`)}function $P($){return typeof $==="object"&&$!==null&&"type"in $&&$.type==="tool-result"}function
|
|
165
|
-
[... ${$.length-
|
|
166
|
-
`)}return""}function
|
|
164
|
+
`):"Create a new anchored summary from the conversation history above.";return[J,z,"",Lf].filter(Boolean).join(`
|
|
165
|
+
`)}function $P($){return typeof $==="object"&&$!==null&&"type"in $&&$.type==="tool-result"}function eZ($,Z){if($.length<=Z)return $;return`${$.slice(0,Z)}
|
|
166
|
+
[... ${$.length-Z} chars omitted ...]`}function rX($){return If.has($)?wf:bf}function lf($){if(typeof $.content==="string")return $.content;if(Array.isArray($.content)){let Z=[];for(let J of $.content)if("text"in J&&typeof J.text==="string")Z.push(J.text);else if(J.type==="tool-call"){let z="toolName"in J?String(J.toolName):"tool",G="";try{G=JSON.stringify("input"in J?J.input:void 0)}catch{G=""}Z.push(`[tool-call ${z}] ${eZ(G,rX(z))}`)}else if($P(J)){let z=J.toolName||"tool",G=J.output,Q=typeof G==="string"?G:G&&typeof G==="object"&&("value"in G)&&G.value!=null?String(G.value):JSON.stringify(G);Z.push(`[tool-result ${z}] ${eZ(Q,rX(z))}`)}return Z.join(`
|
|
167
|
+
`)}return""}function tf($){let Z=$.map((z)=>`[${z.role}]: ${eZ(lf(z),1500)}`).join(`
|
|
167
168
|
|
|
168
|
-
`);if(
|
|
169
|
+
`);if(Z.length<=dX)return Z;let J=Math.floor((dX-40)/2);return`${Z.slice(0,J)}
|
|
169
170
|
|
|
170
171
|
[... middle omitted ...]
|
|
171
172
|
|
|
172
|
-
${
|
|
173
|
+
${Z.slice(-J)}`}async function af($,Z,J){let z=()=>_f({model:$,system:cf,messages:[{role:"user",content:Z}],abortSignal:J?.abortSignal});try{let G=await z();if(G.text.trim())return G;console.error("[compaction] empty summary, retrying once")}catch(G){if(J?.abortSignal?.aborted)throw G;console.error("[compaction] summary attempt failed, retrying once:",G)}return z()}async function d6($,Z,J){let z=p6($,{force:!0}),G=()=>z===$?{messages:$,compacted:!1}:{messages:z,compacted:!0},{headEnd:Q,tailStart:Y}=await nf(z,J);if(Q<=0)return G();let K=z.slice(0,Q),X=z.slice(Y),P=of(K),W=tf(K),H=pf(Z);try{let q=rf(P,J?.taskGoal),U=await af(H,W+`
|
|
173
174
|
|
|
174
|
-
`+
|
|
175
|
+
`+q,J),M=U.text,F=T2(X),N=[...new Set([...T2(K),...df(K)])].filter((_)=>!F.has(_)),f=EZ(N);return{messages:[{role:"system",content:`[Context Summary - Previous conversation was compacted]
|
|
175
176
|
|
|
176
|
-
${M}${
|
|
177
|
+
${M}${f?`
|
|
177
178
|
|
|
178
|
-
${
|
|
179
|
+
${f}`:""}`},...X],compacted:!0,usage:U.usage}}catch(q){return console.error("[compaction] summary generation failed, keeping pruned messages:",q),G()}}var Lf=`Output exactly the Markdown structure shown below. Keep the section order unchanged.
|
|
179
180
|
|
|
180
181
|
## Goal
|
|
181
182
|
- [single-sentence task summary]
|
|
@@ -209,7 +210,7 @@ Rules:
|
|
|
209
210
|
- Keep every section, even when empty.
|
|
210
211
|
- Use terse bullets, not prose paragraphs.
|
|
211
212
|
- Preserve exact file paths, commands, error strings, and identifiers when known.
|
|
212
|
-
- Do not mention the summary process or that context was compacted.`,
|
|
213
|
+
- Do not mention the summary process or that context was compacted.`,r3=0.75,$J=0.6,ZJ=0.45,jf=2,Af=0.04,Df=2000,Of=48000,oX=4,Cf=400,tZ=500,bf=400,wf=2500,dX=1e5,lX="old tool output omitted",If,Tf,kf=800,cf=`You are an anchored context summarization assistant for coding sessions.
|
|
213
214
|
|
|
214
215
|
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.
|
|
215
216
|
|
|
@@ -219,82 +220,82 @@ Always follow the exact output structure requested by the user prompt. Keep ever
|
|
|
219
220
|
|
|
220
221
|
When the history includes web search or fetched pages, copy concrete facts (names, scores, dates, URLs) into Critical Context. Do not drop numbers.
|
|
221
222
|
|
|
222
|
-
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.`,
|
|
223
|
+
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.`,eX="## Skills Previously Loaded";var g1=C(()=>{l();h4();m4();n$();If=new Set(["search_web","web_fetch"]),Tf=new Set(["skill"])});var a3={};M0(a3,{getModelPrice:()=>r6,formatCost:()=>K_,estimateCost:()=>l6});import{readFileSync as sf,mkdirSync as ef,existsSync as $_}from"fs";import zP from"path";function GP(){return zP.join(P0(),"pricing-cache.json")}function QP(){let $=GP();if(!$_($))return{};try{return JSON.parse(sf($,"utf-8"))}catch{return{}}}function J_($){let Z=GP();ef(zP.dirname(Z),{recursive:!0}),T0(Z,JSON.stringify($))}function z_($){let Z=GJ.get($);if(Z&&Date.now()-Z.timestamp<=ZP)return Z;let J=QP()[$];if(J&&Date.now()-J.timestamp<=ZP)return GJ.set($,J),J;return null}function G_($,Z){let J={price:Z,timestamp:Date.now()};GJ.set($,J);let z=QP();z[$]=J,J_(z)}function Q_($){let Z=a().pricing?.[$];if(!Z)return null;if(typeof Z.inputPerMillion!=="number"||typeof Z.outputPerMillion!=="number")return null;return{inputPerMillion:Z.inputPerMillion,outputPerMillion:Z.outputPerMillion}}async function Y_($){try{let Z=await fetch("https://models.dev/api.json",{signal:AbortSignal.timeout(1e4)});if(!Z.ok)return null;let J=await Z.json();for(let z of Object.values(J)){if(!z.models)continue;for(let[G,Q]of Object.entries(z.models))if(G===$||G.endsWith(`/${$}`)||$.endsWith(`/${G}`)){let Y=Q?.pricing;if(Y&&typeof Y.input==="number"&&typeof Y.output==="number")return{inputPerMillion:Y.input,outputPerMillion:Y.output}}}return null}catch{return null}}async function r6($){let Z=Q_($);if(Z)return Z;let J=z_($);if(J)return J.price;let z=JP.get($);if(z!==void 0&&Date.now()-z<=Z_)return null;let G=zJ.get($);if(G)return G;let Q=Y_($).then((Y)=>{if(Y)G_($,Y);else JP.set($,Date.now());return Y});zJ.set($,Q);try{return await Q}finally{zJ.delete($)}}function l6($,Z){if(!Z)return null;let J=$.inputTokens/1e6*Z.inputPerMillion+$.outputTokens/1e6*Z.outputPerMillion;return J>0?J:null}function K_($){if($===null)return"--";return $>=0.1?`$${$.toFixed(3)}`:`$${$.toFixed(4)}`}var ZP=604800000,GJ,zJ,Z_=3600000,JP;var y2=C(()=>{L$();l();GJ=new Map,zJ=new Map,JP=new Map});var WP={};M0(WP,{resolveBashTimeout:()=>PP,resetSandboxWarningShown:()=>q_,killActiveProcesses:()=>KJ,executeBash:()=>e3,bashTool:()=>XJ,DEFAULT_BASH_TIMEOUT_MS:()=>XP});import{tool as X_,jsonSchema as P_}from"ai";import{spawn as W_}from"child_process";import H_ from"path";function PP($){if(typeof $==="number"&&Number.isFinite($)&&$>=0)return Math.floor($);let Z=G0().tools?.bashTimeoutMs;if(typeof Z==="number"&&Number.isFinite(Z)&&Z>=0)return Math.floor(Z);return XP}function q_(){YJ=!1}function U_(){if(QJ)return;QJ=!0;let $=()=>{if(n4.size===0){process.removeListener("SIGINT",$),QJ=!1,process.kill(process.pid,"SIGINT");return}for(let Z of[...n4])M_(Z)};process.on("SIGINT",$)}function M_($){if($.killed=!0,$.settled=!0,$.timer)clearTimeout($.timer);PJ($.proc.pid),$.resolve(s3($)+`
|
|
223
224
|
|
|
224
|
-
[Command interrupted by user.]`)}function
|
|
225
|
+
[Command interrupted by user.]`)}function KJ(){for(let $ of n4){if($.killed=!0,$.settled=!0,$.timer)clearTimeout($.timer);PJ($.proc.pid),$.resolve(s3($)+`
|
|
225
226
|
|
|
226
|
-
[Command interrupted by user.]`)}
|
|
227
|
+
[Command interrupted by user.]`)}n4.clear()}async function e3($,Z,J){return U_(),new Promise((z)=>{let G=process.platform==="win32",Q=J?H_.resolve(process.cwd(),J):process.cwd(),Y=K5($,Q,{...process.env,...G?{PYTHONIOENCODING:"utf-8"}:{}});if("error"in Y){z(Y.error);return}let K="";if(Y.warning&&!YJ)YJ=!0,K=`${Y.warning}
|
|
227
228
|
|
|
228
|
-
`;let
|
|
229
|
+
`;let X={proc:void 0,resolve:(q)=>z(K+q),stdoutChunks:[],stderrChunks:[],killed:!1,settled:!1,stdoutTruncated:!1,stderrTruncated:!1};n4.add(X);let P=W_(Y.file,Y.args,{shell:Y.shell,cwd:Y.cwd,stdio:["ignore","pipe","pipe"],detached:process.platform!=="win32",env:Y.env});X.proc=P;let W=(q,U)=>(M)=>{if(q.reduce((N,f)=>N+f.byteLength,0)>=KP){X[U]=!0;return}q.push(M)};P.stdout?.on("data",W(X.stdoutChunks,"stdoutTruncated")),P.stderr?.on("data",W(X.stderrChunks,"stderrTruncated"));let H=PP(Z);if(H>0)X.timer=setTimeout(()=>{X.killed=!0,X.settled=!0,PJ(P.pid),X.resolve(s3(X)+`
|
|
229
230
|
|
|
230
|
-
[Command timed out after ${
|
|
231
|
-
${U||"(no output)"}`)}),P.on("error",(
|
|
231
|
+
[Command timed out after ${H}ms and was killed. Retry with a larger timeout if needed.]`)},H);P.on("close",(q)=>{if(n4.delete(X),X.timer)clearTimeout(X.timer);if(X.killed||X.settled)return;X.settled=!0;let U=s3(X);if(q===0)X.resolve(U||"(no output)");else X.resolve(`Exit code ${q}
|
|
232
|
+
${U||"(no output)"}`)}),P.on("error",(q)=>{if(n4.delete(X),X.timer)clearTimeout(X.timer);if(X.killed||X.settled)return;X.settled=!0,X.resolve(`Error: ${q.message}`)})})}function s3($){let Z=Buffer.concat($.stdoutChunks).toString("utf-8").trim(),J=Buffer.concat($.stderrChunks).toString("utf-8").trim(),z=Z;if(J)z=z?`${z}
|
|
232
233
|
|
|
233
234
|
--- stderr ---
|
|
234
|
-
${
|
|
235
|
+
${J}`:J;if($.stdoutTruncated||$.stderrTruncated)z+=`
|
|
235
236
|
|
|
236
|
-
[Output capped at ${
|
|
237
|
+
[Output capped at ${KP} bytes; the remainder was discarded.]`;if(Buffer.byteLength(z,"utf-8")<=YP)return z;let Q=qZ(z);return`${F_(z,YP)}
|
|
237
238
|
|
|
238
|
-
Full output saved to: ${
|
|
239
|
+
Full output saved to: ${Q}`}function F_($,Z){let J=Buffer.from($,"utf-8"),z=Math.floor(Z*0.5),G=Math.floor(Z*0.1),Q=z;while(Q>0&&(J[Q]&192)===128)Q--;let Y=J.length-G;while(Y<J.length&&(J[Y]&192)===128)Y++;return J.subarray(0,Q).toString("utf-8")+`
|
|
239
240
|
|
|
240
|
-
...(truncated, ${
|
|
241
|
+
...(truncated, ${J.length} bytes total)...
|
|
241
242
|
|
|
242
|
-
`+
|
|
243
|
-
`))),
|
|
244
|
-
`).length,
|
|
243
|
+
`+J.subarray(Math.max(Y,Q)).toString("utf-8")}function PJ($){if(!$)return;try{if(process.platform!=="win32")process.kill(-$,"SIGTERM"),setTimeout(()=>{try{process.kill(-$,"SIGKILL")}catch{}},3000);else process.kill($,"SIGTERM")}catch{}}var KP=204800,YP=1e5,XP=600000,n4,QJ=!1,YJ=!1,XJ;var i6=C(()=>{Z$();I$();u0();l();n4=new Set;XJ=X_({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:P_({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:Z,cwd:J})=>{if(B5()?y8($):!A4()&&L5($)){let G=y8($)?"destructive":"dangerous";if(!await d$(`Execute ${G} command: ${$}`))return"Command rejected by user."}return e3($,Z,J)}})});import{tool as N_,jsonSchema as B_}from"ai";import{createReadStream as HP}from"fs";import{stat as V_,readFile as f_}from"fs/promises";import{createInterface as __}from"readline";import L_ from"path";function A_($,Z,J){return new Promise((z,G)=>{let Q=[],Y=__({input:HP($),crlfDelay:1/0}),K=0;Y.on("line",(X)=>{if(K++,K>=Z&&K<=J)Q.push(X);if(K>J)Y.close()}),Y.on("close",()=>z(Q.join(`
|
|
244
|
+
`))),Y.on("error",G)})}function D_($,Z){return new Promise((J,z)=>{let G=[],Q=0,Y=!1,K=0,X=HP($);X.on("data",(P)=>{let W=typeof P==="string"?Buffer.from(P):P;if(Q+=W.byteLength,Q>Z){let H=W.byteLength-(Q-Z);G.push(W.subarray(0,H)),Y=!0,X.destroy();return}G.push(W)}),X.on("close",()=>{K=Buffer.concat(G).toString("utf-8").split(`
|
|
245
|
+
`).length,J({text:Buffer.concat(G).toString("utf-8"),truncated:Y,totalLines:K})}),X.on("error",z)})}var j_=20971520,$9;var WJ=C(()=>{I$();P4();u0();$9=N_({description:"Read the contents of a file. Returns the file content as text. Use this to understand code, check configurations, etc.",inputSchema:B_({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:Z,endLine:J})=>{let z=j$($,"read");if(z)return`Error: ${z}`;let G=L_.resolve(process.cwd(),$);try{let Q=await V_(G);if(Q.isDirectory())return`Error: ${$} is a directory, not a file`;if(Q.size>j_&&!Z&&!J){let{text:X,truncated:P,totalLines:W}=await D_(G,HZ),H=X;if(P)H+=`
|
|
245
246
|
|
|
246
|
-
...(file too large: ${
|
|
247
|
+
...(file too large: ${Q.size} bytes, ${W}+ lines — use startLine/endLine to read specific ranges)...`;return H}let Y;if(Z!=null||J!=null){let X=Z??1,P=J??Number.MAX_SAFE_INTEGER;if(X<1)return"Error: startLine must be >= 1";if(J!=null&&P<X)return`Error: endLine (${P}) must be >= startLine (${X})`;if(Y=await A_(G,X,P),!Y)return`Error: no lines found in range ${X}-${P}`}else Y=await f_(G,"utf-8");let K=gZ().resolveForFile(G);if(K.length>0)Y+=`
|
|
247
248
|
|
|
248
249
|
<system-reminder>
|
|
249
|
-
`+
|
|
250
|
+
`+K.join(`
|
|
250
251
|
|
|
251
252
|
`)+`
|
|
252
|
-
</system-reminder>`;return
|
|
253
|
-
`),
|
|
254
|
-
`)[0].trim(),U=
|
|
253
|
+
</system-reminder>`;return f0(Y,{direction:"head"}).content}catch(Q){return`Error reading file: ${Q.message}`}}})});import{tool as O_,jsonSchema as C_}from"ai";import{mkdir as b_,writeFile as w_}from"fs/promises";import{existsSync as I_}from"fs";import qP from"path";var UP=10485760,MP;var FP=C(()=>{Z$();u0();L$();MP=O_({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:C_({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:Z,append:J})=>{if(Buffer.byteLength(Z,"utf-8")>UP)return`Error: content exceeds ${UP} bytes. Write in smaller chunks or check the content size.`;let z=j$($,"write");if(z)return`Error: ${z}`;let G=qP.resolve(process.cwd(),$);if(!D4()){let Q=I_(G),Y=J?`Append to file: ${$}`:Q?`Overwrite existing file: ${$}`:`Create new file: ${$}`;if(!await d$(Y))return"Write rejected by user."}try{if(await b_(qP.dirname(G),{recursive:!0}),J)await w_(G,Z,{flag:"a",encoding:"utf-8"});else await a4(G,Z);return`Written ${Buffer.byteLength(Z,"utf-8")} bytes to ${$}${J?" (appended)":""}`}catch(Q){return`Error writing file: ${Q instanceof Error?Q.message:String(Q)}`}}})});import{tool as T_,jsonSchema as R_}from"ai";import{readFile as k_}from"fs/promises";import y_ from"path";var NP;var BP=C(()=>{Z$();u0();L$();NP=T_({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:R_({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:Z,newText:J})=>{if(!Z)return"Error: oldText must not be empty";if(Z===J)return"No change: oldText equals newText";let z=j$($,"write");if(z)return`Error: ${z}`;let G=y_.resolve(process.cwd(),$),Q;try{Q=await k_(G,"utf-8")}catch(W){return`Error: cannot read ${$}: ${W instanceof Error?W.message:String(W)}`}let Y=Q.split(Z).length-1;if(Y===0){let W=Q.split(`
|
|
254
|
+
`),q=Z.split(`
|
|
255
|
+
`)[0].trim(),U=W.findIndex((M)=>M.includes(q));if(U>=0){let M=W.slice(Math.max(0,U-1),U+3).join(`
|
|
255
256
|
`);return`Error: oldText not found exactly. Found similar content near line ${U+1}:
|
|
256
257
|
${M}
|
|
257
258
|
|
|
258
|
-
Make sure whitespace and indentation match exactly.`}return`Error: oldText not found in ${$}. Make sure the text matches exactly including whitespace.`}if(
|
|
259
|
-
replace "${
|
|
260
|
-
with "${
|
|
261
|
-
`).length,P=
|
|
262
|
-
`).length;return`Edited ${$}: replaced ${
|
|
259
|
+
Make sure whitespace and indentation match exactly.`}return`Error: oldText not found in ${$}. Make sure the text matches exactly including whitespace.`}if(Y>1)return`Error: oldText found ${Y} times in ${$}. Please provide more context to make the match unique.`;if(!D4()){let W=(q)=>q.length>80?q.slice(0,80)+"...":q;if(!await d$(`Edit ${$}:
|
|
260
|
+
replace "${W(Z)}"
|
|
261
|
+
with "${W(J)}"`))return"Edit rejected by user."}let K=Q.replace(Z,J);try{await a4(G,K)}catch(W){return`Error: cannot write ${$}: ${W instanceof Error?W.message:String(W)}`}let X=Z.split(`
|
|
262
|
+
`).length,P=J.split(`
|
|
263
|
+
`).length;return`Edited ${$}: replaced ${X} line(s) with ${P} line(s)`}})});import{tool as S_,jsonSchema as E_}from"ai";import{readFileSync as v_,existsSync as _P}from"fs";import{mkdir as x_,readFile as g_,rename as u_,unlink as Z9,writeFile as h_}from"fs/promises";import J9 from"path";function m_($){let Z=[],J=null,z=null,G=null,Q=0,Y=0,K=$.replace(/\r\n/g,`
|
|
263
264
|
`).split(`
|
|
264
|
-
`);for(let
|
|
265
|
-
`)+(
|
|
266
|
-
`:""),original:null});continue}if(!
|
|
267
|
-
`);for(let
|
|
268
|
-
`),original:
|
|
269
|
-
`);if(!
|
|
270
|
-
${z}`))return"Patch rejected by user."}let
|
|
271
|
-
${z}`}})});import{tool as
|
|
265
|
+
`);for(let X of K){if(z===null&&X.startsWith("--- ")){G=X.slice(4);continue}if(z===null&&G!==null&&X.startsWith("+++ ")){let P=X.slice(4);if(J)Z.push(J);J={path:n_(P),isNew:G==="/dev/null",hunks:[]},z=null,G=null;continue}if(z===null&&X.startsWith("@@ ")){let P=X.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(P&&J)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:[]},J.hunks.push(z),Q=z.oldCount,Y=z.newCount;continue}if(z&&J){if(X.startsWith("+"))z.lines.push({type:"add",text:X.slice(1)}),Y--;else if(X.startsWith("-"))z.lines.push({type:"delete",text:X.slice(1)}),Q--;else if(X.startsWith(" "))z.lines.push({type:"context",text:X.slice(1)}),Q--,Y--;if(Q<=0&&Y<=0)z=null}}if(J)Z.push(J);return Z}function n_($){let Z=$.trim();if(Z==="/dev/null")return Z;if(Z.startsWith("a/"))return Z.slice(2);if(Z.startsWith("b/"))return Z.slice(2);return Z}function c_($,Z,J){if(J.length===0)return Math.max(0,Math.min(Z,$.length));for(let z=Math.max(0,Z-VP);z<=Math.min($.length-J.length,Z+VP);z++){let G=!0;for(let Q=0;Q<J.length;Q++)if($[z+Q]!==J[Q]){G=!1;break}if(G)return z}return-1}function fP($,Z){let J=Z.lines.filter((Y)=>Y.type!=="add").map((Y)=>Y.text),z=c_($,Z.oldStart-1,J);if(z===-1)return{error:`第 ${Z.oldStart} 行附近的 hunk 未找到匹配(需要匹配 ${J.length} 行)`};let G=[...$.slice(0,z)],Q=z;for(let Y of Z.lines)if(Y.type==="context")G.push($[Q]),Q++;else if(Y.type==="delete")Q++;else G.push(Y.text);return G.push(...$.slice(Q)),{lines:G}}function p_($,Z=process.cwd()){let J=[];for(let z of $){let G=J9.resolve(Z,z.path),Q=_P(G);if(z.isNew&&!Q){let X=[];for(let P of z.hunks){let W=fP(X,P);if("error"in W)return{ok:!1,error:`${z.path}: ${W.error}`};X.length=0,X.push(...W.lines)}J.push({file:z,content:X.join(`
|
|
266
|
+
`)+(X.length>0?`
|
|
267
|
+
`:""),original:null});continue}if(!Q)return{ok:!1,error:`${z.path}: 文件不存在`};let Y;try{Y=v_(G,"utf-8")}catch(X){return{ok:!1,error:`${z.path}: 读取失败 ${X instanceof Error?X.message:String(X)}`}}let K=Y.split(`
|
|
268
|
+
`);for(let X of z.hunks){let P=fP(K,X);if("error"in P)return{ok:!1,error:`${z.path}: ${P.error}`};K.length=0,K.push(...P.lines)}J.push({file:z,content:K.join(`
|
|
269
|
+
`),original:Y})}return{ok:!0,contents:J}}function HJ($){return $ instanceof Error?$.message:String($)}async function o_($){let Z=process.cwd(),J=[];for(let G of $){let Q=J9.resolve(Z,G.file.path);if(G.original===null){if(_P(Q))return{ok:!1,error:`${G.file.path}: 文件已存在,未应用任何更改`};continue}let Y;try{Y=await g_(Q,"utf-8")}catch(K){return{ok:!1,error:`${G.file.path}: 读取失败 ${HJ(K)}`}}if(Y!==G.original)return{ok:!1,error:`${G.file.path}: 文件在确认期间已被修改,未应用任何更改`}}for(let G of $){let Q=J9.resolve(Z,G.file.path),Y=f8(Q);try{await x_(J9.dirname(Q),{recursive:!0}),await h_(Y,G.content,"utf-8")}catch(K){for(let X of J)await Z9(X.tmp).catch(()=>{});return await Z9(Y).catch(()=>{}),{ok:!1,error:`${G.file.path}: 写入失败 ${HJ(K)}`}}J.push({rel:G.file.path,target:Q,tmp:Y,original:G.original})}let z=[];for(let G of J)try{await u_(G.tmp,G.target),z.push(G)}catch(Q){for(let Y of[...z].reverse())try{if(Y.original!==null)await a4(Y.target,Y.original);else await Z9(Y.target).catch(()=>{})}catch{}for(let Y of J.slice(z.length))await Z9(Y.tmp).catch(()=>{});return{ok:!1,error:`${G.rel}: 写入失败 ${HJ(Q)},已回滚其他文件`}}return{ok:!0}}var VP=3,LP;var jP=C(()=>{Z$();u0();L$();LP=S_({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:E_({type:"object",properties:{diff:{type:"string",description:"The unified diff text to apply"}},required:["diff"]}),execute:async({diff:$})=>{let Z=m_($);if(Z.length===0)return"Error: 无法解析 diff(缺少 ---/+++ 文件头)";for(let Q of Z){let Y=j$(Q.path,"write");if(Y)return`Error: ${Y}`}let J=p_(Z);if(!J.ok)return`Error: ${J.error}`;let z=J.contents.map((Q)=>{let Y=Q.file.hunks.reduce((X,P)=>X+P.lines.filter((W)=>W.type==="delete").length,0),K=Q.file.hunks.reduce((X,P)=>X+P.lines.filter((W)=>W.type==="add").length,0);return` ${Q.file.path} ${Q.file.isNew?"(new)":""} -${Y}/+${K}`}).join(`
|
|
270
|
+
`);if(!D4()){if(!await d$(`Apply patch to ${J.contents.length} file(s)?
|
|
271
|
+
${z}`))return"Patch rejected by user."}let G=await o_(J.contents);if(!G.ok)return`Error: ${G.error}`;return`Applied patch:
|
|
272
|
+
${z}`}})});import{tool as d_,jsonSchema as r_}from"ai";import{glob as l_}from"glob";var z9;var qJ=C(()=>{I$();u0();z9=d_({description:"Find files matching a glob pattern. Returns a list of file paths. Use this to discover project structure and find files.",inputSchema:r_({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:Z})=>{let J=j$(Z??".","read");if(J)return`Error: ${J}`;try{let z=await l_($,{cwd:Z??process.cwd(),ignore:["**/node_modules/**","**/.git/**","**/dist/**","**/build/**"],nodir:!0});if(z.length===0)return"No files found matching pattern";let G;if(z.length>100)G=z.slice(0,100).join(`
|
|
272
273
|
`)+`
|
|
273
274
|
|
|
274
|
-
... (${z.length-100} more files)`;else
|
|
275
|
-
`);return
|
|
276
|
-
`).filter(Boolean).slice(0,
|
|
277
|
-
`);for(let U=0;U<
|
|
278
|
-
`).forEach((
|
|
279
|
-
`):"No matches found";return
|
|
280
|
-
`);if(
|
|
275
|
+
... (${z.length-100} more files)`;else G=z.join(`
|
|
276
|
+
`);return f0(G,{direction:"head"}).content}catch(z){return`Error: ${z.message}`}}})});import{tool as i_,jsonSchema as t_}from"ai";import{readdir as a_,readFile as AP,stat as DP}from"fs/promises";import{spawn as s_}from"child_process";import UJ from"path";function ZL($){let Z=$.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${Z}$`)}function JL($,Z,J,z){let G=["--no-heading","--line-number","-i","-e",$,"--max-count","1","-g","!*.lock","--max-filesize",String(CP)];for(let Q of z)G.push("-g",`!${Q}/**`);if(J){let Q=J.source.replace(/^\^/,"").replace(/\$$/,"").replace(/\\\./g,".").replace(/\.\*/g,"*");G.push("-g",Q)}return G.push(Z),new Promise((Q)=>{let Y=s_("rg",G,{stdio:["ignore","pipe","pipe"]}),K=[],X=0,P=!1,W=(q)=>{if(P)return;P=!0,clearTimeout(H),Q(q)},H=setTimeout(()=>{Y.kill("SIGKILL"),W(null)},15000);Y.stdout.on("data",(q)=>{if(X+=q.byteLength,X>e_){Y.kill("SIGKILL"),W(null);return}K.push(q)}),Y.on("error",()=>W(null)),Y.on("close",(q)=>{if(q===1)W([]);else if(q===0)W(Buffer.concat(K).toString("utf-8").split(`
|
|
277
|
+
`).filter(Boolean).slice(0,G9));else W(null)})})}async function zL($,Z,J,z){let G=[$];await Promise.all(Array.from({length:$L},async()=>{while(G.length>0&&z.length<G9){let Y=G.pop(),K;try{K=await a_(Y,{withFileTypes:!0})}catch{continue}await Promise.all(K.map(async(X)=>{let P=UJ.join(Y,X.name);if(X.isDirectory()){if(!OP.has(X.name)&&z.length<G9)G.push(P);return}if(!X.isFile())return;if(J&&!J.test(X.name))return;try{if((await DP(P)).size>CP)return;let H=await AP(P,"utf-8");if(H.includes("\x00"))return;let q=H.split(`
|
|
278
|
+
`);for(let U=0;U<q.length&&z.length<G9;U++)if(Z.test(q[U]))z.push(`${UJ.relative(process.cwd(),P)}:${U+1}:${q[U]}`)}catch{}}))}}))}var OP,G9=500,CP=5242880,e_=8388608,$L=8,Q9;var MJ=C(()=>{I$();u0();OP=new Set(["node_modules",".git","dist","build",".next",".out","coverage",".min-agent"]);Q9=i_({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:t_({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:Z,include:J})=>{try{let z=new RegExp($),G=J?ZL(J):null,Q=UJ.resolve(process.cwd(),Z??"."),Y=j$(Q,"read");if(Y)return`Error: ${Y}`;let K=[],X=await DP(Q).catch(()=>null);if(!X)return`Error: path not found: ${Z??"."}`;if(X.isFile())try{let W=await AP(Q,"utf-8");if(!W.includes("\x00"))W.split(`
|
|
279
|
+
`).forEach((H,q)=>{if(z.test(H))K.push(`${Q}:${q+1}:${H}`)})}catch{}else{let W=await JL($,Q,G,[...OP]);if(W!==null)K.push(...W);else await zL(Q,z,G,K)}let P=K.length>0?K.join(`
|
|
280
|
+
`):"No matches found";return f0(P,{direction:"head"}).content}catch(z){return`Error: ${z.message}`}}})});import{lookup as GL}from"dns/promises";import{isIP as IP}from"net";function bP($){if($.length!==4||$.some((z)=>Number.isNaN(z)))return!0;let[Z,J]=$;if(Z===0||Z===10||Z===127)return!0;if(Z===169&&J===254)return!0;if(Z===172&&J>=16&&J<=31)return!0;if(Z===192&&J===168)return!0;if(Z===100&&J>=64&&J<=127)return!0;if(Z===198&&(J===18||J===19))return!0;return!1}function QL($){let Z=$.slice(7);if(Z.includes("."))return Z.split(".").map(Number);let J=Z.split(":");if(J.length!==2)return null;let z=parseInt(J[0],16),G=parseInt(J[1],16);if(Number.isNaN(z)||Number.isNaN(G))return null;return[z>>8,z&255,G>>8,G&255]}function wP($){if($.startsWith("::ffff:")){let Z=QL($);if(Z)return bP(Z);return!0}if(IP($)===6){let Z=$.toLowerCase();if(Z==="::1"||Z.startsWith("::"))return!0;if(Z.startsWith("fc")||Z.startsWith("fd"))return!0;if(Z.startsWith("fe8")||Z.startsWith("fe9")||Z.startsWith("fea")||Z.startsWith("feb"))return!0;if(Z.startsWith("2001:db8"))return!0;return!1}return bP($.split(".").map(Number))}async function TP($){let Z;try{Z=new URL($)}catch{return"Invalid URL"}if(Z.protocol!=="http:"&&Z.protocol!=="https:")return"Only http/https URLs are allowed";let J=Z.hostname;if(J==="localhost"||J.endsWith(".localhost")||J.endsWith(".local")||J.endsWith(".internal"))return`Blocked: local hostname "${J}"`;if(IP(J))return wP(J)?`Blocked: private/internal IP "${J}"`:null;try{let z=await GL(J,{all:!0});for(let G of z)if(wP(G.address))return`Blocked: "${J}" resolves to private address "${G.address}"`}catch{}return null}async function t6($,Z){if(!$.body)return{text:"",truncated:!1};let J=$.body.getReader(),z=[],G=0,Q=!1;for(;;){let{done:Y,value:K}=await J.read();if(Y)break;if(G+=K.byteLength,G>Z){z.push(Buffer.from(K.subarray(0,K.byteLength-(G-Z)))),Q=!0,await J.cancel();break}z.push(Buffer.from(K))}return{text:Buffer.concat(z).toString("utf-8"),truncated:Q}}var FJ=()=>{};function a6($){return`Configure a working instance via "${$.configKey}" in ~/.min-agent/config.json or the ${$.envName} env var.`}function NJ($,Z){let J=$.trim();if(J==="")return{ok:!1,error:`${Z} is empty`};let z;try{z=new URL(J)}catch{return{ok:!1,error:`${Z} is not a valid absolute URL: ${J}`}}if(z.protocol!=="http:"&&z.protocol!=="https:")return{ok:!1,error:`${Z} must use http or https, got "${z.protocol}"`};return z.search="",z.hash="",{ok:!0,base:z.toString().replace(/\/+$/,"")}}function Y9($,Z){let J=process.env[$.envName];if(J?.trim())return NJ(J,$.envName);if(Z?.trim())return NJ(Z,`"${$.configKey}" in config.json`);return NJ($.fallback,"the built-in default backend URL")}function H4($){if($ instanceof Error){if($.name==="TimeoutError"||$.name==="AbortError")return"the request timed out";let Z=$.cause,J=typeof Z==="object"&&Z!==null?Z.code:void 0;if(typeof J==="string")return`${$.message} (${J})`;return $.message}return String($)}function WL(){let $=process.env[kP];if($?.trim())return $.trim();let Z=a().serperApiKey;if(Z?.trim())return Z.trim();return XL.trim()}function yP(){return`Set your Serper API key via "serperApiKey" in ~/.min-agent/config.json or the ${kP} env var, or configure a SearXNG instance via "webSearchURL" / MIN_AGENT_SEARXNG_URL.`}function HL($){if(typeof $!=="object"||$===null)return null;let Z=$;if(!_0(Z.link)||Z.link.trim()==="")return null;return{title:_0(Z.title)?Z.title:"",url:Z.link,content:_0(Z.snippet)?Z.snippet:"",engine:BJ(Z.link),score:0,publishedDate:_0(Z.date)?Z.date:"",imgSrc:""}}function qL(){return{...q9(),questions:[]}}function RP($,Z){return(Array.isArray($)?$:[]).map((J)=>{if(typeof J==="object"&&J!==null){let z=J;if(_0(z[Z]))return z[Z]}return""}).filter((J)=>J.trim()!=="")}function UL($){if(typeof $!=="object"||$===null)return qL();let Z=$,J=(Array.isArray(Z.organic)?Z.organic:[]).map(HL).filter((P)=>P!==null),z=[],G=Z.answerBox;if(typeof G==="object"&&G!==null){let P=G;for(let W of["answer","snippet","title"])if(_0(P[W])&&P[W].trim()){z.push(K$(P[W]));break}}let Q=RP(Z.relatedSearches,"query"),Y=RP(Z.peopleAlsoAsk,"question"),K=[],X=Z.knowledgeGraph;if(typeof X==="object"&&X!==null){let P=X,W=_0(P.title)?P.title:"",H=_0(P.description)?P.description:"";if(W||H)K.push({infobox:W,content:H})}return{results:J,answers:z,suggestions:Q,corrections:[],infoboxes:K,unresponsive_engines:[],questions:Y}}async function ML($,Z){return U9(YL,{method:"POST",headers:{"X-API-KEY":Z,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify($),signal:AbortSignal.timeout(KL)},UL)}function FL($){let Z=yP();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 ${s6/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 J=$.backendMessage?` Backend message: ${$.backendMessage}.`:"";if($.status===429)return`Search error: the search API is rate-limiting (HTTP 429).${J} Wait a few seconds before retrying.`;if($.status===401||$.status===403)return`Search error: the search API rejected the API key (HTTP ${$.status}).${J} ${Z}`;if($.status===400||$.status===422)return`Search error: the search API rejected these parameters (HTTP ${$.status}).${J} 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}.${J} It may be temporarily overloaded — retry once.`;return`Search error: HTTP ${$.status} from the search API.${J}`}}}function NL($,Z,J){let z={q:$.query,num:J},G=($.language??"").trim().toLowerCase();if(G)if(X9.test(G)&&G!=="all")z.hl=G.replace("_","-");else Z.push(`ignored invalid language "${$.language}"; use a code like "zh", "en" or "zh-CN"`);let Q=($.time_range??"").trim().toLowerCase();if(Q)if(K9.has(Q))z.tbs=PL[Q];else Z.push(`ignored invalid time_range "${Q}"; valid values: day, week, month, year`);return z}async function SP($,Z,J){let z=WL();if(!z)return`Search error: no Serper API key configured. ${yP()}`;let G=H9($.max_results,J),Q=NL($,J,G),Y=await ML(Q,z);if(Y.kind!=="ok")return FL(Y);let K=Y.data,X=P9(K.results).slice(0,G),P=J.map((H)=>`Note: ${H}`).join(`
|
|
281
|
+
`);if(X.length===0){let H=[`No search results found for "${Z}".`];if(P)H.push(P);if(K.questions.length>0)H.push(`Related questions: ${K.questions.slice(0,5).join(" · ")}`);if(K.suggestions.length>0)H.push(`Related searches: ${K.suggestions.slice(0,8).join(" · ")}`);if(K.questions.length===0&&K.suggestions.length===0)H.push("Try a different query or a broader wording.");return H.join(`
|
|
281
282
|
|
|
282
|
-
`)}let
|
|
283
|
+
`)}let W=[];if(P)W.push(P);for(let H of K.answers)W.push(`Answer: ${K$(H)}`);for(let H of K.infoboxes)W.push(`Infobox${H.infobox?` (${K$(H.infobox)})`:""}: ${S2(K$(H.content),600)}`);if(W.push(`Found ${X.length} result${X.length===1?"":"s"} for "${Z}":`),W.push(W9(X)),K.questions.length>0)W.push(`Related questions: ${K.questions.slice(0,5).join(" · ")}`);if(K.suggestions.length>0)W.push(`Related searches: ${K.suggestions.slice(0,8).join(" · ")}`);return f0(W.join(`
|
|
283
284
|
|
|
284
|
-
`),{direction:"head"}).content}var kP="MIN_AGENT_SERPER_API_KEY",
|
|
285
|
-
`);if(P.length===0){let
|
|
285
|
+
`),{direction:"head"}).content}var kP="MIN_AGENT_SERPER_API_KEY",YL="https://google.serper.dev/search",KL=35000,XL="7913c19ae7a80320771b843ddffa152c9162c9f2",PL;var EP=C(()=>{l();I$();M9();PL={day:"qdr:d",week:"qdr:w",month:"qdr:m",year:"qdr:y"}});function gP(){if(process.env[e6.envName]?.trim())return!0;return!!a().webSearchURL?.trim()}function fL($){if(typeof $!=="object"||$===null)return null;let Z=$;if(!_0(Z.url))return null;return{title:_0(Z.title)?Z.title:"",url:Z.url,content:_0(Z.content)?Z.content:"",engine:_0(Z.engine)?Z.engine:"",score:typeof Z.score==="number"?Z.score:0,publishedDate:_0(Z.publishedDate)?Z.publishedDate:"",imgSrc:_0(Z.img_src)?Z.img_src:_0(Z.thumbnail)?Z.thumbnail:""}}function _L($){if(typeof $!=="object"||$===null)return q9();let Z=$,J=(Array.isArray(Z.results)?Z.results:[]).map(fL).filter((X)=>X!==null),z=(Array.isArray(Z.answers)?Z.answers:[]).map((X)=>{if(_0(X))return X;if(typeof X==="object"&&X!==null){let P=X;if(_0(P.answer))return P.answer;if(_0(P.content))return P.content}return""}).filter((X)=>X!==""),G=Array.isArray(Z.suggestions)?Z.suggestions.filter(_0):[],Q=Array.isArray(Z.corrections)?Z.corrections.filter(_0):[],Y=(Array.isArray(Z.infoboxes)?Z.infoboxes:[]).map((X)=>{if(typeof X!=="object"||X===null)return null;let P=X;return{infobox:_0(P.infobox)?P.infobox:"",content:_0(P.content)?P.content:""}}).filter((X)=>X!==null&&(X.infobox!==""||X.content!=="")),K=(Array.isArray(Z.unresponsive_engines)?Z.unresponsive_engines:[]).map((X)=>{if(!Array.isArray(X)||!_0(X[0]))return null;return[X[0],_0(X[1])?X[1]:""]}).filter((X)=>X!==null);return{results:J,answers:z,suggestions:G,corrections:Q,infoboxes:Y,unresponsive_engines:K}}async function vP($,Z){return U9(`${$}/search?${Z}`,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(BL)},_L)}function xP($){let Z=a6(e6);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. ${Z}`;case"invalid-json":if($.bodyTooLarge)return`Search error: the search backend response exceeded ${s6/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. ${Z}`;case"http":{let J=$.backendMessage?` Backend message: ${$.backendMessage}.`:"";if($.status===429)return`Search error: the search backend is rate-limiting (HTTP 429).${J} Wait a few seconds before retrying, or use a different instance. ${Z}`;if($.status===401||$.status===403)return`Search error: the search backend rejected the request (HTTP ${$.status}).${J} The instance likely requires authentication or has the JSON output format disabled. ${Z}`;if($.status===400||$.status===422)return`Search error: the search backend rejected these parameters (HTTP ${$.status}).${J} 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}.${J} It may be temporarily overloaded — retry once, then try a different instance. ${Z}`;return`Search error: HTTP ${$.status} from the search backend.${J} ${Z}`}}}function LL(){let $=process.env.MIN_AGENT_SEARXNG_FALLBACK_ENGINES;if($!==void 0)return $.trim();let Z=a().webSearchFallbackEngines;if(Z!==void 0)return Z.trim();return VL}function jL($,Z){let J=new URLSearchParams({q:$.query,format:"json",categories:"general"}),z=($.language??"").trim();if(z)if(X9.test(z))J.set("language",z.replace("_","-"));else Z.push(`ignored invalid language "${z}"; use a code like "zh", "en" or "zh-CN"`);let G=($.time_range??"").trim().toLowerCase();if(G)if(K9.has(G))J.set("time_range",G);else Z.push(`ignored invalid time_range "${G}"; valid values: day, week, month, year`);return J}function AL($,Z){let J=$;if(Z&&Z.length>0){let Q=new Set(Z.map((Y)=>Y.toLowerCase()));J=$.filter(([Y])=>Q.has(Y.toLowerCase()))}if(J.length===0)return"";let z=J.map(([Q,Y])=>Y?`${Q} (${Y})`:Q).join(", ");return`${Z?"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 uP($,Z,J){let z=Y9(e6,a().webSearchURL);if(!z.ok)return`Search error: ${z.error}. ${a6(e6)}`;let G=H9($.max_results,J),Q=jL({...$,query:Z},J),Y=await vP(z.base,Q),K=null;if(Y.kind==="ok"&&Y.data.results.length===0){let q=LL();if(q){let U=new URLSearchParams(Q);U.set("engines",q);let M=await vP(z.base,U);if(M.kind==="ok"&&M.data.results.length>0)Y=M,K=q;else if(M.kind!=="ok")J.push(`the fallback engines (${q}) also failed: ${xP(M).replace(/^Search error: /,"")}`)}}if(Y.kind!=="ok")return xP(Y);let X=Y.data,P=P9(X.results).slice(0,G),W=J.map((q)=>`Note: ${q}`).join(`
|
|
286
|
+
`);if(P.length===0){let q=[`No search results found for "${Z}".`];if(W)q.push(W);let U=AL(X.unresponsive_engines,K?K.split(","):null);if(U)q.push(U);if(X.corrections.length>0)q.push(`Did you mean: ${X.corrections.join(", ")}`);if(X.suggestions.length>0)q.push(`Related queries: ${X.suggestions.slice(0,8).join(", ")}`);if(!U&&X.corrections.length===0&&X.suggestions.length===0)q.push("Try a different query or a broader wording.");return q.join(`
|
|
286
287
|
|
|
287
|
-
`)}let
|
|
288
|
+
`)}let H=[];if(W)H.push(W);for(let q of X.answers)H.push(`Answer: ${K$(q)}`);for(let q of X.infoboxes)H.push(`Infobox${q.infobox?` (${K$(q.infobox)})`:""}: ${S2(K$(q.content),600)}`);if(H.push(`Found ${P.length} result${P.length===1?"":"s"} for "${Z}"${K?` via fallback engines ${K}`:""}:`),H.push(W9(P)),X.corrections.length>0)H.push(`Did you mean: ${X.corrections.join(", ")}`);if(X.suggestions.length>0)H.push(`Related queries: ${X.suggestions.slice(0,8).join(", ")}`);return f0(H.join(`
|
|
288
289
|
|
|
289
|
-
`),{direction:"head"}).content}var e6,
|
|
290
|
+
`),{direction:"head"}).content}var e6,BL=20000,VL="google,bing";var VJ=C(()=>{l();I$();M9();e6={envName:"MIN_AGENT_SEARXNG_URL",configKey:"webSearchURL",fallback:"https://searxng.xc.lonae.com"}});import{tool as DL,jsonSchema as OL}from"ai";function _0($){return typeof $==="string"}function K$($){return $.replace(/\s+/g," ").trim()}function S2($,Z){let J=Array.from($);if(J.length<=Z)return $;return J.slice(0,Z-1).join("")+"…"}function BJ($){try{return new URL($).hostname.replace(/^www\./,"")}catch{return $}}function wL($){if(!$)return"";let Z=Date.parse($);if(Number.isNaN(Z))return K$($);return new Date(Z).toISOString().slice(0,10)}function IL($){try{let Z=new URL($),J=Z.hostname.toLowerCase().replace(/^www\./,""),z=Z.pathname.replace(/\/+$/,""),G=[...Z.searchParams].filter(([Y])=>!Y.toLowerCase().startsWith("utm_")&&!bL.has(Y.toLowerCase()));G.sort((Y,K)=>Y[0]<K[0]?-1:Y[0]>K[0]?1:0);let Q=G.map(([Y,K])=>`${Y}=${K}`).join("&");return`${J}${z}${Q?`?${Q}`:""}`}catch{return $.trim().toLowerCase()}}function P9($){let Z=new Set;return $.filter((J)=>{let z=IL(J.url);if(Z.has(z))return!1;return Z.add(z),!0})}function W9($){return $.map((Z,J)=>{let z=[`${J+1}. ${K$(Z.title)||BJ(Z.url)}`,` ${Z.url}`],G=[],Q=wL(Z.publishedDate);if(Q)G.push(Q);if(Z.engine)G.push(Z.engine);if(G.length>0)z.push(` [${G.join(" · ")}]`);let Y=S2(K$(Z.content),CL);if(Y)z.push(` ${Y}`);return z.join(`
|
|
290
291
|
`)}).join(`
|
|
291
292
|
|
|
292
|
-
`)}function
|
|
293
|
+
`)}function H9($,Z){if($===void 0)return F9;let J=Math.floor(Number($));if(!Number.isFinite(J)||J<1)return Z.push(`ignored invalid max_results "${$}"; using ${F9}`),F9;if(J>N9)return Z.push(`max_results capped at ${N9}`),N9;return J}function q9(){return{results:[],answers:[],suggestions:[],corrections:[],infoboxes:[],unresponsive_engines:[]}}function TL($){if(typeof $!=="object"||$===null)return"";let Z=$;for(let J of["error","detail","message"]){let z=Z[J];if(_0(z)&&z.trim())return K$(z);if(typeof z==="object"&&z!==null){let G=z.message;if(_0(G)&&G.trim())return K$(G)}}return""}async function U9($,Z,J){let z;try{z=await fetch($,Z)}catch(P){return{kind:"network",message:H4(P)}}let G,Q;try{let P=await t6(z,s6);G=P.text,Q=P.truncated}catch(P){return{kind:"network",message:H4(P)}}let Y,K=!1;try{Y=JSON.parse(G)}catch{K=!0}let X=K?"":TL(Y);if(!z.ok)return{kind:"http",status:z.status,backendMessage:X};if(K)return{kind:"invalid-json",bodyTooLarge:Q,sample:S2(K$(G),100)};if(Q)return{kind:"invalid-json",bodyTooLarge:!0,sample:""};if(X)return{kind:"http",status:z.status,backendMessage:X};return{kind:"ok",data:J(Y)}}var s6=2097152,F9=10,N9=30,CL=300,K9,X9,bL,hP;var M9=C(()=>{FJ();u0();EP();VJ();VJ();K9=new Set(["day","week","month","year"]),X9=/^(all|[a-z]{2,3}([-_][a-zA-Z]{2,4})?)$/,bL=new Set(["ref","ref_src","referrer","fbclid","gclid","msclkid","igshid","mc_cid","mc_eid","spm","source"]);hP=DL({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:OL({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 ${F9}, max ${N9})`}},required:["query"]}),execute:async($)=>{if(t0().network==="deny")return`Search error: ${m1()}`;let Z=($.query??"").trim();if(!Z)return'Search error: "query" must be a non-empty string.';let J=[];if(gP())return uP($,Z,J);return SP($,Z,J)}})});import{tool as RL,jsonSchema as kL}from"ai";function B9($,Z){let{content:J}=f0($,{direction:"head"});if(!Z)return J;return`${J}
|
|
293
294
|
|
|
294
|
-
...(response body was cut off at ${
|
|
295
|
+
...(response body was cut off at ${fJ/1024/1024} MB)`}function mP($,Z){switch($.kind){case"ok":return`HTTP 200 but the body had almost no readable content (${Z} may require JavaScript)`;case"binary":return`non-text response (${$.contentType})`;case"http":return`HTTP ${$.status}${$.statusText?` ${$.statusText}`:""}`;case"network":return $.message}}function vL($){return/html|xhtml/i.test($)}function xL($){if(!$)return!0;let Z=$.toLowerCase();if(Z.startsWith("text/"))return!0;return/(json|xml|javascript|ecmascript|yaml|csv|graphql|x-www-form-urlencoded|\+json)/.test(Z)}async function gL($,Z){let J;try{J=await fetch($,{method:Z,headers:{"User-Agent":EL,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,application/json;q=0.9,*/*;q=0.8"},signal:AbortSignal.timeout(yL)})}catch(G){return{kind:"network",message:H4(G)}}let z=J.headers.get("content-type")??"";if(!J.ok)return{kind:"http",status:J.status,statusText:J.statusText};if(!xL(z))return{kind:"binary",contentType:z};try{let{text:G,truncated:Q}=await t6(J,fJ);if(G.includes("\x00"))return{kind:"binary",contentType:z||"unknown (binary)"};return{kind:"ok",text:G,bodyTruncated:Q,html:vL(z)||hL(G)}}catch(G){return{kind:"network",message:H4(G)}}}async function uL($){let Z=Y9(cP,a().webFetchURL);if(!Z.ok)return{kind:"unavailable",reason:Z.error};let J;try{J=await fetch(`${Z.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(SL)})}catch(P){return{kind:"unavailable",reason:`could not reach the scrape backend (${H4(P)})`}}let z,G;try{let P=await t6(J,fJ);z=P.text,G=P.truncated}catch(P){return{kind:"unavailable",reason:`could not read the scrape response (${H4(P)})`}}let Q;try{Q=JSON.parse(z)}catch{return{kind:"unavailable",reason:J.ok?"the scrape backend returned a non-JSON response":`HTTP ${J.status} from the scrape backend`}}let Y=typeof Q==="object"&&Q!==null?Q:{};if(!J.ok){let P=typeof Y.error==="string"?Y.error:J.statusText;return{kind:"unavailable",reason:`HTTP ${J.status} from the scrape backend${P?` (${P})`:""}`}}let K=typeof Y.data==="object"&&Y.data!==null?Y.data:{},X=typeof K.markdown==="string"?K.markdown:typeof K.content==="string"?K.content:"";if(!X.trim())return{kind:"unavailable",reason:"the scrape backend returned no content for this URL"};return{kind:"ok",markdown:X,bodyTruncated:G}}function hL($){return/^\s*(<!doctype html|<html\b|<head\b)/i.test($)}function nP($){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 cP,fJ=2097152,yL=8000,SL=35000,EL="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",pP;var oP=C(()=>{I$();FJ();l();u0();cP={envName:"MIN_AGENT_FIRECRAWL_URL",configKey:"webFetchURL",fallback:"https://fireclawl.xc.lonae.com"},pP=RL({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:kL({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:Z})=>{if(t0().network==="deny")return`Error: ${m1()}`;let J=($??"").trim();if(!J)return'Error: "url" must be a non-empty string.';let z=await TP(J);if(z)return`Error: ${z}`;let G=(Z??"GET").trim().toUpperCase()||"GET",Q=await gL(J,G);if(Q.kind==="ok"&&!Q.html&&nP(Q.text))return B9(Q.text,Q.bodyTruncated);if(Q.kind==="binary")return`Error: the response is not text (Content-Type: ${Q.contentType}). Use a different tool to download binary content.`;if(G!=="GET"){if(Q.kind==="ok")return B9(Q.text,Q.bodyTruncated);return`Error: ${mP(Q,J)}`}let Y=await uL(J);if(Y.kind==="ok")return B9(Y.markdown,Y.bodyTruncated);if(Q.kind==="ok"&&nP(Q.text))return[`Note: returning raw HTML — the scrape backend could not convert this page (${Y.reason}).`,B9(Q.text,Q.bodyTruncated)].join(`
|
|
295
296
|
|
|
296
|
-
`);return[`Failed to fetch content from ${
|
|
297
|
-
`)}})});import{tool as
|
|
297
|
+
`);return[`Failed to fetch content from ${J}.`,`Direct request: ${mP(Q,J)}`,`Scrape backend: ${Y.reason}`,a6(cP)].join(`
|
|
298
|
+
`)}})});import{tool as mL,jsonSchema as nL}from"ai";var dP;var rP=C(()=>{Z$();e2();dP=mL({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.
|
|
298
299
|
|
|
299
300
|
Use this when:
|
|
300
301
|
- The task is ambiguous and you need more information
|
|
@@ -302,29 +303,29 @@ Use this when:
|
|
|
302
303
|
- You need confirmation before a potentially destructive action
|
|
303
304
|
- You're unsure about a requirement or preference
|
|
304
305
|
|
|
305
|
-
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:
|
|
306
|
-
`)}`}})});import{tool as
|
|
307
|
-
`)){if(!
|
|
306
|
+
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:nL({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:Z,multiple:J})=>{let z=p1($);if(!z.trim())return"Error: question is required.";let G=d1(o1(Z)),Q=await _5(z,G.length>0?G:void 0,Boolean(J));if(Q===null)return"User cancelled the question";let Y=uz(Q);if(Y.length===0)return"User cancelled the question";if(G.length>0)return hz(Y);return`User answered: ${Y.join(`
|
|
307
|
+
`)}`}})});import{tool as cL,jsonSchema as pL}from"ai";async function dL($,Z){let J=JSON.stringify({jsonrpc:"2.0",id:1,method:"tools/call",params:{name:"get_code_context_exa",arguments:{query:$,tokensNum:Z}}}),z=await fetch(oL,{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:J,signal:AbortSignal.timeout(30000)});if(!z.ok)throw Error(`Exa API returned ${z.status}`);return await rL(await z.text())}async function rL($){for(let Z of $.split(`
|
|
308
|
+
`)){if(!Z.startsWith("data: "))continue;try{let z=JSON.parse(Z.slice(6))?.result?.content?.[0]?.text;if(z)return z}catch{}}try{let J=JSON.parse($)?.result?.content?.[0]?.text;if(J)return J}catch{}return null}var oL="https://mcp.exa.ai/mcp",lP;var iP=C(()=>{I$();u0();lP=cL({description:`Search and get relevant context for any programming task using Exa Code API.
|
|
308
309
|
Provides high-quality, fresh context for libraries, SDKs, and APIs.
|
|
309
310
|
Use this for ANY question or task related to programming — finding code examples, documentation, API references, and patterns.
|
|
310
311
|
|
|
311
312
|
Usage:
|
|
312
313
|
- Adjustable token count (1000-50000) for focused or comprehensive results
|
|
313
314
|
- Default 5000 tokens for balanced context
|
|
314
|
-
- Examples: 'React useState hook examples', 'Python pandas dataframe filtering', 'Express.js middleware', 'Rust async trait implementation'`,inputSchema:
|
|
315
|
-
`)}}function p4($,
|
|
316
|
-
`)}var $
|
|
317
|
-
${
|
|
315
|
+
- Examples: 'React useState hook examples', 'Python pandas dataframe filtering', 'Express.js middleware', 'Rust async trait implementation'`,inputSchema:pL({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:Z})=>{if(t0().network==="deny")return`Code search error: ${m1()}`;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 J=Math.max(1000,Math.min(50000,Z??5000));try{let z=await dL($,J);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 f0(z,{direction:"head"}).content}catch(z){return`Code search error: ${z instanceof Error?z.message:String(z)}`}}})});function V9(){let $={bash:XJ,read:$9,write:MP,edit:NP,apply_patch:LP,glob:z9,grep:Q9,search_web:hP,web_fetch:pP,question:dP};if(process.env.EXA_API_KEY)$.codesearch=lP;return $}var _J=C(()=>{i6();WJ();FP();BP();jP();qJ();MJ();M9();oP();rP();iP()});import{execSync as lL}from"child_process";import{existsSync as f9,readFileSync as iL,readdirSync as tL,statSync as aL}from"fs";import c4 from"path";function u1(){let $=process.cwd(),Z=f9(c4.join($,".git")),J;if(Z)try{J=lL("git branch --show-current",{encoding:"utf-8",cwd:$,timeout:5000}).trim()}catch{}let z=[],G=[],Q=[],Y=[{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:""}],K,X;for(let H of Y)if(f9(c4.join($,H.file))){if(G.push(H.file),H.lang&&!z.includes(H.lang))z.push(H.lang);if(H.pm&&!K)K=H.pm}if(f9(c4.join($,"package.json")))try{let H=JSON.parse(iL(c4.join($,"package.json"),"utf-8")),q={...H.dependencies,...H.devDependencies};if(q.next)X="Next.js";else if(q.nuxt)X="Nuxt";else if(q["@angular/core"])X="Angular";else if(q.vue)X="Vue";else if(q.react)X="React";else if(q.svelte)X="Svelte";else if(q.express)X="Express";else if(q.fastify)X="Fastify";else if(q.hono)X="Hono";else if(q.effect)X="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 H of P)if(f9(c4.join($,H)))Q.push(H);let W=[];if(W.push(`Directory: ${$}`),Z)W.push(`Git: yes (branch: ${J??"unknown"})`);if(z.length)W.push(`Languages: ${z.join(", ")}`);if(X)W.push(`Framework: ${X}`);if(K)W.push(`Package manager: ${K}`);if(G.length)W.push(`Config files: ${G.join(", ")}`);if(Q.length)W.push(`Entry points: ${Q.join(", ")}`);try{let H=tL($).filter((q)=>!q.startsWith(".")||q===".env.example").filter((q)=>q!=="node_modules"&&q!==".git").slice(0,30).map((q)=>{return aL(c4.join($,q)).isDirectory()?`${q}/`:q});W.push(`Structure: ${H.join(", ")}`)}catch{}return{directory:$,isGitRepo:Z,branch:J,languages:z,framework:X,packageManager:K,entryFiles:Q,configFiles:G,summary:W.join(`
|
|
316
|
+
`)}}function p4($,Z){let J=["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(Z.length>0)J.push("","# User Instructions",""),J.push(...Z);return J.join(`
|
|
317
|
+
`)}var $8=()=>{};import{tool as sL,jsonSchema as eL}from"ai";import{existsSync as tP,readdirSync as aP,statSync as $j}from"fs";import{pathToFileURL as Zj}from"url";import E2 from"path";function zj($){if($.readOnly===!0)return!1;if($.dangerous===!1)return!1;return!0}function sP(){return _9}function Gj($){return $.map((Z)=>{if(!tP(Z))return`${Z}:missing`;let J=aP(Z).filter((G)=>G.endsWith(".ts")||G.endsWith(".js")||G.endsWith(".mjs")).sort(),z=J.map((G)=>$j(E2.join(Z,G)).mtimeMs).join(",");return`${Z}:${J.join(",")}:${z}`}).join("|")}async function L9($){let Z=$??Jj,J=Gj(Z);if(Z8&&Z8.signature===J)return _9=Z8.readOnlyIds,Z8.tools;let z=await Qj(Z);return Z8={signature:J,tools:z,readOnlyIds:_9},z}async function Qj($){let Z={},J=new Set;for(let G of $){if(!tP(G))continue;let Q=aP(G).filter((Y)=>Y.endsWith(".ts")||Y.endsWith(".js")||Y.endsWith(".mjs"));for(let Y of Q){let K=E2.join(G,Y),X=E2.basename(Y,E2.extname(Y));try{let P=await import(Zj(K).href);for(let[W,H]of Object.entries(P)){if(!Xj(H))continue;let q=W==="default"?X:`${X}_${W}`;if(Z[q]){console.warn(`\x1B[33m ⚠ Plugin tool "${q}" from ${K} conflicts with an existing tool; skipping\x1B[0m`);continue}let U={},M=[];for(let[F,N]of Object.entries(H.parameters)){let f=Kj(N.type);U[F]={type:f,...N.description?{description:N.description}:{}},M.push(F)}if(H.readOnly===!0)J.add(q);Z[q]=sL({description:H.description,inputSchema:eL({type:"object",properties:U,required:M}),execute:async(F)=>{if(zj(H)&&!A4()){let N=Yj(F);if(!await d$(`运行自定义工具 ${q}${N?`
|
|
318
|
+
${N}`:""}`))return"自定义工具已被拒绝。"}try{let N=await H.execute(F);return typeof N==="string"?N:JSON.stringify(N)??"undefined"}catch(N){return`Plugin error: ${String(N instanceof Error?N.message:N)}`}}})}}catch(P){console.error(`\x1B[90m Plugin "${Y}" failed to load: ${String(P instanceof Error?P.message:P)}\x1B[0m`)}}}_9=J;let z=Object.keys(Z).length;if(z>0)console.log(`\x1B[90m Plugins loaded: ${z} tool(s)\x1B[0m`);return Z}function Yj($){try{let Z=JSON.stringify($);if(!Z||Z==="{}")return"";return Z.length>400?`${Z.slice(0,400)}…`:Z}catch{return""}}function Kj($){if($==="number"||$==="boolean"||$==="object"||$==="array")return $;return"string"}function Xj($){if(!$||typeof $!=="object")return!1;let Z=$;return typeof Z.description==="string"&&typeof Z.parameters==="object"&&typeof Z.execute==="function"}var Jj,Z8=null,_9;var LJ=C(()=>{l();Z$();Jj=[E2.join(process.cwd(),".min-agent","tools"),E2.join(P0(),"tools")],_9=new Set});var JW={};M0(JW,{identityPayload:()=>$W,extractSources:()=>ZW,WEB_RESEARCH_TOOLS:()=>v2,STEER_PROMPT:()=>AJ,RESEARCH_TOTAL_CAP:()=>Uj,RESEARCH_STUB_RESULT:()=>A9,RESEARCH_STOP_AFTER:()=>qj,RESEARCH_STEER_AFTER:()=>Hj,REPEAT_TOTAL_THRESHOLD:()=>Wj,LOOP_HALT_MESSAGE:()=>D9,EXACT_LOOP_THRESHOLD:()=>Pj,DoomLoopDetector:()=>x2,DELIVER_PROMPT:()=>j9});function jJ($,Z){if(typeof $!=="number"||!Number.isFinite($)||$<1)return Z;return Math.floor($)}function J8($){try{if($===null||typeof $!=="object")return JSON.stringify($);if(Array.isArray($))return JSON.stringify($.map(J8));let Z={};for(let J of Object.keys($).sort())Z[J]=J8($[J]);return JSON.stringify(Z)}catch{return String($)}}function Fj($){if($&&typeof $==="object"&&!Array.isArray($))return $;return null}function Nj($){if(typeof $!=="string")return"";return $.toLowerCase().replace(/\s+/g," ").trim()}function Bj($){try{return new URL($.trim()).hostname.toLowerCase().replace(/^www\./,"")}catch{return""}}function eP($){if(typeof $!=="string")return"";try{let Z=new URL($.trim()),J=Z.hostname.toLowerCase().replace(/^www\./,""),z=Z.pathname.replace(/\/+$/,"");return`${Z.protocol}//${J}${z}${Z.search}`}catch{return $.trim().toLowerCase()}}function $W($,Z){let J=Fj(Z);if($==="search_web"&&J)return J8({query:Nj(J.query)});if($==="web_fetch"&&J)return J8({url:eP(J.url)});return J8(Z)}function ZW($){let Z=new Set,J=new Set;for(let z of $.match(Vj)??[]){let G=eP(z);if(G)Z.add(G);let Q=Bj(z);if(Q)J.add(Q)}return{urls:[...Z],hosts:[...J]}}class x2{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=jJ($?.steerAfter,3),this.stopAfter=Math.max(jJ($?.stopAfter,5),this.steerAfter+1),this.totalCap=jJ($?.totalCap,24)}get webResearchCount(){return this.webTotal}get researchCapped(){return this.capped}get producedArtifact(){return this.delivered}get unproductiveStreak(){return this.unproductiveRounds}record($,Z){return this.observe($,Z)==="halt"}observe($,Z){let J=`${$}\x00${$W($,Z)}`;if(this.lastCall.key===J)this.lastCall.count++;else this.lastCall={key:J,count:1};let z=(this.callCounts.get(J)??0)+1;if(this.callCounts.set(J,z),this.lastCall.count>=3||z>=5)return this.lastCall={key:"",count:0},this.callCounts.delete(J),"halt";if(v2.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(Mj.has($))this.delivered=!0,this.unproductiveRounds=0;return"ok"}observeResult($,Z){if(!v2.has($))return"ok";let J=typeof Z==="string"?Z:_j(Z);if(!fj.test(J.trim())){let{urls:z,hosts:G}=ZW(J),Q=0;for(let Y of z)if(!this.seenUrls.has(Y))this.seenUrls.add(Y),Q++;for(let Y of G)if(!this.seenHosts.has(Y))this.seenHosts.add(Y),Q++;if(Q>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(`
|
|
318
319
|
`);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(`
|
|
319
|
-
`)}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
|
|
320
|
-
`||$==="\r"}function
|
|
321
|
-
`,1)[0]??"");if(
|
|
322
|
-
`).length} lines)`,z);return
|
|
323
|
-
`).length;if(
|
|
324
|
-
${
|
|
325
|
-
`),
|
|
326
|
-
${
|
|
327
|
-
`)}function
|
|
320
|
+
`)}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 _j($){try{return JSON.stringify($)??String($)}catch{return String($)}}var Pj=3,Wj=5,Hj=3,qj=5,Uj=24,v2,Mj,AJ="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.",j9="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.",A9="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.",D9="同一操作连续重复了多次,已停止以免空转。发送消息可继续。",Vj,fj;var O9=C(()=>{v2=new Set(["search_web","web_fetch"]),Mj=new Set(["write","edit","apply_patch"]);Vj=/https?:\/\/[^\s"'<>)\]}]+/g,fj=/^(error|search error|fetch error)\b/i});function zW($){return $.toLowerCase()}function Lj($){let Z=zW($),J=null;for(let z of DJ){let G=Z.indexOf(z.open);if(G>=0&&(!J||G<J.index))J={index:G,tag:z}}return J}class OJ{buf="";feed($){return this.buf+=$,this.drain(!1)}flush(){return this.drain(!0)}drain($){let Z="",J="",z=!1;while(this.buf.length>0){let G=Lj(this.buf);if(!G){if($)Z+=this.buf,this.buf="";else{let P=jj(this.buf);if(P>=0)Z+=this.buf.slice(0,P),this.buf=this.buf.slice(P);else Z+=this.buf,this.buf=""}break}if(G.index>0){let P=this.buf.slice(0,G.index);if(P=P.replace(/\n+$/,""),P)Z+=P;this.buf=this.buf.slice(G.index)}let Q=zW(this.buf),Y=G.tag.open.length,K=Q.indexOf(G.tag.close,Y);if(K<0){if($)J+=this.buf.slice(Y),this.buf="";else if(this.buf.length-Y>16384)J+=this.buf.slice(Y),this.buf="",z=!0;break}let X=this.buf.slice(Y,K);J+=X,z=!0,this.buf=this.buf.slice(K+G.tag.close.length)}if(z)Z=Z.replace(/^\n+/,"");return{display:Z,thinking:J}}}function jj($){let Z=Math.max(0,$.length-72),z=$.slice(Z).lastIndexOf("<");if(z<0)return-1;let G=Z+z,Q=$.slice(G).toLowerCase();if(Q.length>64)return-1;for(let Y of DJ)if(Y.open.startsWith(Q))return G;return-1}function U4($){let Z=$;for(let{open:J,close:z}of DJ){let G=new RegExp(J.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"[\\s\\S]*?"+z.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi");Z=Z.replace(G,"")}return Z}var q4,DJ;var C9=C(()=>{q4=String.fromCharCode(96),DJ=[{open:"<think>",close:"</think>"},{open:"<thinking>",close:"</thinking>"},{open:`<${q4}think${q4}>`,close:`<${q4}/think${q4}>`},{open:`<${q4}redacted_thinking${q4}>`,close:`<${q4}/redacted_thinking${q4}>`}]});function Aj($){return $.replace(/\s+/g," ").trim()}function YW($){return $===void 0||$===">"||$==="/"||$===" "||$==="\t"||$===`
|
|
321
|
+
`||$==="\r"}function Dj($){let Z=$.toLowerCase(),J=0;while(J<Z.length){let z=Z.indexOf("<web_search",J);if(z<0)return null;if(!YW(Z[z+11])){J=z+1;continue}let G=$.indexOf(">",z);if(G<0)return null;return{index:z,openLen:G-z+1,raw:$.slice(z,G+1)}}return null}function Oj($,Z){let J=$.toLowerCase(),z=Z;while(z<J.length){let G=J.indexOf("</web_search",z);if(G<0)return null;if(!YW(J[G+12])){z=G+1;continue}let Q=$.indexOf(">",G);if(Q<0)return null;return{innerEnd:G,tagEnd:Q+1}}return null}function GW($){return(/\bquery\s*=\s*"([^"]*)"/i.exec($)??/\bquery\s*=\s*'([^']*)'/i.exec($))?.[1]?.trim()??""}function QW($,Z=""){let J=$.trim();if(!J){let Q=Z.trim();return Q?{kind:"invoke",query:Q}:{kind:"results",query:"",body:""}}let z=Cj.exec(J);if(z)return{kind:"results",query:z[1].trim()||Z,body:J};if(/^\d+\.\s+Title\s*:/m.test(J)&&/\bURL\s*:/m.test(J))return{kind:"results",query:Z,body:J};let G=Aj(J)||Z;if(G&&G.length<=500&&!/\bURL\s*:\s*https?:\/\//i.test(J))return{kind:"invoke",query:G};return{kind:"results",query:Z||G,body:J}}function bj($){let Z=Math.max(0,$.length-80),z=$.slice(Z).lastIndexOf("<");if(z<0)return-1;let G=Z+z,Q=$.slice(G).toLowerCase();if(Q.length>72)return-1;if("<web_search".startsWith(Q)||"</web_search".startsWith(Q))return G;if(Q.startsWith("<web_search")&&!Q.includes(">"))return G;if(Q.startsWith("</web_search")&&!Q.includes(">"))return G;return-1}class b9{buf="";feed($){return this.buf+=$,this.drain(!1)}flush(){return this.drain(!0)}drain($){let Z=[],J=!1,z=(G)=>{if(!G)return;let Q=Z[Z.length-1];if(Q?.type==="display")Q.text+=G;else Z.push({type:"display",text:G})};while(this.buf.length>0){let G=Dj(this.buf);if(!G){if($)z(this.buf),this.buf="";else{let K=bj(this.buf);if(K>=0)z(this.buf.slice(0,K)),this.buf=this.buf.slice(K);else z(this.buf),this.buf=""}break}if(G.index>0){let K=this.buf.slice(0,G.index);if(K=K.replace(/\n+$/,""),K)z(K);this.buf=this.buf.slice(G.index)}let Q=Oj(this.buf,G.openLen);if(!Q){let K=this.buf.length-G.openLen;if($||K>65536){let X=this.buf.slice(G.openLen);Z.push({type:"search",block:QW(X,GW(G.raw))}),J=!0,this.buf=""}break}let Y=this.buf.slice(G.openLen,Q.innerEnd);Z.push({type:"search",block:QW(Y,GW(G.raw))}),J=!0,this.buf=this.buf.slice(Q.tagEnd).replace(/^\n+/,"")}if(J){let G=Z[0];if(G?.type==="display")G.text=G.text.replace(/^\n+/,"")}return Z.filter((G)=>G.type==="search"||G.text.length>0)}}function CJ($){let Z=new b9,J=[...Z.feed($),...Z.flush()],z="",G=[];for(let Q of J)if(Q.type==="display")z+=Q.text;else G.push(Q.block);return{display:z,blocks:G,slices:J}}function f1($){let{slices:Z}=CJ($);if(Z.every((J)=>J.type==="display"))return $;return Z.map((J)=>{if(J.type==="display")return J.text;return J.block.kind==="results"?J.block.body:J.block.query}).join("").replace(/^\n+/,"").replace(/\n+$/,"")}var Cj;var z8=C(()=>{Cj=/^Search results for\s+"([^"]*)"\s*:/im});var wJ={};M0(wJ,{truncateDisplay:()=>_1,toolResultText:()=>g2,summarizeToolResult:()=>w9,summarizeToolCall:()=>G8,formatToolArgs:()=>PW});function _1($,Z){let J=Array.from($);if(J.length<=Z)return $;return J.slice(0,Math.max(1,Z-1)).join("")+"…"}function bJ($){return $.replace(/\s+/g," ").trim()}function XW($){return typeof $==="object"&&$!==null&&!Array.isArray($)?$:null}function v0($,Z){let J=$[Z];return typeof J==="string"?bJ(J):""}function KW($){let Z=$.split("/").filter(Boolean);return Z.length<=2?$:`…/${Z.slice(-2).join("/")}`}function PW($,Z=60){let J=XW($);if(!J)return"";let z=[];for(let[G,Q]of Object.entries(J)){if(Q===void 0||Q===null)continue;let Y=typeof Q==="string"?bJ(Q):JSON.stringify(Q);if(Y===void 0)continue;z.push(`${G}=${_1(Y,Z)}`)}return z.join(" ")}function G8($,Z,J=120){let z=XW(Z);if(!z)return"";let G=wj($,z);return _1(G||PW(z,60),J)}function wj($,Z){switch($){case"search_web":{let J=v0(Z,"query");if(!J)return"";let z=[],G=v0(Z,"categories");if(G&&G!=="general")z.push(G);let Q=v0(Z,"language");if(Q)z.push(Q);let Y=v0(Z,"time_range");if(Y)z.push(`past ${Y}`);let K=v0(Z,"engines");if(K)z.push(`via ${K}`);return`"${J}"${z.length>0?` (${z.join(", ")})`:""}`}case"web_fetch":{let J=v0(Z,"url"),z=v0(Z,"method");return J?`${z&&z.toUpperCase()!=="GET"?`${z.toUpperCase()} `:""}${J}`:""}case"read":{let J=v0(Z,"filePath");if(!J)return"";let{startLine:z,endLine:G}=Z,Q=typeof z==="number"||typeof G==="number"?`:${z??1}-${G??""}`:"";return`${KW(J)}${Q}`}case"write":case"edit":case"apply_patch":{let J=v0(Z,"filePath")||v0(Z,"path");return J?KW(J):""}case"bash":return v0(Z,"command");case"grep":{let J=v0(Z,"pattern");if(!J)return"";let z=v0(Z,"path"),G=v0(Z,"include"),Q=[z,G].filter(Boolean).join(" ");return`${J}${Q?` in ${Q}`:""}`}case"glob":return v0(Z,"pattern");case"todo":{let J=Z.todos;return Array.isArray(J)?`${J.length} item${J.length===1?"":"s"}`:""}case"skill":return v0(Z,"name");case"question":return v0(Z,"question");case"task":return v0(Z,"description");case"explore":case"codesearch":return v0(Z,"query");default:return""}}function g2($){if(typeof $==="string")return $;if($===void 0||$===null)return"";try{return JSON.stringify($,null,2)}catch{return String($)}}function w9($,Z,J=!1,z=100){let G=g2(Z).trim();if(G==="")return J?"error":"(empty)";let Q=bJ(G.split(`
|
|
322
|
+
`,1)[0]??"");if(J||/^(error|search error)\b/i.test(Q))return _1(Q.replace(/^Error:\s*/i,""),z);if($==="search_web"){let K=/^Found (\d+) results? for /m.exec(G);if(K)return`${K[1]} results`;if(/^No search results found/m.test(G))return"no results";let X=G.match(/^\d+\.\s+Title\s*:/gm);if(X&&X.length>0)return`${X.length} results`;if(/^Search results for /m.test(G))return"results"}if($==="skill"){let K=/^<skill_content name="([^"]*)"/m.exec(G);if(K)return _1(`loaded ${K[1]} (${G.split(`
|
|
323
|
+
`).length} lines)`,z);return _1(Q,z)}let Y=G.split(`
|
|
324
|
+
`).length;if(Y===1)return _1(Q,z);return _1(`${Q} (${Y} lines)`,z)}function HW($){let Z=$??s(a())?.defaultModel??"unknown";console.log(`${x0.bold}\uD83E\uDD16 min-agent${x0.reset} ${x0.dim}(${Z})${x0.reset}`)}function I9(){console.log(`${x0.dim}${"─".repeat(60)}${x0.reset}`)}function IJ($,Z){let J=G8($,Z,160);console.log(`
|
|
325
|
+
${x0.yellow}⚡ ${$}${x0.reset} ${x0.dim}${J}${x0.reset}`)}function Q8($,Z,J=!1){let z=g2(Z).replace(/\s+$/,""),G=z===""?[]:z.split(`
|
|
326
|
+
`),Q=[],Y=0;for(let H of G){if(Q.length>=Ij)break;if(Y+H.length>WW)break;Q.push(H),Y+=H.length+1}if(Q.length===0&&G.length>0)Q.push(_1(G[0],WW));let K=G.length-Q.length,X=K>0?` (${K} more line${K===1?"":"s"})`:"",P=J?`${x0.red} ✗${x0.reset}`:`${x0.green} ✓${x0.reset}`,W=Q.join(`
|
|
327
|
+
${x0.dim} `);console.log(`${P} ${x0.dim}${W}${X}${x0.reset}
|
|
328
|
+
`)}function qW($,Z,J,z){let G=Z?.inputTokens??0,Q=Z?.outputTokens??0,Y=G+Q,K=z!==void 0?z:G,X="";if(K>0&&J&&J>0){let P=Math.round(K/J*100);X=` | Context: ${Tj(P)} ${P}%`}console.log(`${x0.dim}Done in ${$} step(s) | Tokens: ${G} in / ${Q} out / ${Y} total${X}${x0.reset}`)}function Tj($){let J=Math.max(0,Math.min(100,$)),z=Math.round(J/100*10),G=10-z;return`${$>=80?"\x1B[31m":$>=50?"\x1B[33m":"\x1B[32m"}${"█".repeat(z)}${"░".repeat(G)}\x1B[0m\x1B[90m`}var x0,Ij=20,WW=1200;var UW=C(()=>{l();x0={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 RJ={};M0(RJ,{createSaveThrottle:()=>TJ});function TJ($,Z=2000,J=Date.now){let z=0,G,Q=!1,Y=()=>{G=void 0,Q=!1,z=J();try{$()}catch{}};return{request(){if(G){Q=!0;return}let K=J()-z;if(K>=Z){Y();return}Q=!0,G=setTimeout(Y,Z-K)},flush(){if(G)clearTimeout(G),G=void 0;if(Q)Y()},cancel(){if(G)clearTimeout(G);G=void 0,Q=!1}}}var _W={};M0(_W,{readOnlyBashTool:()=>fW,isReadOnlyCommand:()=>VW,createExploreTool:()=>Ej});import{tool as FW,jsonSchema as NW,streamText as Rj,stepCountIs as kj}from"ai";function yj(){return`You are a file search specialist. You excel at thoroughly navigating and exploring codebases.
|
|
328
329
|
|
|
329
330
|
Your strengths:
|
|
330
331
|
- Rapidly finding files using glob patterns
|
|
@@ -344,7 +345,7 @@ Guidelines:
|
|
|
344
345
|
Complete the search request efficiently and report findings clearly.
|
|
345
346
|
|
|
346
347
|
Working directory: ${process.cwd()}
|
|
347
|
-
Platform: ${process.platform}`}function
|
|
348
|
+
Platform: ${process.platform}`}function Sj($){let Z=G0().agent?.exploreMaxSteps,J=$??Z??MW;return Number.isFinite(J)&&J>=1?Math.floor(J):MW}function Ej($,Z,J,z={}){return FW({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.
|
|
348
349
|
|
|
349
350
|
Specify thoroughness:
|
|
350
351
|
- "quick": basic search, 1-3 tool calls
|
|
@@ -354,14 +355,14 @@ Specify thoroughness:
|
|
|
354
355
|
Examples:
|
|
355
356
|
- "Find all API route handlers" (medium)
|
|
356
357
|
- "How does the auth system work?" (thorough)
|
|
357
|
-
- "Where is the database config?" (quick)`,inputSchema:
|
|
358
|
-
${
|
|
359
|
-
${
|
|
360
|
-
${
|
|
358
|
+
- "Where is the database config?" (quick)`,inputSchema:NW({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:G,thoroughness:Q})=>{let Y=Q??"medium";console.error(`\x1B[90m ┌─ Explore (${Y}): ${G.slice(0,60)}\x1B[0m`);try{let K=await vj(G,Y,$,Z,z);if(K.usage)J?.(K.usage);return console.error("\x1B[90m └─ ✓ Done\x1B[0m"),f0(K.text,{direction:"tail"}).content}catch(K){if(Z?.aborted)return"Explore cancelled by user.";return Q0("error",`explore agent failed: ${K?.message??String(K)}`),console.error(`\x1B[90m └─ ✗ Failed: ${K.message}\x1B[0m`),`Explore error: ${K.message}`}}})}async function vj($,Z,J,z,G={}){let Q=s$(J),Y={glob:z9,grep:Q9,read:$9,bash:fW},X=[{role:"user",content:`Thoroughness level: ${Z}
|
|
359
|
+
${Z==="quick"?"Do a quick search (1-3 tool calls max).":""}
|
|
360
|
+
${Z==="medium"?"Do a moderate exploration, follow references if needed.":""}
|
|
361
|
+
${Z==="thorough"?"Do a comprehensive analysis. Check multiple locations, naming conventions, and cross-references.":""}
|
|
361
362
|
|
|
362
|
-
Task: ${$}`}],P=new AbortController,
|
|
363
|
+
Task: ${$}`}],P=new AbortController,W=z?AbortSignal.any([z,P.signal]):P.signal,H=Rj({model:Q,system:yj(),messages:X,allowSystemInMessages:!0,tools:Y,stopWhen:kj(Sj(G.maxSteps)),maxRetries:2,abortSignal:W,onError({error:M}){Q0("warn",`explore step failed (will retry): ${String(M)}`)}}),q="";for await(let M of H.fullStream)switch(M.type){case"text-delta":q+=M.text;break;case"tool-call":if(console.error(`\x1B[90m │ ⚡ ${M.toolName}\x1B[0m`),G.shouldStop?.())return Q0("warn","explore agent stopped: parent budget reached"),P.abort(),{text:f1(U4(q))+`
|
|
363
364
|
|
|
364
|
-
[Explore stopped: run budget reached]`};break;case"error":return
|
|
365
|
+
[Explore stopped: run budget reached]`};break;case"error":return Q0("error",`explore stream error: ${String(M.error)}`),P.abort(),{text:f1(U4(q))||`[Explore error: ${M.error}]`}}let U;try{U=await H.usage}catch{}return{text:f1(U4(q))||"(explore agent produced no output)",usage:U}}function VW($){let Z=$.trim();if(!Z)return!1;if(/[<>|]|&&|;|`|\$\(/.test(Z))return!1;let J=Z.split(/\s+/),z=J[0].toLowerCase();if(!BW.has(z))return!1;if(z==="git"){let G=J[1]?.toLowerCase();if(!G||!xj.has(G))return!1}if(z==="find"&&/\s-(delete|exec|ok|execdir)\b/.test(Z))return!1;if((z==="sed"||z==="awk"||z==="perl")&&/\s-i(\.[a-zA-Z0-9_-]+)?\b/.test(Z))return!1;return!0}var MW=20,BW,xj,fW;var LW=C(()=>{h4();i6();WJ();qJ();MJ();C9();z8();I$();v4();l();BW=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"]),xj=new Set(["status","log","diff","show","rev-parse","branch","remote","tag","ls-files","help","--version","version"]);fW=FW({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:NW({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:Z,cwd:J})=>{if(!VW($))return`Error: "${$.slice(0,80)}" is not a read-only command. Allowed: ${[...BW].join(", ")} (read-only git subcommands only).`;return e3($,Z,J)}})});var kJ={};M0(kJ,{setSubAgentListener:()=>cj,createTaskTool:()=>pj});import{tool as gj,jsonSchema as uj,streamText as hj,stepCountIs as mj}from"ai";function nj($){let Z=G0().agent?.subAgentMaxSteps,J=$??Z??jW;return Number.isFinite(J)&&J>=1?Math.floor(J):jW}function AW(){return`You are a focused sub-agent executing a specific task. Complete the task thoroughly and return a clear result.
|
|
365
366
|
|
|
366
367
|
Rules:
|
|
367
368
|
- Focus only on the assigned task
|
|
@@ -371,62 +372,63 @@ Rules:
|
|
|
371
372
|
|
|
372
373
|
Working directory: ${process.cwd()}
|
|
373
374
|
Platform: ${process.platform}
|
|
374
|
-
Date: ${new Date().toDateString()}`}function
|
|
375
|
+
Date: ${new Date().toDateString()}`}function cj($){R9=$}function T9($){if(!R9)console.error($)}function pj($,Z,J,z={}){return gj({description:`Launch a sub-agent to execute a task independently. The sub-agent has its own context and tools. Use this for:
|
|
375
376
|
- Parallel execution: call multiple tasks at once for independent work
|
|
376
377
|
- Context isolation: keep the main conversation clean while the sub-agent explores
|
|
377
378
|
- Delegation: hand off well-defined subtasks (search, analysis, file operations)
|
|
378
379
|
|
|
379
380
|
The sub-agent can read/write files, run commands, search, and use all available tools.
|
|
380
|
-
Call multiple tasks in parallel when the work is independent.`,inputSchema:
|
|
381
|
+
Call multiple tasks in parallel when the work is independent.`,inputSchema:uj({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:G,prompt:Q},Y)=>{let K=Y?.toolCallId;T9(`\x1B[90m ┌─ Sub-agent: ${G}\x1B[0m`);try{let X=await oj(Q,$,Z,K,z);if(X.usage)J?.(X.usage);return T9("\x1B[90m └─ ✓ Done\x1B[0m"),f0(X.text,{direction:"tail"}).content}catch(X){if(Z?.aborted)return"Sub-agent cancelled by user.";let P=X instanceof Error?X.message:String(X);return Q0("error",`sub-agent failed: ${P}`),T9(`\x1B[90m └─ ✗ Failed: ${P}\x1B[0m`),`Sub-agent error: ${P}`}}})}async function oj($,Z,J,z,G={}){let Q=s$(Z),Y=V9();Y.todo=y3({silent:!0});let K=C2(),X=x6(),P=await L9(),W={...Y,...P,...K,...X},H=h6(W);delete W.task,delete W.explore;let q=[{role:"user",content:$}],U=G.loopGuard??new x2,M=nj(G.maxSteps),F=new AbortController,N=J?AbortSignal.any([J,F.signal]):F.signal,f=hj({model:Q,system:H?`${AW()}
|
|
381
382
|
|
|
382
|
-
${
|
|
383
|
+
${H}`:AW(),messages:q,allowSystemInMessages:!0,tools:W,stopWhen:mj(M),maxRetries:2,abortSignal:N,onError({error:A}){Q0("warn",`sub-agent step failed (will retry): ${String(A)}`)}}),B="";for await(let A of f.fullStream)switch(A.type){case"text-delta":B+=A.text;break;case"tool-call":{let O=U.observe(A.toolName,A.input);if(O==="halt"||O==="cap"){F.abort();let v=O==="halt"?"[Sub-agent stopped: repeated the same action too many times]":"[Sub-agent stopped: too many web searches. Summarize what was found.]";return{text:f1(B)+`
|
|
383
384
|
|
|
384
|
-
`+v}}
|
|
385
|
+
`+v}}R9?.({parentToolCallId:z,name:A.toolName,input:A.input,phase:"call"}),T9(`\x1B[90m │ ⚡ ${A.toolName}\x1B[0m`);break}case"tool-result":{if(R9?.({parentToolCallId:z,name:A.toolName,output:A.output,phase:"result"}),U.observeResult(A.toolName,A.output)==="cap")return F.abort(),{text:f1(B)+`
|
|
385
386
|
|
|
386
|
-
[Sub-agent stopped: research budget spent. Summarize what was found.]`};if(
|
|
387
|
+
[Sub-agent stopped: research budget spent. Summarize what was found.]`};if(G.shouldStop?.())return Q0("warn","sub-agent stopped: parent budget reached"),F.abort(),{text:f1(B)+`
|
|
387
388
|
|
|
388
|
-
[Sub-agent stopped: run budget reached]`};break}case"error":return
|
|
389
|
+
[Sub-agent stopped: run budget reached]`};break}case"error":return Q0("error",`sub-agent stream error: ${String(A.error)}`),F.abort(),{text:f1(B)+`
|
|
389
390
|
|
|
390
|
-
[Sub-agent error: ${A.error}]`}}let
|
|
391
|
-
`);let P=await
|
|
392
|
-
Resume with: min-agent exec --resume ${M}`);return
|
|
391
|
+
[Sub-agent error: ${A.error}]`}}let _=f1(U4(B)),V;try{V=await f.usage}catch{}return{text:_||"(sub-agent produced no output)",usage:V}}var jW=15,R9=null;var yJ=C(()=>{h4();_J();m$();n$();LJ();O9();v4();l();C9();z8();I$();S4()});var xJ={};M0(xJ,{runOnceWithSystem:()=>vJ,runOnce:()=>mW,runAgent:()=>EJ,pushTurn:()=>yW,parseContextOverflow:()=>EW,loadImageParts:()=>y9,formatErrorMessage:()=>o4,emptyRetryDelay:()=>TW,emptyResponseMessage:()=>RW,buildUserContent:()=>P8,WRAP_UP_PROMPT_TEXT:()=>QA,WRAP_UP_MESSAGE:()=>kW,SESSION_STATE_HEADER:()=>SW});import{streamText as dj,stepCountIs as rj}from"ai";import{readFileSync as lj,existsSync as ij,statSync as tj}from"fs";import DW from"path";function KA($){if(typeof $!=="number"||!Number.isFinite($)||$<1)return{cap:aj,bounded:!1};return{cap:Math.floor($),bounded:!0}}function TW($,Z=bW){if($<=1||Z<=0)return 0;return Math.min($A,Z*2**($-2))}function XA($){if($<=0)return Promise.resolve();return new Promise((Z)=>setTimeout(Z,$))}function RW($){return`模型连续 ${$} 次返回空响应(provider 可能超时或被限流),本轮已停止。发送消息可重试`}function OW(...$){for(let Z of $)if(typeof Z==="number"&&Number.isFinite(Z)&&Z>=0)return Z;return}function PA(){let{dim:$,reset:Z}=u2;console.log(`${$}⟳ 正在初始化(MCP、技能、规则)…${Z}`)}function WA(){let{dim:$,reset:Z}=u2;console.log(`${$}✓ 就绪${Z}`)}function y9($,Z){let J=[];for(let z of $){let G=DW.resolve(process.cwd(),z);if(!ij(G)){Z?.("not_found",z);continue}let Q=tj(G).size;if(Q>IW){Z?.("too_large",z,Q);continue}let Y=lj(G),K=DW.extname(G).toLowerCase();J.push({type:"image",image:Y,mimeType:YA[K]??"image/png"}),Z?.("attached",z)}return J}async function P8($,Z){if(!Z||Z.length===0)return $;let J=y9(Z,(z,G,Q)=>{if(z==="not_found")console.error(`\x1B[33m Warning: Image not found: ${G}\x1B[0m`);else if(z==="too_large")console.error(`\x1B[33m Warning: Image skipped (${((Q??0)/1024/1024).toFixed(1)} MB exceeds ${IW/1024/1024} MB limit): ${G}\x1B[0m`);else console.log(`\x1B[90m \uD83D\uDCCE ${G}\x1B[0m`)});return[{type:"text",text:$},...J]}async function EJ($,Z,J,z,G){HW(Z),I9(),PA(),await u4();try{T$();let Q=await V1(),{loadExecHistory:Y,saveSession:K}=await Promise.resolve().then(() => (u$(),E4)),X=Y(G);if(!X.ok)return console.error(X.error),!0;WA(),console.log(`\x1B[36m> ${$}\x1B[0m
|
|
392
|
+
`);let P=await P8($,J),W=[...X.messages,{role:"user",content:P}],H=new W4,q=g$();if(X.taskState)w6(X.taskState,q);let{createSaveThrottle:U}=await Promise.resolve().then(() => RJ),M=X.sessionId,F=()=>{try{M=K(W,M,void 0,void 0,q)}catch{}},N=U(F),{hasError:f}=await mW(W,Q,Z,void 0,void 0,H,{providerName:z,taskState:q,onStepPersist:()=>N.request()});if(N.cancel(),F(),M)console.log(`
|
|
393
|
+
Resume with: min-agent exec --resume ${M}`);return f}finally{await X4()}}function yW($,Z,J,z){let G=U4(Z),Q=new Set(z.map((K)=>K.toolCallId)),Y=[];if(G.trim())Y.push({type:"text",text:G});for(let K of J){if(!Q.has(K.toolCallId))continue;Y.push({type:"tool-call",toolCallId:K.toolCallId,toolName:K.toolName,input:K.input})}if(Y.length>0)$.push({role:"assistant",content:Y});for(let K of z){let X=k9(K.output);$.push({role:"tool",content:[{type:"tool-result",toolCallId:K.toolCallId,toolName:K.toolName,output:{type:"text",value:X}}]})}}async function HA($,Z,J,z,G,Q,Y){let K=V9();K.todo=y3({store:G});let X=C2(),P=x6(),W=X1(Y)?l5():{},H=await L9(),q={...K,...W,...H,...X,...P},U=z?(N)=>z.add(N):void 0,{createExploreTool:M}=await Promise.resolve().then(() => (LW(),_W));q.explore=M($,Z,U,{shouldStop:Q.shouldStop});let{createTaskTool:F}=await Promise.resolve().then(() => (yJ(),kJ));if(q.task=F($,Z,U,{loopGuard:Q.loopGuard,shouldStop:Q.shouldStop}),J){for(let B of["bash","write","edit","apply_patch"])delete q[B];let N=TZ();for(let B of Object.keys(X))if(!N.has(B))delete q[B];let f=sP();for(let B of Object.keys(H))if(!f.has(B))delete q[B]}return q}function qA($,Z,J,z,G){return{stable:[h6($,T2(Z))].filter((Y)=>Y.length>0),volatile:[r5(G),IK(J),z.promptHint()].filter((Y)=>Y.length>0)}}function UA($){if($.length===0)return null;return{role:"system",content:[SW,...$].join(`
|
|
393
394
|
|
|
394
|
-
`)}}function EX($){if(!Qf($))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 HA($){let f=EX($),Z=f?.promptTokens!=null?$4(f.promptTokens):null,z=f?.ctxTokens!=null?$4(f.ctxTokens):null;if(Z&&z)return`请求内容约 ${Z} token,超过当前上下文窗口 ${z}。请把窗口调大后再试。`;return"请求内容超过当前上下文窗口。请把窗口调大后再试。"}function g2($){if(Qf($))return HA($);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 R3($){if(typeof $==="string")return $;try{return JSON.stringify($)??String($)}catch{return String($)}}function Qf($){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 d0($,...f){if(!$)return;try{$(...f)}catch(Z){J0("error",`callback failed: ${Z instanceof Error?Z.message:String(Z)}`)}}function MA($,f){let Z=new Set(f.map((G)=>G.toolCallId)),z=new Set($.map((G)=>G.toolCallId)),J=f.filter((G)=>z.has(G.toolCallId)),K=$.filter((G)=>!Z.has(G.toolCallId)).map((G)=>({toolCallId:G.toolCallId,toolName:G.toolName,output:UA}));return{calls:$,results:[...J,...K]}}async function CX($){try{return await $.usage}catch{return}}function Yf($){return($?.inputTokens??0)>0||($?.outputTokens??0)>0}function vX($,f){if(!Yf(f))return $??f;if(!Yf($))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 qA(...$){let f=$.filter((J)=>J!=null);if(f.length===0)return;let Z=f.filter(Yf);return(Z.length>0?Z:f).reduce((J,K)=>{let G=(K.outputTokens??0)-(J.outputTokens??0);if(G!==0)return G>0?K:J;return(K.inputTokens??0)>(J.inputTokens??0)?K:J})}function EZ($,f){let Z=$[$.length-1];if(Z&&_2(Z)&&Z.role==="user"){Z.content=f;return}let z={role:"user",content:f};$.push(z),CQ(z)}function FA($){if($.researchCapped)return A3;if($.webResearchCount>=6)return bZ;return ZA}function NA($){for(let f of E2){let Z=$[f];if(!Z)continue;$[f]={...Z,execute:async()=>b3}}}function BA($){let f=[];for(let Z of E2){if(!$[Z])continue;delete $[Z],f.push(Z)}return f}async function Gf($,f,Z,z,J,K,G={}){r6($,G);try{if(!await zZ($,Z,K))return!1;if(z.onCompaction)d0(z.onCompaction,"compacting_start");else if(!J)console.log("\x1B[90m⟳ Compacting context...\x1B[0m");let Q=await o6($,f,K);if(!Q.compacted)return!1;if(Q.usage&&Z)Z.add(Q.usage);if($.length=0,$.push(...Q.messages),Z)Z.resetContext();if(n7(),z.onCompaction)d0(z.onCompaction,`compacted_ok estimated_tokens=${E1($)}`);else if(!J)console.log(`\x1B[90m ✓ Compacted (${E1($)} tokens estimated)\x1B[0m`);return!0}catch(Q){return J0("warn",`compaction failed: ${Q instanceof Error?Q.message:String(Q)}`),d0(z.onCompaction,"compacted_failed"),!1}}async function uX($,f,Z,z,J,K,G){return x7(()=>VA($,f,Z,z,J,K,G))}async function VA($,f,Z,z,J,K,G){let Q=s$(Z,G?.providerName);F7(),J0("info",`run start messages=${$.length} model=${typeof Q==="string"?Q:Q.modelId}`);let Y=J??{},P=K0(),X=P.sampling??{},W=G?.temperature??X.temperature,H=G?.maxTokens??X.maxTokens,U=G?.topP??X.topP,M=G?.taskState??x$();wQ(M,$);let{cap:N,bounded:q}=KA(G?.maxSteps??P.agent?.maxSteps),L=G?.maxContinues??P.agent?.maxContinues??tD,F=G?.autoContinue??P.agent?.autoContinue??P.compaction?.autoContinue??!0,V=Math.max(1,G?.maxEmptyAttempts??P.agent?.maxEmptyAttempts??aD),B=G?.emptyRetryDelayMs??P.agent?.emptyRetryDelayMs??OX,A=jX(G?.turnTimeLimitMs,P.agent?.turnTimeLimitMs)??eD,j=jX(G?.softStepLimit,P.agent?.softStepLimit)??$A,v=Date.now(),O=(m)=>A>0&&Date.now()-v>=A||j>0&&m>=j,b=new v2({steerAfter:G?.researchSteerAfter??P.agent?.researchSteerAfter,stopAfter:G?.researchStopAfter??P.agent?.researchStopAfter,totalCap:G?.researchTotalCap??P.agent?.researchTotalCap}),T={tokens:0},I={abortSignal:z,modelId:Z,taskGoal:M.goal||void 0,get overheadTokens(){return T.tokens}},h=(await e$(Z)).tokens,$0=h*l8,u=()=>({pressureTokens:h*fZ,targetTokens:h*ZZ,overheadTokens:T.tokens}),y=P.budget?.maxCostUSD,r=null;if(y!=null&&y>0){let m=G?.providerName?P.providers?.find((m0)=>m0.name===G.providerName):s(P);r=await d6(Z??m?.defaultModel??"")}let S=!1,p=()=>{if(!K||y==null||y<=0)return!1;let m=l6({inputTokens:K.totalInputTokens,outputTokens:K.totalOutputTokens},r);if(m!=null&&m>y)return S=!0,!0;return!1};await Gf($,Q,K,Y,J,I,u());let z0=0,g=0,w=0,R0=!1,G0=!1,H0,f0=!0,Q0=await PA(Z,z,G?.planMode??!1,K,M,{loopGuard:b,shouldStop:()=>p()||O(z0)},G?.memory),U0=async(m)=>{if(J0("info",`run end steps=${z0} continues=${g} tokens_in=${H0?.inputTokens??0} tokens_out=${H0?.outputTokens??0}`),lQ(),Y.onRunFinish){try{await Y.onRunFinish({stepCount:z0,usage:H0,contextTokens:K?.lastInputTokens??0,hasError:G0,aborted:m.aborted,maxStepsReached:m.maxStepsReached,budgetExceeded:S,continues:g,incomplete:m.incomplete??!1,stopped:m.stopped??!1,emptyResponse:m.emptyResponse??!1,emptyAttempts:w,wrapUp:m.wrapUp??!1})}catch(m0){J0("error",`onRunFinish failed: ${m0 instanceof Error?m0.message:String(m0)}`)}return{hasError:G0}}if(G0)return y3(),{hasError:G0};if(y3(),HX(z0,H0,h,K?.lastInputTokens),S)console.log(`\x1B[33m⚠ 已达到预算上限 ($${y}),运行已中断\x1B[0m`);if(m.stopped)console.log(`\x1B[33m⚠ ${j3}\x1B[0m`);if(m.emptyResponse)console.log(`\x1B[33m⚠ ${IX(w)}\x1B[0m`);else if(m.wrapUp)console.log(`\x1B[33m⚠ ${kX}\x1B[0m`);else if(m.maxStepsReached)console.log("\x1B[33m⚠ 已达到自动续跑上限,发送消息继续\x1B[0m");else if(m.incomplete)console.log("\x1B[33m⚠ 还没有完整回复,发送消息可继续\x1B[0m");return{hasError:G0}};while(!0){if(z?.aborted)return U0({aborted:!0,maxStepsReached:!1});if(p())return U0({aborted:!0,maxStepsReached:!1});let m;dQ();try{m=await LA({messages:$,systemPrompt:f,model:Q,abortSignal:z,callbacks:J,cbs:Y,tracker:K,taskState:M,allTools:Q0,maxSteps:N,stepBounded:q,temperature:W,maxTokens:H,topP:U,thinking:G?.thinking,memory:G?.memory,providerType:(G?.providerName?P.providers?.find((E)=>E.name===G.providerName):s(P))?.type,modelId:Z,checkBudget:p,overTurnBudget:(E)=>O(z0+E),pruneBudget:u,overhead:T,compactThreshold:$0,allowContextAbort:f0,loopGuard:b,onStepPersist:G?.onStepPersist})}catch(E){let i=E instanceof Error?E.message:String(E);if(J0("error",i),G0=!0,Y.onStreamError)d0(Y.onStreamError,g2(i));else console.error(`\x1B[31m${g2(i)}\x1B[0m`);return U0({aborted:Boolean(z?.aborted),maxStepsReached:!1})}if(z0+=m.stepCount,H0=vX(H0,m.usage),m.hasError)G0=!0;if(m.budgetExceeded)S=!0;if(m.userAborted)return U0({aborted:!0,maxStepsReached:!1});if(m.doomLoop)return U0({aborted:!1,maxStepsReached:!1,stopped:!0});if(m.hasError&&!m.contextPressure&&!m.toolPressure)return U0({aborted:!1,maxStepsReached:!1});if(S)return U0({aborted:!0,maxStepsReached:!1});if(m.toolPressure){r6($,u());continue}if(m.contextPressure&&m.stepCount===0&&!m.lastStepHadTools){if(await Gf($,Q,K,Y,J,{...I,force:!0},u())){if(g++,g>L)return U0({aborted:!1,maxStepsReached:!0,incomplete:!0});continue}G0=!0;let i=g2(m.overflowError??"");if(Y.onStreamError)d0(Y.onStreamError,i);else console.error(`\x1B[31m${i}\x1B[0m`);return U0({aborted:!1,maxStepsReached:!1})}if(m.emptyCompletion){if(w++,w>=V)return J0("warn",`empty response from provider ${w}x, ending run`),U0({aborted:!1,maxStepsReached:!1,incomplete:!0,emptyResponse:!0});if(g++,g>L)return U0({aborted:!1,maxStepsReached:!0,incomplete:!0});let E=yX(w,B);if(J0("warn",`empty response from provider, retry ${w}/${V-1} after ${E}ms`),Y.onRetryNotice)d0(Y.onRetryNotice,{kind:"empty_response",attempt:w,maxAttempts:V-1,delayMs:E});else if(!J)console.log(`\x1B[90m⟳ 模型返回空响应,重试 ${w}/${V-1}…\x1B[0m`);await GA(E);continue}let m0=m.researchCap||m.researchSteer,V$=!b.producedArtifact&&(m0||m.lastStepHadTools&&(b.researchCapped||!F&&b.webResearchCount>0)),x0=m.lastStepHadTools||m.xmlToolFollowUp||m.providerStall,L$=m.xmlToolFollowUp||F&&(m.contextPressure||m.lastStepHadTools||m.providerStall);if(!V$&&!L$){let E=!F&&m.maxStepsReached&&m.lastStepHadTools;if(E&&!J)console.log(`\x1B[33m⚠ 本轮已达到步数上限(${N}),发送消息继续\x1B[0m`);return U0({aborted:!1,maxStepsReached:E,incomplete:x0&&!E})}if(m.wrapUp||O(z0)){if(R0)return J0("warn",`turn budget spent after wrap-up (steps=${z0})`),U0({aborted:!1,maxStepsReached:!1,incomplete:!0,wrapUp:!0});if(R0=!0,g++,g>L)return U0({aborted:!1,maxStepsReached:!0,incomplete:!0});if(J0("info",`auto-continue reason=wrap_up steps=${z0} elapsed=${Date.now()-v}ms`),Y.onRetryNotice)d0(Y.onRetryNotice,{kind:"wrap_up",attempt:1,maxAttempts:1,delayMs:0});else if(!J)console.log("\x1B[90m⟳ 本轮预算用尽,正在收尾…\x1B[0m");await Gf($,Q,K,Y,J,I,u()),EZ($,wX);continue}if(V$){if(g++,g>L)return U0({aborted:!1,maxStepsReached:!0,incomplete:!0});BA(Q0),b.markCapped(),J0("info",`auto-continue reason=${m0?m.researchCap?"research_cap":"research_steer":"awaiting_deliverable"}`),await Gf($,Q,K,Y,J,I,u()),EZ($,A3);continue}if(g++,g>L)return U0({aborted:!1,maxStepsReached:!0,incomplete:x0});J0("info",`auto-continue reason=${m.xmlToolFollowUp?"xml_search":m.contextPressure?"context":m.providerStall?"provider_stall":"tools_without_reply"}`);let n=await Gf($,Q,K,Y,J,{...I,force:m.contextPressure},u());if(m.contextPressure&&!n)f0=!1;EZ($,FA(b))}}class xX{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+=i8(this.stepText);for(let z of this.toolCalls)this.producedTokens+=i8(R3(z.input));let Z=MA(this.toolCalls,this.toolResults);RX(this.messages,this.stepText,Z.calls,Z.results),this.innerSteps++,this.stepText="",this.toolCalls=[],this.toolResults=[],this.onFlush?.({steps:this.innerSteps})}}class gX{cbs;interactive;md=new _6;thinkingSplit=new CZ;xmlSplit=new w3;rawText="";hadThinking=!1;thinkingOpen=!1;constructor($,f){this.cbs=$;this.interactive=f}emitThinking($){if(!$)return;if(this.hadThinking=!0,this.cbs.onThinkingDelta){d0(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(`
|
|
395
|
-
${x2.dim}\uD83D\uDCAD 思考${x2.reset}
|
|
396
|
-
`);process.stderr.write(`${x2.dim}${$}${x2.reset}`)}emitDisplay($){try{if(this.cbs.onAssistantDisplayDelta){this.cbs.onAssistantDisplayDelta($);return}let f=this.md.write($);if(f)process.stdout.write(f)}catch(f){J0("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 nX{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 xX($.messages,(f)=>{if($.onStepPersist)d0($.onStepPersist,f)}),this.renderer=new gX($.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:G}=this.params;if($&&f)f.update($);if(this.usageSteps++,Z())this.stop.budget=!0,this.innerController.abort();else if(G(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>=fA&&p6(K,this.params.pruneBudget())!==K)this.stop.tools=!0,this.innerController.abort()}noteStepUsage($){this.stepUsage=vX(this.stepUsage,$)}resolvedUsage($){let f=qA($,this.totalUsage,this.stepUsage);if(Yf(f))return f;let Z=this.estimateUsage();if(!Z)return f;if(this.params.tracker)this.params.tracker.update(Z);return J0("info",`usage estimated for aborted pass in=${Z.inputTokens} out=${Z.outputTokens}`),Z}estimateUsage(){let $=this.assembler.producedTokens;if($===0)return;let f=E1(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(Qf(f))this.stop.context=!0;J0("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=$,NA(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},G=this.assembler.nextMissingCallId();if(this.renderer.flushMarkdown(),this.assembler.recordCall({toolCallId:G,toolName:"search_web",input:K}),N7("search_web",K),f.onToolCall)d0(f.onToolCall,"search_web",K,G);else yZ("search_web",K);if(Z.researchCapped){let P=b3;if(this.assembler.recordResult({toolCallId:G,toolName:"search_web",output:P}),S6("search_web",P),f.onToolResult)d0(f.onToolResult,"search_web",P,{toolCallId:G,isError:!1});else Kf("search_web",P,!1);return this.xmlSearchRecovered=!0,!1}if(this.applyLoopAction(Z.observe("search_web",K))){let P=j3;if(this.assembler.recordResult({toolCallId:G,toolName:"search_web",output:P}),S6("search_web",P),f.onToolResult)d0(f.onToolResult,"search_web",P,{toolCallId:G,isError:!1});else Kf("search_web",P,!1);return!0}let Q=$.kind==="results"?$.body:await this.executeSearchWeb(J,G),Y=typeof Q==="string"&&/^(error|search error)\b/i.test(Q);if(this.assembler.recordResult({toolCallId:G,toolName:"search_web",output:Q}),S6("search_web",Q),f.onToolResult)d0(f.onToolResult,"search_web",Q,{toolCallId:G,isError:Y});else Kf("search_web",Q,Y);return this.xmlSearchRecovered=!0,this.applyLoopAction(Z.observeResult("search_web",Y?"error":Q)),!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:R3(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(Yf($.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}),N7(z,$.input),f.onToolCall)d0(f.onToolCall,z,$.input,J);else yZ(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: ${R3($.error)}`:$.output;if(this.assembler.recordResult({toolCallId:$.toolCallId,toolName:$.toolName||"unknown",output:J}),S6($.toolName,K),f.onToolResult)d0(f.onToolResult,$.toolName,K,{toolCallId:$.toolCallId,isError:z});else Kf($.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(m7($.error))return this.stop.stall=!0,J0("warn",`provider stall: ${r8($.error)}`),await this.flushOutputAndStep(),this.innerController.abort(),!0;if(Qf(z))return this.stop.context=!0,this.overflowError=z,J0("warn",`context overflow: ${z}`),await this.flushOutputAndStep(),this.innerController.abort(),!0;if(this.hasError=!0,J0("error",`stream error: ${z}`),f.onStreamError)d0(f.onStreamError,g2(z));else console.error(`\x1B[31m${g2(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 CX($):void 0))}async handleException($,f){await this.applySlices(this.renderer.flushOnError()),this.assembler.flushStep(),this.settlePendingLoop();let Z=this.resolvedUsage(f?await CX(f):void 0);if(this.params.abortSignal?.aborted)return this.snapshot(Z,{userAborted:!0});if(m7($)){let K=this.assembler.hadAssistantText||this.assembler.hadTools||this.renderer.hadThinking;return J0("warn",`provider stall: ${r8($)}`),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(J0("error",z),Qf(z))return this.stop.context=!0,this.overflowError=z,this.snapshot(Z,{hasError:!1,contextPressure:!0,userAborted:!1});this.hasError=!0;let J=g2(z);if(this.params.cbs.onStreamError)d0(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 LA($){let f=new nX($),Z;try{f.attachAbort();let z=XA($.allTools,$.messages,$.taskState,$.loopGuard,$.memory),J=[$.systemPrompt,...z.stable].join(`
|
|
395
|
+
`)}}function EW($){if(!K8($))return null;let Z=$.match(/n_prompt_tokens["\s:=]+(\d+)/i)?.[1]??$.match(/request\s*\((\d+)\s*tokens?\)/i)?.[1],J=$.match(/n_ctx["\s:=]+(\d+)/i)?.[1]??$.match(/context size\s*\((\d+)\s*tokens?\)/i)?.[1];return{...Z?{promptTokens:Number(Z)}:{},...J?{ctxTokens:Number(J)}:{}}}function MA($){let Z=EW($),J=Z?.promptTokens!=null?Z4(Z.promptTokens):null,z=Z?.ctxTokens!=null?Z4(Z.ctxTokens):null;if(J&&z)return`请求内容约 ${J} token,超过当前上下文窗口 ${z}。请把窗口调大后再试。`;return"请求内容超过当前上下文窗口。请把窗口调大后再试。"}function o4($){if(K8($))return MA($);if($.includes("API key")||$.includes("Unauthorized")||$.includes("Forbidden"))return"Authentication error: Check your API key.";if($.includes("429")||$.includes("rate limit")||$.includes("Rate limit")){if(z1(s(G0())))return["内置免费模型(openrouter/free)当前时段的免费额度已用尽。","免费额度由所有用户共享,通常会在稍后(次日或下一时段)自动恢复,可稍后再试。","如需立即继续使用,请自行提供模型:"," 1. 设置环境变量 MIN_AGENT_NO_BUILTIN_PROVIDER=1 关闭内置预设"," 2. 运行 `min-agent setup` 配置自己的服务商与模型(OpenAI / Ollama / 任意 OpenAI 兼容接口)"].join(`
|
|
396
|
+
`);return"Rate limited after retries. Please wait and try again."}if($.includes("timeout")||$.includes("ETIMEDOUT"))return`Network error (retries exhausted): ${$}`;return $}function k9($){if(typeof $==="string")return $;try{return JSON.stringify($)??String($)}catch{return String($)}}function K8($){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 r0($,...Z){if(!$)return;try{$(...Z)}catch(J){Q0("error",`callback failed: ${J instanceof Error?J.message:String(J)}`)}}function NA($,Z){let J=new Set(Z.map((Y)=>Y.toolCallId)),z=new Set($.map((Y)=>Y.toolCallId)),G=Z.filter((Y)=>z.has(Y.toolCallId)),Q=$.filter((Y)=>!J.has(Y.toolCallId)).map((Y)=>({toolCallId:Y.toolCallId,toolName:Y.toolName,output:FA}));return{calls:$,results:[...G,...Q]}}async function CW($){try{return await $.usage}catch{return}}function X8($){return($?.inputTokens??0)>0||($?.outputTokens??0)>0}function vW($,Z){if(!X8(Z))return $??Z;if(!X8($))return Z;let J=($.inputTokens??0)+(Z.inputTokens??0),z=($.outputTokens??0)+(Z.outputTokens??0);return{...$,...Z,inputTokens:J,outputTokens:z,totalTokens:($.totalTokens??0)+(Z.totalTokens??0)||J+z}}function BA(...$){let Z=$.filter((G)=>G!=null);if(Z.length===0)return;let J=Z.filter(X8);return(J.length>0?J:Z).reduce((G,Q)=>{let Y=(Q.outputTokens??0)-(G.outputTokens??0);if(Y!==0)return Y>0?Q:G;return(Q.inputTokens??0)>(G.inputTokens??0)?Q:G})}function SJ($,Z){let J=$[$.length-1];if(J&&j2(J)&&J.role==="user"){J.content=Z;return}let z={role:"user",content:Z};$.push(z),CK(z)}function VA($){if($.researchCapped)return j9;if($.webResearchCount>=6)return AJ;return GA}function fA($){for(let Z of v2){let J=$[Z];if(!J)continue;$[Z]={...J,execute:async()=>A9}}}function _A($){let Z=[];for(let J of v2){if(!$[J])continue;delete $[J],Z.push(J)}return Z}async function Y8($,Z,J,z,G,Q,Y={}){o6($,Y);try{if(!await JJ($,J,Q))return!1;if(z.onCompaction)r0(z.onCompaction,"compacting_start");else if(!G)console.log("\x1B[90m⟳ Compacting context...\x1B[0m");let K=await d6($,Z,Q);if(!K.compacted)return!1;if(K.usage&&J)J.add(K.usage);if($.length=0,$.push(...K.messages),J)J.resetContext();if(uZ(),z.onCompaction)r0(z.onCompaction,`compacted_ok estimated_tokens=${x1($)}`);else if(!G)console.log(`\x1B[90m ✓ Compacted (${x1($)} tokens estimated)\x1B[0m`);return!0}catch(K){return Q0("warn",`compaction failed: ${K instanceof Error?K.message:String(K)}`),r0(z.onCompaction,"compacted_failed"),!1}}async function xW($,Z,J,z,G,Q,Y){return xZ(()=>LA($,Z,J,z,G,Q,Y))}async function LA($,Z,J,z,G,Q,Y){let K=s$(J,Y?.providerName);FZ(),Q0("info",`run start messages=${$.length} model=${typeof K==="string"?K:K.modelId}`);let X=G??{},P=G0(),W=P.sampling??{},H=Y?.temperature??W.temperature,q=Y?.maxTokens??W.maxTokens,U=Y?.topP??W.topP,M=Y?.taskState??g$();wK(M,$);let{cap:F,bounded:N}=KA(Y?.maxSteps??P.agent?.maxSteps),f=Y?.maxContinues??P.agent?.maxContinues??sj,B=Y?.autoContinue??P.agent?.autoContinue??P.compaction?.autoContinue??!0,_=Math.max(1,Y?.maxEmptyAttempts??P.agent?.maxEmptyAttempts??ej),V=Y?.emptyRetryDelayMs??P.agent?.emptyRetryDelayMs??bW,A=OW(Y?.turnTimeLimitMs,P.agent?.turnTimeLimitMs)??ZA,O=OW(Y?.softStepLimit,P.agent?.softStepLimit)??JA,v=Date.now(),b=(c)=>A>0&&Date.now()-v>=A||O>0&&c>=O,D=new x2({steerAfter:Y?.researchSteerAfter??P.agent?.researchSteerAfter,stopAfter:Y?.researchStopAfter??P.agent?.researchStopAfter,totalCap:Y?.researchTotalCap??P.agent?.researchTotalCap}),I={tokens:0},R={abortSignal:z,modelId:J,taskGoal:M.goal||void 0,get overheadTokens(){return I.tokens}},m=(await e$(J)).tokens,$0=m*r3,x=()=>({pressureTokens:m*$J,targetTokens:m*ZJ,overheadTokens:I.tokens}),T=P.budget?.maxCostUSD,o=null;if(T!=null&&T>0){let c=Y?.providerName?P.providers?.find((c0)=>c0.name===Y.providerName):s(P);o=await r6(J??c?.defaultModel??"")}let S=!1,p=()=>{if(!Q||T==null||T<=0)return!1;let c=l6({inputTokens:Q.totalInputTokens,outputTokens:Q.totalOutputTokens},o);if(c!=null&&c>T)return S=!0,!0;return!1};await Y8($,K,Q,X,G,R,x());let z0=0,u=0,w=0,y0=!1,Y0=!1,q0,Z0=!0,K0=await HA(J,z,Y?.planMode??!1,Q,M,{loopGuard:D,shouldStop:()=>p()||b(z0)},Y?.memory),U0=async(c)=>{if(Q0("info",`run end steps=${z0} continues=${u} tokens_in=${q0?.inputTokens??0} tokens_out=${q0?.outputTokens??0}`),lK(),X.onRunFinish){try{await X.onRunFinish({stepCount:z0,usage:q0,contextTokens:Q?.lastInputTokens??0,hasError:Y0,aborted:c.aborted,maxStepsReached:c.maxStepsReached,budgetExceeded:S,continues:u,incomplete:c.incomplete??!1,stopped:c.stopped??!1,emptyResponse:c.emptyResponse??!1,emptyAttempts:w,wrapUp:c.wrapUp??!1})}catch(c0){Q0("error",`onRunFinish failed: ${c0 instanceof Error?c0.message:String(c0)}`)}return{hasError:Y0}}if(Y0)return I9(),{hasError:Y0};if(I9(),qW(z0,q0,m,Q?.lastInputTokens),S)console.log(`\x1B[33m⚠ 已达到预算上限 ($${T}),运行已中断\x1B[0m`);if(c.stopped)console.log(`\x1B[33m⚠ ${D9}\x1B[0m`);if(c.emptyResponse)console.log(`\x1B[33m⚠ ${RW(w)}\x1B[0m`);else if(c.wrapUp)console.log(`\x1B[33m⚠ ${kW}\x1B[0m`);else if(c.maxStepsReached)console.log("\x1B[33m⚠ 已达到自动续跑上限,发送消息继续\x1B[0m");else if(c.incomplete)console.log("\x1B[33m⚠ 还没有完整回复,发送消息可继续\x1B[0m");return{hasError:Y0}};while(!0){if(z?.aborted)return U0({aborted:!0,maxStepsReached:!1});if(p())return U0({aborted:!0,maxStepsReached:!1});let c;rK();try{c=await jA({messages:$,systemPrompt:Z,model:K,abortSignal:z,callbacks:G,cbs:X,tracker:Q,taskState:M,allTools:K0,maxSteps:F,stepBounded:N,temperature:H,maxTokens:q,topP:U,thinking:Y?.thinking,memory:Y?.memory,providerType:(Y?.providerName?P.providers?.find((E)=>E.name===Y.providerName):s(P))?.type,modelId:J,checkBudget:p,overTurnBudget:(E)=>b(z0+E),pruneBudget:x,overhead:I,compactThreshold:$0,allowContextAbort:Z0,loopGuard:D,onStepPersist:Y?.onStepPersist})}catch(E){let t=E instanceof Error?E.message:String(E);if(Q0("error",t),Y0=!0,X.onStreamError)r0(X.onStreamError,o4(t));else console.error(`\x1B[31m${o4(t)}\x1B[0m`);return U0({aborted:Boolean(z?.aborted),maxStepsReached:!1})}if(z0+=c.stepCount,q0=vW(q0,c.usage),c.hasError)Y0=!0;if(c.budgetExceeded)S=!0;if(c.userAborted)return U0({aborted:!0,maxStepsReached:!1});if(c.doomLoop)return U0({aborted:!1,maxStepsReached:!1,stopped:!0});if(c.hasError&&!c.contextPressure&&!c.toolPressure)return U0({aborted:!1,maxStepsReached:!1});if(S)return U0({aborted:!0,maxStepsReached:!1});if(c.toolPressure){o6($,x());continue}if(c.contextPressure&&c.stepCount===0&&!c.lastStepHadTools){if(await Y8($,K,Q,X,G,{...R,force:!0},x())){if(u++,u>f)return U0({aborted:!1,maxStepsReached:!0,incomplete:!0});continue}Y0=!0;let t=o4(c.overflowError??"");if(X.onStreamError)r0(X.onStreamError,t);else console.error(`\x1B[31m${t}\x1B[0m`);return U0({aborted:!1,maxStepsReached:!1})}if(c.emptyCompletion){if(w++,w>=_)return Q0("warn",`empty response from provider ${w}x, ending run`),U0({aborted:!1,maxStepsReached:!1,incomplete:!0,emptyResponse:!0});if(u++,u>f)return U0({aborted:!1,maxStepsReached:!0,incomplete:!0});let E=TW(w,V);if(Q0("warn",`empty response from provider, retry ${w}/${_-1} after ${E}ms`),X.onRetryNotice)r0(X.onRetryNotice,{kind:"empty_response",attempt:w,maxAttempts:_-1,delayMs:E});else if(!G)console.log(`\x1B[90m⟳ 模型返回空响应,重试 ${w}/${_-1}…\x1B[0m`);await XA(E);continue}let c0=c.researchCap||c.researchSteer,f$=!D.producedArtifact&&(c0||c.lastStepHadTools&&(D.researchCapped||!B&&D.webResearchCount>0)),g0=c.lastStepHadTools||c.xmlToolFollowUp||c.providerStall,_$=c.xmlToolFollowUp||B&&(c.contextPressure||c.lastStepHadTools||c.providerStall);if(!f$&&!_$){let E=!B&&c.maxStepsReached&&c.lastStepHadTools;if(E&&!G)console.log(`\x1B[33m⚠ 本轮已达到步数上限(${F}),发送消息继续\x1B[0m`);return U0({aborted:!1,maxStepsReached:E,incomplete:g0&&!E})}if(c.wrapUp||b(z0)){if(y0)return Q0("warn",`turn budget spent after wrap-up (steps=${z0})`),U0({aborted:!1,maxStepsReached:!1,incomplete:!0,wrapUp:!0});if(y0=!0,u++,u>f)return U0({aborted:!1,maxStepsReached:!0,incomplete:!0});if(Q0("info",`auto-continue reason=wrap_up steps=${z0} elapsed=${Date.now()-v}ms`),X.onRetryNotice)r0(X.onRetryNotice,{kind:"wrap_up",attempt:1,maxAttempts:1,delayMs:0});else if(!G)console.log("\x1B[90m⟳ 本轮预算用尽,正在收尾…\x1B[0m");await Y8($,K,Q,X,G,R,x()),SJ($,wW);continue}if(f$){if(u++,u>f)return U0({aborted:!1,maxStepsReached:!0,incomplete:!0});_A(K0),D.markCapped(),Q0("info",`auto-continue reason=${c0?c.researchCap?"research_cap":"research_steer":"awaiting_deliverable"}`),await Y8($,K,Q,X,G,R,x()),SJ($,j9);continue}if(u++,u>f)return U0({aborted:!1,maxStepsReached:!0,incomplete:g0});Q0("info",`auto-continue reason=${c.xmlToolFollowUp?"xml_search":c.contextPressure?"context":c.providerStall?"provider_stall":"tools_without_reply"}`);let h=await Y8($,K,Q,X,G,{...R,force:c.contextPressure},x());if(c.contextPressure&&!h)Z0=!1;SJ($,VA(D))}}class gW{messages;onFlush;stepText="";toolCalls=[];toolResults=[];innerSteps=0;lastStepHadTools=!1;hadTools=!1;hadAssistantText=!1;producedTokens=0;constructor($,Z){this.messages=$;this.onFlush=Z}get pendingResults(){return this.toolResults.length}get hasUnpairedCalls(){let $=new Set(this.toolResults.map((Z)=>Z.toolCallId));return this.toolCalls.some((Z)=>!$.has(Z.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,Z=Boolean(this.stepText.trim());if(!Z&&!$)return;if(this.lastStepHadTools=$,$)this.hadTools=!0;if(Z)this.hadAssistantText=!0;this.producedTokens+=l3(this.stepText);for(let z of this.toolCalls)this.producedTokens+=l3(k9(z.input));let J=NA(this.toolCalls,this.toolResults);yW(this.messages,this.stepText,J.calls,J.results),this.innerSteps++,this.stepText="",this.toolCalls=[],this.toolResults=[],this.onFlush?.({steps:this.innerSteps})}}class uW{cbs;interactive;md=new L6;thinkingSplit=new OJ;xmlSplit=new b9;rawText="";hadThinking=!1;thinkingOpen=!1;constructor($,Z){this.cbs=$;this.interactive=Z}emitThinking($){if(!$)return;if(this.hadThinking=!0,this.cbs.onThinkingDelta){r0(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(`
|
|
397
|
+
${u2.dim}\uD83D\uDCAD 思考${u2.reset}
|
|
398
|
+
`);process.stderr.write(`${u2.dim}${$}${u2.reset}`)}emitDisplay($){try{if(this.cbs.onAssistantDisplayDelta){this.cbs.onAssistantDisplayDelta($);return}let Z=this.md.write($);if(Z)process.stdout.write(Z)}catch(Z){Q0("error",`display callback failed: ${Z instanceof Error?Z.message:String(Z)}`)}}feedReasoning($){this.emitThinking($)}mirror($){if(!$)return;this.rawText+=$,this.emitDisplay($)}pipeXml($,Z){let J=$?this.xmlSplit.feed($):[];if(Z)J.push(...this.xmlSplit.flush());let z=[];for(let G of J)if(G.type==="display"){if(!G.text)continue;this.mirror(G.text),z.push(G)}else z.push(G);return z}feedText($){let{display:Z,thinking:J}=this.thinkingSplit.feed($);return this.emitThinking(J),this.pipeXml(Z,!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 hW{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 gW($.messages,(Z)=>{if($.onStepPersist)r0($.onStepPersist,Z)}),this.renderer=new uW($.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:Z,checkBudget:J,allowContextAbort:z,compactThreshold:G,messages:Q,overTurnBudget:Y}=this.params;if($&&Z)Z.update($);if(this.usageSteps++,J())this.stop.budget=!0,this.innerController.abort();else if(Y(this.assembler.innerSteps))this.stop.wrapUp=!0,this.innerController.abort();else if(z&&this.usageSteps>=2&&Z&&Z.lastInputTokens>G)this.stop.context=!0,this.innerController.abort();else if(this.usageSteps>=zA&&p6(Q,this.params.pruneBudget())!==Q)this.stop.tools=!0,this.innerController.abort()}noteStepUsage($){this.stepUsage=vW(this.stepUsage,$)}resolvedUsage($){let Z=BA($,this.totalUsage,this.stepUsage);if(X8(Z))return Z;let J=this.estimateUsage();if(!J)return Z;if(this.params.tracker)this.params.tracker.update(J);return Q0("info",`usage estimated for aborted pass in=${J.inputTokens} out=${J.outputTokens}`),J}estimateUsage(){let $=this.assembler.producedTokens;if($===0)return;let Z=x1(this.params.messages)+this.params.overhead.tokens;return{inputTokens:Z,outputTokens:$,totalTokens:Z+$,inputTokenDetails:{noCacheTokens:Z,cacheReadTokens:void 0,cacheWriteTokens:void 0},outputTokenDetails:{textTokens:$,reasoningTokens:void 0}}}onStepError($){let Z=String($);if(K8(Z))this.stop.context=!0;Q0("warn",`step failed (will retry): ${Z}`)}async applySlices($){for(let Z of $)if(Z.type==="display"){if(!Z.text)continue;if(this.assembler.pendingResults>0)this.assembler.flushStep();if(this.assembler.appendText(Z.text),this.xmlSearchRecovered&&Z.text.trim())this.answerAfterXml=!0}else if(await this.materializeXmlSearch(Z.block))return!0;return!1}applyLoopAction($){if($==="ok")return!1;if($==="halt")return this.stop.doom=!0,this.innerController.abort(),!0;return this.pendingLoop=$,fA(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:Z,loopGuard:J}=this.params,z="search_web",G=$.query.trim(),Q={query:G},Y=this.assembler.nextMissingCallId();if(this.renderer.flushMarkdown(),this.assembler.recordCall({toolCallId:Y,toolName:"search_web",input:Q}),NZ("search_web",Q),Z.onToolCall)r0(Z.onToolCall,"search_web",Q,Y);else IJ("search_web",Q);if(J.researchCapped){let P=A9;if(this.assembler.recordResult({toolCallId:Y,toolName:"search_web",output:P}),S6("search_web",P),Z.onToolResult)r0(Z.onToolResult,"search_web",P,{toolCallId:Y,isError:!1});else Q8("search_web",P,!1);return this.xmlSearchRecovered=!0,!1}if(this.applyLoopAction(J.observe("search_web",Q))){let P=D9;if(this.assembler.recordResult({toolCallId:Y,toolName:"search_web",output:P}),S6("search_web",P),Z.onToolResult)r0(Z.onToolResult,"search_web",P,{toolCallId:Y,isError:!1});else Q8("search_web",P,!1);return!0}let K=$.kind==="results"?$.body:await this.executeSearchWeb(G,Y),X=typeof K==="string"&&/^(error|search error)\b/i.test(K);if(this.assembler.recordResult({toolCallId:Y,toolName:"search_web",output:K}),S6("search_web",K),Z.onToolResult)r0(Z.onToolResult,"search_web",K,{toolCallId:Y,isError:X});else Q8("search_web",K,X);return this.xmlSearchRecovered=!0,this.applyLoopAction(J.observeResult("search_web",X?"error":K)),!1}async executeSearchWeb($,Z){if(!$)return'Search error: "query" must be a non-empty string.';let J=this.params.allTools.search_web;if(typeof J?.execute!=="function")return"Search error: search_web is unavailable.";try{let z=await J.execute({query:$},{toolCallId:Z,messages:this.params.messages,abortSignal:this.signal});return typeof z==="string"?z:k9(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:Z,loopGuard:J}=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(X8($.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",G=$.toolCallId||this.assembler.nextMissingCallId();if(this.assembler.recordCall({toolCallId:G,toolName:z,input:$.input}),NZ(z,$.input),Z.onToolCall)r0(Z.onToolCall,z,$.input,G);else IJ(z,$.input);if(this.applyLoopAction(J.observe(z,$.input)))return await this.flushOutputAndStep(),!0;return!1}case"tool-result":case"tool-error":{let z=$.type==="tool-error",G=z?$.error:$.output,Q=z?`Error: ${k9($.error)}`:$.output;if(this.assembler.recordResult({toolCallId:$.toolCallId,toolName:$.toolName||"unknown",output:G}),S6($.toolName,Q),Z.onToolResult)r0(Z.onToolResult,$.toolName,Q,{toolCallId:$.toolCallId,isError:z});else Q8($.toolName,Q,z);if(this.applyLoopAction(J.observeResult($.toolName||"unknown",z?"error":G)),this.stepFinishSeen||this.pendingLoop)return await this.flushAndSettleLoop();return!1}case"error":{let z=String($.error);if(nZ($.error))return this.stop.stall=!0,Q0("warn",`provider stall: ${p3($.error)}`),await this.flushOutputAndStep(),this.innerController.abort(),!0;if(K8(z))return this.stop.context=!0,this.overflowError=z,Q0("warn",`context overflow: ${z}`),await this.flushOutputAndStep(),this.innerController.abort(),!0;if(this.hasError=!0,Q0("error",`stream error: ${z}`),Z.onStreamError)r0(Z.onStreamError,o4(z));else console.error(`\x1B[31m${o4(z)}\x1B[0m`);return!1}}return!1}snapshot($,Z={}){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:$,...Z}}async finalize($){return await this.flushOutputAndStep(),this.settlePendingLoop(),this.snapshot(this.resolvedUsage($?await CW($):void 0))}async handleException($,Z){await this.applySlices(this.renderer.flushOnError()),this.assembler.flushStep(),this.settlePendingLoop();let J=this.resolvedUsage(Z?await CW(Z):void 0);if(this.params.abortSignal?.aborted)return this.snapshot(J,{userAborted:!0});if(nZ($)){let Q=this.assembler.hadAssistantText||this.assembler.hadTools||this.renderer.hadThinking;return Q0("warn",`provider stall: ${p3($)}`),this.stop.stall=!0,this.snapshot(J,{hasError:!1,userAborted:!1,emptyCompletion:!Q})}if($ instanceof Error&&$.name==="AbortError")return this.snapshot(J,{userAborted:!1});let z=$ instanceof Error?$.message:String($);if(Q0("error",z),K8(z))return this.stop.context=!0,this.overflowError=z,this.snapshot(J,{hasError:!1,contextPressure:!0,userAborted:!1});this.hasError=!0;let G=o4(z);if(this.params.cbs.onStreamError)r0(this.params.cbs.onStreamError,G);else if(G!==z)console.error(`\x1B[31m${G}\x1B[0m`);else console.error(`\x1B[31mError: ${z}\x1B[0m`);return this.snapshot(J,{hasError:!0,userAborted:!1,contextPressure:!1})}}async function jA($){let Z=new hW($),J;try{Z.attachAbort();let z=qA($.allTools,$.messages,$.taskState,$.loopGuard,$.memory),G=[$.systemPrompt,...z.stable].join(`
|
|
397
399
|
|
|
398
|
-
`);
|
|
399
|
-
… [diff 过长,已截断]`:z;return{ok:!0,diff:
|
|
400
|
+
`);o6($.messages,$.pruneBudget());let Q=UA(z.volatile),Y=Q?[...$.messages,Q]:$.messages;$.overhead.tokens=i3(G,$.allTools)+(Q?i3(String(Q.content)):0);let K=u5({runOverride:$.thinking,providerType:$.providerType,modelId:$.modelId}),X=()=>dj({model:$.model,system:G,messages:Y,allowSystemInMessages:!0,tools:$.allTools,stopWhen:rj($.maxSteps),maxRetries:3,abortSignal:Z.signal,...$.temperature!=null?{temperature:$.temperature}:{},...$.maxTokens!=null?{maxOutputTokens:$.maxTokens}:{},...$.topP!=null?{topP:$.topP}:{},onStepFinish({usage:P}){Z.onStepFinish(P)},onError({error:P}){Z.onStepError(P)}});J=P6.run(K,X);for await(let P of J.fullStream)if(await Z.handleEvent(P))break;return await Z.finalize(J)}catch(z){return Z.handleException(z,J)}finally{Z.detachAbort()}}async function mW($,Z,J,z,G,Q,Y){let K=u1(),X=p4(K,Z);return xW($,X,J,z,G,Q,Y)}async function vJ($,Z,J,z,G,Q,Y){return xW($,Z,J,z,G,Q,Y)}var aj=1e5,sj=40,ej=4,bW=1000,$A=8000,ZA=1200000,JA=120,zA=4,GA="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.",wW="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.",QA,IW=5242880,YA,u2,kW="本轮已达时间或步数预算,已让模型收尾并停止。发送消息可继续",SW="## Session state (reference only — not a to-do list, not part of the conversation)",FA="Error: tool call was interrupted before a result was returned.";var d4=C(()=>{h4();cZ();l();y2();_J();$8();m$();n$();P4();K1();b1();g1();LJ();g7();O9();C9();z8();UW();S4();m4();v4();k3();P4();QA=wW,YA={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},u2="NO_COLOR"in process.env?{dim:"",reset:""}:{dim:"\x1B[90m",reset:"\x1B[0m"}});var E9={};M0(E9,{pushTurn:()=>AA,popTurn:()=>DA,createUndoStack:()=>gJ,clearStack:()=>S9});function gJ(){return[]}function AA($,Z,J,z){return[...$,{start:Z,end:J,uiEnd:z}]}function DA($){if($.length===0)return null;return{turn:$[$.length-1],stack:$.slice(0,-1)}}function S9($){return[]}var cW={};M0(cW,{getWorkingTreeDiff:()=>uJ});import{execFile as OA}from"child_process";import{promisify as CA}from"util";async function uJ($=process.cwd(),Z=wA){try{await Z("git rev-parse --is-inside-work-tree",$)}catch{return{ok:!1,reason:"not_git",message:"当前目录不是 git 仓库"}}let J="",z="";try{J=await Z("git diff --stat",$),z=await Z("git diff",$)}catch(Q){return{ok:!1,reason:"error",message:Q instanceof Error?Q.message:String(Q)}}if(!z.trim())return{ok:!1,reason:"no_changes",message:"工作区无未提交变更"};let G=z.length>nW?z.slice(0,nW)+`
|
|
401
|
+
… [diff 过长,已截断]`:z;return{ok:!0,diff:J?`${J}
|
|
400
402
|
|
|
401
|
-
${
|
|
403
|
+
${G}`:G}}async function wA($,Z){let J=IA($),{stdout:z}=await bA(J[0],J.slice(1),{cwd:Z,encoding:"utf-8",timeout:1e4,maxBuffer:10485760});return z}function IA($){let Z=[],J="",z=null;for(let G of $)if(z)if(G===z)z=null;else J+=G;else if(G==='"'||G==="'")z=G;else if(G===" "){if(J)Z.push(J),J=""}else J+=G;if(J)Z.push(J);return Z}var nW=8000,bA;var hJ=C(()=>{bA=CA(OA)});var v9={};M0(v9,{snapshotTokenInfo:()=>TA});async function TA($,Z,J){let z=await e$(Z);return aY($,z.tokens,x1(J))}var x9=C(()=>{g1();m4()});function k($,Z){$.addMessage({id:`sys-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,role:"system",content:Z,timestamp:Date.now()})}async function pW($,Z,J,z,G,Q,Y,K){let{parseSlashArgs:X}=await Promise.resolve().then(() => (H3(),nQ)),P=X($),W=$.slice(1).trim().split(/\s+/),H=(P?.command||W[0]||"").toLowerCase(),q=P?[...P.tokens,...P.partial?[P.partial]:[]]:W.slice(1),U=q.join(" "),{truncateDisplay:M}=await Promise.resolve().then(() => wJ);switch(H){case"exit":case"quit":case"q":Y();break;case"new":K.startNewSession();break;case"undo":{let{popTurn:F}=await Promise.resolve().then(() => E9),N=F(K.undoStack);if(!N){k(Z,"没有可撤销的内容");break}K.setUndoStack(N.stack),J.splice(N.turn.start,N.turn.end-N.turn.start),Z.truncateMessages(N.turn.uiEnd),k(Z,"✓ 已撤销 1 轮");break}case"redo":{if(!K.lastUserMessage){k(Z,"没有可重发的消息");break}let F=K.lastUserMessage;return Z.addMessage({id:`user-${Date.now()}`,role:"user",content:F,timestamp:Date.now()}),J.push({role:"user",content:F}),"run"}case"diff":{let{getWorkingTreeDiff:F}=await Promise.resolve().then(() => (hJ(),cW)),N=await F();if(!N.ok){let f=N.reason==="not_git"?"非 git 仓库,无法显示 diff":N.reason==="no_changes"?"工作区无未提交变更":`diff 失败: ${N.message}`;k(Z,f)}else k(Z,N.diff);break}case"plan":{K.togglePlanMode(),k(Z,K.planMode?"✓ 计划模式已开启:仅只读工具可用,输出计划后再次输入 /plan 确认并执行":"✓ 已退出计划模式");break}case"reload":await K.reloadSystemPrompt();break;case"resume":case"sessions":{let F=U.trim();if(!F){K.openSessionPicker();break}K.applySession(F);break}case"rename":{let F=U.trim();if(!F){k(Z,"用法: /rename <标题>");break}let{saveSession:N,renameSession:f}=await Promise.resolve().then(() => (u$(),E4)),B=K.sessionId;if(!B)B=N(J,void 0,void 0,void 0,K.taskState),K.setSessionId(B);if(f(B,F))k(Z,`✓ 会话已重命名为: ${F}`);else k(Z,"重命名失败: 会话不存在");break}case"attach":case"image":{let F=U;if(!F){k(Z,"用法: /attach <图片路径>");break}let{loadImageParts:N}=await Promise.resolve().then(() => (d4(),xJ)),B=[{type:"text",text:""},...N([F],(_,V)=>{if(_==="not_found")k(Z,`⚠ 图片不存在: ${V}`);else if(_==="too_large")k(Z,`⚠ 图片超过 5MB 限制: ${V}`)})];if(B.length<=1)break;return J.push({role:"user",content:B}),Z.addMessage({id:`user-${Date.now()}`,role:"user",content:`[\uD83D\uDCCE 图片] ${F}`,timestamp:Date.now()}),"run"}case"compact":{let{compactMessages:F}=await Promise.resolve().then(() => (g1(),t3)),{estimateTokens:N}=await Promise.resolve().then(() => (g1(),t3)),{resolveModel:f}=await Promise.resolve().then(() => (h4(),uX)),{clearStack:B}=await Promise.resolve().then(() => E9);if(J.length<4)k(Z,"消息太少,无需压缩");else{k(Z,"⟳ 正在压缩上下文...");let _=f(z);K.setUndoStack(B(K.undoStack));let V=await F(J,_,{keepRecentTurns:2,taskGoal:K.taskState.goal||void 0});if(J.length=0,J.push(...V.messages),G)G.resetContext();k(Z,`✓ 已压缩 (约 ${N(J)} tokens)`);let{snapshotTokenInfo:A}=await Promise.resolve().then(() => (x9(),v9));Z.setTokenInfo(await A(G,z,J))}break}case"provider":{let{applyProviderSwitch:F,listProviderChoices:N}=await Promise.resolve().then(() => (R3(),fK));if(U){let f=F(U);if(!f.ok){k(Z,f.message);break}Q(f.defaultModel),K.setProvider(f.name),k(Z,`✓ 当前服务商已切换为: ${f.name}`);break}if(N().length===0){k(Z,"无已配置服务商,运行: min-agent setup");break}Z.showProviderPicker();break}case"model":{if(U){let F=await Promise.resolve().then(() => (l(),C1)),N=F.loadConfig(),f=F.getActiveProvider(N);if(f&&F.isBuiltinProvider(f)&&U!==F.BUILTIN_MODEL){k(Z,`内置服务商仅支持模型: ${F.BUILTIN_MODEL}`);break}if(f)f.defaultModel=U,F.saveConfig(N);Q(U),k(Z,`✓ 默认模型已设为: ${U}`)}else Z.showModelPicker();break}case"models":{let{fetchModels:F}=await Promise.resolve().then(() => (l(),C1)),{loadConfig:N,getActiveProvider:f}=await Promise.resolve().then(() => (l(),C1)),B=N(),_=f(B);if(!_?.baseURL||!_?.apiKey){k(Z,"未配置 Provider,运行: min-agent setup");break}k(Z,"正在获取模型列表...");let V=await F(_.baseURL,_.apiKey);if(V.length===0)k(Z,"无法获取模型列表");else{let A=V.map((O)=>{let v=O===_.defaultModel?" ← 默认":"";return` ${O}${v}`});k(Z,`可用模型 (${V.length}):
|
|
402
404
|
${A.join(`
|
|
403
|
-
`)}`)}break}case"memory":{let{takeScopeFlags:
|
|
405
|
+
`)}`)}break}case"memory":{let{takeScopeFlags:F}=await Promise.resolve().then(() => W2),{addMemory:N,loadMemories:f,defaultMemoryScope:B,formatMemoryLine:_,parseMemoryMode:V,resolveMemoryMode:A,setMemoryMode:O,setMemoryOverride:v,isMemoryEnabled:b}=await Promise.resolve().then(() => (b1(),i5)),{scope:D,rest:I}=F(q),R=I.length===1?V(I[0]):void 0;if(R){let m=D==="project"?"project":"global";O(R,m),v(R),k(Z,`✓ 记忆已${R==="on"?"开启":"关闭"}(${m==="project"?"项目":"全局"})`);break}let J0=I.join(" ").trim();if(J0){let m=D??B();N(J0,[],m);let $0=b()?"":"(当前未开启,下一轮对话不会用到;可用 /memory on 开启)";k(Z,`✓ 已保存${m==="project"?"项目":"全局"}记忆: "${J0}"${$0}`)}else{let m=A(),$0=m.source==="cli"?"本次启动参数":m.source==="project"?"项目":m.source==="global"?"全局":"默认",x=`记忆:${m.memory==="on"?"开":"关"}(${$0})`,o=(D?[D]:["project","global"]).map((p)=>{let z0=f(p),u=p==="project"?"项目记忆":"全局记忆";if(z0.length===0)return`${u}: 无`;let w=z0.map((y0,Y0)=>_(y0,Y0));return`${u} (${z0.length}):
|
|
404
406
|
${w.join(`
|
|
405
|
-
`)}`}),S=!
|
|
407
|
+
`)}`}),S=!D&&f("project").length===0&&f("global").length===0;k(Z,[x,S?"无已保存的记忆":o.join(`
|
|
406
408
|
`),"设置: /memory on|off [--project]","保存: /memory <文本> [--project]"].join(`
|
|
407
|
-
`))}break}case"path":case"pwd":k(
|
|
408
|
-
`));break}case"budget":{let{takeScopeFlags:
|
|
409
|
-
设置: /budget <金额> 或 /budget <金额> --project`);break}case"permission":{let{takeScopeFlags:
|
|
410
|
-
`));break}let
|
|
411
|
-
${
|
|
412
|
-
`)}`)}break}case"skills":{let{discoverSkills:
|
|
413
|
-
可用: ${
|
|
414
|
-
`));break}if(A==="info"){let
|
|
415
|
-
可用: ${
|
|
416
|
-
`));break}if(A&&A!=="list"){k(
|
|
417
|
-
${
|
|
409
|
+
`))}break}case"path":case"pwd":k(Z,process.cwd());break;case"paste":{let{getClipboardImage:F}=await Promise.resolve().then(() => (B3(),sQ)),N=F();if(!N){k(Z,"剪贴板中未找到图片");break}k(Z,`\uD83D\uDCCE 剪贴板图片 (${(N.data.length/1024).toFixed(1)} KB)`);let f=U||"What's in this image?",B=[{type:"text",text:f},{type:"image",image:N.data,mimeType:N.mimeType}];return J.push({role:"user",content:B}),Z.addMessage({id:`user-${Date.now()}`,role:"user",content:`${f} [\uD83D\uDCCE 图片]`,timestamp:Date.now()}),"run"}case"tokens":{let{getContextWindowInfo:F}=await Promise.resolve().then(() => (m4(),iZ)),{getModelPrice:N,estimateCost:f,formatCost:B}=await Promise.resolve().then(() => (y2(),a3)),{estimateTokens:_}=await Promise.resolve().then(() => (g1(),t3)),V=await F(z),A=_(J),O=G.lastInputTokens>0?G.lastInputTokens:A,v=V.tokens>0&&O>0?Math.round(O/V.tokens*100):0,b=await N(z??""),D=f({inputTokens:G.totalInputTokens,outputTokens:G.totalOutputTokens},b),I=G.lastInputTokens>0?"":",按对话内容估算",R=V.source==="fallback"?`,未读到接口窗口,按 ${V.tokens} 默认`:"";k(Z,[`上下文: ${O} / ${V.tokens} tokens (${v}%${I}${R})`,`累计: ${G.totalInputTokens} in / ${G.totalOutputTokens} out`,...D!=null?[`成本: 约 ${B(D)}`]:[],`消息: ${J.length}`].join(`
|
|
410
|
+
`));break}case"budget":{let{takeScopeFlags:F}=await Promise.resolve().then(() => W2),{getBudgetSnapshot:N,setBudgetMaxCost:f}=await Promise.resolve().then(() => (l(),C1)),{getModelPrice:B,estimateCost:_,formatCost:V}=await Promise.resolve().then(() => (y2(),a3)),{scope:A,rest:O}=F(q),v=O.join(" ").trim();if(v){let x=parseFloat(v);if(Number.isNaN(x)||x<=0){k(Z,"用法: /budget <USD 金额> [--project]");break}let T=A==="project"?"project":"global";f(x,T),k(Z,`✓ 预算上限已设为: $${x}(${T==="project"?"项目":"全局"})`);break}let b=N(),D=b.maxCostUSD,I=b.source==="project"?"项目":b.source==="global"?"全局":null,R=await B(z??""),J0=_({inputTokens:G.totalInputTokens,outputTokens:G.totalOutputTokens},R),m=J0!=null?`约 ${V(J0)}`:"--",$0=D!=null?`上限 $${D}${I?`(${I})`:""}`:"未设置上限";k(Z,`预算: 已用${m} / ${$0}
|
|
411
|
+
设置: /budget <金额> 或 /budget <金额> --project`);break}case"permission":{let{takeScopeFlags:F}=await Promise.resolve().then(() => W2),{getPermissionSnapshot:N,parsePermissionMode:f,permissionModeLabel:B,setPermissionMode:_}=await Promise.resolve().then(() => (l(),C1)),{getPermissionOverride:V,setPermissionOverride:A}=await Promise.resolve().then(() => (Z$(),S8)),{scope:O,rest:v}=F(q),b=(R)=>R==="cli"?"本次启动参数":R==="project"?"项目":R==="global"?"全局":"默认";if(v.length===0){let R=N(),J0=V(),m=J0??R.permission,$0=J0?"cli":R.source;k(Z,[`当前确认: ${B(m)}(${b($0)})`,"设置: /permission ask|accept-edits|allow-all [--project]"].join(`
|
|
412
|
+
`));break}let D=f(v[0]);if(!D||v.length>1){k(Z,"用法: /permission ask|accept-edits|allow-all [--project]");break}let I=O==="project"?"project":"global";_(D,I),A(D),k(Z,`✓ 确认已设为${B(D)}(${I==="project"?"项目":"全局"})`);break}case"think":case"thinking":{let{takeScopeFlags:F}=await Promise.resolve().then(() => W2),{parseThinkingEffort:N,thinkingEffortLabel:f,thinkingChoicesForModel:B,setThinkingEffort:_,setThinkingOverride:V}=await Promise.resolve().then(() => (K1(),h5)),{scope:A,rest:O}=F(q);if(O.length===0){Z.showThinkPicker(A==="project"?"project":"global");break}let v=N(O[0]),b=B(z);if(!v||O.length>1){k(Z,`用法: /think [${b.join("|")}] [--project]`);break}if(!b.includes(v)){k(Z,`该模型支持: ${b.join(", ")}`);break}let D=A==="project"?"project":"global";_(v,D),V(v),k(Z,`✓ 思考强度已设为 ${f(v)}(${D==="project"?"项目":"全局"})`);break}case"ctx":{let{getActiveProvider:F,getEffectiveConfig:N}=await Promise.resolve().then(() => (l(),C1)),{CTX_CHOICES:f,parseCtxChoice:B,setOllamaContextChoice:_,ctxChoiceLabel:V}=await Promise.resolve().then(() => (f2(),UK));if(F(N())?.type!=="ollama"){k(Z,"窗口档位仅本地模型可用");break}if(q.length===0){Z.showCtxPicker();break}let A=B(q[0]);if(!A||q.length>1){k(Z,`用法: /ctx [${f.join("|")}]`);break}if(!_(A).ok){k(Z,"窗口档位仅本地模型可用");break}K.refreshTokenBar(),k(Z,`✓ 上下文窗口已设为${V(A)}`);break}case"mcp":{let{loadMcpConfig:F}=await Promise.resolve().then(() => (m$(),b2)),{getMcpStatus:N}=await Promise.resolve().then(() => (m$(),b2)),f=F(),B=Object.entries(f.mcpServers);if(B.length===0)k(Z,"无 MCP 服务器配置");else{let _=N(),V=B.map(([A,O])=>{let v=O.enabled===!1,b=_[A],D=b?.connected??!1,I=b?.tools.length??0,R=[I>0?`${I} tools`:"",(b?.resource_count??0)>0?`${b.resource_count} resources`:"",(b?.prompt_count??0)>0?`${b.prompt_count} prompts`:""].filter(Boolean).join(", "),J0=v?"disabled":D?"connected":"disconnected",m=!v&&!D&&b?.error?` — ${b.error}`:"";return` ${A}: ${J0}${R?` (${R})`:""}${m}`});k(Z,`MCP 服务器 (${B.length}):
|
|
413
|
+
${V.join(`
|
|
414
|
+
`)}`)}break}case"skills":{let{discoverSkills:F,getAllSkills:N,getSkill:f,getStaleDisabledSkills:B,setSkillEnabled:_}=await Promise.resolve().then(() => (n$(),m6));F({silent:!0});let V=q.filter(Boolean),A=V[0],O=N().sort((D,I)=>D.name.localeCompare(I.name));if(A==="enable"||A==="disable"){let D=V.includes("--project")?"project":"global",I=V.slice(1).filter((x)=>x!=="--project"&&x!=="--global");if(I.length===0){k(Z,`用法: /skills ${A} <name...> [--project]`);break}let R=new Set(O.map((x)=>x.name)),J0=I.filter((x)=>!R.has(x));if(J0.length>0){k(Z,`未找到 skill: ${J0.join(", ")}
|
|
415
|
+
可用: ${R.size?[...R].join(", "):"无"}`);break}let $0=_(I,A==="enable",D).filter((x)=>x.blockedBy).map((x)=>` ⚠ ${x.name} 仍为${x.enabled?"启用":"禁用"}(被 ${x.blockedBy} 范围覆盖)`);k(Z,[`✓ 已${A==="enable"?"启用":"禁用"}(${D}): ${I.join(", ")}`,...$0].join(`
|
|
416
|
+
`));break}if(A==="info"){let D=V[1],I=D?f(D):void 0;if(!I){k(Z,`未找到 skill: ${D??"(未指定)"}
|
|
417
|
+
可用: ${O.length?O.map(($0)=>$0.name).join(", "):"无"}`);break}let R=I.enabled?"enabled":`disabled(${I.disabledScope==="project"?"proj":"glob"})`,J0=[`Name: ${I.name}`,`Status: ${R}`,...I.builtin?["Source: 内置"]:[],...I.version?[`Version: ${I.version}`]:[],`Description: ${I.description.replace(/\s+/g," ")}`,`Location: ${I.location}`,...I.allowedTools.length?[`Tools: ${I.allowedTools.join(", ")}`]:[],...I.requiredBins.length?[`Requires: ${I.requiredBins.join(", ")}`]:[]],m=I.content.trim();k(Z,[...J0,...m?["","--- Content ---","",m.slice(0,4000)]:[]].join(`
|
|
418
|
+
`));break}if(A&&A!=="list"){k(Z,"用法: /skills [list|info <name>|enable <name...> [--project]|disable <name...> [--project]]");break}let v=B();if(O.length===0&&v.length===0){k(Z,"无可用 skills。添加 SKILL.md 到 .min-agent/skills/<name>/");break}let b=O.map((D)=>{let I=D.enabled?"enabled":`disabled(${D.disabledScope==="project"?"proj":"glob"})`,R=D.builtin?" 内置":"";return` ${D.name} ${I}${R} ${M(D.description.replace(/\s+/g," "),56)}`});if(v.length>0)b.push(` ⚠ disabledSkills/enabledSkills 中无对应 skill: ${v.join(", ")}`);k(Z,`Skills (${O.filter((D)=>D.enabled).length} enabled / ${O.length}):
|
|
419
|
+
${b.join(`
|
|
418
420
|
`)}
|
|
419
|
-
切换: /skills disable <name> [--project]`);break}case"sandbox":{let{takeScopeFlags:
|
|
420
|
-
`));break}let
|
|
421
|
-
/sandbox network allow|deny [--project]`);break}
|
|
422
|
-
`));break}case"help":k(
|
|
423
|
-
`));break;default:k(f,`未知命令: /${W},输入 /help 查看可用命令`)}}function rX($){let f=null;return{run:async()=>{let K=$.messages.length,G=$.tui.messageCount(),Q=!1;f=new AbortController,$.tui.setRunning(!0,"思考中...");let{summarizeToolCall:Y,summarizeToolResult:P,toolResultText:X}=await Promise.resolve().then(() => TZ),{getContextWindowInfo:W}=await Promise.resolve().then(() => (h4(),t7)),{getModelPrice:H,estimateCost:U,formatCost:M}=await Promise.resolve().then(() => (k2(),s8)),{runOnceWithSystem:N,emptyResponseMessage:q,WRAP_UP_MESSAGE:L}=await Promise.resolve().then(() => (r4(),xZ)),{clearStack:F,pushTurn:V}=await Promise.resolve().then(() => v3),{setSubAgentListener:B}=await Promise.resolve().then(() => (SZ(),RZ)),{LOOP_HALT_MESSAGE:A}=await Promise.resolve().then(() => (C3(),ZX)),{createSaveThrottle:j}=await Promise.resolve().then(() => kZ),{snapshotTokenInfo:v}=await Promise.resolve().then(() => (x3(),u3)),O=j(()=>$.persist?.()),b=$.tracker.totalInputTokens,T=$.tracker.totalOutputTokens,I=null,Z0=0,h=async()=>{let S=++Z0,p=await v($.tracker,$.getModel(),$.messages);if(S!==Z0)return;$.tui.setTokenInfo(p)},$0=()=>{if(I!=null)return;I=setTimeout(()=>{I=null,h()},50)},u=async()=>{if(I!=null)clearTimeout(I),I=null;await h()},y=$.tracker.subscribe($0);h();let r={onAssistantDisplayDelta:(S)=>$.tui.appendToLast(S),onThinkingDelta:(S)=>{$.tui.setRunning(!0,"推理中..."),$.tui.appendToThinking(S)},onToolCall:(S,p,z0)=>{$.tui.setRunning(!0,`执行 ${S}...`),$.tui.addMessage({id:`tool-${z0||`${Date.now()}-${Math.random().toString(36).slice(2,6)}`}`,role:"tool",content:Y(S,p),toolName:S,toolCallId:z0,timestamp:Date.now()})},onToolResult:(S,p,z0)=>{$.tui.setRunning(!0,"思考中..."),$.tui.setToolResult(z0.toolCallId,S,P(S,p,z0.isError),X(p),z0.isError)},onStreamError:(S)=>{$.tui.addMessage({id:`err-${Date.now()}`,role:"system",content:`错误: ${S}`,timestamp:Date.now()})},onCompaction:(S)=>{if(Q=!0,$.setUndoStack(F($.getUndoStack())),S==="compacting_start")$.tui.addMessage({id:`compact-${Date.now()}`,role:"system",content:"正在整理过长的对话记录…",timestamp:Date.now()});else if(S.startsWith("compacted_ok"))$.tui.addMessage({id:`compact-ok-${Date.now()}`,role:"system",content:"✓ 已整理对话记录,继续执行",timestamp:Date.now()})},onRetryNotice:(S)=>{$.tui.addMessage({id:`retry-${Date.now()}`,role:"system",content:S.kind==="wrap_up"?"⟳ 本轮预算用尽,正在收尾…":`⟳ 模型返回空响应,重试 ${S.attempt}/${S.maxAttempts}…`,timestamp:Date.now()})},onRunFinish:async(S)=>{if(f=null,$.tui.setRunning(!1),await u(),S.aborted)return;if(S.budgetExceeded)$.tui.addMessage({id:`budget-${Date.now()}`,role:"system",content:"⚠ 已达到预算上限。/budget 查看或调高",timestamp:Date.now()});let p=Math.max(0,$.tracker.totalInputTokens-b),z0=Math.max(0,$.tracker.totalOutputTokens-T),g=$.tracker.lastInputTokens;if(p>0||z0>0||g>0){let w=await W($.getModel()),R0=w.tokens>0&&g>0?Math.round(g/w.tokens*100):null,G0=await H($.getModel()??""),H0=U({inputTokens:p,outputTokens:z0},G0),f0=[`Done in ${S.stepCount} step(s)`,`Tokens: ${p} in / ${z0} out / ${p+z0} total`,...R0!=null?[`Context: ${R0}%`]:[],...H0!=null?[`约 ${M(H0)}`]:[]];$.tui.addMessage({id:`done-${Date.now()}`,role:"system",content:f0.join(" | "),timestamp:Date.now()})}if(S.maxStepsReached)$.tui.addMessage({id:`maxsteps-${Date.now()}`,role:"system",content:"⚠ 已达到自动续跑上限,发送消息继续",timestamp:Date.now()});if(S.stopped)$.tui.addMessage({id:`stopped-${Date.now()}`,role:"system",content:`⚠ ${A}`,timestamp:Date.now()});else if(S.wrapUp)$.tui.addMessage({id:`wrapup-${Date.now()}`,role:"system",content:`⚠ ${L}`,timestamp:Date.now()});else if(S.emptyResponse)$.tui.addMessage({id:`empty-${Date.now()}`,role:"system",content:`⚠ ${q(S.emptyAttempts??0)}`,timestamp:Date.now()});else if(S.incomplete)$.tui.addMessage({id:`incomplete-${Date.now()}`,role:"system",content:"还没有完整回复,发送消息可继续",timestamp:Date.now()})}};try{B((p)=>{if(p.phase!=="call")return;$.tui.appendToolChild(p.parentToolCallId,{name:p.name,summary:Y(p.name,p.input)})});let S={providerName:$.getProvider(),taskState:$.getTaskState(),onStepPersist:()=>O.request(),...$.getPlanMode()?{planMode:!0}:{}};await N($.messages,$.getSystemPrompt(),$.getModel(),f?.signal,r,$.tracker,S)}catch(S){if(!f)return;let p=S instanceof Error?S.message:String(S);r.onStreamError(p)}finally{if(y(),I!=null)clearTimeout(I),I=null;if(B(null),O.cancel(),!Q)$.setUndoStack(V($.getUndoStack(),K,$.messages.length,G));f=null,$.tui.setRunning(!1),await u()}},abort:(K)=>{if(!f)return!1;return Promise.resolve().then(() => (i6(),XP)).then((G)=>G.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 g3($){return typeof $==="object"&&$!==null}function Xf($){if(typeof $==="string")return $;if(!Array.isArray($))return"";let f=[];for(let Z of $)if(g3(Z)&&Z.type==="text"&&typeof Z.text==="string")f.push(Z.text);return f.join("")}function TA($){if(!Array.isArray($))return!1;return $.some((f)=>g3(f)&&(f.type==="image"||f.type==="file"))}function yA($){if(!g3($))return $;if(($.type==="text"||$.type==="json")&&"value"in $)return $.value;return $}function IA($){if(Xf($).trim())return Xf($);if(TA($))return"[\uD83D\uDCCE 图片]";return null}function n3($){for(let f=$.length-1;f>=0;f--){let Z=$[f];if(Z?.role!=="user")continue;if(Xf(Z.content).trim())return Xf(Z.content)}return null}function cZ($){let f=[];for(let Z=0;Z<$.length;Z++){let z=$[Z];if(z.role==="assistant"){f.push(...kA(z,Z));continue}let J=RA(z,Z);if(J)f.push(J)}return f}function kA($,f){let Z=Xf($.content);if(!Z)return[];let{slices:z}=OZ(Z);if(z.every((G)=>G.type==="display"))return[{id:`hyd-${f}-assistant`,role:"assistant",content:Z,timestamp:0}];let J=[],K=0;for(let G of z){if(G.type==="display"){if(!G.text.trim())continue;J.push({id:`hyd-${f}-assistant-${K++}`,role:"assistant",content:G.text,timestamp:0});continue}let Q=G.block.query,Y=G.block.kind==="results"?G.block.body:G.block.query,P={query:Q};J.push({id:`hyd-${f}-search-${K++}`,role:"tool",content:Jf("search_web",P),toolName:"search_web",toolCallId:`xml-search-hyd-${f}-${K}`,toolResult:Y,toolResultSummary:T3("search_web",Y),timestamp:0})}return J}function RA($,f){if($.role==="user"){let Z=IA($.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(!g3(Z)||Z.type!=="tool-result")continue;let z=typeof Z.toolName==="string"?Z.toolName:"";if(!z)continue;let J=yA(Z.output),K=u2(J),G=typeof Z.toolCallId==="string"?Z.toolCallId:void 0;return{id:`hyd-${f}-tool`,role:"tool",content:z,toolName:z,toolCallId:G,toolResult:K,toolResultSummary:T3(z,J),timestamp:0}}return null}return null}var mZ=C(()=>{zf()});function oX(){let $=Promise.resolve(),f=0,Z=0,z=()=>{return};return{run(J,K){let G=f;Z++;let Q=()=>G!==f?Promise.resolve(K()):J(),Y=$.then(Q,Q);return $=Y.then(z,z),Y.finally(()=>{Z--})},cancelAll(){f++},get size(){return Z}}}function dX($){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 pZ($){if($==="running")return"请先等待当前回合结束或按 Esc 取消";if($==="current")return"已是当前会话";return"会话不存在"}function lX($){if($.running)return{ok:!1,reason:"running"};if(!$.sessionId&&$.messageCount===0)return{ok:!1,reason:"already_new"};return{ok:!0}}function iX($){if($==="running")return"请先等待当前回合结束或按 Esc 取消";return"已是新会话"}var tX={};M0(tX,{runTui:()=>cA});function SA(){S$("provider",($)=>{if($.length>0)return[];return L2().map((f)=>({value:f.name,description:f.current?`${f.baseURL}(当前)`:f.baseURL}))})}function EA(){let $=()=>z4().map((f)=>({value:f.id,description:f.title}));S$("sessions",$),S$("resume",$)}function vA(){S$("ctx",($)=>{if($.length>0)return[];return F$.map((f)=>f==="auto"?{value:f,description:"按模型探测"}:{value:f})})}function uA(){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=s(K0())?.defaultModel;return[...l1(K).map((G)=>({value:G})),...J]}return J};S$("think",$),S$("thinking",$)}function xA(){S$("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 gA(){S$("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 nA(){S$("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 hA(){S$("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 q1().map((J)=>({value:J.name,description:J.description}));if(f!=="enable"&&f!=="disable")return[];let Z=q1();return[...(f==="enable"?[...Z.filter((J)=>!J.enabled).map((J)=>({value:J.name,description:J.description})),...w2().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 cA($){let{modelId:f,resumeSessionId:Z,images:z,providerName:J,initialPrompt:K}=$;await g4(),y$(),hA(),gA(),uA(),vA(),SA(),xA(),nA(),EA();let G=await F1(),Q=t(),Y=u1(),P=p4(Y,G),X=[],W=Z,H=f??s(Q)?.defaultModel,U=J;if(H)Q2(H);let M=new P4,N=x$(),q=gZ(),L=null,F=!1;if(Z){let y=K$(Z);if(y)X=y.messages,W=Z,w6(y.taskState,N)}let V=null,B=new X7({onSubmit:async(y)=>{let r=y.display;if(r.trim().startsWith("/")){if(await pX(r,B,X,H,M,(p)=>{H=p,B.setModel(p),j()},Z0,{undoStack:q,setUndoStack:(p)=>{q=p},lastUserMessage:L,setLastUserMessage:(p)=>{L=p},sessionId:W,setSessionId:(p)=>{W=p},planMode:F,togglePlanMode:()=>{F=!F},reloadSystemPrompt:async()=>{let p=await F1();P=p4(u1(),p),k(B,`✓ 已重载规则(${p.join("").length} 字符)`)},applySession:v,startNewSession:O,openSessionPicker:b,taskState:N,refreshTokenBar:j,setProvider:(p)=>{U=p}})==="run"&&V)await V.run(),A();return}if(L=r,B.addMessage({id:`user-${Date.now()}`,role:"user",content:r,timestamp:Date.now()}),X.push({role:"user",content:y.content}),V)await V.run(),A()},onNotice:(y)=>{k(B,y)},onConfirm:(y)=>{if(B.hideConfirm(),o4)o4(y),o4=null},onQuestionAnswer:(y)=>{if(B.hideQuestion(),d4)d4(y),d4=null},onModelPick:(y)=>{B.hideModelPicker();let r=t(),S=s(r);if(S)S.defaultModel=y,Promise.resolve().then(() => (l(),b1)).then((p)=>p.saveConfig(r));H=y,B.setModel(y),j(),k(B,`✓ 默认模型已设为: ${y}`)},onModelCancel:()=>{B.hideModelPicker()},onThinkPick:(y,r)=>{i1(y,r),G2(y),B.hideThinkPicker(),k(B,`✓ 思考强度已设为 ${b$(y)}(${r==="project"?"项目":"全局"})`)},onThinkCancel:()=>{B.hideThinkPicker()},onCtxPick:(y)=>{let r=R4(y);if(B.hideCtxPicker(),!r.ok){k(B,"窗口档位仅本地模型可用");return}j(),k(B,`✓ 上下文窗口已设为${f4(y)}`)},onCtxCancel:()=>{B.hideCtxPicker()},onProviderPick:(y)=>{B.hideProviderPicker();let r=$7(y);if(!r.ok){k(B,r.message);return}if(U=r.name,H=r.defaultModel,B.setModel(r.defaultModel),j(),r.defaultModel)Q2(r.defaultModel);k(B,`✓ 当前服务商已切换为: ${r.name}`)},onProviderCancel:()=>{B.hideProviderPicker()},onSessionPick:(y)=>{B.hideSessionPicker(),v(y)},onSessionCancel:()=>{B.hideSessionPicker()},onToggleSelectionMode:()=>{B.toggleSelectionMode()},onExitSelectionMode:()=>{B.setSelectionMode(!1)},onExit:()=>{Z0()}},f??s(Q)?.defaultModel,W);V=rX({tui:B,messages:X,tracker:M,getModel:()=>H,getProvider:()=>U,getPlanMode:()=>F,getUndoStack:()=>q,setUndoStack:(y)=>{q=y},getSystemPrompt:()=>P,getTaskState:()=>N,persist:()=>A()});function A(){if(X.length===0)return;try{W=w$(X,W,void 0,void 0,N)}catch{}}async function j(){let{snapshotTokenInfo:y}=await Promise.resolve().then(() => (x3(),u3));B.setTokenInfo(await y(M,H,X))}function v(y){let r=dX({running:Boolean(V?.getController()),currentId:W,targetId:y,exists:Boolean(K$(y))});if(!r.ok){k(B,pZ(r.reason));return}if(X.length>0)W=w$(X,W,void 0,void 0,N);let S=K$(y);if(!S){k(B,pZ("missing"));return}X.length=0,X.push(...S.messages),w6(S.taskState,N),W=y,q=E3(q),M.reset(),L=n3(S.messages),B.setSessionId(y),B.update({messages:cZ(S.messages)}),j(),k(B,`✓ 已切换到: ${S.meta.title}`)}function O(){let y=lX({running:Boolean(V?.getController()),sessionId:W,messageCount:X.length});if(!y.ok){k(B,iX(y.reason));return}if(X.length>0)W=w$(X,W,void 0,void 0,N);X.length=0,z7(N),W=void 0,q=E3(q),M.reset(),L=null,B.setSessionId(void 0),B.update({messages:[]}),j(),k(B,"✓ 已新建会话")}function b(){if(z4().length===0){k(B,"无已保存的会话");return}B.showSessionPicker()}If((y)=>rZ.run(()=>new Promise((r)=>{o4=r,B.showConfirm(y)}),()=>!1)),kf((y,r,S)=>rZ.run(()=>new Promise((p)=>{d4=p,B.showQuestion(y,r,Boolean(S))}),()=>null));let T,I=new Promise((y)=>{T=y}),Z0=()=>{if(B.setSelectionMode(!1),A(),V?.getController()){if(YZ(),rZ.cancelAll(),o4)o4(!1),o4=null,B.hideConfirm();if(d4)d4(null),d4=null,B.hideQuestion();V.getController().abort(),B.setRunning(!1),B.addMessage({id:`sys-${Date.now()}`,role:"system",content:"(已取消)",timestamp:Date.now()})}else T?.()};if(B.start(),X.length>0)B.update({messages:cZ(X)});await j();let h=K?.trim()??"",$0=(y,r)=>{if(y==="not_found")k(B,`⚠ 图片不存在: ${r}`);else if(y==="too_large")k(B,`⚠ 图片超过 5 MB 限制: ${r}`);else k(B,`\uD83D\uDCCE ${r}`)};if(z&&z.length>0){let y=[{type:"text",text:h},...S3(z,$0)];if(y.length>1||h){if(X.push({role:"user",content:y}),B.addMessage({id:`user-${Date.now()}`,role:"user",content:h?h:`[\uD83D\uDCCE 图片] ${z.join(", ")}`,timestamp:Date.now()}),h)L=h;await V.run(),A()}}else if(h)L=h,B.addMessage({id:`user-${Date.now()}`,role:"user",content:h,timestamp:Date.now()}),X.push({role:"user",content:h}),await V.run(),A();let u=()=>{if(V?.getController())Z0()};process.on("SIGINT",u),await I,process.off("SIGINT",u);try{A()}finally{If(null),kf(null),B.destroy(),await Q4()}}var o4=null,d4=null,rZ;var aX=C(()=>{mQ();h$();c$();H8();Y4();v1();S4();r4();i6();f$();l();$f();g$();mZ();G1();B2();k8();rZ=oX()});var sX={};M0(sX,{startTuiSession:()=>oZ});async function oZ($){if(!z1()){let z=Boolean(process.stdin.isTTY&&process.stdout.isTTY);if(!PK(!1,z))throw new a("Not configured.",{hint:"Run: min-agent setup"});let{offerInteractiveSetup:J}=await Promise.resolve().then(() => (X5(),VK));if(await J("session-gate"),!z1())throw new a("Not configured.",{hint:"Run: min-agent setup"})}let{runTui:f}=await Promise.resolve().then(() => (aX(),tX)),Z=$.positionals.join(" ").trim();await f({modelId:$.model,providerName:$.provider,resumeSessionId:$.resume,images:$.images,initialPrompt:Z||void 0})}var dZ=C(()=>{l();H$();J5()});function JW($=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 KW}from"crypto";function lZ(){let $=process.env.MIN_AGENT_SERVE_CORS;return $==="1"||$==="true"}function m3(){if(lZ())return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization"};return{}}function p3($){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 _($,f,Z){let z={"Content-Type":"application/json; charset=utf-8",...m3()};$.writeHead(f,z),$.end(JSON.stringify(Z))}function B$($){try{return decodeURIComponent($)}catch{return null}}function sA($){return new Promise((f,Z)=>{let z=[],J=0,K=setTimeout(()=>{$.destroy(),Z(Error("body_timeout"))},aA);$.on("data",(G)=>{if(J+=G.length,J>GW){clearTimeout(K),$.removeAllListeners("data"),$.pause(),Z(Error("body_too_large"));return}z.push(G)}),$.on("end",()=>{clearTimeout(K),f(Buffer.concat(z).toString("utf-8"))}),$.on("error",(G)=>{clearTimeout(K),Z(G)})})}async function D0($){let f;try{f=await sA($)}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 O0($,f){if(f.status===413)$.shouldKeepAlive=!1;_($,f.status,f.status===413?{error:f.error,max_bytes:GW}:{error:f.error})}function $1($,f){try{if($.writableEnded)return;$.write(`data: ${JSON.stringify(f)}
|
|
424
|
-
|
|
425
|
-
`)}catch{}}function
|
|
426
|
-
… [truncated ${$.length-
|
|
427
|
-
`).length}),!0;if($.method==="POST"&&(J==="/v1/chat"||J==="/v1/code"))return await zb(Z,$,f),!0;if($.method==="POST"&&J==="/v1/chat/redo"){let K=await D0($);if(!K.ok)return O0(f,K),!0;let G=K.value,Q=typeof G.session_id==="string"?G.session_id:void 0;if(!Q)return _(f,400,{error:"missing_session_id"}),!0;let Y=r3(G);if(!Y.ok)return _(f,400,{error:Y.error,detail:Y.detail}),!0;let P=l3(G);if(!P.ok)return _(f,400,{error:P.error,detail:P.detail}),!0;if(Z.activeChats>=l4)return _(f,429,{error:"too_many_concurrent_requests",detail:`Max ${l4} concurrent chats`}),!0;Z.activeChats++;try{await y6(Q,async()=>{let X=K$(Q);if(!X){_(f,404,{error:"session_not_found",session_id:Q});return}let W=n3(X.messages);if(!W){_(f,400,{error:"no_user_message"});return}await qf(Z,{res:f,messages:[...X.messages,{role:"user",content:W}],modelId:typeof G.model==="string"?G.model:void 0,stream:G.stream===!0,sessionId:Q,runOptions:Mf(G),autoApprove:G.auto_approve!==!1,taskState:X.taskState??x$(),sandboxTighten:Y.policy})})}finally{Z.activeChats--}return!0}if($.method==="POST"&&J==="/v1/approvals"){let K=await D0($);if(!K.ok)return O0(f,K),!0;let G=K.value.id?.trim();if(!G)return _(f,400,{error:"missing_id"}),!0;if(typeof K.value.accepted!=="boolean")return _(f,400,{error:"missing_accepted"}),!0;if(!Z.approvalGate.resolveConfirm(G,K.value.accepted))return _(f,404,{error:"unknown_approval_id",id:G}),!0;return _(f,200,{ok:!0,id:G,accepted:K.value.accepted}),!0}if($.method==="POST"&&J==="/v1/answers"){let K=await D0($);if(!K.ok)return O0(f,K),!0;let G=K.value.id?.trim();if(!G)return _(f,400,{error:"missing_id"}),!0;let Q=K.value.answer===void 0?null:K.value.answer;if(Q!==null&&typeof Q!=="string")return _(f,400,{error:"invalid_answer"}),!0;if(!Z.approvalGate.resolveQuestion(G,Q))return _(f,404,{error:"unknown_answer_id",id:G}),!0;return _(f,200,{ok:!0,id:G}),!0}if($.method==="POST"&&J==="/v1/paste"){if($.headers["content-type"]?.split(";")[0]?.trim()!=="application/json")return _(f,415,{error:"unsupported_media_type"}),!0;if(Z.activeChats>=l4)return _(f,429,{error:"too_many_concurrent_requests",detail:`Max ${l4} concurrent chats`}),!0;let K=await D0($);if(!K.ok)return O0(f,K),!0;let G=K.value;if(!G.image_base64)return _(f,400,{error:"missing_image_base64"}),!0;let Q=r3(G);if(!Q.ok)return _(f,400,{error:Q.error,detail:Q.detail}),!0;let Y=l3(G);if(!Y.ok)return _(f,400,{error:Y.error,detail:Y.detail}),!0;let P=Buffer.from(G.image_base64,"base64"),X=G.mime_type??"image/png",W=G.message??"What's in this image?",H=G.model,U=G.session_id,M=G.stream===!0;Z.activeChats++;try{await y6(U,async()=>{let N=[],q;if(U){let L=K$(U);if(!L){_(f,404,{error:"session_not_found",session_id:U});return}N=[...L.messages],q=L.taskState}N.push({role:"user",content:[{type:"text",text:W},{type:"image",image:P,mimeType:X}]}),await qf(Z,{res:f,messages:N,modelId:H,stream:M,sessionId:U,runOptions:Mf(G),autoApprove:G.auto_approve!==!1,taskState:q??x$(),sandboxTighten:Q.policy})})}finally{Z.activeChats--}return!0}if($.method==="POST"&&J==="/v1/chat/compact"){let K=await D0($);if(!K.ok)return O0(f,K),!0;let G=K.value;if(!G.session_id)return _(f,400,{error:"missing_session_id"}),!0;let Q=K$(G.session_id);if(!Q)return _(f,404,{error:"session_not_found"}),!0;let Y=s$(),P=await o6(Q.messages,Y,{taskGoal:Q.taskState?.goal});if(P.compacted)w$(P.messages,G.session_id);return _(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 O0(f,K),!0;let G=K.value;if(!G.session_id)return _(f,400,{error:"missing_session_id"}),!0;let Q=K$(G.session_id);if(!Q)return _(f,404,{error:"session_not_found"}),!0;let Y=-1;for(let P=Q.messages.length-1;P>=0;P--)if(Q.messages[P].role==="user"){Y=P;break}if(Y===-1)return _(f,400,{error:"no_user_message"}),!0;return Q.messages=Q.messages.slice(0,Y+1),w$(Q.messages,G.session_id),_(f,200,{ok:!0,message_count:Q.messages.length,messages:Q.messages}),!0}return!1};var XW=C(()=>{Y4();g$();r4();mZ();v1();n4();S4();U4()});var WW=async($,f,Z,z,J)=>{if($.method==="GET"&&J==="/v1/sessions"){let K=z4();return _(f,200,{sessions:K}),!0}if($.method==="DELETE"&&J.startsWith("/v1/sessions/")){let K=B$(J.slice(13));if(!K)return _(f,400,{error:"missing_session_id"}),!0;if(!Q7(K))return _(f,404,{error:"session_not_found",session_id:K}),!0;return _(f,200,{ok:!0,deleted:K}),!0}if($.method==="GET"&&J.startsWith("/v1/sessions/")){let K=B$(J.slice(13));if(!K)return _(f,400,{error:"missing_session_id"}),!0;let G=K$(K);if(!G)return _(f,404,{error:"session_not_found",session_id:K}),!0;return _(f,200,{session:G}),!0}if($.method==="POST"&&J.startsWith("/v1/sessions/")&&J.endsWith("/rename")){let K=B$(J.slice(13,-7));if(!K)return _(f,400,{error:"missing_session_id"}),!0;let G=await D0($);if(!G.ok)return O0(f,G),!0;let Q=G.value.title?.trim();if(!Q)return _(f,400,{error:"missing_title"}),!0;if(!Y7(K,Q))return _(f,404,{error:"session_not_found",session_id:K}),!0;return _(f,200,{ok:!0,session_id:K,title:Q}),!0}return!1};var HW=C(()=>{g$();U4()});var UW=async($,f,Z,z,J)=>{if($.method==="GET"&&J==="/v1/memory/mode")return _(f,200,a1()),!0;if($.method==="POST"&&J==="/v1/memory/mode"){let K=await D0($);if(!K.ok)return O0(f,K),!0;let G=n0(K.value.memory);if(!G)return _(f,400,{error:"invalid_memory",detail:"memory must be on or off"}),!0;let Q=j$(K.value.scope);if(!Q.ok)return _(f,400,{error:"invalid_scope",allowed:["global","project"]}),!0;let Y=Q.scope??"global";return X2(G,Y),_(f,200,{ok:!0,scope:Y,...a1()}),!0}if($.method==="GET"&&J==="/v1/memory")return _(f,200,{...a1(),memories:C$("global"),project_memories:C$("project")}),!0;if($.method==="POST"&&J==="/v1/memory"){let K=await D0($);if(!K.ok)return O0(f,K),!0;let G=K.value;if(!G.content)return _(f,400,{error:"missing_content"}),!0;let Q=j$(G.scope);if(!Q.ok)return _(f,400,{error:"invalid_scope",allowed:["global","project"]}),!0;let Y=Q.scope??"global",P=W2(G.content,G.tags??[],Y);return _(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 _(f,400,{error:"missing_query_param_q"}),!0;let G=j$(z.searchParams.get("scope"));if(!G.ok)return _(f,400,{error:"invalid_scope",allowed:["global","project"]}),!0;let Q=G.scope==="project"?[]:O4(K,"global"),Y=G.scope==="global"?[]:O4(K,"project");return _(f,200,{results:Q,project_results:Y}),!0}if($.method==="DELETE"&&J.startsWith("/v1/memory/")){let K=parseInt(J.slice(11),10);if(Number.isNaN(K))return _(f,400,{error:"invalid_index"}),!0;let G=j$(z.searchParams.get("scope"));if(!G.ok)return _(f,400,{error:"invalid_scope",allowed:["global","project"]}),!0;let Q=G.scope??"global";if(!H2(K-1,Q))return _(f,404,{error:"memory_not_found",index:K,scope:Q}),!0;return _(f,200,{ok:!0,deleted:K,scope:Q}),!0}return!1};var MW=C(()=>{j1();U4()});var qW=async($,f,Z,z,J)=>{if($.method==="GET"&&J==="/v1/mcp"){let X=a$();return _(f,200,{servers:X}),!0}let K=J.match(/^\/v1\/mcp\/([^/]+)\/resources$/);if($.method==="GET"&&K){let X=B$(K[1]);if(!X)return _(f,400,{error:"missing_name"}),!0;let W=a$()[X];if(!W)return _(f,404,{error:"mcp_not_found",name:X}),!0;if(!W.connected)return _(f,404,{error:"mcp_not_connected",name:X}),!0;let H=G4(X).servers[0];return _(f,200,{name:X,resources:H.resources,templates:H.templates}),!0}let G=J.match(/^\/v1\/mcp\/([^/]+)\/prompts$/);if($.method==="GET"&&G){let X=B$(G[1]);if(!X)return _(f,400,{error:"missing_name"}),!0;let W=a$()[X];if(!W)return _(f,404,{error:"mcp_not_found",name:X}),!0;if(!W.connected)return _(f,404,{error:"mcp_not_connected",name:X}),!0;let H=G4(X).servers[0];return _(f,200,{name:X,prompts:H.prompts}),!0}let Q=J.match(/^\/v1\/mcp\/([^/]+)\/resources\/read$/);if($.method==="POST"&&Q){let X=B$(Q[1]);if(!X)return _(f,400,{error:"missing_name"}),!0;let W=await D0($);if(!W.ok)return O0(f,W),!0;let H=W.value.uri?.trim();if(!H)return _(f,400,{error:"missing_uri"}),!0;let U=a$()[X];if(!U)return _(f,404,{error:"mcp_not_found",name:X}),!0;if(!U.connected)return _(f,404,{error:"mcp_not_connected",name:X}),!0;let M=await g8(H,X);return _(f,200,{ok:!0,name:X,uri:H,content:M}),!0}let Y=J.match(/^\/v1\/mcp\/([^/]+)\/prompts\/get$/);if($.method==="POST"&&Y){let X=B$(Y[1]);if(!X)return _(f,400,{error:"missing_name"}),!0;let W=await D0($);if(!W.ok)return O0(f,W),!0;let H=W.value.prompt?.trim();if(!H)return _(f,400,{error:"missing_prompt"}),!0;let U=a$()[X];if(!U)return _(f,404,{error:"mcp_not_found",name:X}),!0;if(!U.connected)return _(f,404,{error:"mcp_not_connected",name:X}),!0;let M=await n8(H,W.value.arguments,X);return _(f,200,{ok:!0,name:X,prompt:H,content:M}),!0}if($.method==="POST"&&J==="/v1/mcp"){let X=await D0($);if(!X.ok)return O0(f,X),!0;let W=X.value;if(!W.name)return _(f,400,{error:"missing_name"}),!0;if(W.remoteTransport&&!["streamable-http","sse","auto"].includes(W.remoteTransport))return _(f,400,{error:"invalid_remote_transport",allowed:["streamable-http","sse","auto"]}),!0;let H=W.project?"project":"global",{loadMcpConfigFile:U,saveMcpConfig:M}=await Promise.resolve().then(() => (h$(),C2)),N=U(H),q={...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)N.mcpServers[W.name]={url:W.url,...W.token?{token:W.token}:{},...q};else if(typeof W.command==="string"&&W.command.length>0)N.mcpServers[W.name]={command:W.command,...W.args?{args:W.args}:{},...q};else if(Array.isArray(W.command)&&W.command.length>0)N.mcpServers[W.name]={command:W.command,...q};else return _(f,400,{error:"provide command or url"}),!0;M(N,H),await b2();let L=a$()[W.name];return _(f,201,{ok:!0,name:W.name,scope:H,connected:L?.connected??!1,...L?.error?{error:L.error}:{},...L?.tools?.length?{tools:L.tools}:{}}),!0}if($.method==="DELETE"&&J.startsWith("/v1/mcp/")){let X=B$(J.slice(8));if(!X)return _(f,400,{error:"missing_name"}),!0;let W=z.searchParams.get("project")==="1"?"project":"global",{loadMcpConfigFile:H,saveMcpConfig:U}=await Promise.resolve().then(() => (h$(),C2)),M=H(W);if(!M.mcpServers[X])return _(f,404,{error:"mcp_not_found",name:X,scope:W,available:Object.keys(M.mcpServers)}),!0;return delete M.mcpServers[X],U(M,W),await b2(),_(f,200,{ok:!0,deleted:X,scope:W}),!0}let P=J.match(/^\/v1\/mcp\/([^/]+)\/(enable|disable)$/);if($.method==="POST"&&P){let X=B$(P[1]);if(!X)return _(f,400,{error:"missing_name"}),!0;let W=P[2]==="enable",H=await D0($),U=H.ok&&H.value.scope==="project"?"project":"global",{loadMcpConfigFile:M,saveMcpConfig:N}=await Promise.resolve().then(() => (h$(),C2)),q=M(U);if(!q.mcpServers[X]){let L=U1().some((F)=>F.name===X);return _(f,404,{error:"mcp_not_found",name:X,scope:U,...L?{hint:"server exists in another scope; pass the matching scope"}:{available:Object.keys(q.mcpServers)}}),!0}return q.mcpServers[X].enabled=W,N(q,U),await b2(),_(f,200,{ok:!0,name:X,enabled:W,scope:U,connected:a$()[X]?.connected??!1}),!0}return!1};var FW=C(()=>{h$();U4()});var NW=async($,f,Z,z,J)=>{if($.method==="GET"&&J==="/v1/skills"){let Q=q1();return _(f,200,{count:Q.length,enabled_count:Q.filter((Y)=>Y.enabled).length,stale_disabled:w2(),skills:Q.map(p3)}),!0}if($.method==="POST"&&J==="/v1/skills/reload"){y$({silent:!0});let Q=q1();return _(f,200,{ok:!0,count:Q.length,enabled_count:Q.filter((Y)=>Y.enabled).length,stale_disabled:w2(),skills:Q.map(p3)}),!0}let K=J.match(/^\/v1\/skills\/([^/]+)$/);if($.method==="GET"&&K){let Q=B$(K[1]);if(!Q)return _(f,400,{error:"invalid_skill_name"}),!0;let Y=c8(Q);if(!Y)return _(f,404,{error:"skill_not_found",name:Q,available:q1().map((P)=>P.name)}),!0;return _(f,200,{skill:{...p3(Y),content:Y.content}}),!0}let G=J.match(/^\/v1\/skills\/([^/]+)\/(enable|disable)$/);if($.method==="POST"&&G){let Q=B$(G[1]);if(!Q)return _(f,400,{error:"invalid_skill_name"}),!0;let Y=G[2]==="enable";if(!c8(Q))return _(f,404,{error:"skill_not_found",name:Q,available:q1().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 _(f,400,{error:"invalid_scope",allowed:["global","project"]}),!0;let[W]=S7([Q],Y,X??"global");return _(f,200,{ok:!0,name:Q,enabled:W.enabled,scope:X??"global",...W.blockedBy?{blocked_by:W.blockedBy}:{}}),!0}return!1};var BW=C(()=>{c$();U4()});var VW=async($,f,Z,z,J)=>{if($.method==="GET"&&J==="/health")return _(f,200,{ok:!0,service:"min-agent",version:Z.version}),!0;if($.method==="GET"&&J==="/v1/meta")return _(f,200,{version:Z.version,cwd:process.cwd(),instructions_chars:Z.instructions.join(`
|
|
428
|
-
`).length,sandbox:
|
|
429
|
-
`)[0]??"").replace("Instructions from: ",""),chars:
|
|
421
|
+
切换: /skills disable <name> [--project]`);break}case"sandbox":{let{takeScopeFlags:F}=await Promise.resolve().then(() => W2),{getSandboxSnapshot:N,setSandboxConfig:f}=await Promise.resolve().then(() => (l(),C1)),{parseSandboxMode:B,parseNetworkPolicy:_,getEffectiveSandboxPolicy:V,sandboxEnforcementCaveat:A,sandboxModeLabel:O,setSandboxOverride:v}=await Promise.resolve().then(() => (u0(),X5)),{scope:b,rest:D}=F(q),I=(x)=>x==="cli"?"本次启动参数":x==="env"?"环境变量":x==="project"?"项目":x==="global"?"全局":"默认";if(D.length===0){let x=N(),T=[...x.extraWriteRoots.length>0?[`额外可写目录: ${x.extraWriteRoots.join(", ")}`]:[],...x.extraReadRoots.length>0?[`额外可读目录: ${x.extraReadRoots.join(", ")}`]:[]],o=A(V().mode);k(Z,[`当前隔离: ${x.label}(${I(x.source)})`,...T,...o?[o]:[],"设置: /sandbox off|workspace|strict [--project]"," /sandbox network allow|deny [--project]"].join(`
|
|
422
|
+
`));break}let R=b==="project"?"project":"global",J0=R==="project"?"项目":"全局";if(D[0]==="network"){let x=_(D[1]);if(!x||D.length>2){k(Z,"用法: /sandbox network allow|deny [--project]");break}f({network:x},R),v({network:x}),k(Z,`✓ 联网已设为${x==="deny"?"禁止":"允许"}(${J0})`);break}let m=B(D[0]);if(!m||D.length>1){k(Z,`用法: /sandbox off|workspace|strict [--project]
|
|
423
|
+
/sandbox network allow|deny [--project]`);break}f({mode:m},R),v({mode:m});let $0=A(m);k(Z,[`✓ 隔离已设为${O(m)}(${J0})`,...$0?[$0]:[]].join(`
|
|
424
|
+
`));break}case"help":k(Z,["命令:"," 输入 / 弹出命令菜单 (输入过滤, ↑↓ 选择, 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(`
|
|
425
|
+
`));break;default:k(Z,`未知命令: /${H},输入 /help 查看可用命令`)}}function oW($){let Z=null;return{run:async()=>{let Q=$.messages.length,Y=$.tui.messageCount(),K=!1;Z=new AbortController,$.tui.setRunning(!0,"思考中...");let{summarizeToolCall:X,summarizeToolResult:P,toolResultText:W}=await Promise.resolve().then(() => wJ),{getContextWindowInfo:H}=await Promise.resolve().then(() => (m4(),iZ)),{getModelPrice:q,estimateCost:U,formatCost:M}=await Promise.resolve().then(() => (y2(),a3)),{runOnceWithSystem:F,emptyResponseMessage:N,WRAP_UP_MESSAGE:f}=await Promise.resolve().then(() => (d4(),xJ)),{clearStack:B,pushTurn:_}=await Promise.resolve().then(() => E9),{setSubAgentListener:V}=await Promise.resolve().then(() => (yJ(),kJ)),{LOOP_HALT_MESSAGE:A}=await Promise.resolve().then(() => (O9(),JW)),{createSaveThrottle:O}=await Promise.resolve().then(() => RJ),{snapshotTokenInfo:v}=await Promise.resolve().then(() => (x9(),v9)),b=O(()=>$.persist?.()),D=$.tracker.totalInputTokens,I=$.tracker.totalOutputTokens,R=null,J0=0,m=async()=>{let S=++J0,p=await v($.tracker,$.getModel(),$.messages);if(S!==J0)return;$.tui.setTokenInfo(p)},$0=()=>{if(R!=null)return;R=setTimeout(()=>{R=null,m()},50)},x=async()=>{if(R!=null)clearTimeout(R),R=null;await m()},T=$.tracker.subscribe($0);m();let o={onAssistantDisplayDelta:(S)=>$.tui.appendToLast(S),onThinkingDelta:(S)=>{$.tui.setRunning(!0,"推理中..."),$.tui.appendToThinking(S)},onToolCall:(S,p,z0)=>{$.tui.setRunning(!0,`执行 ${S}...`),$.tui.addMessage({id:`tool-${z0||`${Date.now()}-${Math.random().toString(36).slice(2,6)}`}`,role:"tool",content:X(S,p),toolName:S,toolCallId:z0,timestamp:Date.now()})},onToolResult:(S,p,z0)=>{$.tui.setRunning(!0,"思考中..."),$.tui.setToolResult(z0.toolCallId,S,P(S,p,z0.isError),W(p),z0.isError)},onStreamError:(S)=>{$.tui.addMessage({id:`err-${Date.now()}`,role:"system",content:`错误: ${S}`,timestamp:Date.now()})},onCompaction:(S)=>{if(K=!0,$.setUndoStack(B($.getUndoStack())),S==="compacting_start")$.tui.addMessage({id:`compact-${Date.now()}`,role:"system",content:"正在整理过长的对话记录…",timestamp:Date.now()});else if(S.startsWith("compacted_ok"))$.tui.addMessage({id:`compact-ok-${Date.now()}`,role:"system",content:"✓ 已整理对话记录,继续执行",timestamp:Date.now()})},onRetryNotice:(S)=>{$.tui.addMessage({id:`retry-${Date.now()}`,role:"system",content:S.kind==="wrap_up"?"⟳ 本轮预算用尽,正在收尾…":`⟳ 模型返回空响应,重试 ${S.attempt}/${S.maxAttempts}…`,timestamp:Date.now()})},onRunFinish:async(S)=>{if(Z=null,$.tui.setRunning(!1),await x(),S.aborted)return;if(S.budgetExceeded)$.tui.addMessage({id:`budget-${Date.now()}`,role:"system",content:"⚠ 已达到预算上限。/budget 查看或调高",timestamp:Date.now()});let p=Math.max(0,$.tracker.totalInputTokens-D),z0=Math.max(0,$.tracker.totalOutputTokens-I),u=$.tracker.lastInputTokens;if(p>0||z0>0||u>0){let w=await H($.getModel()),y0=w.tokens>0&&u>0?Math.round(u/w.tokens*100):null,Y0=await q($.getModel()??""),q0=U({inputTokens:p,outputTokens:z0},Y0),Z0=[`Done in ${S.stepCount} step(s)`,`Tokens: ${p} in / ${z0} out / ${p+z0} total`,...y0!=null?[`Context: ${y0}%`]:[],...q0!=null?[`约 ${M(q0)}`]:[]];$.tui.addMessage({id:`done-${Date.now()}`,role:"system",content:Z0.join(" | "),timestamp:Date.now()})}if(S.maxStepsReached)$.tui.addMessage({id:`maxsteps-${Date.now()}`,role:"system",content:"⚠ 已达到自动续跑上限,发送消息继续",timestamp:Date.now()});if(S.stopped)$.tui.addMessage({id:`stopped-${Date.now()}`,role:"system",content:`⚠ ${A}`,timestamp:Date.now()});else if(S.wrapUp)$.tui.addMessage({id:`wrapup-${Date.now()}`,role:"system",content:`⚠ ${f}`,timestamp:Date.now()});else if(S.emptyResponse)$.tui.addMessage({id:`empty-${Date.now()}`,role:"system",content:`⚠ ${N(S.emptyAttempts??0)}`,timestamp:Date.now()});else if(S.incomplete)$.tui.addMessage({id:`incomplete-${Date.now()}`,role:"system",content:"还没有完整回复,发送消息可继续",timestamp:Date.now()})}};try{V((p)=>{if(p.phase!=="call")return;$.tui.appendToolChild(p.parentToolCallId,{name:p.name,summary:X(p.name,p.input)})});let S={providerName:$.getProvider(),taskState:$.getTaskState(),onStepPersist:()=>b.request(),...$.getPlanMode()?{planMode:!0}:{}};await F($.messages,$.getSystemPrompt(),$.getModel(),Z?.signal,o,$.tracker,S)}catch(S){if(!Z)return;let p=S instanceof Error?S.message:String(S);o.onStreamError(p)}finally{if(T(),R!=null)clearTimeout(R),R=null;if(V(null),b.cancel(),!K)$.setUndoStack(_($.getUndoStack(),Q,$.messages.length,Y));Z=null,$.tui.setRunning(!1),await x()}},abort:(Q)=>{if(!Z)return!1;return Promise.resolve().then(() => (i6(),WP)).then((Y)=>Y.killActiveProcesses()).catch(()=>{}),Z.abort(),Z=null,Q.setRunning(!1),Q.addMessage({id:`sys-${Date.now()}`,role:"system",content:"(已取消)",timestamp:Date.now()}),!0},getController:()=>Z}}function g9($){return typeof $==="object"&&$!==null}function W8($){if(typeof $==="string")return $;if(!Array.isArray($))return"";let Z=[];for(let J of $)if(g9(J)&&J.type==="text"&&typeof J.text==="string")Z.push(J.text);return Z.join("")}function RA($){if(!Array.isArray($))return!1;return $.some((Z)=>g9(Z)&&(Z.type==="image"||Z.type==="file"))}function kA($){if(!g9($))return $;if(($.type==="text"||$.type==="json")&&"value"in $)return $.value;return $}function yA($){if(W8($).trim())return W8($);if(RA($))return"[\uD83D\uDCCE 图片]";return null}function u9($){for(let Z=$.length-1;Z>=0;Z--){let J=$[Z];if(J?.role!=="user")continue;if(W8(J.content).trim())return W8(J.content)}return null}function mJ($){let Z=[];for(let J=0;J<$.length;J++){let z=$[J];if(z.role==="assistant"){Z.push(...SA(z,J));continue}let G=EA(z,J);if(G)Z.push(G)}return Z}function SA($,Z){let J=W8($.content);if(!J)return[];let{slices:z}=CJ(J);if(z.every((Y)=>Y.type==="display"))return[{id:`hyd-${Z}-assistant`,role:"assistant",content:J,timestamp:0}];let G=[],Q=0;for(let Y of z){if(Y.type==="display"){if(!Y.text.trim())continue;G.push({id:`hyd-${Z}-assistant-${Q++}`,role:"assistant",content:Y.text,timestamp:0});continue}let K=Y.block.query,X=Y.block.kind==="results"?Y.block.body:Y.block.query,P={query:K};G.push({id:`hyd-${Z}-search-${Q++}`,role:"tool",content:G8("search_web",P),toolName:"search_web",toolCallId:`xml-search-hyd-${Z}-${Q}`,toolResult:X,toolResultSummary:w9("search_web",X),timestamp:0})}return G}function EA($,Z){if($.role==="user"){let J=yA($.content);if(J==null)return null;return{id:`hyd-${Z}-user`,role:"user",content:J,timestamp:0}}if($.role==="tool"){if(!Array.isArray($.content))return null;for(let J of $.content){if(!g9(J)||J.type!=="tool-result")continue;let z=typeof J.toolName==="string"?J.toolName:"";if(!z)continue;let G=kA(J.output),Q=g2(G),Y=typeof J.toolCallId==="string"?J.toolCallId:void 0;return{id:`hyd-${Z}-tool`,role:"tool",content:z,toolName:z,toolCallId:Y,toolResult:Q,toolResultSummary:w9(z,G),timestamp:0}}return null}return null}var nJ=C(()=>{z8()});function dW(){let $=Promise.resolve(),Z=0,J=0,z=()=>{return};return{run(G,Q){let Y=Z;J++;let K=()=>Y!==Z?Promise.resolve(Q()):G(),X=$.then(K,K);return $=X.then(z,z),X.finally(()=>{J--})},cancelAll(){Z++},get size(){return J}}}function rW($){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 cJ($){if($==="running")return"请先等待当前回合结束或按 Esc 取消";if($==="current")return"已是当前会话";return"会话不存在"}function lW($){if($.running)return{ok:!1,reason:"running"};if(!$.sessionId&&$.messageCount===0)return{ok:!1,reason:"already_new"};return{ok:!0}}function iW($){if($==="running")return"请先等待当前回合结束或按 Esc 取消";return"已是新会话"}var tW={};M0(tW,{runTui:()=>pA});function vA(){S$("provider",($)=>{if($.length>0)return[];return L2().map((Z)=>({value:Z.name,description:Z.current?`${Z.baseURL}(当前)`:Z.baseURL}))})}function xA(){let $=()=>G4().map((Z)=>({value:Z.id,description:Z.title}));S$("sessions",$),S$("resume",$)}function gA(){S$("ctx",($)=>{if($.length>0)return[];return N$.map((Z)=>Z==="auto"?{value:Z,description:"按模型探测"}:{value:Z})})}function uA(){let $=(Z)=>{let J=[{value:"--project",description:"写入当前项目"},{value:"--global",description:"写入全局配置"}],z=new Set(Z),G=J.filter((Q)=>!z.has(Q.value));if(Z.length===0){let Q=s(G0())?.defaultModel;return[...t1(Q).map((Y)=>({value:Y})),...G]}return G};S$("think",$),S$("thinking",$)}function hA(){S$("memory",($)=>{let Z=[{value:"--project",description:"写入当前项目"},{value:"--global",description:"写入全局配置"}],J=new Set($),z=Z.filter((G)=>!J.has(G.value));if($.length===0)return[{value:"on",description:"开启记忆(跨会话保留)"},{value:"off",description:"关闭记忆(默认)"},...z];return z})}function mA(){S$("permission",($)=>{let Z=[{value:"--project",description:"写入当前项目"},{value:"--global",description:"写入全局配置"}],J=new Set($),z=Z.filter((G)=>!J.has(G.value));if($.length===0)return[{value:"ask",description:"危险操作前询问"},{value:"accept-edits",description:"自动允许改文件,危险命令仍询问(默认)"},{value:"allow-all",description:"全部自动允许"},...z];return z})}function nA(){S$("sandbox",($)=>{let Z=[{value:"--project",description:"写入当前项目"},{value:"--global",description:"写入全局配置"}],J=new Set($),z=Z.filter((G)=>!J.has(G.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((Q)=>!J.has(Q.value)),...z];return z})}function cA(){S$("skills",($)=>{let Z=$[0];if(Z===void 0)return[{value:"list",description:"列出全部 skills"},{value:"info",description:"查看 skill 详情"},{value:"enable",description:"启用 skill"},{value:"disable",description:"禁用 skill"}];if(Z==="info")return B1().map((G)=>({value:G.name,description:G.description}));if(Z!=="enable"&&Z!=="disable")return[];let J=B1();return[...(Z==="enable"?[...J.filter((G)=>!G.enabled).map((G)=>({value:G.name,description:G.description})),...I2().map((G)=>({value:G,description:"(配置中的孤儿条目)"}))]:J.filter((G)=>G.enabled).map((G)=>({value:G.name,description:G.description}))).filter((G)=>!$.includes(G.value)),...$.includes("--project")?[]:[{value:"--project",description:"仅对当前项目生效"}]]})}async function pA($){let{modelId:Z,resumeSessionId:J,images:z,providerName:G,initialPrompt:Q}=$;await u4(),T$(),cA(),mA(),uA(),gA(),vA(),hA(),nA(),xA();let Y=await V1(),K=a(),X=u1(),P=p4(X,Y),W=[],H=J,q=Z??s(K)?.defaultModel,U=G;if(q)X2(q);let M=new W4,F=g$(),N=gJ(),f=null,B=!1;if(J){let T=Q$(J);if(T)W=T.messages,H=J,w6(T.taskState,F)}let _=null,V=new PZ({onSubmit:async(T)=>{let o=T.display;if(o.trim().startsWith("/")){if(await pW(o,V,W,q,M,(p)=>{q=p,V.setModel(p),O()},J0,{undoStack:N,setUndoStack:(p)=>{N=p},lastUserMessage:f,setLastUserMessage:(p)=>{f=p},sessionId:H,setSessionId:(p)=>{H=p},planMode:B,togglePlanMode:()=>{B=!B},reloadSystemPrompt:async()=>{let p=await V1();P=p4(u1(),p),k(V,`✓ 已重载规则(${p.join("").length} 字符)`)},applySession:v,startNewSession:b,openSessionPicker:D,taskState:F,refreshTokenBar:O,setProvider:(p)=>{U=p}})==="run"&&_)await _.run(),A();return}if(f=o,V.addMessage({id:`user-${Date.now()}`,role:"user",content:o,timestamp:Date.now()}),W.push({role:"user",content:T.content}),_)await _.run(),A()},onNotice:(T)=>{k(V,T)},onConfirm:(T)=>{if(V.hideConfirm(),r4)r4(T),r4=null},onQuestionAnswer:(T)=>{if(V.hideQuestion(),l4)l4(T),l4=null},onModelPick:(T)=>{V.hideModelPicker();let o=a(),S=s(o);if(S)S.defaultModel=T,Promise.resolve().then(() => (l(),C1)).then((p)=>p.saveConfig(o));q=T,V.setModel(T),O(),k(V,`✓ 默认模型已设为: ${T}`)},onModelCancel:()=>{V.hideModelPicker()},onThinkPick:(T,o)=>{a1(T,o),K2(T),V.hideThinkPicker(),k(V,`✓ 思考强度已设为 ${D$(T)}(${o==="project"?"项目":"全局"})`)},onThinkCancel:()=>{V.hideThinkPicker()},onCtxPick:(T)=>{let o=y4(T);if(V.hideCtxPicker(),!o.ok){k(V,"窗口档位仅本地模型可用");return}O(),k(V,`✓ 上下文窗口已设为${J4(T)}`)},onCtxCancel:()=>{V.hideCtxPicker()},onProviderPick:(T)=>{V.hideProviderPicker();let o=e7(T);if(!o.ok){k(V,o.message);return}if(U=o.name,q=o.defaultModel,V.setModel(o.defaultModel),O(),o.defaultModel)X2(o.defaultModel);k(V,`✓ 当前服务商已切换为: ${o.name}`)},onProviderCancel:()=>{V.hideProviderPicker()},onSessionPick:(T)=>{V.hideSessionPicker(),v(T)},onSessionCancel:()=>{V.hideSessionPicker()},onToggleSelectionMode:()=>{V.toggleSelectionMode()},onExitSelectionMode:()=>{V.setSelectionMode(!1)},onExit:()=>{J0()}},Z??s(K)?.defaultModel,H);_=oW({tui:V,messages:W,tracker:M,getModel:()=>q,getProvider:()=>U,getPlanMode:()=>B,getUndoStack:()=>N,setUndoStack:(T)=>{N=T},getSystemPrompt:()=>P,getTaskState:()=>F,persist:()=>A()});function A(){if(W.length===0)return;try{H=w$(W,H,void 0,void 0,F)}catch{}}async function O(){let{snapshotTokenInfo:T}=await Promise.resolve().then(() => (x9(),v9));V.setTokenInfo(await T(M,q,W))}function v(T){let o=rW({running:Boolean(_?.getController()),currentId:H,targetId:T,exists:Boolean(Q$(T))});if(!o.ok){k(V,cJ(o.reason));return}if(W.length>0)H=w$(W,H,void 0,void 0,F);let S=Q$(T);if(!S){k(V,cJ("missing"));return}W.length=0,W.push(...S.messages),w6(S.taskState,F),H=T,N=S9(N),M.reset(),f=u9(S.messages),V.setSessionId(T),V.update({messages:mJ(S.messages)}),O(),k(V,`✓ 已切换到: ${S.meta.title}`)}function b(){let T=lW({running:Boolean(_?.getController()),sessionId:H,messageCount:W.length});if(!T.ok){k(V,iW(T.reason));return}if(W.length>0)H=w$(W,H,void 0,void 0,F);W.length=0,JZ(F),H=void 0,N=S9(N),M.reset(),f=null,V.setSessionId(void 0),V.update({messages:[]}),O(),k(V,"✓ 已新建会话")}function D(){if(G4().length===0){k(V,"无已保存的会话");return}V.showSessionPicker()}R8((T)=>pJ.run(()=>new Promise((o)=>{r4=o,V.showConfirm(T)}),()=>!1)),k8((T,o,S)=>pJ.run(()=>new Promise((p)=>{l4=p,V.showQuestion(T,o,Boolean(S))}),()=>null));let I,R=new Promise((T)=>{I=T}),J0=()=>{if(V.setSelectionMode(!1),A(),_?.getController()){if(KJ(),pJ.cancelAll(),r4)r4(!1),r4=null,V.hideConfirm();if(l4)l4(null),l4=null,V.hideQuestion();_.getController().abort(),V.setRunning(!1),V.addMessage({id:`sys-${Date.now()}`,role:"system",content:"(已取消)",timestamp:Date.now()})}else I?.()};if(V.start(),W.length>0)V.update({messages:mJ(W)});await O();let m=Q?.trim()??"",$0=(T,o)=>{if(T==="not_found")k(V,`⚠ 图片不存在: ${o}`);else if(T==="too_large")k(V,`⚠ 图片超过 5 MB 限制: ${o}`);else k(V,`\uD83D\uDCCE ${o}`)};if(z&&z.length>0){let T=[{type:"text",text:m},...y9(z,$0)];if(T.length>1||m){if(W.push({role:"user",content:T}),V.addMessage({id:`user-${Date.now()}`,role:"user",content:m?m:`[\uD83D\uDCCE 图片] ${z.join(", ")}`,timestamp:Date.now()}),m)f=m;await _.run(),A()}}else if(m)f=m,V.addMessage({id:`user-${Date.now()}`,role:"user",content:m,timestamp:Date.now()}),W.push({role:"user",content:m}),await _.run(),A();let x=()=>{if(_?.getController())J0()};process.on("SIGINT",x),await R,process.off("SIGINT",x);try{A()}finally{R8(null),k8(null),V.destroy(),await X4()}}var r4=null,l4=null,pJ;var aW=C(()=>{cK();m$();n$();H3();P4();g1();S4();d4();i6();Z$();l();$8();u$();nJ();K1();f2();R3();pJ=dW()});var sW={};M0(sW,{startTuiSession:()=>oJ});async function oJ($){if(!G1()){let z=Boolean(process.stdin.isTTY&&process.stdout.isTTY);if(!PQ(!1,z))throw new e("Not configured.",{hint:"Run: min-agent setup"});let{offerInteractiveSetup:G}=await Promise.resolve().then(() => (P7(),fQ));if(await G("session-gate"),!G1())throw new e("Not configured.",{hint:"Run: min-agent setup"})}let{runTui:Z}=await Promise.resolve().then(() => (aW(),tW)),J=$.positionals.join(" ").trim();await Z({modelId:$.model,providerName:$.provider,resumeSessionId:$.resume,images:$.images,initialPrompt:J||void 0})}var dJ=C(()=>{l();q$();z7()});function GH($=300000){let Z=new Map,J=(z)=>{let G=Z.get(z);if(!G)return;return clearTimeout(G.timer),Z.delete(z),G};return{waitConfirm(z){return new Promise((G)=>{let Q=setTimeout(()=>{Z.delete(z),G(!1)},$);Z.set(z,{kind:"confirm",resolve:G,timer:Q})})},waitQuestion(z){return new Promise((G)=>{let Q=setTimeout(()=>{Z.delete(z),G(null)},$);Z.set(z,{kind:"question",resolve:G,timer:Q})})},resolveConfirm(z,G){let Q=Z.get(z);if(!Q||Q.kind!=="confirm")return!1;return J(z),Q.resolve(G),!0},resolveQuestion(z,G){let Q=Z.get(z);if(!Q||Q.kind!=="question")return!1;return J(z),Q.resolve(G),!0},cancel(z){let G=J(z);if(!G)return;if(G.kind==="confirm")G.resolve(!1);else G.resolve(null)},has(z){return Z.has(z)}}}import{randomUUID as QH}from"crypto";function rJ(){let $=process.env.MIN_AGENT_SERVE_CORS;return $==="1"||$==="true"}function n9(){if(rJ())return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization"};return{}}function c9($){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($,Z,J){let z={"Content-Type":"application/json; charset=utf-8",...n9()};$.writeHead(Z,z),$.end(JSON.stringify(J))}function V$($){try{return decodeURIComponent($)}catch{return null}}function $D($){return new Promise((Z,J)=>{let z=[],G=0,Q=setTimeout(()=>{$.destroy(),J(Error("body_timeout"))},eA);$.on("data",(Y)=>{if(G+=Y.length,G>YH){clearTimeout(Q),$.removeAllListeners("data"),$.pause(),J(Error("body_too_large"));return}z.push(Y)}),$.on("end",()=>{clearTimeout(Q),Z(Buffer.concat(z).toString("utf-8"))}),$.on("error",(Y)=>{clearTimeout(Q),J(Y)})})}async function j0($){let Z;try{Z=await $D($)}catch(J){if(J?.message==="body_too_large")return{ok:!1,status:413,error:"payload_too_large"};if(J?.message==="body_timeout")return{ok:!1,status:408,error:"payload_timeout"};throw J}try{return{ok:!0,value:JSON.parse(Z)}}catch{return{ok:!1,status:400,error:"invalid_json"}}}function b0($,Z){if(Z.status===413)$.shouldKeepAlive=!1;L($,Z.status,Z.status===413?{error:Z.error,max_bytes:YH}:{error:Z.error})}function $1($,Z){try{if($.writableEnded)return;$.write(`data: ${JSON.stringify(Z)}
|
|
426
|
+
|
|
427
|
+
`)}catch{}}function m9($,Z){if(typeof $==="string"&&$.length>Z)return $.slice(0,Z)+`
|
|
428
|
+
… [truncated ${$.length-Z} chars]`;return $}function ZD($){return{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no",...$}}function JD($,Z,J={}){return{onAssistantDisplayDelta(z){$1($,{type:"assistant",text:z})},onThinkingDelta(z){$1($,{type:"thinking",text:z})},onToolCall(z,G){$1($,{type:"tool_call",name:z,input:m9(G,h9)})},onToolResult(z,G){$1($,{type:"tool_result",name:z,output:m9(G,h9)})},onCompaction(z){$1($,{type:"compaction",line:z})},onRetryNotice(z){$1($,{type:"notice",kind:z.kind,attempt:z.attempt,max_attempts:z.maxAttempts,delay_ms:z.delayMs})},onStreamError(z){$1($,{type:"error",message:z})},onRunFinish(z){let G;if(J.sessionId&&Z.length>0)try{G=w$(Z,J.sessionId,void 0,void 0,J.taskState)}catch{G=void 0}if($1($,{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:G,messages:y6(Z),task_state:J.taskState,project:J.project}),!$.writableEnded)$.end()}}}function zD(){let $=[],Z=[],J=null;return{callbacks:{onToolCall(G,Q){$.push({name:G,input:m9(Q,h9)})},onToolResult(G,Q){Z.push({name:G,output:m9(Q,h9)})},onRunFinish(G){J=G}},toolCalls:$,toolResults:Z,finishInfo:()=>J}}function p9($){let Z={};if($.sandbox!==void 0){let J=y$($.sandbox);if(!J)return{ok:!1,error:"invalid_sandbox",detail:"sandbox must be off, workspace, or strict"};Z.mode=J}if($.network!==void 0){let J=o$($.network);if(!J)return{ok:!1,error:"invalid_network",detail:"network must be allow or deny"};Z.network=J}return{ok:!0,policy:Z}}function lJ($){if($===void 0)return{ok:!0};if(!Array.isArray($)||$.some((Z)=>typeof Z!=="string"||Z.length===0))return{ok:!1};return{ok:!0,value:$}}function o9(){let $=a2();return{mode:$.mode,network:$.network,extraWriteRoots:$.extraWriteRoots,extraReadRoots:$.extraReadRoots,source:$.source,label:$.label}}function d9(){let $=z6(),Z=t2(),J=$??Z.permission,z=$?"cli":Z.source;return{permission:J,source:z,label:f4(J)}}function r9($){if($.thinking===void 0)return{ok:!0};let Z=S0($.thinking);if(!Z)return{ok:!1,error:"invalid_thinking",detail:"thinking must be off, low, medium, high, or max"};return{ok:!0,thinking:Z}}function KH($){if($.memory===void 0)return{ok:!0};let Z=h0($.memory);if(!Z)return{ok:!1,error:"invalid_memory",detail:"memory must be on or off"};return{ok:!0,memory:Z}}function XH($){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 M8($){return{temperature:typeof $.temperature==="number"?$.temperature:void 0,maxTokens:typeof $.maxTokens==="number"?$.maxTokens:void 0,topP:typeof $.topP==="number"?$.topP:void 0,thinking:S0($.thinking),memory:h0($.memory),providerName:typeof $.provider==="string"?$.provider:void 0,...$.plan_mode===!0?{planMode:!0}:{}}}function GD($,Z,J,z){if(J)return{autoApprove:!0};return{autoApprove:!1,onConfirm:async(G)=>{let Q=QH();return z.push(Q),$1(Z,{type:"confirm",id:Q,message:G}),$.approvalGate.waitConfirm(Q)},onQuestion:async(G,Q,Y)=>{let K=QH();return z.push(K),$1(Z,{type:"question",id:K,prompt:G,...Q&&Q.length>0?{options:Q}:{},...Y?{multiple:!0}:{}}),$.approvalGate.waitQuestion(K)}}}async function F8($,Z){let{res:J,messages:z,modelId:G,stream:Q,sessionId:Y,runOptions:K,autoApprove:X}=Z,P=Z.taskState??g$();if(!X&&!Q){L(J,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 W=new AbortController,H=[],q=()=>{W.abort();for(let I of H)$.approvalGate.cancel(I)};J.on("close",q);let U=new W4,M=u1(),F=p4(M,$.instructions),N=GD($,J,X,H),f=Z.sandboxTighten,B=(I)=>{let R=Y!=null?TJ(()=>{try{w$(z,Y,void 0,void 0,P)}catch{}}):null,J0=()=>f5(N,()=>vJ(z,F,G,W.signal,I,U,{...K,taskState:P,...R?{onStepPersist:()=>R.request()}:{}})),m=($0)=>$0.finally(()=>{R?.cancel()});if(f&&(f.mode||f.network))return m(z5(f,J0));return m(J0())};if(Q){J.writeHead(200,ZD(n9())),J.flushHeaders?.();let I=JD(J,z,{sessionId:Y,project:M,taskState:P});try{await B(I)}catch(R){let J0=R instanceof Error?R.message:String(R);if(!J.writableEnded)$1(J,{type:"fatal",message:J0}),J.end()}return}let{callbacks:_,toolCalls:V,toolResults:A,finishInfo:O}=zD();await B(_);let v=[...z].reverse().find((I)=>I.role==="assistant"),b;if(Y&&z.length>0)try{b=w$(z,Y,void 0,void 0,P)}catch{b=void 0}let D=O();L(J,200,{messages:y6(z),assistant:v??null,tool_calls:V,tool_results:A,session_id:b,step_count:D?.stepCount??0,usage:D?.usage??null,context_tokens:D?.contextTokens??0,has_error:D?.hasError??!1,aborted:D?.aborted??!1,max_steps_reached:D?.maxStepsReached??!1,incomplete:D?.incomplete??!1,budget_exceeded:D?.budgetExceeded??!1,continues:D?.continues??0,stopped:D?.stopped??!1,empty_response:D?.emptyResponse??!1,empty_attempts:D?.emptyAttempts??0,wrap_up:D?.wrapUp??!1,task_state:P,project:M})}var YH=2097152,eA=30000,h9=48000,i4=8;var M4=C(()=>{l();u0();Z$();K1();b1();d4();u$();$8();g1();S4();Y6()});async function QD($,Z,J){if(Z.headers["content-type"]?.split(";")[0]?.trim()!=="application/json"){L(J,415,{error:"unsupported_media_type",detail:"Use Content-Type: application/json"});return}if($.activeChats>=i4){L(J,429,{error:"too_many_concurrent_requests",detail:`Max ${i4} concurrent chats`});return}$.activeChats++;try{let z=await j0(Z);if(!z.ok){b0(J,z);return}let G=z.value,Q=p9(G);if(!Q.ok){L(J,400,{error:Q.error,detail:Q.detail});return}let Y=Q.policy,K=r9(G);if(!K.ok){L(J,400,{error:K.error,detail:K.detail});return}let X=KH(G);if(!X.ok){L(J,400,{error:X.error,detail:X.detail});return}let P=typeof G.model==="string"?G.model:void 0,W=G.stream===!0,H=typeof G.session_id==="string"?G.session_id:void 0,q;if(H){await T6(H,async()=>{let U=Q$(H);if(!U){L(J,404,{error:"session_not_found",session_id:H});return}if(typeof G.message!=="string"||!G.message.trim()){L(J,400,{error:"session_requires_message",detail:"With `session_id`, send a non-empty `message` for the new user turn"});return}let M=[...U.messages],F=G.images&&G.images.length>0?await P8(G.message,G.images):G.message;M.push({role:"user",content:F}),await F8($,{res:J,messages:M,modelId:P,stream:W,sessionId:H,runOptions:M8(G),autoApprove:G.auto_approve!==!1,taskState:U.taskState??g$(),sandboxTighten:Y})});return}else{let U=XH(G);if(!U.ok){L(J,400,{error:"invalid_body",detail:U.error});return}if(q=U.messages,G.images&&G.images.length>0){let M=q[q.length-1];if(!M||M.role!=="user"||typeof G.message!=="string"){L(J,400,{error:"images_require_message",detail:"With `images`, send a top-level `message` string for the user turn"});return}q[q.length-1]={role:"user",content:await P8(G.message,G.images)}}}await F8($,{res:J,messages:q,modelId:P,stream:W,sessionId:H,runOptions:M8(G),autoApprove:G.auto_approve!==!1,sandboxTighten:Y})}finally{$.activeChats--}}var PH=async($,Z,J,z,G)=>{if($.method==="POST"&&G==="/v1/chat/reload-instructions")return J.instructions=await V1(),L(Z,200,{ok:!0,instructions_chars:J.instructions.join(`
|
|
429
|
+
`).length}),!0;if($.method==="POST"&&(G==="/v1/chat"||G==="/v1/code"))return await QD(J,$,Z),!0;if($.method==="POST"&&G==="/v1/chat/redo"){let Q=await j0($);if(!Q.ok)return b0(Z,Q),!0;let Y=Q.value,K=typeof Y.session_id==="string"?Y.session_id:void 0;if(!K)return L(Z,400,{error:"missing_session_id"}),!0;let X=p9(Y);if(!X.ok)return L(Z,400,{error:X.error,detail:X.detail}),!0;let P=r9(Y);if(!P.ok)return L(Z,400,{error:P.error,detail:P.detail}),!0;if(J.activeChats>=i4)return L(Z,429,{error:"too_many_concurrent_requests",detail:`Max ${i4} concurrent chats`}),!0;J.activeChats++;try{await T6(K,async()=>{let W=Q$(K);if(!W){L(Z,404,{error:"session_not_found",session_id:K});return}let H=u9(W.messages);if(!H){L(Z,400,{error:"no_user_message"});return}await F8(J,{res:Z,messages:[...W.messages,{role:"user",content:H}],modelId:typeof Y.model==="string"?Y.model:void 0,stream:Y.stream===!0,sessionId:K,runOptions:M8(Y),autoApprove:Y.auto_approve!==!1,taskState:W.taskState??g$(),sandboxTighten:X.policy})})}finally{J.activeChats--}return!0}if($.method==="POST"&&G==="/v1/approvals"){let Q=await j0($);if(!Q.ok)return b0(Z,Q),!0;let Y=Q.value.id?.trim();if(!Y)return L(Z,400,{error:"missing_id"}),!0;if(typeof Q.value.accepted!=="boolean")return L(Z,400,{error:"missing_accepted"}),!0;if(!J.approvalGate.resolveConfirm(Y,Q.value.accepted))return L(Z,404,{error:"unknown_approval_id",id:Y}),!0;return L(Z,200,{ok:!0,id:Y,accepted:Q.value.accepted}),!0}if($.method==="POST"&&G==="/v1/answers"){let Q=await j0($);if(!Q.ok)return b0(Z,Q),!0;let Y=Q.value.id?.trim();if(!Y)return L(Z,400,{error:"missing_id"}),!0;let K=Q.value.answer===void 0?null:Q.value.answer;if(K!==null&&typeof K!=="string")return L(Z,400,{error:"invalid_answer"}),!0;if(!J.approvalGate.resolveQuestion(Y,K))return L(Z,404,{error:"unknown_answer_id",id:Y}),!0;return L(Z,200,{ok:!0,id:Y}),!0}if($.method==="POST"&&G==="/v1/paste"){if($.headers["content-type"]?.split(";")[0]?.trim()!=="application/json")return L(Z,415,{error:"unsupported_media_type"}),!0;if(J.activeChats>=i4)return L(Z,429,{error:"too_many_concurrent_requests",detail:`Max ${i4} concurrent chats`}),!0;let Q=await j0($);if(!Q.ok)return b0(Z,Q),!0;let Y=Q.value;if(!Y.image_base64)return L(Z,400,{error:"missing_image_base64"}),!0;let K=p9(Y);if(!K.ok)return L(Z,400,{error:K.error,detail:K.detail}),!0;let X=r9(Y);if(!X.ok)return L(Z,400,{error:X.error,detail:X.detail}),!0;let P=Buffer.from(Y.image_base64,"base64"),W=Y.mime_type??"image/png",H=Y.message??"What's in this image?",q=Y.model,U=Y.session_id,M=Y.stream===!0;J.activeChats++;try{await T6(U,async()=>{let F=[],N;if(U){let f=Q$(U);if(!f){L(Z,404,{error:"session_not_found",session_id:U});return}F=[...f.messages],N=f.taskState}F.push({role:"user",content:[{type:"text",text:H},{type:"image",image:P,mimeType:W}]}),await F8(J,{res:Z,messages:F,modelId:q,stream:M,sessionId:U,runOptions:M8(Y),autoApprove:Y.auto_approve!==!1,taskState:N??g$(),sandboxTighten:K.policy})})}finally{J.activeChats--}return!0}if($.method==="POST"&&G==="/v1/chat/compact"){let Q=await j0($);if(!Q.ok)return b0(Z,Q),!0;let Y=Q.value;if(!Y.session_id)return L(Z,400,{error:"missing_session_id"}),!0;let K=Q$(Y.session_id);if(!K)return L(Z,404,{error:"session_not_found"}),!0;let X=s$(),P=await d6(K.messages,X,{taskGoal:K.taskState?.goal});if(P.compacted)w$(P.messages,Y.session_id);return L(Z,200,{ok:!0,compacted:P.compacted,message_count:P.messages.length}),!0}if($.method==="POST"&&G==="/v1/chat/undo"){let Q=await j0($);if(!Q.ok)return b0(Z,Q),!0;let Y=Q.value;if(!Y.session_id)return L(Z,400,{error:"missing_session_id"}),!0;let K=Q$(Y.session_id);if(!K)return L(Z,404,{error:"session_not_found"}),!0;let X=-1;for(let P=K.messages.length-1;P>=0;P--)if(K.messages[P].role==="user"){X=P;break}if(X===-1)return L(Z,400,{error:"no_user_message"}),!0;return K.messages=K.messages.slice(0,X+1),w$(K.messages,Y.session_id),L(Z,200,{ok:!0,message_count:K.messages.length,messages:K.messages}),!0}return!1};var WH=C(()=>{P4();u$();d4();nJ();g1();h4();S4();M4()});var HH=async($,Z,J,z,G)=>{if($.method==="GET"&&G==="/v1/sessions"){let Q=G4();return L(Z,200,{sessions:Q}),!0}if($.method==="DELETE"&&G.startsWith("/v1/sessions/")){let Q=V$(G.slice(13));if(!Q)return L(Z,400,{error:"missing_session_id"}),!0;if(!YZ(Q))return L(Z,404,{error:"session_not_found",session_id:Q}),!0;return L(Z,200,{ok:!0,deleted:Q}),!0}if($.method==="GET"&&G.startsWith("/v1/sessions/")){let Q=V$(G.slice(13));if(!Q)return L(Z,400,{error:"missing_session_id"}),!0;let Y=Q$(Q);if(!Y)return L(Z,404,{error:"session_not_found",session_id:Q}),!0;return L(Z,200,{session:Y}),!0}if($.method==="POST"&&G.startsWith("/v1/sessions/")&&G.endsWith("/rename")){let Q=V$(G.slice(13,-7));if(!Q)return L(Z,400,{error:"missing_session_id"}),!0;let Y=await j0($);if(!Y.ok)return b0(Z,Y),!0;let K=Y.value.title?.trim();if(!K)return L(Z,400,{error:"missing_title"}),!0;if(!KZ(Q,K))return L(Z,404,{error:"session_not_found",session_id:Q}),!0;return L(Z,200,{ok:!0,session_id:Q,title:K}),!0}return!1};var qH=C(()=>{u$();M4()});var UH=async($,Z,J,z,G)=>{if($.method==="GET"&&G==="/v1/memory/mode")return L(Z,200,e1()),!0;if($.method==="POST"&&G==="/v1/memory/mode"){let Q=await j0($);if(!Q.ok)return b0(Z,Q),!0;let Y=h0(Q.value.memory);if(!Y)return L(Z,400,{error:"invalid_memory",detail:"memory must be on or off"}),!0;let K=O$(Q.value.scope);if(!K.ok)return L(Z,400,{error:"invalid_scope",allowed:["global","project"]}),!0;let X=K.scope??"global";return H2(Y,X),L(Z,200,{ok:!0,scope:X,...e1()}),!0}if($.method==="GET"&&G==="/v1/memory")return L(Z,200,{...e1(),memories:C$("global"),project_memories:C$("project")}),!0;if($.method==="POST"&&G==="/v1/memory"){let Q=await j0($);if(!Q.ok)return b0(Z,Q),!0;let Y=Q.value;if(!Y.content)return L(Z,400,{error:"missing_content"}),!0;let K=O$(Y.scope);if(!K.ok)return L(Z,400,{error:"invalid_scope",allowed:["global","project"]}),!0;let X=K.scope??"global",P=q2(Y.content,Y.tags??[],X);return L(Z,201,{ok:!0,memory:P,scope:X}),!0}if($.method==="GET"&&G==="/v1/memory/search"){let Q=z.searchParams.get("q")??"";if(!Q)return L(Z,400,{error:"missing_query_param_q"}),!0;let Y=O$(z.searchParams.get("scope"));if(!Y.ok)return L(Z,400,{error:"invalid_scope",allowed:["global","project"]}),!0;let K=Y.scope==="project"?[]:b4(Q,"global"),X=Y.scope==="global"?[]:b4(Q,"project");return L(Z,200,{results:K,project_results:X}),!0}if($.method==="DELETE"&&G.startsWith("/v1/memory/")){let Q=parseInt(G.slice(11),10);if(Number.isNaN(Q))return L(Z,400,{error:"invalid_index"}),!0;let Y=O$(z.searchParams.get("scope"));if(!Y.ok)return L(Z,400,{error:"invalid_scope",allowed:["global","project"]}),!0;let K=Y.scope??"global";if(!U2(Q-1,K))return L(Z,404,{error:"memory_not_found",index:Q,scope:K}),!0;return L(Z,200,{ok:!0,deleted:Q,scope:K}),!0}return!1};var MH=C(()=>{b1();M4()});var FH=async($,Z,J,z,G)=>{if($.method==="GET"&&G==="/v1/mcp"){let W=a$();return L(Z,200,{servers:W}),!0}let Q=G.match(/^\/v1\/mcp\/([^/]+)\/resources$/);if($.method==="GET"&&Q){let W=V$(Q[1]);if(!W)return L(Z,400,{error:"missing_name"}),!0;let H=a$()[W];if(!H)return L(Z,404,{error:"mcp_not_found",name:W}),!0;if(!H.connected)return L(Z,404,{error:"mcp_not_connected",name:W}),!0;let q=K4(W).servers[0];return L(Z,200,{name:W,resources:q.resources,templates:q.templates}),!0}let Y=G.match(/^\/v1\/mcp\/([^/]+)\/prompts$/);if($.method==="GET"&&Y){let W=V$(Y[1]);if(!W)return L(Z,400,{error:"missing_name"}),!0;let H=a$()[W];if(!H)return L(Z,404,{error:"mcp_not_found",name:W}),!0;if(!H.connected)return L(Z,404,{error:"mcp_not_connected",name:W}),!0;let q=K4(W).servers[0];return L(Z,200,{name:W,prompts:q.prompts}),!0}let K=G.match(/^\/v1\/mcp\/([^/]+)\/resources\/read$/);if($.method==="POST"&&K){let W=V$(K[1]);if(!W)return L(Z,400,{error:"missing_name"}),!0;let H=await j0($);if(!H.ok)return b0(Z,H),!0;let q=H.value.uri?.trim();if(!q)return L(Z,400,{error:"missing_uri"}),!0;let U=a$()[W];if(!U)return L(Z,404,{error:"mcp_not_found",name:W}),!0;if(!U.connected)return L(Z,404,{error:"mcp_not_connected",name:W}),!0;let M=await g3(q,W);return L(Z,200,{ok:!0,name:W,uri:q,content:M}),!0}let X=G.match(/^\/v1\/mcp\/([^/]+)\/prompts\/get$/);if($.method==="POST"&&X){let W=V$(X[1]);if(!W)return L(Z,400,{error:"missing_name"}),!0;let H=await j0($);if(!H.ok)return b0(Z,H),!0;let q=H.value.prompt?.trim();if(!q)return L(Z,400,{error:"missing_prompt"}),!0;let U=a$()[W];if(!U)return L(Z,404,{error:"mcp_not_found",name:W}),!0;if(!U.connected)return L(Z,404,{error:"mcp_not_connected",name:W}),!0;let M=await u3(q,H.value.arguments,W);return L(Z,200,{ok:!0,name:W,prompt:q,content:M}),!0}if($.method==="POST"&&G==="/v1/mcp"){let W=await j0($);if(!W.ok)return b0(Z,W),!0;let H=W.value;if(!H.name)return L(Z,400,{error:"missing_name"}),!0;if(H.remoteTransport&&!["streamable-http","sse","auto"].includes(H.remoteTransport))return L(Z,400,{error:"invalid_remote_transport",allowed:["streamable-http","sse","auto"]}),!0;let q=H.project?"project":"global",{loadMcpConfigFile:U,saveMcpConfig:M}=await Promise.resolve().then(() => (m$(),b2)),F=U(q),N={...H.environment?{environment:H.environment}:{},...H.headers?{headers:H.headers}:{},...H.remoteTransport?{remoteTransport:H.remoteTransport}:{},...H.timeout!==void 0?{timeout:H.timeout}:{},...H.connectTimeout!==void 0?{connectTimeout:H.connectTimeout}:{},...H.callTimeout!==void 0?{callTimeout:H.callTimeout}:{},enabled:H.enabled!==!1};if(H.url)F.mcpServers[H.name]={url:H.url,...H.token?{token:H.token}:{},...N};else if(typeof H.command==="string"&&H.command.length>0)F.mcpServers[H.name]={command:H.command,...H.args?{args:H.args}:{},...N};else if(Array.isArray(H.command)&&H.command.length>0)F.mcpServers[H.name]={command:H.command,...N};else return L(Z,400,{error:"provide command or url"}),!0;M(F,q),await O2();let f=a$()[H.name];return L(Z,201,{ok:!0,name:H.name,scope:q,connected:f?.connected??!1,...f?.error?{error:f.error}:{},...f?.tools?.length?{tools:f.tools}:{}}),!0}if($.method==="DELETE"&&G.startsWith("/v1/mcp/")){let W=V$(G.slice(8));if(!W)return L(Z,400,{error:"missing_name"}),!0;let H=z.searchParams.get("project")==="1"?"project":"global",{loadMcpConfigFile:q,saveMcpConfig:U}=await Promise.resolve().then(() => (m$(),b2)),M=q(H);if(!M.mcpServers[W])return L(Z,404,{error:"mcp_not_found",name:W,scope:H,available:Object.keys(M.mcpServers)}),!0;return delete M.mcpServers[W],U(M,H),await O2(),L(Z,200,{ok:!0,deleted:W,scope:H}),!0}let P=G.match(/^\/v1\/mcp\/([^/]+)\/(enable|disable)$/);if($.method==="POST"&&P){let W=V$(P[1]);if(!W)return L(Z,400,{error:"missing_name"}),!0;let H=P[2]==="enable",q=await j0($),U=q.ok&&q.value.scope==="project"?"project":"global",{loadMcpConfigFile:M,saveMcpConfig:F}=await Promise.resolve().then(() => (m$(),b2)),N=M(U);if(!N.mcpServers[W]){let f=F1().some((B)=>B.name===W);return L(Z,404,{error:"mcp_not_found",name:W,scope:U,...f?{hint:"server exists in another scope; pass the matching scope"}:{available:Object.keys(N.mcpServers)}}),!0}return N.mcpServers[W].enabled=H,F(N,U),await O2(),L(Z,200,{ok:!0,name:W,enabled:H,scope:U,connected:a$()[W]?.connected??!1}),!0}return!1};var NH=C(()=>{m$();M4()});var BH=async($,Z,J,z,G)=>{if($.method==="GET"&&G==="/v1/skills"){let K=B1();return L(Z,200,{count:K.length,enabled_count:K.filter((X)=>X.enabled).length,stale_disabled:I2(),skills:K.map(c9)}),!0}if($.method==="POST"&&G==="/v1/skills/reload"){T$({silent:!0});let K=B1();return L(Z,200,{ok:!0,count:K.length,enabled_count:K.filter((X)=>X.enabled).length,stale_disabled:I2(),skills:K.map(c9)}),!0}let Q=G.match(/^\/v1\/skills\/([^/]+)$/);if($.method==="GET"&&Q){let K=V$(Q[1]);if(!K)return L(Z,400,{error:"invalid_skill_name"}),!0;let X=m3(K);if(!X)return L(Z,404,{error:"skill_not_found",name:K,available:B1().map((P)=>P.name)}),!0;return L(Z,200,{skill:{...c9(X),content:X.content}}),!0}let Y=G.match(/^\/v1\/skills\/([^/]+)\/(enable|disable)$/);if($.method==="POST"&&Y){let K=V$(Y[1]);if(!K)return L(Z,400,{error:"invalid_skill_name"}),!0;let X=Y[2]==="enable";if(!m3(K))return L(Z,404,{error:"skill_not_found",name:K,available:B1().map((q)=>q.name)}),!0;let P=await j0($),W=P.ok?P.value.scope:void 0;if(W!==void 0&&W!=="global"&&W!=="project")return L(Z,400,{error:"invalid_scope",allowed:["global","project"]}),!0;let[H]=yZ([K],X,W??"global");return L(Z,200,{ok:!0,name:K,enabled:H.enabled,scope:W??"global",...H.blockedBy?{blocked_by:H.blockedBy}:{}}),!0}return!1};var VH=C(()=>{n$();M4()});var fH=async($,Z,J,z,G)=>{if($.method==="GET"&&G==="/health")return L(Z,200,{ok:!0,service:"min-agent",version:J.version}),!0;if($.method==="GET"&&G==="/v1/meta")return L(Z,200,{version:J.version,cwd:process.cwd(),instructions_chars:J.instructions.join(`
|
|
430
|
+
`).length,sandbox:o9(),permission:d9(),thinking:P2(),memory:e1()}),!0;if($.method==="GET"&&G==="/v1/update"){let Q=await JG({currentVersion:J.version});return L(Z,200,{current:Q.current,latest:Q.latest,update_available:Q.updateAvailable,...Q.latest===null?{error:"registry_unavailable"}:{}}),!0}if($.method==="GET"&&G==="/v1/models"){let Q=G0(),Y=s(Q),K=Y?.baseURL,X=Y?.apiKey;if(!K||!X)return L(Z,500,{error:"provider_not_configured"}),!0;let P=await j4(K,X);return L(Z,200,{default_model:Y?.defaultModel??null,models:P}),!0}if($.method==="GET"&&G==="/v1/budget"){let Q=O8();return L(Z,200,{maxCostUSD:Q.maxCostUSD??null,source:Q.source}),!0}if($.method==="POST"&&G==="/v1/budget"){let Q=await j0($);if(!Q.ok)return b0(Z,Q),!0;let Y=Q.value.maxCostUSD;if(typeof Y!=="number"||!Number.isFinite(Y)||Y<=0)return L(Z,400,{error:"invalid_max_cost",detail:"maxCostUSD must be a positive number"}),!0;let K=O$(Q.value.scope);if(!K.ok)return L(Z,400,{error:"invalid_scope",allowed:["global","project"]}),!0;let X=K.scope??"global";U5(Y,X);let P=O8();return L(Z,200,{ok:!0,maxCostUSD:P.maxCostUSD??Y,source:P.source,scope:X}),!0}if($.method==="GET"&&G==="/v1/sandbox")return L(Z,200,o9()),!0;if($.method==="GET"&&G==="/v1/permission")return L(Z,200,d9()),!0;if($.method==="POST"&&G==="/v1/permission"){let Q=await j0($);if(!Q.ok)return b0(Z,Q),!0;let Y=A$(Q.value.permission);if(!Y)return L(Z,400,{error:"invalid_permission",detail:"permission must be ask, accept-edits, or allow-all"}),!0;let K=O$(Q.value.scope);if(!K.ok)return L(Z,400,{error:"invalid_scope",allowed:["global","project"]}),!0;let X=K.scope??"global";return J2(Y,X),L(Z,200,{ok:!0,scope:X,...d9()}),!0}if($.method==="GET"&&G==="/v1/thinking")return L(Z,200,P2()),!0;if($.method==="POST"&&G==="/v1/thinking"){let Q=await j0($);if(!Q.ok)return b0(Z,Q),!0;let Y=S0(Q.value.thinking);if(!Y)return L(Z,400,{error:"invalid_thinking",detail:"thinking must be off, low, medium, high, or max"}),!0;let K=O$(Q.value.scope);if(!K.ok)return L(Z,400,{error:"invalid_scope",allowed:["global","project"]}),!0;let X=K.scope??"global";return a1(Y,X),L(Z,200,{ok:!0,scope:X,...P2()}),!0}if($.method==="POST"&&G==="/v1/sandbox"){let Q=await j0($);if(!Q.ok)return b0(Z,Q),!0;let Y=Q.value,K=Y.mode===void 0?void 0:y$(Y.mode);if(Y.mode!==void 0&&!K)return L(Z,400,{error:"invalid_sandbox",detail:"mode must be off, workspace, or strict"}),!0;let X=Y.network===void 0?void 0:o$(Y.network);if(Y.network!==void 0&&!X)return L(Z,400,{error:"invalid_network",detail:"network must be allow or deny"}),!0;let P=lJ(Y.extraWriteRoots),W=lJ(Y.extraReadRoots);if(!P.ok||!W.ok)return L(Z,400,{error:"invalid_roots",detail:"extraWriteRoots and extraReadRoots must be arrays of non-empty strings"}),!0;if(!K&&!X&&P.value===void 0&&W.value===void 0)return L(Z,400,{error:"invalid_body",detail:"Provide mode, network, extraWriteRoots, or extraReadRoots"}),!0;let H=O$(Y.scope);if(!H.ok)return L(Z,400,{error:"invalid_scope",allowed:["global","project"]}),!0;let q=H.scope??"global";return _4({...K?{mode:K}:{},...X?{network:X}:{},...P.value?{extraWriteRoots:P.value}:{},...W.value?{extraReadRoots:W.value}:{}},q),L(Z,200,{ok:!0,scope:q,...o9()}),!0}if($.method==="GET"&&G==="/v1/diff"){let Q=await uJ();if(!Q.ok)return L(Z,200,{ok:!1,reason:Q.reason,message:Q.message}),!0;return L(Z,200,{ok:!0,diff:Q.diff}),!0}if($.method==="GET"&&G==="/v1/rules")return L(Z,200,{count:J.instructions.length,rules:J.instructions.map((Q)=>{return{source:(Q.split(`
|
|
431
|
+
`)[0]??"").replace("Instructions from: ",""),chars:Q.length}})}),!0;if($.method==="GET"&&G==="/v1/project"){let Q=u1();return L(Z,200,{project:Q}),!0}if($.method==="GET"&&G==="/v1/context"){let Q=G0(),Y=s(Q),K=await e$(Y?.defaultModel);return L(Z,200,{context_window:K.tokens,source:K.source,model:Y?.defaultModel??null,...T3()}),!0}if($.method==="POST"&&G==="/v1/context"){let Q=await j0($);if(!Q.ok)return b0(Z,Q),!0;let Y=typeof Q.value.level==="string"?C6(Q.value.level):null;if(!Y)return L(Z,400,{error:"invalid_context_level",detail:`level must be one of: ${N$.join(", ")}`}),!0;if(!y4(Y).ok)return L(Z,400,{error:"ctx_not_supported",detail:"context levels are only available for an Ollama provider"}),!0;let X=s(G0()),P=await e$(X?.defaultModel);return L(Z,200,{ok:!0,context_window:P.tokens,source:P.source,model:X?.defaultModel??null,...T3()}),!0}if($.method==="GET"&&G==="/v1/cost"){let Q=G0(),Y=s(Q),K=z.searchParams.get("model")??Y?.defaultModel??null,X=z.searchParams.get("input"),P=z.searchParams.get("output"),W=X?parseInt(X,10):0,H=P?parseInt(P,10):0;if(Number.isNaN(W)||Number.isNaN(H)||W<0||H<0)return L(Z,400,{error:"invalid_tokens",detail:"input/output must be non-negative integers"}),!0;let q=K?await r6(K):null,U=q?l6({inputTokens:W,outputTokens:H},q):null;return L(Z,200,{model:K,price:q,cost_usd:U}),!0}return!1};var _H=C(()=>{l();K1();u0();hJ();$8();m4();f2();y2();Y6();M4()});var LH={};M0(LH,{runServe:()=>WD});import{createServer as YD}from"http";import{timingSafeEqual as KD}from"crypto";function XD($){if(process.env.MIN_AGENT_SERVE_TOKEN?.trim())return!0;let Z=$.headers.origin?.trim();if(!Z||Z==="null")return!0;try{let J=new URL(Z).hostname;if(J==="localhost"||J==="127.0.0.1"||J==="[::1]")return!0}catch{return!1}return!1}function PD($){let Z=process.env.MIN_AGENT_SERVE_TOKEN?.trim();if(!Z)return!0;let J=$.headers.authorization?.trim();if(!J?.startsWith("Bearer "))return!1;let z=Buffer.from(J.slice(7)),G=Buffer.from(Z);return z.length===G.length&&KD(z,G)}async function WD($={}){if(!G1())console.error("Not configured. Run: min-agent setup"),process.exit(1);let Z=$.host??process.env.MIN_AGENT_SERVE_HOST??"127.0.0.1",J=$.port??parseInt(process.env.MIN_AGENT_SERVE_PORT??"8787",10);if(!(Z==="127.0.0.1"||Z==="::1"||Z==="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"),J6(!0),console.error("\x1B[90m⟳ Initializing MCP, skills, instructions…\x1B[0m"),await u4(),T$();let G={host:Z,version:r1(),instructions:await V1(),approvalGate:GH(),activeChats:0},Q=[fH,PH,HH,UH,FH,BH],Y=YD(async(P,W)=>{let H=n9();if(P.method==="OPTIONS"){W.writeHead(204,H),W.end();return}if(!PD(P)){L(W,401,{error:"unauthorized",detail:"Set Authorization: Bearer <MIN_AGENT_SERVE_TOKEN> when MIN_AGENT_SERVE_TOKEN is set"});return}if(rJ()&&!XD(P)){L(W,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 q=new URL(P.url??"/",`http://${Z}`),U=q.pathname.replace(/\/$/,"")||"/";try{for(let M of Q)if(await M(P,W,G,q,U))return;L(W,404,{error:"not_found",path:U})}catch(M){L(W,500,{error:"internal_error",message:M?.message??String(M)})}});await new Promise((P,W)=>{Y.once("error",W),Y.listen(J,Z,()=>{console.error(`\x1B[32m✓ min-agent serve\x1B[0m http://${Z}:${J} (API: docs/API.md)`),P()})});let K=async()=>{await X4(),Y.closeAllConnections?.(),await new Promise((P)=>Y.close(()=>P()))},X=async()=>{await K(),process.exit(0)};return process.on("SIGINT",X),process.on("SIGTERM",X),{close:K}}var jH=C(()=>{m$();n$();P4();l();Z$();M4();WH();qH();MH();NH();VH();_H()});Z$();q$();v8();Y6();import{Command as oA,Option as H8}from"commander";function dA($,Z){return[...Z,$]}function rA($){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)",dA,[]).addOption(new H8("--sandbox <mode>","isolation mode (off, workspace, strict)").argParser(oz)).addOption(new H8("--network <policy>","network policy (allow, deny)").argParser(dz)).addOption(new H8("--permission <mode>","confirmation mode (ask, accept-edits, allow-all)").argParser(rz)).addOption(new H8("--think <level>","thinking intensity (off, low, medium, high, max)").argParser(lz)).addOption(new H8("--memory <mode>","memory across sessions (on, off; default off)").argParser(iz)).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 lA(){let $=new oA("min-agent");return $.description("min-agent - Minimal AI coding agent").version(r1(),"-v, --version","show version number").helpOption("-h, --help","show help").allowUnknownOption().enablePositionalOptions().configureOutput({writeErr:(Z)=>process.stderr.write(Z),outputError:(Z)=>process.stderr.write(Z)}).exitOverride(),rA($),$.argument("[prompt...]","prompt to send in an interactive session"),$.addHelpText("after",`
|
|
430
432
|
session:
|
|
431
433
|
min-agent start interactive session
|
|
432
434
|
min-agent <message> start interactive session and send message
|
|
@@ -506,29 +508,30 @@ examples:
|
|
|
506
508
|
min-agent rules edit
|
|
507
509
|
min-agent mcp add filesystem npx -y @modelcontextprotocol/server-filesystem /tmp
|
|
508
510
|
min-agent mcp add remote --url https://example.com/mcp --token "$TOKEN"
|
|
509
|
-
`),$}function
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
`))
|
|
514
|
-
`)),!
|
|
515
|
-
`)),!
|
|
516
|
-
`)
|
|
517
|
-
`)
|
|
518
|
-
`);
|
|
519
|
-
`)
|
|
511
|
+
`),$}function q8($){if($.yes)J6(!0)}async function U8($){if($.sandbox!==void 0||$.network!==void 0){let{setSandboxOverride:Z}=await Promise.resolve().then(() => (u0(),X5));if($.sandbox!==void 0)Z({mode:$.sandbox});if($.network!==void 0)Z({network:$.network})}if($.permission!==void 0){let{setPermissionOverride:Z}=await Promise.resolve().then(() => (Z$(),S8));Z($.permission)}if($.think!==void 0){let{setThinkingOverride:Z}=await Promise.resolve().then(() => (K1(),h5));Z($.think)}if($.memory!==void 0){let{setMemoryOverride:Z}=await Promise.resolve().then(() => (b1(),i5));Z($.memory)}}function iA($,Z){return Z.length>0||Boolean($.resume)||$.image.length>0||Boolean($.model)||Boolean($.provider)}function tA($){let Z=[],J=[];for(let z of $)if(z.startsWith("--"))J.push(`Unknown option: ${z}`);else Z.push(z);return{rest:Z,errors:J}}async function aA($,Z){q8(Z);let{rest:J,errors:z}=tA($),G=iA(Z,J);if((Z.sandbox!==void 0||Z.network!==void 0||Z.permission!==void 0||Z.think!==void 0||Z.memory!==void 0)&&!G){let{runWriteConfig:K}=await Promise.resolve().then(() => (zQ(),JQ));await K({sandbox:Z.sandbox,network:Z.network,permission:Z.permission,think:Z.think,memory:Z.memory,scope:Z.project?"project":Z.global?"global":void 0});return}if(await U8(Z),z.length>0){console.error(z[0]),process.exitCode=1;return}let{startTuiSession:Y}=await Promise.resolve().then(() => (dJ(),sW));await Y({model:Z.model,provider:Z.provider,resume:Z.resume,images:Z.image,positionals:J})}async function eW($,Z){if($.length===1&&$[0]==="-V"){process.stdout.write(`${r1()}
|
|
512
|
+
`);return}let J=lA();J.action((z,G)=>aA(z,G)),Z(J);try{await J.parseAsync($,{from:"user"})}catch(z){if(z instanceof e){console.error(E8(z)),process.exitCode=A5(z);return}if(sA(z)){process.exitCode=z.exitCode;return}console.error(E8(z)),process.exitCode=2}}function sA($){return typeof $==="object"&&$!==null&&"exitCode"in $&&"code"in $}v8();P7();import{Option as sH}from"commander";l();q$();async function $H($){let Z=a(),J=$.provider?Z.providers?.find((G)=>G.name===$.provider):s(Z);if(!J?.baseURL||!J?.apiKey)throw new e("Not configured.",{hint:"Run: min-agent setup"});if(z1(J)){console.log("Available models (1):"),console.log(` ${J.defaultModel} ← default`);return}console.log(`Fetching models (${J.name??"default"})...`);let z=await j4(J.baseURL,J.apiKey);if(z.length===0)console.log("No models found or unable to fetch model list.");else{console.log(`
|
|
513
|
+
Available models (${z.length}):`);for(let G of z){let Q=G===J.defaultModel?" ← default":"";console.log(` ${G}${Q}`)}}}dJ();async function ZH($,Z){q8(Z),await U8(Z),await oJ({model:Z.model,provider:Z.provider,resume:Z.resume,images:Z.image,positionals:$})}d4();l();function JH($,Z,J){let z=$.join(" "),G=Z.length>0;if(z==="-"){let Q=Z;if(!Q.trim())return{ok:!1,error:"Usage: min-agent exec <message>"};return{ok:!0,prompt:Q}}if(!z){if(J||!G)return{ok:!1,error:"Usage: min-agent exec <message>"};return{ok:!0,prompt:Z}}if(G&&!J)return{ok:!0,prompt:`${z}
|
|
514
|
+
|
|
515
|
+
${Z}`};return{ok:!0,prompt:z}}q$();async function zH($,Z){if(!G1())throw new e("Not configured.",{hint:"Run: min-agent setup"});if(q8(Z),await U8(Z),Z.permission===void 0&&!Z.yes){let{setExecPermissiveDefault:X}=await Promise.resolve().then(() => (Z$(),S8));X(!0)}let J=Boolean(process.stdin.isTTY),G=$.join(" ")==="-"||!J,Q="";if(G)try{let X=[];for await(let P of process.stdin)X.push(Buffer.isBuffer(P)?P:Buffer.from(P));Q=Buffer.concat(X).toString("utf-8")}catch{throw new e("Failed to read stdin")}let Y=JH($,Q,J);if(!Y.ok)throw new e(Y.error);if(await EJ(Y.prompt,Z.model,Z.image.length>0?Z.image:void 0,Z.provider,Z.resume))process.exitCode=1}l();q$();async function AH($){if(!G1())throw new e("Not configured.",{hint:"Run: min-agent setup"});let{runServe:Z}=await Promise.resolve().then(() => (jH(),LH));await Z({port:$.port,host:$.host})}t5();async function iJ($,Z,J){let z=Z.project?"project":Z.global?"global":void 0,G=r8({positionals:$,flagMode:J.sandbox,flagNetwork:J.network??Z.network,scope:z});if(console.log(G.lines.join(`
|
|
516
|
+
`)),!G.ok)process.exitCode=1}a5();async function DH($,Z,J){let z=Z.project?"project":Z.global?"global":void 0,G=i8({positionals:$,flagMode:J.permission,scope:z});if(console.log(G.lines.join(`
|
|
517
|
+
`)),!G.ok)process.exitCode=1}s5();async function OH($,Z,J){let z=Z.project?"project":Z.global?"global":void 0,G=a8({positionals:$,flagEffort:J.think,scope:z});if(console.log(G.lines.join(`
|
|
518
|
+
`)),!G.ok)process.exitCode=1}f2();var h2=["Usage: min-agent ctx [2k|4k|8k|12k|16k|32k|64k|128k|256k|auto]"," Context levels are only available for an Ollama provider."].join(`
|
|
519
|
+
`);function CH($){if($.positionals[0]==="--help"||$.positionals[0]==="-h")return{ok:!0,lines:[h2]};if(!a7())return{ok:!1,lines:["Context levels are only available for an Ollama provider.",h2]};if($.positionals.length===0){let z=s7();return{ok:!0,lines:[`Current context window: ${z.choice==="auto"&&z.tokens!=null?`${z.tokens}`:z.choice}`,h2]}}if($.positionals.length>1)return{ok:!1,lines:[h2]};let Z=C6($.positionals[0]);if(!Z)return{ok:!1,lines:[h2]};let J=y4(Z);if(!J.ok)return{ok:!1,lines:["Context levels are only available for an Ollama provider.",h2]};return{ok:!0,lines:[`✓ Context window set to ${J.choice==="auto"?"auto":J4(J.choice)}`]}}async function bH($){let Z=CH({positionals:$});if(console.log(Z.lines.join(`
|
|
520
|
+
`)),!Z.ok)process.exitCode=1}import{existsSync as wH,writeFileSync as HD,mkdirSync as IH}from"fs";import tJ from"path";function qD(){let $=tJ.join(process.cwd(),".min-agent"),Z=tJ.join($,"skills"),J=tJ.join($,"mcp.json");if(!wH(Z))IH(Z,{recursive:!0});if(!wH(J))IH($,{recursive:!0}),HD(J,JSON.stringify({mcpServers:{}},null,2),"utf-8")}async function TH(){qD(),console.log(`✓ Initialized .min-agent/ in ${process.cwd()}`)}l();import{existsSync as UD,writeFileSync as MD,mkdirSync as FD}from"fs";async function RH(){let{loadInstructions:$}=await Promise.resolve().then(() => (P4(),IX)),Z=await $();if(Z.length===0)console.log("No instruction rules loaded."),console.log(""),console.log("Add rules by creating:"),console.log(` Global: ${$2()}`),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 ${Z.length} instruction source(s):
|
|
521
|
+
`);for(let J of Z){let z=J.split(`
|
|
522
|
+
`)[0];console.log(` ${z}`)}}}async function kH(){let $=$2();if(!UD($))FD(P0(),{recursive:!0}),MD($,`# Global Agent Rules
|
|
520
523
|
|
|
521
524
|
<!-- Add your custom instructions here. They will be included in every conversation. -->
|
|
522
|
-
`,"utf-8");let
|
|
523
|
-
Resume with: min-agent --resume <id>`)}}async function
|
|
524
|
-
`)),!z.ok)process.exitCode=1;return!0}async function
|
|
525
|
-
or: min-agent mcp add <name> --url <https://host/mcp> [--sse|--streamable-http] [--token <bearer>] [--project] [--skip-check]`,
|
|
526
|
-
Use: min-agent mcp info <name> for details`)}async function
|
|
527
|
-
All enabled MCP servers are available.`)}async function
|
|
528
|
-
\x1B[33m⚠ disabledSkills/enabledSkills entries matching no skill: ${
|
|
529
|
-
Use: min-agent skills info <name> for details`)}async function
|
|
525
|
+
`,"utf-8");let Z=process.env.EDITOR||"vi",{execSync:J}=await import("child_process");J(`${Z} "${$}"`,{stdio:"inherit"})}Y6();async function yH(){let $=await zG();if($.status==="check-failed"||$.status==="install-failed")process.exitCode=1}q$();import{writeFileSync as ND}from"fs";async function SH(){let{listSessions:$}=await Promise.resolve().then(() => (u$(),E4)),Z=$();if(Z.length===0)console.log("No saved sessions."),console.log("Sessions are auto-saved when you exit interactive chat.");else{console.log(`Sessions (${Z.length}):`);for(let J of Z.slice(0,20)){let z=J.updated.split("T")[0];console.log(` ${J.id} ${z} ${J.title} (${J.messageCount} msgs)`)}console.log(`
|
|
526
|
+
Resume with: min-agent --resume <id>`)}}async function EH($){let{deleteSession:Z}=await Promise.resolve().then(() => (u$(),E4));if(Z($))console.log(`✓ Session ${$} deleted`);else throw new e(`Session ${$} not found`)}async function vH($,Z){let J=Z.join(" ");if(!J)throw new e("Usage: min-agent history rename <id> <title>");let{renameSession:z}=await Promise.resolve().then(() => (u$(),E4));if(z($,J))console.log(`✓ Session ${$} renamed to: ${J}`);else throw new e(`Session ${$} not found`)}async function xH($,Z){let{loadSession:J}=await Promise.resolve().then(() => (u$(),E4)),z=J($);if(!z)throw new e(`Session ${$} not found`);let G=JSON.stringify(z,null,2);if(Z.output)try{ND(Z.output,G,"utf-8"),console.log(`✓ Session ${$} exported to ${Z.output}`)}catch(Q){throw new e(`Export failed: ${Q.message}`,{exitCode:2})}else console.log(G)}b1();e5();q$();function BD($){let Z=C$($),J=$==="project"?"Project memories":"Global memories";if(Z.length===0){console.log(`${J}: none`);return}console.log(`${J} (${Z.length}):`);for(let z of Z.map((G,Q)=>d5(G,Q,{date:!0})))console.log(z)}async function gH($,Z,J){if(!$&&J===void 0)return!1;if($&&$!=="list"&&!h0($))return!1;if($==="list")return!1;let z=e8({positionals:$?[$]:[],flagMode:J,scope:Z});if(console.log(z.lines.join(`
|
|
527
|
+
`)),!z.ok)process.exitCode=1;return!0}async function uH($){let{memory:Z,source:J}=C4();if(console.log(`Current memory: ${s1(Z)} (${W6(J)})`),!$&&C$("project").length===0&&C$("global").length===0){if(console.log("No memories stored."),!X1())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 G of z)BD(G);if(!X1())console.log("Memories are stored but not used in chat until you run: min-agent memory on")}async function hH($,Z){let J=$.join(" ");if(!J)throw new e("Usage: min-agent memory add <text> [--project|--global]");let z=Z??H6();q2(J,[],z);let G=X1()?"":" (memory is off — turn on with: min-agent memory on)";console.log(`✓ ${z==="project"?"Project":"Global"} memory saved: "${J}"${G}`)}async function mH($,Z){let J=$.join(" ");if(!J)throw new e("Usage: min-agent memory search <query> [--project|--global]");let G=(Z?[Z]:["project","global"]).flatMap((Q)=>b4(J,Q).map((Y)=>{let K=Y.tags.length>0?` [${Y.tags.join(", ")}]`:"";return` [${Q}] #${Y.index+1}: ${Y.content}${K}`}));if(G.length===0)console.log(`No memories matching "${J}"`);else{console.log(`Found ${G.length} memory(s):`);for(let Q of G)console.log(Q)}}async function nH($,Z){let J=Number.parseInt($,10);if(Number.isNaN(J))throw new e("Usage: min-agent memory delete <number> [--project|--global]");let z=Z??H6();if(U2(J-1,z))console.log(`✓ ${z==="project"?"Project":"Global"} memory #${J} deleted`);else throw new e(`${z==="project"?"Project":"Global"} memory #${J} not found`)}m$();q$();function VD($){let Z={};for(let J of $??[]){let z=J.indexOf("=");if(z<=0)throw new e(`Invalid --env format: ${J}`,{hint:"use KEY=VALUE"});Z[J.slice(0,z)]=J.slice(z+1)}return Z}async function cH($,Z,J){let z=J.project?"project":"global";if(J.sse&&J.streamableHttp)throw new e("--sse and --streamable-http are mutually exclusive");let G=`Usage: min-agent mcp add <name> [--project] [--skip-check] <command...>
|
|
528
|
+
or: min-agent mcp add <name> --url <https://host/mcp> [--sse|--streamable-http] [--token <bearer>] [--project] [--skip-check]`,Q;if(J.url?.trim()){if(Q={url:J.url.trim(),enabled:!0,remoteTransport:J.streamableHttp?"streamable-http":J.sse?"sse":"auto",...J.timeout?{timeout:J.timeout}:{}},J.token?.trim())Q.token=J.token.trim()}else if(Z.length>0)Q={command:Z,enabled:!0,...J.timeout?{timeout:J.timeout}:{}};else throw new e(G);let Y=VD(J.env);if(Object.keys(Y).length>0)Q.environment=Y;let K=0;if(!J.skipCheck){console.log(`Validating MCP server "${$}"...`);let H=await x3($,Q);if(!H.ok)throw new e(`MCP server "${$}" validation failed: ${H.error??"unknown error"}`,{exitCode:2});K=H.toolCount}else console.log(`Skipping MCP validation for "${$}" (--skip-check).`);let X=S1(z);X.mcpServers[$]=Q,v6(X,z);let P=J.skipCheck?"":` (${K} tools detected)`,W=J.project?" [project]":"";console.log(`✓ MCP server "${$}" added${W}: ${v3(Q)}${P}`)}async function pH($,Z){let J=Z.project?"project":"global",z=S1(J);if(!z.mcpServers[$]){let G=F1().find((Q)=>Q.name===$);throw new e(G?`MCP server "${$}" is defined in ${G.scope} scope, not ${J}.`:`MCP server "${$}" not found`)}delete z.mcpServers[$],v6(z,J),console.log(`✓ MCP server "${$}" removed${Z.project?" [project]":""}`)}async function oH(){let $=F1();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:Z,config:J,scope:z}of $){let G=J.enabled===!1?"\x1B[90mdisabled\x1B[0m":"\x1B[32menabled\x1B[0m";console.log(` ${Z} ${G}${z==="project"?" \x1B[90m[project]\x1B[0m":""}`)}console.log(`
|
|
529
|
+
Use: min-agent mcp info <name> for details`)}async function dH($){let Z=F1().find((G)=>G.name===$);if(!Z)throw new e(`MCP server "${$}" not found`);let J=Z.config;if(console.log(`Name: ${$}`),console.log(`Scope: ${Z.scope}`),console.log(`Status: ${J.enabled===!1?"disabled":"enabled"}`),console.log(`Binding: ${v3(J)}`),J.command)console.log(`Command: ${Array.isArray(J.command)?J.command.join(" "):`${J.command} ${(J.args??[]).join(" ")}`.trim()}`);if(J.url){if(console.log(`URL: ${J.url}`),J.remoteTransport)console.log(`Transport: ${J.remoteTransport}`);if(J.oauth===!1)console.log("OAuth: disabled");else if(J.oauth)console.log(`OAuth: enabled${J.oauth.clientId?" (clientId set)":""}`)}if(J.headers)console.log(`Headers: ${Object.keys(J.headers).join(", ")} (values hidden)`);if(J.token)console.log("Token: ***");if(J.environment)console.log(`Env: ${Object.keys(J.environment).join(", ")}`);if(J.timeout)console.log(`Timeout: ${J.timeout}ms`);if(J.connectTimeout)console.log(`ConnectTimeout: ${J.connectTimeout}ms`);if(J.callTimeout)console.log(`CallTimeout: ${J.callTimeout}ms`);let z=a$()[$];if(z?.connected){let G=K4($).servers[0];if(G)console.log(`Tools: ${z.tools.join(", ")||"(none)"}`),console.log(`Resources: ${G.resources.length===0?"(none)":G.resources.map((Q)=>Q.uri).join(", ")}`),console.log(`Prompts: ${G.prompts.length===0?"(none)":G.prompts.map((Q)=>Q.name).join(", ")}`)}}async function rH(){let $=await IZ();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 Z=0;console.log("MCP Check Results:");for(let J of $){if(!J.enabled){console.log(` ${J.name}: skipped (disabled)`);continue}if(J.ok)console.log(` ${J.name}: ok (${J.toolCount} tools)`);else Z++,console.log(` ${J.name}: failed${J.error?` - ${J.error}`:""}`)}if(Z>0)throw new e(`${Z} MCP server(s) failed.`,{exitCode:1});console.log(`
|
|
530
|
+
All enabled MCP servers are available.`)}async function aJ($,Z,J){let z=J.project?"project":"global",G=Z?"enable":"disable";if($.length===0)throw new e(`Usage: min-agent mcp ${G} <name...> [--project]`);let Q=S1(z);for(let Y of $){if(!Q.mcpServers[Y]){console.error(`MCP server "${Y}" not found${J.project?" in project scope":""}`);continue}Q.mcpServers[Y].enabled=Z,console.log(`✓ MCP server "${Y}" ${G}d${J.project?" [project]":""}`)}v6(Q,z)}n$();q$();import{existsSync as lH,writeFileSync as fD,mkdirSync as _D}from"fs";import t4 from"path";import LD from"os";function jD($,Z){let J=$.replace(/\s+/g," ").trim();return J.length<=Z?J:`${J.slice(0,Z-1)}…`}async function iH($){T$({silent:!0});let{getAllSkills:Z,getStaleDisabledSkills:J}=await Promise.resolve().then(() => (n$(),m6)),z=Z().sort((Q,Y)=>Q.name.localeCompare(Y.name)),G=J();if($){console.log(JSON.stringify({count:z.length,enabled_count:z.filter((Q)=>Q.enabled).length,stale_disabled:G,skills:z.map((Q)=>({name:Q.name,description:Q.description,location:Q.location,enabled:Q.enabled,...Q.disabledScope?{disabled_scope:Q.disabledScope}:{},...Q.version?{version:Q.version}:{},...Q.allowedTools.length?{allowed_tools:Q.allowedTools}:{},...Q.requiredBins.length?{requires_bins:Q.requiredBins}:{},...Q.builtin?{builtin:!0}:{},...Q.alwaysLoad?{always_load:!0}:{}}))},null,2));return}if(z.length===0&&G.length===0){console.log("No skills found. Add SKILL.md files in .min-agent/skills/<name>/");return}console.log(`Skills (${z.filter((Q)=>Q.enabled).length} enabled, ${z.filter((Q)=>!Q.enabled).length} disabled):`);for(let Q of z){let Y=Q.enabled?"\x1B[32menabled \x1B[0m":`\x1B[90mdisabled(${Q.disabledScope==="project"?"proj":"glob"})\x1B[0m`,K=Q.builtin?" \x1B[90mbuiltin\x1B[0m":"";console.log(` ${Q.name} ${Y}${K} \x1B[90m${jD(Q.description,60)}\x1B[0m`),console.log(` \x1B[90m${Q.location}\x1B[0m`)}if(G.length>0)console.log(`
|
|
531
|
+
\x1B[33m⚠ disabledSkills/enabledSkills entries matching no skill: ${G.join(", ")}\x1B[0m`),console.log(`\x1B[33m Remove them with: min-agent skills enable ${G.join(" ")} (add --project if the entry is project-scoped)\x1B[0m`);console.log(`
|
|
532
|
+
Use: min-agent skills info <name> for details`)}async function tH($,Z){T$({silent:!0});let{getSkill:J,getAllSkills:z}=await Promise.resolve().then(() => (n$(),m6)),G=J($);if(!G){let Q=z().map((Y)=>Y.name);throw new e(`Skill "${$}" not found.${Q.length?` Available: ${Q.join(", ")}`:" No skills discovered."}`)}if(Z){console.log(JSON.stringify(G,null,2));return}if(console.log(`Name: ${G.name}`),console.log(`Status: ${G.enabled?"enabled":`disabled (${G.disabledScope} scope)`}`),G.builtin)console.log("Source: builtin");if(G.version)console.log(`Version: ${G.version}`);if(console.log(`Description: ${G.description}`),console.log(`Location: ${G.location}`),G.allowedTools.length>0)console.log(`Tools: ${G.allowedTools.join(", ")}`);if(G.requiredBins.length>0)console.log(`Requires: ${G.requiredBins.join(", ")}`);if(G.content.trim())console.log(`
|
|
530
533
|
--- Content ---
|
|
531
|
-
`),console.log(
|
|
534
|
+
`),console.log(G.content.trim())}async function sJ($,Z,J){let z=Z?"enable":"disable";if($.length===0)throw new e(`Usage: min-agent skills ${z} <name...> [--project]`);T$({silent:!0});let{getAllSkills:G,setSkillEnabled:Q,getStaleDisabledSkills:Y}=await Promise.resolve().then(() => (n$(),m6)),K=new Set(G().map((W)=>W.name)),X=new Set(Y()),P=$.filter((W)=>!K.has(W)&&!(Z&&X.has(W)));if(P.length>0)throw new e(`Skill${P.length>1?"s":""} not found: ${P.join(", ")}`,{hint:K.size?`Available: ${[...K].join(", ")}`:"No skills discovered."});for(let W of Q($,Z,J))if(console.log(`✓ Skill "${W.name}" ${z}d (${J} scope)`),W.blockedBy)console.log(`\x1B[33m ⚠ still ${W.enabled?"enabled":"disabled"} — overridden by ${W.blockedBy} scope\x1B[0m`)}async function aH($,Z){if(!/^[\w-]+$/.test($))throw new e("Invalid skill name",{hint:"use letters, digits, _ or -"});if(!Z&&!lH(t4.join(process.cwd(),".min-agent")))throw new e("当前目录没有 .min-agent/,无法创建项目级 skill。",{hint:"先运行: min-agent init"});let J=Z?t4.join(LD.homedir(),".agents","skills"):t4.join(process.cwd(),".min-agent","skills"),z=t4.join(J,$);if(lH(t4.join(z,"SKILL.md")))throw new e(`Skill "${$}" already exists at ${z}`);_D(z,{recursive:!0}),fD(t4.join(z,"SKILL.md"),`---
|
|
532
535
|
name: ${$}
|
|
533
536
|
description: What this skill does
|
|
534
537
|
# version: 1.0.0
|
|
@@ -541,4 +544,4 @@ description: What this skill does
|
|
|
541
544
|
# ${$}
|
|
542
545
|
|
|
543
546
|
Write the skill instructions here.
|
|
544
|
-
`,"utf-8"),console.log(`✓ Created skill "${$}" at ${
|
|
547
|
+
`,"utf-8"),console.log(`✓ Created skill "${$}" at ${t4.join(z,"SKILL.md")}`)}function eH($){let Z=()=>$.opts();for(let X of["chat","code"])$.command(X).description("same as interactive session (compat)").argument("[prompt...]","prompt to send").allowUnknownOption().action(async(P)=>{await ZH(P,Z())});$.command("exec").description("run one message non-interactively").argument("[message...]",'message to send (use "-" to read from stdin)').allowUnknownOption().action(async(X)=>{await zH(X,Z())}),X7($,Z),$.command("init").description("initialize .min-agent/ in current directory").action(TH),$.command("models").description("list available models").action(async()=>{await $H(Z())});let J=$.command("rules").description("show or edit instruction rules");J.action(RH),J.command("edit").description("edit the global rules file").action(kH);let z=$.command("memory").description("show or set memory, and manage saved memories");z.argument("[state]","on or off"),z.action(async(X)=>{let P=Z(),W=P.project?"project":P.global?"global":void 0;if(await gH(X,W,P.memory))return;if(X&&X!=="list"){let{CliError:H}=await Promise.resolve().then(() => (q$(),pz));throw new H("Usage: min-agent memory [on|off|list|add|search|delete] [--project|--global]")}await uH(W)}),z.command("add").argument("<text...>").description("add a memory").action(async(X)=>{let P=Z();await hH(X,P.project?"project":P.global?"global":void 0)}),z.command("search").argument("<query...>").description("search memories").action(async(X)=>{let P=Z();await mH(X,P.project?"project":P.global?"global":void 0)}),z.command("delete").argument("<index>").description("delete a memory by index").action(async(X)=>{let P=Z();await nH(X,P.project?"project":P.global?"global":void 0)});let G=$.command("sandbox").description("show or set isolation mode (uses --project/--global)").argument("[mode]","off, workspace, or strict");G.action(async(X)=>{let P=Z();await iJ(X?[X]:[],P,P)}),G.command("network").description("show or set network policy").argument("[policy]","allow or deny").action(async(X)=>{let P=Z();await iJ(["network",...X?[X]:[]],P,P)}),$.command("permission").description("show or set confirmation mode (uses --project/--global)").argument("[mode]","ask, accept-edits, or allow-all").action(async(X)=>{let P=Z();await DH(X?[X]:[],P,P)}),$.command("think").description("show or set thinking intensity (uses --project/--global)").argument("[level]","off, low, medium, high, or max").action(async(X)=>{let P=Z();await OH(X?[X]:[],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(X)=>{await bH(X?[X]:[])});let Q=$.command("mcp").description("manage MCP servers");Q.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)",(X,P)=>[...P,X],[]).addOption(new sH("--timeout <ms>","connection/call timeout").argParser(Q6("--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(X,P,W)=>{await cH(X,P,{...W,project:Z().project})}),Q.command("remove").argument("<name>").description("remove a server").action(async(X)=>{await pH(X,{project:Z().project})}),Q.command("list").description("list configured MCP servers").action(oH),Q.command("info").argument("<name>").description("show details of a server").action(dH),Q.command("check").description("test connectivity of all servers").action(rH),Q.command("enable").argument("<names...>").description("enable disabled servers (use --project to target project scope)").action(async(X)=>{await aJ(X,!0,{project:Z().project})}),Q.command("disable").argument("<names...>").description("disable servers (use --project to target project scope)").action(async(X)=>{await aJ(X,!1,{project:Z().project})});let Y=$.command("skills").description("manage skills");Y.command("list").option("--json","machine-readable JSON output").description("list skills").action(async(X)=>{await iH(Boolean(X.json))}),Y.command("info").argument("<name>").option("--json","machine-readable JSON output").description("show details of a skill").action(async(X,P)=>{await tH(X,Boolean(P.json))}),Y.command("new").argument("<name>").description("create a new skill scaffold (use --global on `min-agent` for ~/.agents/skills/)").action(async(X)=>{await aH(X,Boolean(Z().global))}),Y.command("enable").argument("<names...>").description("enable disabled skills (use --project to target this project only)").action(async(X)=>{await sJ(X,!0,D5(Z()))}),Y.command("disable").argument("<names...>").description("disable skills (use --project to target this project only)").action(async(X)=>{await sJ(X,!1,D5(Z()))}),$.command("serve").description("start the HTTP API (see docs/API.md)").option("--host <host>","bind host").addOption(new sH("--port <port>","bind port").argParser(Q6("--port"))).action(async(X)=>{await AH(X)});let K=$.command("history").description("manage saved sessions");K.action(SH),K.command("delete").argument("<id>").description("delete a saved session").action(EH),K.command("rename").argument("<id>").argument("<title...>").description("rename a saved session").action(async(X,P)=>{await vH(X,P)}),K.command("export").argument("<id>").option("-o, --output <file>","write to a file instead of stdout").description("export a session as JSON").action(async(X,P)=>{await xH(X,P)}),$.command("update").description("upgrade to the latest npm release").action(yH)}v4();async function AD(){dK(),Q0("info","min-agent started"),await eW(process.argv.slice(2),eH)}AD().catch(($)=>{console.error(`\x1B[31mFatal error: ${$.message}\x1B[0m`),process.exitCode=1});
|